Skip to content

Commit 752d97f

Browse files
browclaude
authored andcommitted
fix(ios): mint hosted NIP-FI assertions in the notification extension (#9228)
Share the hosted Builderlab session with the iOS notification extension so it can mint hosted NIP-FI assertions. The extension queries a hosted relay without an assertion first and mints only after a NIP-FI challenge, for a key the account is already bound to. Credential headers never follow redirects, and flag-off builds clear a previously shared session. Signed-off-by: Tom Brow <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]> (cherry picked from commit 794ee64) Signed-off-by: Tom Brow <[email protected]>
1 parent c1d6489 commit 752d97f

12 files changed

Lines changed: 649 additions & 68 deletions

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

Lines changed: 41 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -82,32 +82,59 @@ public final class BuzzNotificationAvatarLoader {
8282
completion(.failure(BuzzNotificationCacheError.revoked))
8383
return
8484
}
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-
}
9385
guard let assertionIssuer, let relayURL = URL(string: scope.relayOrigin) else {
86+
do {
87+
request.setValue(
88+
try Self.authorization(url: url, key: key, account: scope.account),
89+
forHTTPHeaderField: "Authorization")
90+
} catch {
91+
completion(.failure(error))
92+
return
93+
}
9494
download(request, scope: scope, completion: completion)
9595
return
9696
}
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
97+
// Each attempt is signed afresh. The signed request never follows a redirect, so the
98+
// assertion stays on the relay.
99+
func fetch(
100+
_ assertion: BuzzRelayAssertion?, _ completion: @escaping (Result<Data, Error>) -> Void
101+
) {
100102
// The community may have been removed or its key changed while the assertion was issued.
101103
// Sending the signed request now would present revoked proofs to the relay.
102104
guard self.isCurrent(scope) else {
103105
completion(.failure(BuzzNotificationCacheError.revoked))
104106
return
105107
}
106-
var request = signed
108+
var signed = request
109+
do {
110+
signed.setValue(
111+
try Self.authorization(url: url, key: key, account: scope.account),
112+
forHTTPHeaderField: "Authorization")
113+
} catch {
114+
completion(.failure(error))
115+
return
116+
}
107117
if let assertion {
108-
request.setValue(assertion.header, forHTTPHeaderField: "Nostr-Federated-Identity")
118+
signed.setValue(assertion.header, forHTTPHeaderField: "Nostr-Federated-Identity")
119+
}
120+
self.download(signed, scope: scope, assertion: assertion, completion: completion)
121+
}
122+
assertionIssuer.header(relayURL: relayURL, privateKeyHex: key) { assertion in
123+
fetch(assertion) { result in
124+
// A hosted relay is tried without an assertion first, and asks for one by challenging.
125+
guard assertion == nil, case .failure(BuzzNotificationDownload.Failure.challenged) = result
126+
else {
127+
completion(result)
128+
return
129+
}
130+
assertionIssuer.header(relayURL: relayURL, privateKeyHex: key, challenged: true) { answer in
131+
guard let answer else {
132+
completion(result)
133+
return
134+
}
135+
fetch(answer, completion)
136+
}
109137
}
110-
self.download(request, scope: scope, assertion: assertion, completion: completion)
111138
}
112139
}
113140

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

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ final class BuzzNotificationDownload: NSObject, URLSessionDataDelegate, @uncheck
55
enum Failure: Error {
66
case tooLarge
77
case status(Int)
8+
/// A 401 carrying `WWW-Authenticate: Nostr`: the relay requires NIP-FI evidence.
9+
case challenged
810
case empty, invalidResponse
911
}
1012
private let maximumBytes: Int
@@ -38,7 +40,9 @@ final class BuzzNotificationDownload: NSObject, URLSessionDataDelegate, @uncheck
3840
return
3941
}
4042
guard (200..<300).contains(response.statusCode) else {
41-
failure = Failure.status(response.statusCode)
43+
failure =
44+
BuzzRelayAssertionIssuer.isChallenge(response)
45+
? Failure.challenged : Failure.status(response.statusCode)
4246
completionHandler(.cancel)
4347
return
4448
}
@@ -80,8 +84,13 @@ final class BuzzNotificationDownload: NSObject, URLSessionDataDelegate, @uncheck
8084
willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest,
8185
completionHandler: @escaping (URLRequest?) -> Void
8286
) {
83-
// Signed relay requests must not follow redirects or forward their proof.
84-
guard task.originalRequest?.value(forHTTPHeaderField: "Authorization") == nil,
87+
// Signed relay requests and account requests must not follow redirects or
88+
// forward their proof or session.
89+
let original = task.originalRequest
90+
guard
91+
["Authorization", "X-BB-Session-Credential", "Nostr-Federated-Identity"].allSatisfy({
92+
original?.value(forHTTPHeaderField: $0) == nil
93+
}),
8594
let url = request.url, ["https", "http"].contains(url.scheme?.lowercased() ?? ""),
8695
url.user == nil, url.password == nil,
8796
!(task.originalRequest?.url?.scheme == "https" && url.scheme != "https")

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

Lines changed: 60 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -201,31 +201,60 @@ public final class BuzzPushNotificationResolver: BuzzPushNotificationResolving {
201201
completion([], nil)
202202
return
203203
}
204-
federatedIdentity(relayURL: relayURL, privateKey: privateKey) { assertion in
204+
withFederatedIdentity(relayURL: relayURL, privateKey: privateKey) {
205+
(assertion, finish: @escaping ((Data?, URLResponse?), Bool) -> Void) in
205206
self.send(
206207
url: url, body: body, privateKey: privateKey, federatedIdentity: assertion?.header,
207208
session: self.session,
208209
canRetry: {
209210
self.matchingPrivateKey(for: community) == privateKey && self.isCurrent(assertion)
210211
}
211212
) { data, response in
212-
guard self.matchingPrivateKey(for: community) != nil, self.isCurrent(assertion),
213-
let response = response as? HTTPURLResponse, (200..<300).contains(response.statusCode),
214-
let data, let events = try? JSONDecoder().decode([VerifiedNostrEvent].self, from: data)
215-
else {
216-
completion([], assertion)
213+
finish((data, response), BuzzRelayAssertionIssuer.isChallenge(response))
214+
}
215+
} completion: { result, assertion in
216+
let (data, response) = result
217+
guard self.matchingPrivateKey(for: community) != nil, self.isCurrent(assertion),
218+
let response = response as? HTTPURLResponse, (200..<300).contains(response.statusCode),
219+
let data, let events = try? JSONDecoder().decode([VerifiedNostrEvent].self, from: data)
220+
else {
221+
completion([], assertion)
222+
return
223+
}
224+
completion(
225+
Self.messages(
226+
events: events.filter { event in
227+
event.hasValidIDAndSignature()
228+
&& community.policies.contains { policy in
229+
PushLeaseMatcher.matches(event: event, policy: policy)
230+
}
231+
},
232+
community: community
233+
), assertion)
234+
}
235+
}
236+
237+
/// Runs `attempt` with the relay's NIP-FI assertion, if any. A hosted relay is tried without
238+
/// one first; only if it challenges does the extension ask Builderlab, then retry once.
239+
private func withFederatedIdentity<Output>(
240+
relayURL: URL, privateKey: String,
241+
attempt: @escaping (BuzzRelayAssertion?, @escaping (Output, Bool) -> Void) -> Void,
242+
completion: @escaping (Output, BuzzRelayAssertion?) -> Void
243+
) {
244+
federatedIdentity(relayURL: relayURL, privateKey: privateKey) { assertion in
245+
attempt(assertion) { output, challenged in
246+
guard challenged, assertion == nil, let assertionIssuer = self.assertionIssuer else {
247+
completion(output, assertion)
217248
return
218249
}
219-
completion(
220-
Self.messages(
221-
events: events.filter { event in
222-
event.hasValidIDAndSignature()
223-
&& community.policies.contains { policy in
224-
PushLeaseMatcher.matches(event: event, policy: policy)
225-
}
226-
},
227-
community: community
228-
), assertion)
250+
assertionIssuer.header(relayURL: relayURL, privateKeyHex: privateKey, challenged: true) {
251+
answer in
252+
guard let answer else {
253+
completion(output, nil)
254+
return
255+
}
256+
attempt(answer) { output, _ in completion(output, answer) }
257+
}
229258
}
230259
}
231260
}
@@ -412,15 +441,16 @@ public final class BuzzPushNotificationResolver: BuzzPushNotificationResolving {
412441
completion([])
413442
return
414443
}
415-
federatedIdentity(relayURL: relayURL, privateKey: privateKey) { assertion in
444+
withFederatedIdentity(relayURL: relayURL, privateKey: privateKey) {
445+
(assertion, finish: @escaping (Result<Data, Error>?, Bool) -> Void) in
416446
var request = URLRequest(url: url)
417447
request.httpMethod = "POST"
418448
request.httpBody = body
419449
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
420450
guard let auth = try? NostrHTTPAuth.authorizationHeader(
421451
url: url, method: "POST", body: body, privateKeyHex: privateKey)
422452
else {
423-
completion([])
453+
finish(nil, false)
424454
return
425455
}
426456
request.setValue(auth, forHTTPHeaderField: "Authorization")
@@ -431,15 +461,21 @@ public final class BuzzPushNotificationResolver: BuzzPushNotificationResolving {
431461
request: request, configuration: self.session.configuration,
432462
maximumBytes: Self.maximumPresentationResponseBytes
433463
) { result in
434-
guard self.matchingPrivateKey(for: community) != nil, self.isCurrent(assertion),
435-
case .success(let data) = result,
436-
let events = try? JSONDecoder().decode([VerifiedNostrEvent].self, from: data)
437-
else {
438-
completion([])
464+
guard case .failure(BuzzNotificationDownload.Failure.challenged) = result else {
465+
finish(result, false)
439466
return
440467
}
441-
completion(events.filter { $0.hasValidIDAndSignature() })
468+
finish(result, true)
469+
}
470+
} completion: { result, assertion in
471+
guard self.matchingPrivateKey(for: community) != nil, self.isCurrent(assertion),
472+
case .success(let data)? = result,
473+
let events = try? JSONDecoder().decode([VerifiedNostrEvent].self, from: data)
474+
else {
475+
completion([])
476+
return
442477
}
478+
completion(events.filter { $0.hasValidIDAndSignature() })
443479
}
444480
}
445481

0 commit comments

Comments
 (0)