Files
buzz/mobile/ios/BuzzPushKit/Sources/BuzzPushKit/PushLease.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

148 lines
4.0 KiB
Swift

import Foundation
public struct PushLeaseSnapshot: Codable, Equatable, Sendable {
public let communities: [PushLeaseCommunity]
public init(communities: [PushLeaseCommunity]) {
self.communities = communities
}
}
public struct PushLeaseCommunity: Codable, Equatable, Sendable {
public let id: String
public let name: String
public let relayUrl: String
/// Relay NIP-11 `self` key used to verify NIP-29 channel metadata.
public let relayMetadataPubkey: String?
public let pubkey: String?
/// Identity of this local sign-in, renewed after account removal.
public var notificationSessionID: String?
public let policies: [PushResolutionPolicy]
public init(
id: String,
name: String,
relayUrl: String,
relayMetadataPubkey: String? = nil,
pubkey: String?,
policies: [PushResolutionPolicy],
notificationSessionID: String? = nil
) {
self.id = id
self.name = name
self.relayUrl = relayUrl
self.relayMetadataPubkey = relayMetadataPubkey
self.pubkey = pubkey
self.policies = policies
self.notificationSessionID = notificationSessionID
}
}
public struct PushResolutionPolicy: Codable, Equatable, Sendable {
public let filter: PushLeaseFilter
public let ignore: [PushLeaseFilter]
public let suppress: PushLeaseSuppression?
public init(
filter: PushLeaseFilter,
ignore: [PushLeaseFilter] = [],
suppress: PushLeaseSuppression? = nil
) {
self.filter = filter
self.ignore = ignore
self.suppress = suppress
}
}
public struct PushLeaseSuppression: Codable, Equatable, Sendable {
public let pTagsMax: Int
enum CodingKeys: String, CodingKey {
case pTagsMax = "p_tags_max"
}
public init(pTagsMax: Int) {
self.pTagsMax = pTagsMax
}
}
public struct PushLeaseFilter: Codable, Equatable, Sendable {
public let kinds: [Int]
public let authors: [String]?
public let pTags: [String]?
public let hTags: [String]?
public let eTags: [String]?
enum CodingKeys: String, CodingKey {
case kinds
case authors
case pTags = "#p"
case hTags = "#h"
case eTags = "#e"
}
public init(
kinds: [Int],
authors: [String]? = nil,
pTags: [String]? = nil,
hTags: [String]? = nil,
eTags: [String]? = nil
) {
self.kinds = kinds
self.authors = authors
self.pTags = pTags
self.hTags = hTags
self.eTags = eTags
}
public func queryFilter(since: Int?, limit: Int) -> [String: Any] {
var filter: [String: Any] = ["kinds": kinds, "limit": limit]
if let authors { filter["authors"] = authors }
if let pTags { filter["#p"] = pTags }
if let hTags { filter["#h"] = hTags }
if let eTags { filter["#e"] = eTags }
if let since { filter["since"] = since }
return filter
}
public func matches(_ event: VerifiedNostrEvent) -> Bool {
guard kinds.contains(event.kind) else { return false }
if let authors, !authors.contains(event.pubkey.lowercased()) { return false }
if let pTags, !event.hasAnyTag(named: "p", values: pTags) { return false }
if let hTags, !event.hasAnyTag(named: "h", values: hTags) { return false }
if let eTags, !event.hasAnyTag(named: "e", values: eTags) { return false }
return true
}
}
public enum PushLeaseMatcher {
public static func matches(
event: VerifiedNostrEvent,
policy: PushResolutionPolicy
) -> Bool {
guard policy.filter.matches(event) else { return false }
if policy.ignore.contains(where: { $0.matches(event) }) { return false }
if let maximum = policy.suppress?.pTagsMax,
event.tagCount(named: "p") > maximum
{
return false
}
return true
}
}
extension VerifiedNostrEvent {
public func tagCount(named name: String) -> Int {
tags.reduce(into: 0) { count, tag in
if tag.count >= 2 && tag[0] == name { count += 1 }
}
}
public func hasAnyTag(named name: String, values: [String]) -> Bool {
let expected = Set(values.map { $0.lowercased() })
return tags.contains { tag in
tag.count >= 2 && tag[0] == name && expected.contains(tag[1].lowercased())
}
}
}