Files
buzz/mobile/ios/Runner/PushSnapshotBridge.swift
Tom Brow fea02d174d fix(ios): fetch profiles and avatars in notification extension (#8369)
A notification can arrive from someone whose profile the main app has
never loaded. The iOS notification extension now fetches and caches
sender profiles, channel details, and avatars itself. The main app
supplies account configuration and Keychain credentials only.

After resolving the message, the extension allows 1.5 seconds for sender
and channel details. It uses available stale data when a refresh is slow
or fails, delivers once, and lets late results update its private cache.
Profiles, channel details, and avatar refresh checks share a one-hour
freshness threshold. A verified avatar removal clears the previous
image. Account removal prevents further use of that sign-in's cached
data.

Profile, channel metadata, and membership use separate bounded
downloads, so an oversized roster cannot discard the smaller records.
Sender enrichment can finish while channel requests are pending. A
successful partial channel refresh atomically removes its old
counterpart, preventing a mixed group identity or recipient count.
Group-specific notification presentation still requires a verified
recipient count.

The
[specification](https://github.com/block/buzz/blob/native-notification-enrichment/docs/native-notification-enrichment.md)
describes the display, caching, and account-removal behavior. General
persistent image caching in Flutter remains separate.

### Validation

[Hosted CI](https://github.com/block/buzz/actions/runs/38780108487)
passed on the final commit, including all Flutter shards, Android, the
full iOS release and simulator builds, and native
controls/push-navigation tests. The [current-commit security
review](https://github.com/block/buzz/pull/8369#issuecomment-6197508385)
found no issues.

The native package passed 159 tests, including new coverage for cache
freshness, avatar replacement and removal, sign-in isolation, concurrent
storage, late results, single delivery, bounded downloads, and SVG
validation. A regression test exposed identical HTTP authentication
event IDs for requests in the same second; each request now includes a
unique nonce, matching the Dart and CLI clients.

Full local CI passed before that small authentication fix. The complete
native suite and signed device build passed again on the latest commit,
including response-size limits, overlapping avatar downloads, canonical
relay-origin matching, independent profile/channel refreshes,
account-key changes before and during requests, and a single initial
snapshot read across 64 accounts, signed IPv6 avatar authorities, and
partial channel refreshes. Focused Flutter regression tests passed 198
tests with three configuration-specific skips; seven avatar widget tests
also passed. Flutter analysis is clean, and the notification extension
builds for the simulator.

On an iPhone SE, the notification displayed the sender name, avatar,
channel, and message before the updated main app was opened. Repeat
notifications used a byte-identical private cache. Three notifications
delivered together displayed the avatar after the authentication fix.
The next notification also displayed correctly after terminating the
extension process. The existing generic-push design can select the same
newest unread message for several pushes; this change does not alter
message selection.

![Notification before first app launch after
upgrade](https://raw.githubusercontent.com/block/buzz/37d450855e026178836e2a9e05b0081ebbc3b479/pr-8369--before-first-app-launch.png)

Authenticated HTTP avatar fetching and persistent HTTP cache reuse also
passed on the SE. The first notification downloaded a relay thumbnail.
After terminating the extension and expiring its separate avatar entry,
the next notification displayed the avatar and refreshed that entry
without another media request in the relay logs. The main app remained
unopened throughout. The original app build and test profile were
restored afterward.

Automated tests cover slow and failed requests, stale images, removal,
and account revocation; those cases have not all been exercised on the
phone.

### Before merge

- [x] Verify authenticated HTTP avatar fetching and cache reuse on iOS
against a working relay media service.

<!-- buzz-review-completed -->

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
2026-10-15 11:16:04 -07:00

239 lines
7.8 KiB
Swift

import BuzzPushKit
import Flutter
import Foundation
import Intents
import UserNotifications
final class BuzzPushSnapshotBridge {
private let containerURL: () -> URL?
private let endpointGrantStore: BuzzPushEndpointGrantKeychainStore
private let interactionDeletionDeadline: BuzzInteractionDeletionDeadline
private let keychainAccessGroup: String?
private let queue = DispatchQueue(
label: "xyz.block.buzz.push-snapshot",
qos: .utility
)
private lazy var store: BuzzPushPresentationCacheStore? = {
guard let container = containerURL() else { return nil }
return BuzzPushPresentationCacheStore(containerURL: container)
}()
private let ageRestrictionSession = BuzzAgeRestrictionSession()
init(
appGroupIdentifier: String?,
endpointGrantStore: BuzzPushEndpointGrantKeychainStore,
keychainAccessGroup: String?,
containerURL: (() -> URL?)? = nil,
interactionDeletionDeadline: BuzzInteractionDeletionDeadline =
BuzzInteractionDeletionDeadline(
timeout: 5,
deleteAllInteractions: { completion in
INInteraction.deleteAll(completion: completion)
},
scheduleTimeout: { delay, action in
DispatchQueue.global(qos: .utility).asyncAfter(
deadline: .now() + delay,
execute: action
)
}
)
) {
self.containerURL = containerURL ?? {
guard let appGroupIdentifier else { return nil }
return FileManager.default.containerURL(
forSecurityApplicationGroupIdentifier: appGroupIdentifier)
}
self.endpointGrantStore = endpointGrantStore
self.keychainAccessGroup = keychainAccessGroup
self.interactionDeletionDeadline = interactionDeletionDeadline
}
@discardableResult
func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) -> Bool {
if call.method == "restoreAgeRestrictedNotifications" {
queue.async { [self] in
ageRestrictionSession.release()
BuzzInteractionCleanupRetry(
containerURL: containerURL(), deletion: interactionDeletionDeadline
).retryPending { error in
Self.complete(result, value: error.map {
FlutterError(code: "interaction_cleanup_retry_failed",
message: "Unable to finish pending interaction cleanup.",
details: $0.localizedDescription)
})
}
}
return true
}
if call.method == "purgeAgeRestrictedNotifications" {
purgeAgeRestrictedNotifications(result: result)
return true
}
let strictAgeGateWrite = call.method == "syncAgeGatePushSnapshot"
guard strictAgeGateWrite || call.method == "syncPushSnapshot",
let arguments = call.arguments as? [String: Any],
let section = arguments["section"] as? String
else {
return false
}
switch section {
case "communities":
syncCommunities(
arguments,
requiresStore: strictAgeGateWrite,
result: result
)
default: return false
}
return true
}
private func purgeAgeRestrictedNotifications(result: @escaping FlutterResult) {
queue.async { [weak self] in
do {
guard let self, let container = containerURL() else {
throw NSError(
domain: "BuzzPushSnapshotBridge",
code: 1,
userInfo: [
NSLocalizedDescriptionKey: "The age-restriction session container is unavailable."
]
)
}
try ageRestrictionSession.restrict(containerURL: container)
// Preserve snapshots and credentials. Restriction authority expires
// with this process even when cleanup or a later storage read fails.
let center = UNUserNotificationCenter.current()
center.removeAllDeliveredNotifications()
center.removeAllPendingNotificationRequests()
BuzzInteractionCleanupRetry(
containerURL: container, deletion: interactionDeletionDeadline
).request { error in
Self.complete(
result,
value: error.map {
FlutterError(
code: "age_restriction_purge_failed",
message: "Unable to suppress and purge restricted notifications.",
details: $0.localizedDescription
)
}
)
}
} catch {
Self.complete(
result,
value: FlutterError(
code: "age_restriction_purge_failed",
message: "Unable to suppress and purge restricted notifications.",
details: error.localizedDescription
)
)
}
}
}
private func syncCommunities(
_ arguments: [String: Any],
requiresStore: Bool,
result: @escaping FlutterResult
) {
guard let communities = arguments["communities"] as? [[String: Any]],
let signingKeys = arguments["signingKeys"] as? [String: String],
communities.count <= BuzzPushPresentationCacheStore.maximumCommunities,
!requiresStore || arguments["settleFence"] is Bool
else {
result(
FlutterError(
code: "invalid_arguments",
message: "Expected bounded communities and signing keys.",
details: nil
)
)
return
}
queue.async { [weak self] in
do {
guard let self else {
Self.complete(
result,
value: requiresStore
? FlutterError(
code: "snapshot_sync_unavailable",
message: "The push snapshot bridge is unavailable.",
details: nil
)
: nil
)
return
}
guard let store else {
Self.complete(
result,
value: requiresStore
? FlutterError(
code: "snapshot_sync_unavailable",
message: "The push snapshot store is unavailable.",
details: nil
)
: nil
)
return
}
// Relay-metadata enrichment is optional presentation state. A damaged
// grant cache must not block the core NSE snapshot and key update.
let grants = (try? endpointGrantStore.records()) ?? []
let enriched = communities.map { community -> [String: Any] in
var community = community
guard let relayURL = community["relayUrl"] as? String,
let relayMetadataPubkey = Self.relayMetadataPubkey(
relayURL: relayURL,
grants: grants
)
else { return community }
community["relayMetadataPubkey"] = relayMetadataPubkey
return community
}
let data = try JSONSerialization.data(withJSONObject: enriched, options: [.sortedKeys])
let decoded = try JSONDecoder().decode([PushLeaseCommunity].self, from: data)
// Ordinary snapshot maintenance never changes age access.
try store.replaceCommunities(decoded)
try BuzzPushKeychain.replace(
signingKeys: signingKeys,
accessGroup: self.keychainAccessGroup
)
Self.complete(result, value: nil)
} catch {
Self.complete(
result,
value: FlutterError(
code: "snapshot_sync_failed",
message: "Unable to sync push community state.",
details: error.localizedDescription
)
)
}
}
}
static func relayMetadataPubkey(
relayURL: String,
grants: [BuzzPushEndpointGrantRecord]
) -> String? {
guard let origin = BuzzPushPresentationCacheStore.canonicalRelayOrigin(relayURL) else {
return nil
}
return grants.filter {
BuzzPushPresentationCacheStore.canonicalRelayOrigin($0.relayOrigin) == origin
}.max {
$0.generation < $1.generation
}?.relayMetadataPubkey
}
private static func complete(_ result: @escaping FlutterResult, value: Any?) {
DispatchQueue.main.async {
result(value)
}
}
}