Skip to content

Commit 97ede70

Browse files
browsquare-tombclaudestudio
authored
fix(mobile): send hosted relay assertion from native media and tombstone paths (#9069)
Follow-up to #9056, from an audit for other places that miss the hosted relay assertion. Hosted and organization relays require `Nostr-Federated-Identity` on every non-exempt HTTP request and WebSocket upgrade. The Dart `HostedRelayHttpClient` adds it, but anything that downloads or connects outside that client has to add it itself. The notification service extension and the iOS emoji picker both missed it, and these places do too: - **Voice notes** (`just_audio`, mainly Android) and **video preview first frames** fetch media natively with only the Blossom `Authorization` header. Both now use `nativeMediaHeadersProvider` from #9056. - **Push-lease tombstones**: removing a community, and the durable revocation outbox, open a one-off relay socket with no headers. A hosted relay refuses the upgrade, so the lease is never revoked and the outbox keeps retrying. Both now ask `HostedRelayAuth` for that community's own assertion, because the community being removed may not be the active session. - **Notification avatars** (iOS notification service extension): relay-hosted sender avatars were fetched with Blossom auth only. The loader now takes the same `BuzzRelayAssertionIssuer` the resolver uses for `/query`. Signed requests already refuse redirects. The iOS Me-chat agent picker also fetched avatars with no headers, but #9079 removed that native screen, so this PR no longer touches it. ### Validation - Added tests, each checked to fail when the code it guards is reverted: - A queued push-lease revocation and a community-removal tombstone both send `Nostr-Federated-Identity` on the WebSocket upgrade, as background requests. Runs against a local relay socket that handles NIP-42 auth. - A notification avatar on an organization relay is downloaded with the issued assertion (BuzzPushKit). - Issuing for a second community keeps the first one's cached assertion. A background request records no failure, never backs up the key, and its failure never reaches the active community's reconnect waiting on it. - Background issuance never binds an unbound account to its key, bypasses the shared assertion cache (each attempt gets a fresh assertion, and foreground use never inherits one that skipped the key backup), and its failure is never handed to a foreground caller waiting on it. When it can't get an assertion it sends none, so a non-enforcing relay still accepts the tombstone. - A notification avatar whose organization session is replaced mid-download is refused and dropped from the cache (BuzzPushKit). - Voice notes and posterless video previews renew an expired assertion before the native fetch, and fall back to cached headers if renewal fails. A voice-note attachment journey binds the production provider. - Cached reads never present a signed-out or replaced account's assertion. - `flutter analyze` is clean. `swift test` passes for the BuzzPushKit avatar loader tests, and `flutter build ios --simulator --debug` succeeds. - Full mobile suite (`just mobile-check` and `just mobile-test`) passes at 2c84940. - Automated full-app run on an iOS simulator (debug build of this PR before it was rebuilt on main, signed in to the internal Builderlab community with two more communities saved). Passed: launch and channel list, image attachments and avatars in a channel, New chat sheet kept open for about 80 seconds before the agent list was opened (all agent avatars loaded, so headers are requested per download), dismiss and reopen, background and resume, switching to a second community (its icon and avatars loaded), and removing a community. The native New chat sheet is unreachable in the normal flow on this branch (a new chat opens the Flutter draft page; the native sheet only opens when resuming an unfinished chat), so that check ran with a temporary local bypass that was reverted. Limits: none of these communities requires the hosted relay assertion in this build, so the run shows the Swift-to-Dart header bridge, the per-relay cache and the tombstone path cause no regression, not that the assertion is sent or accepted. No voice note, video preview or deleted message was reachable. Screenshots are omitted because they show internal channel content. - Limitations: no end-to-end run against a hosted relay. Simulator sign-in to a hosted relay needs SSO, so a hosted-relay run needs a device build. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Tom Brow <[email protected]> Co-authored-by: Tom Brow <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
1 parent 120d75d commit 97ede70

13 files changed

Lines changed: 670 additions & 91 deletions

File tree

‎mobile/ios/BuzzPushKit/Sources/BuzzPushKit/BuzzNotificationAvatarLoader.swift‎

Lines changed: 51 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,28 @@ public final class BuzzNotificationAvatarLoader {
1010
private let directory: URL
1111
private let privateKey: (String) -> String?
1212
private let isCurrent: (BuzzNotificationCacheScope) -> Bool
13+
private let assertionIssuer: BuzzRelayAssertionIssuer?
1314
private static let maximumDownloadBytes = 2 * 1024 * 1024
15+
/// The network transfer; tests substitute it to observe whether a request would be sent.
16+
var startDownload:
17+
(URLRequest, URLSessionConfiguration, Int, @escaping (Result<Data, Error>) -> Void) -> Void =
18+
{ request, configuration, maximumBytes, completion in
19+
BuzzNotificationDownload.start(
20+
request: request, configuration: configuration, maximumBytes: maximumBytes,
21+
completion: completion)
22+
}
1423

24+
/// `assertionIssuer` supplies the NIP-FI assertion an organization relay requires on media
25+
/// reads, as it does for the resolver's `/query`; without it those avatars are refused.
1526
public init(
1627
directory: URL, privateKey: @escaping (String) -> String?,
17-
isCurrent: @escaping (BuzzNotificationCacheScope) -> Bool
28+
isCurrent: @escaping (BuzzNotificationCacheScope) -> Bool,
29+
assertionIssuer: BuzzRelayAssertionIssuer? = nil
1830
) {
1931
self.directory = directory
2032
self.privateKey = privateKey
2133
self.isCurrent = isCurrent
34+
self.assertionIssuer = assertionIssuer
2235
}
2336

2437
/// Returns a bounded PNG suitable for INImage. HTTP caching retains the original response.
@@ -61,27 +74,52 @@ public final class BuzzNotificationAvatarLoader {
6174
return
6275
}
6376
var request = URLRequest(url: url)
64-
if Self.isRelayMedia(url, scope: scope) {
65-
guard let key = privateKey(scope.communityID) else {
77+
guard Self.isRelayMedia(url, scope: scope) else {
78+
download(request, scope: scope, completion: completion)
79+
return
80+
}
81+
guard let key = privateKey(scope.communityID) else {
82+
completion(.failure(BuzzNotificationCacheError.revoked))
83+
return
84+
}
85+
do {
86+
request.setValue(
87+
try Self.authorization(url: url, key: key, account: scope.account),
88+
forHTTPHeaderField: "Authorization")
89+
} catch {
90+
completion(.failure(error))
91+
return
92+
}
93+
guard let assertionIssuer, let relayURL = URL(string: scope.relayOrigin) else {
94+
download(request, scope: scope, completion: completion)
95+
return
96+
}
97+
// The signed request never follows a redirect, so the assertion stays on the relay.
98+
let signed = request
99+
assertionIssuer.header(relayURL: relayURL, privateKeyHex: key) { assertion in
100+
// The community may have been removed or its key changed while the assertion was issued.
101+
// Sending the signed request now would present revoked proofs to the relay.
102+
guard self.isCurrent(scope) else {
66103
completion(.failure(BuzzNotificationCacheError.revoked))
67104
return
68105
}
69-
do {
70-
request.setValue(
71-
try Self.authorization(url: url, key: key, account: scope.account),
72-
forHTTPHeaderField: "Authorization")
73-
} catch {
74-
completion(.failure(error))
75-
return
106+
var request = signed
107+
if let assertion {
108+
request.setValue(assertion.header, forHTTPHeaderField: "Nostr-Federated-Identity")
76109
}
110+
self.download(request, scope: scope, completion: completion)
77111
}
112+
}
113+
114+
private func download(
115+
_ request: URLRequest, scope: BuzzNotificationCacheScope,
116+
completion: @escaping (Result<Data, Error>) -> Void
117+
) {
78118
let configuration = URLSessionConfiguration.default
79119
configuration.httpCookieStorage = nil
80120
configuration.urlCredentialStorage = nil
81121
configuration.urlCache = httpCache(scope)
82-
BuzzNotificationDownload.start(
83-
request: request, configuration: configuration, maximumBytes: Self.maximumDownloadBytes
84-
) { result in
122+
startDownload(request, configuration, Self.maximumDownloadBytes) { result in
85123
guard self.isCurrent(scope) else {
86124
completion(.failure(BuzzNotificationCacheError.revoked))
87125
return

‎mobile/ios/BuzzPushKit/Tests/BuzzPushKitTests/BuzzNotificationAvatarLoaderTests.swift‎

Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,4 +71,137 @@ struct BuzzNotificationAvatarLoaderTests {
7171
try BuzzNotificationAvatarLoader.decode(Data("not an image".utf8))
7272
}
7373
}
74+
75+
@Test("A scope revoked while the assertion is issued never starts the signed download")
76+
func scopeRevokedDuringAssertionIssuance() async throws {
77+
let key = String(repeating: "0", count: 63) + "1"
78+
let account = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"
79+
let scope = try #require(
80+
BuzzNotificationCacheScope(
81+
community: PushLeaseCommunity(
82+
id: "community", name: "Test", relayUrl: "wss://relay.org.example", pubkey: account,
83+
policies: [], notificationSessionID: "session")))
84+
let configuration = URLSessionConfiguration.ephemeral
85+
configuration.protocolClasses = [AssertionIssuanceStub.self]
86+
let state = AvatarScopeState()
87+
AssertionIssuanceStub.onRequest = { state.revoke() }
88+
defer { AssertionIssuanceStub.onRequest = nil }
89+
let issuer = BuzzRelayAssertionIssuer(
90+
session: URLSession(configuration: configuration),
91+
loadSession: {
92+
BuzzOrganizationSession(
93+
origin: "https://identity.org.example", credential: "session-credential",
94+
relayHosts: ["relay.org.example"])
95+
})
96+
let directory = FileManager.default.temporaryDirectory.appendingPathComponent(
97+
UUID().uuidString)
98+
defer { try? FileManager.default.removeItem(at: directory) }
99+
let loader = BuzzNotificationAvatarLoader(
100+
directory: directory, privateKey: { _ in key }, isCurrent: { _ in state.isCurrent },
101+
assertionIssuer: issuer)
102+
loader.startDownload = { _, _, _, completion in
103+
state.recordDownload()
104+
completion(.failure(URLError(.cancelled)))
105+
}
106+
107+
let result = await withCheckedContinuation { continuation in
108+
loader.load(
109+
source: "https://relay.org.example/media/\(String(repeating: "a", count: 64)).png",
110+
scope: scope
111+
) { continuation.resume(returning: $0) }
112+
}
113+
114+
guard case .failure(BuzzNotificationCacheError.revoked) = result else {
115+
Issue.record("Expected a revoked failure, got \(result)")
116+
return
117+
}
118+
#expect(state.downloads == 0)
119+
}
120+
121+
@Test("An organization relay avatar is fetched with the issued assertion")
122+
func relayAvatarCarriesAssertion() async throws {
123+
let key = String(repeating: "0", count: 63) + "1"
124+
let account = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"
125+
let scope = try #require(
126+
BuzzNotificationCacheScope(
127+
community: PushLeaseCommunity(
128+
id: "community", name: "Test", relayUrl: "wss://relay.org.example", pubkey: account,
129+
policies: [], notificationSessionID: "session")))
130+
let configuration = URLSessionConfiguration.ephemeral
131+
configuration.protocolClasses = [AssertionIssuanceStub.self]
132+
let issuer = BuzzRelayAssertionIssuer(
133+
session: URLSession(configuration: configuration),
134+
loadSession: {
135+
BuzzOrganizationSession(
136+
origin: "https://identity.org.example", credential: "session-credential",
137+
relayHosts: ["relay.org.example"])
138+
})
139+
let directory = FileManager.default.temporaryDirectory.appendingPathComponent(
140+
UUID().uuidString)
141+
defer { try? FileManager.default.removeItem(at: directory) }
142+
let loader = BuzzNotificationAvatarLoader(
143+
directory: directory, privateKey: { _ in key }, isCurrent: { _ in true },
144+
assertionIssuer: issuer)
145+
let requests = AvatarRequests()
146+
loader.startDownload = { request, _, _, completion in
147+
requests.record(request)
148+
completion(.failure(URLError(.cancelled)))
149+
}
150+
151+
_ = await withCheckedContinuation { continuation in
152+
loader.load(
153+
source: "https://relay.org.example/media/\(String(repeating: "a", count: 64)).png",
154+
scope: scope
155+
) { continuation.resume(returning: $0) }
156+
}
157+
158+
let request = try #require(requests.first)
159+
#expect(
160+
request.value(forHTTPHeaderField: "Nostr-Federated-Identity")
161+
== "Bearer header.payload.signature")
162+
#expect(request.value(forHTTPHeaderField: "Authorization") != nil)
163+
}
164+
}
165+
166+
private final class AvatarRequests: @unchecked Sendable {
167+
private let lock = NSLock()
168+
private var requests: [URLRequest] = []
169+
170+
var first: URLRequest? { lock.withLock { requests.first } }
171+
func record(_ request: URLRequest) { lock.withLock { requests.append(request) } }
172+
}
173+
174+
private final class AvatarScopeState: @unchecked Sendable {
175+
private let lock = NSLock()
176+
private var current = true
177+
private var started = 0
178+
179+
var isCurrent: Bool { lock.withLock { current } }
180+
var downloads: Int { lock.withLock { started } }
181+
func revoke() { lock.withLock { current = false } }
182+
func recordDownload() { lock.withLock { started += 1 } }
183+
}
184+
185+
/// Answers the organization's assertion issuer, running `onRequest` while issuance is in flight.
186+
private final class AssertionIssuanceStub: URLProtocol, @unchecked Sendable {
187+
nonisolated(unsafe) static var onRequest: (() -> Void)?
188+
189+
override class func canInit(with request: URLRequest) -> Bool { true }
190+
override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
191+
192+
override func startLoading() {
193+
Self.onRequest?()
194+
let body = try! JSONSerialization.data(withJSONObject: [
195+
"assertion": "header.payload.signature",
196+
"nostr_pubkey": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",
197+
"expires_at": Int(Date().timeIntervalSince1970) + 300,
198+
])
199+
let response = HTTPURLResponse(
200+
url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!
201+
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
202+
client?.urlProtocol(self, didLoad: body)
203+
client?.urlProtocolDidFinishLoading(self)
204+
}
205+
206+
override func stopLoading() {}
74207
}

‎mobile/ios/NotificationService/NotificationService.swift‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,8 @@ final class NotificationService: UNNotificationServiceExtension {
114114
let accessGroup = Bundle.main.object(forInfoDictionaryKey: "BuzzKeychainAccessGroup") as? String
115115
return BuzzNotificationAvatarLoader(directory: directory,
116116
privateKey: { Self.loadPrivateKey(communityID: $0, keychainAccessGroup: accessGroup) },
117-
isCurrent: { [weak self] in self?.isCurrent($0) == true })
117+
isCurrent: { [weak self] in self?.isCurrent($0) == true },
118+
assertionIssuer: Self.assertionIssuer)
118119
}()
119120

120121
private func isCurrent(_ scope: BuzzNotificationCacheScope) -> Bool {

‎mobile/lib/features/channels/message_content.dart‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import '../../shared/mentions/mention_bindings.dart';
2424
import '../../shared/mentions/mention_tags.dart';
2525
import '../../shared/deeplink/deep_link.dart';
2626
import '../../shared/deeplink/pending_deep_link_provider.dart';
27+
import '../../shared/hosted/native_media_headers.dart';
2728
import '../../shared/relay/relay.dart';
2829
import '../../shared/syntax_highlight.dart';
2930
import '../../shared/theme/theme.dart';

‎mobile/lib/features/channels/message_content/video_preview.dart‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,9 @@ typedef VideoPreviewFrameLoader =
2929
final videoPreviewFrameLoaderProvider = Provider<VideoPreviewFrameLoader>((
3030
ref,
3131
) {
32-
final auth = ref.watch(mediaGetAuthServiceProvider);
33-
return (url) => _loadVideoPreviewFrame(url, headers: auth.headersFor(url));
32+
// The native player fetches the URL itself, outside the hosted HTTP client.
33+
final headersFor = ref.watch(nativeMediaHeadersProvider);
34+
return (url) => _loadVideoPreviewFrame(url, headers: headersFor(url));
3435
});
3536

3637
class _MessageVideoPreview extends HookConsumerWidget {

‎mobile/lib/features/channels/voice_note_attachment.dart‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import 'package:flutter_hooks/flutter_hooks.dart';
88
import 'package:hooks_riverpod/hooks_riverpod.dart';
99
import 'package:buzz/shared/theme/buzz_icons.dart';
1010

11-
import '../../shared/relay/relay.dart';
11+
import '../../shared/hosted/native_media_headers.dart';
1212
import '../../shared/theme/theme.dart';
1313
import '../../shared/widgets/buzz_loading_indicator.dart';
1414
import '../../shared/widgets/skeleton.dart';
@@ -54,8 +54,7 @@ class VoiceNoteAttachment extends HookConsumerWidget {
5454
unawaited(
5555
player.loadRemote(
5656
source,
57-
headers: () =>
58-
ref.read(mediaGetAuthServiceProvider).headersFor(source),
57+
headers: () => ref.read(nativeMediaHeadersProvider)(source),
5958
fallbackDuration: duration,
6059
),
6160
);

‎mobile/lib/shared/community/community_provider.dart‎

Lines changed: 24 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import '../push/push_bridge.dart';
1515
import '../push/push_lease_revocation_outbox.dart';
1616
import '../push/push_subscription.dart';
1717
import '../relay/signed_event_relay.dart';
18-
import '../relay/relay_provider.dart' show pubkeyFromNsec;
18+
import '../relay/relay_provider.dart' show RelayConfig, pubkeyFromNsec;
1919
import 'community.dart';
2020
import 'community_storage.dart';
2121

@@ -101,8 +101,11 @@ typedef CommunityPushLeaseDeactivator =
101101

102102
final communityPushLeaseDeactivatorProvider =
103103
Provider<CommunityPushLeaseDeactivator>((ref) {
104-
return (community, {generation}) =>
105-
_deactivateCommunityPushLease(community, generation: generation);
104+
return (community, {generation}) => _deactivateCommunityPushLease(
105+
community,
106+
generation: generation,
107+
relayAuth: ref.read(hostedRelayAuthProvider),
108+
);
106109
});
107110

108111
typedef CommunityPushLeaseRevocationEnqueuer =
@@ -123,6 +126,7 @@ final communityPushLeaseRevocationTriggerProvider =
123126
Future<void> _deactivateCommunityPushLease(
124127
Community community, {
125128
int? generation,
129+
required HostedRelayAuth relayAuth,
126130
}) async {
127131
final state = community.pushSubscriptionState;
128132
final acceptedGeneration = state.acceptedGeneration;
@@ -154,6 +158,12 @@ Future<void> _deactivateCommunityPushLease(
154158
};
155159
final wsScheme = httpScheme == 'https' ? 'wss' : 'ws';
156160
final wsUrl = uri.replace(scheme: wsScheme).toString();
161+
// The community being removed may not be the active session, so ask for its
162+
// own assertion: a hosted relay refuses the socket upgrade without one.
163+
final relayConfig = RelayConfig(
164+
baseUrl: uri.replace(scheme: httpScheme).toString(),
165+
nsec: nsec,
166+
);
157167
// Skip over the one renewal generation that could already be in flight
158168
// when removal begins. Strict relay monotonicity then makes any stale
159169
// active publication lose to this tombstone.
@@ -165,15 +175,17 @@ Future<void> _deactivateCommunityPushLease(
165175
generation: tombstoneGeneration,
166176
nsec: nsec,
167177
memberPubkey: memberPubkey,
168-
submit: ({required kind, required content, required tags, createdAt}) =>
169-
submitSignedEventOnce(
170-
wsUrl: wsUrl,
171-
nsec: nsec,
172-
kind: kind,
173-
content: content,
174-
tags: tags,
175-
createdAt: createdAt,
176-
),
178+
submit:
179+
({required kind, required content, required tags, createdAt}) async =>
180+
submitSignedEventOnce(
181+
wsUrl: wsUrl,
182+
headers: await relayAuth.headers(relayConfig, background: true),
183+
nsec: nsec,
184+
kind: kind,
185+
content: content,
186+
tags: tags,
187+
createdAt: createdAt,
188+
),
177189
);
178190
pushLeaseCleanupError.value = null;
179191
}

0 commit comments

Comments
 (0)