Skip to content

Commit b58ee08

Browse files
browclaude
andauthored
fix(mobile): request hosted relay assertions only when NIP-FI is required (#9225)
Port the desktop NIP-FI requirement rule to mobile: hosted relay connections request an account assertion only when the relay's NIP-11 document requires NIP-FI, so communities that have not enabled it keep connecting with BUZZ_HOSTED_RELAY_AUTH on. Signed-off-by: Tom Brow <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 96af488 commit b58ee08

17 files changed

Lines changed: 402 additions & 51 deletions

‎mobile/lib/shared/agents/remote_agents.dart‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -790,7 +790,7 @@ class RemoteAgentController extends ChangeNotifier {
790790
final config = RelayConfig(baseUrl: relay, nsec: key.nsec);
791791
await submitSignedEventOnce(
792792
wsUrl: config.wsUrl,
793-
headers: await relayAuth.headers(config),
793+
headers: await relayAuth.headers(config, fresh: true),
794794
nsec: key.nsec,
795795
kind: 30177,
796796
content: jsonEncode({
@@ -813,7 +813,7 @@ class RemoteAgentController extends ChangeNotifier {
813813
final config = RelayConfig(baseUrl: relay, nsec: key.nsec);
814814
await submitSignedEventOnce(
815815
wsUrl: config.wsUrl,
816-
headers: await relayAuth.headers(config),
816+
headers: await relayAuth.headers(config, fresh: true),
817817
nsec: key.nsec,
818818
kind: 5,
819819
content: '',

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

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,11 @@ Future<void> _deactivateCommunityPushLease(
179179
({required kind, required content, required tags, createdAt}) async =>
180180
submitSignedEventOnce(
181181
wsUrl: wsUrl,
182-
headers: await relayAuth.headers(relayConfig, background: true),
182+
headers: await relayAuth.headers(
183+
relayConfig,
184+
background: true,
185+
fresh: true,
186+
),
183187
nsec: nsec,
184188
kind: kind,
185189
content: content,

‎mobile/lib/shared/hosted/hosted_admission.dart‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,7 @@ class HostedAdmission {
162162
try {
163163
socket.headers = await relayAuth.headers(
164164
RelayConfig(baseUrl: community.relayUrl, nsec: community.nsec),
165+
fresh: true,
165166
);
166167
await socket.connect().timeout(const Duration(seconds: 30));
167168
if (socket.state != SocketState.connected) throw AccountFailure.denied;

‎mobile/lib/shared/hosted/hosted_relay_auth.dart‎

Lines changed: 65 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import '../relay/relay_provider.dart';
88
import 'builderlab_account.dart';
99
import 'account_identity_store.dart';
1010
import 'hosted_environment.dart';
11+
import 'nip_fi_discovery.dart';
1112
import 'organization_environment.dart';
1213
import 'organization_key_backup.dart';
1314
import '../push/push_bridge.dart';
@@ -61,9 +62,10 @@ final hostedHttpClientFactoryProvider = Provider<http.Client Function()>((ref) {
6162
});
6263

6364
/// One account session per realm, with a short-lived assertion for the current
64-
/// relay/key. Hosted communities use [account] when [enabled]; the build's
65-
/// organization relays use [organization]. Enable alongside backend issuance;
66-
/// legacy and self-hosted builds stay usable.
65+
/// relay/key. Hosted communities use [account] when [enabled] and their relay's
66+
/// NIP-FI discovery requires evidence; the build's organization relays always
67+
/// use [organization]. Enable alongside backend issuance; legacy and
68+
/// self-hosted builds stay usable.
6769
class HostedRelayAuth extends ChangeNotifier {
6870
HostedRelayAuth(
6971
this.account, {
@@ -72,7 +74,18 @@ class HostedRelayAuth extends ChangeNotifier {
7274
this.organizationRelay = OrganizationEnvironment.protects,
7375
this.enabled = const bool.fromEnvironment('BUZZ_HOSTED_RELAY_AUTH'),
7476
DateTime Function()? now,
75-
}) : _now = now ?? DateTime.now;
77+
NipFiRequirementFetch? discover,
78+
}) : _now = now ?? DateTime.now,
79+
_discover = discover ?? _fetchRequirement;
80+
81+
static Future<bool> _fetchRequirement(Uri origin) async {
82+
final client = http.Client();
83+
try {
84+
return await fetchNipFiRequirement(client, origin);
85+
} finally {
86+
client.close();
87+
}
88+
}
7689

7790
final BuilderlabAccountClient account;
7891
final BuilderlabAccountClient? organization;
@@ -82,6 +95,12 @@ class HostedRelayAuth extends ChangeNotifier {
8295
final bool Function(Uri relay) organizationRelay;
8396
final bool enabled;
8497
final DateTime Function() _now;
98+
final NipFiRequirementFetch _discover;
99+
// NIP-FI discovery per hosted relay origin: the read in flight, shared by
100+
// concurrent callers, and the last result. The issuer refuses hosts that have
101+
// not enabled NIP-FI, so those connect without evidence.
102+
final _discovering = <String, Future<bool>>{};
103+
final _required = <String, bool>{};
85104
// One assertion per relay and key, so issuing for an inactive community (for
86105
// example a background revocation) never evicts the active session's
87106
// credentials that native media paths read synchronously.
@@ -130,7 +149,12 @@ class HostedRelayAuth extends ChangeNotifier {
130149
/// recovery state. Null means protected metadata must wait for active auth.
131150
Map<String, String>? cachedHeaders(RelayConfig config) {
132151
if (_disposed) return null;
133-
if (!protects(config)) return const {};
152+
final client = _accountFor(config);
153+
if (client == null) return const {};
154+
if (_hostedOrigin(config, client) case final origin?
155+
when _required[origin] == false) {
156+
return const {};
157+
}
134158
final pubkey = pubkeyFromNsec(config.nsec);
135159
if (pubkey == null) return null;
136160
final cached =
@@ -139,7 +163,7 @@ class HostedRelayAuth extends ChangeNotifier {
139163
pubkey: pubkey,
140164
)];
141165
if (cached == null ||
142-
!identical(cached.account, _accountFor(config)?.account) ||
166+
!identical(cached.account, client.account) ||
143167
!cached.expiry.isAfter(_now())) {
144168
return null;
145169
}
@@ -176,13 +200,23 @@ class HostedRelayAuth extends ChangeNotifier {
176200
/// foreground use never inherits an assertion whose key was not backed up.
177201
/// Without an assertion it gets no headers rather than a failure, so the
178202
/// relay decides.
203+
///
204+
/// A hosted relay gets an assertion only when its NIP-FI discovery requires
205+
/// one. Every caller opening a new socket passes [fresh] to reread
206+
/// discovery, so a community that changes enforcement is picked up on its
207+
/// next connect; HTTP requests reuse the latest discovery.
179208
Future<Map<String, String>> headers(
180209
RelayConfig config, {
181210
bool background = false,
211+
bool fresh = false,
182212
}) async {
183213
final client = _accountFor(config);
184214
if (client == null) return const {};
185215
try {
216+
if (_hostedOrigin(config, client) case final origin?
217+
when !await _requires(origin, fresh)) {
218+
return const {};
219+
}
186220
return await _headers(config, client, background);
187221
} on AccountFailure catch (failure) {
188222
// Cleanup still reaches a relay that does not enforce assertions; an
@@ -198,6 +232,29 @@ class HostedRelayAuth extends ChangeNotifier {
198232
}
199233
}
200234

235+
/// The relay origin whose discovery decides, or null for organization relays,
236+
/// which always use their own issuer.
237+
String? _hostedOrigin(RelayConfig config, BuilderlabAccountClient client) =>
238+
identical(client, organization) ? null : Uri.parse(config.baseUrl).origin;
239+
240+
Future<bool> _requires(String origin, bool fresh) async {
241+
final known = _required[origin];
242+
if (!fresh && known != null) return known;
243+
final pending = _discovering[origin] ??= _discover(Uri.parse(origin));
244+
try {
245+
return _required[origin] = await pending;
246+
} on Exception catch (error) {
247+
// The last answer stays for requests. Without one, or for a new
248+
// connection, retry with backoff rather than guessing.
249+
debugPrint('NIP-FI discovery failed for $origin: $error');
250+
throw AccountFailure.unavailable;
251+
} finally {
252+
if (identical(_discovering[origin], pending)) {
253+
_discovering.remove(origin);
254+
}
255+
}
256+
}
257+
201258
Future<Map<String, String>> _headers(
202259
RelayConfig config,
203260
BuilderlabAccountClient client,
@@ -403,6 +460,8 @@ class HostedRelayAuth extends ChangeNotifier {
403460
void dispose() {
404461
_disposed = true;
405462
_cached.clear();
463+
_discovering.clear();
464+
_required.clear();
406465
super.dispose();
407466
}
408467
}
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import 'package:http/http.dart' as http;
2+
3+
import '../relay/nip11_document.dart';
4+
5+
/// Whether the relay at [origin] requires NIP-FI admission evidence, read from
6+
/// its NIP-11 document. Throws on any failure or malformed document.
7+
typedef NipFiRequirementFetch = Future<bool> Function(Uri origin);
8+
9+
/// Reads [origin]'s NIP-11 document from its root, without following
10+
/// redirects; see [fetchNip11Document].
11+
Future<bool> fetchNipFiRequirement(
12+
http.Client client,
13+
Uri origin, {
14+
Duration deadline = nip11Deadline,
15+
}) async => parseNipFiRequirement(
16+
await fetchNip11Document(
17+
client,
18+
Uri.parse(origin.origin).replace(path: '/'),
19+
deadline: deadline,
20+
followRedirects: false,
21+
),
22+
);
23+
24+
/// NIP-FI Discovery: `limitation.federated_identity` advertises support, as a
25+
/// shadow-mode host does too; the host-specific `requires_nip_fi` says this
26+
/// community requires evidence. A relay without the flag requires what it
27+
/// supports. Same requirement rule as buzz-app's desktop discovery.
28+
bool parseNipFiRequirement(Object? document) {
29+
if (document is! Map<String, dynamic>) {
30+
throw const FormatException('NIP-11 document is not an object');
31+
}
32+
final supports = switch (document['limitation']) {
33+
null => false,
34+
final Map<String, dynamic> limitation =>
35+
switch (limitation['federated_identity']) {
36+
null || false => false,
37+
true => true,
38+
_ => throw const FormatException('Malformed federated_identity'),
39+
},
40+
_ => throw const FormatException('Malformed NIP-11 limitation'),
41+
};
42+
return switch (document['requires_nip_fi']) {
43+
null => supports,
44+
final bool requires => requires,
45+
_ => throw const FormatException('Malformed requires_nip_fi'),
46+
};
47+
}

‎mobile/lib/shared/huddle/huddle_session.dart‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,7 @@ final huddleTransportFactoryProvider = Provider<HuddleTransportFactory>((ref) {
160160
parameters: parameters,
161161
headers: () => auth.headers(
162162
RelayConfig(baseUrl: parameters.relayWebSocketUrl, nsec: parameters.nsec),
163+
fresh: true,
163164
),
164165
);
165166
});

‎mobile/lib/shared/push/push_lease_revocation_outbox.dart‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -553,6 +553,7 @@ Future<void> publishBuzzPushLeaseRevocation(
553553
headers: await relayAuth.headers(
554554
RelayConfig(baseUrl: record.relayUrl, nsec: record.nsec),
555555
background: true,
556+
fresh: true,
556557
),
557558
nsec: record.nsec,
558559
kind: kind,
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import 'dart:async';
2+
import 'dart:convert';
3+
4+
import 'package:http/http.dart' as http;
5+
6+
const _maxDocumentBytes = 256 * 1024;
7+
8+
/// How long a NIP-11 read may take, headers and body together.
9+
const nip11Deadline = Duration(seconds: 10);
10+
11+
/// Reads and decodes the NIP-11 document at [uri] with a size cap. One
12+
/// wall-clock deadline covers headers and the whole body, so a relay trickling
13+
/// bytes cannot keep the read in flight forever. No credential goes on the
14+
/// request. Throws on a non-200 status, an oversized body, the deadline or
15+
/// malformed JSON.
16+
Future<Object?> fetchNip11Document(
17+
http.Client client,
18+
Uri uri, {
19+
Duration deadline = nip11Deadline,
20+
bool followRedirects = true,
21+
}) async {
22+
final abort = Completer<void>();
23+
final request = http.AbortableRequest('GET', uri, abortTrigger: abort.future)
24+
..followRedirects = followRedirects
25+
..headers['Accept'] = 'application/nostr+json';
26+
StreamIterator<List<int>>? body;
27+
Future<List<int>> read() async {
28+
final response = await client.send(request);
29+
final iterator = body = StreamIterator(response.stream);
30+
if (response.statusCode != 200) {
31+
throw http.ClientException('NIP-11 status ${response.statusCode}', uri);
32+
}
33+
final bytes = <int>[];
34+
while (await iterator.moveNext()) {
35+
if (bytes.length + iterator.current.length > _maxDocumentBytes) {
36+
throw const FormatException('NIP-11 exceeds size limit');
37+
}
38+
bytes.addAll(iterator.current);
39+
}
40+
return bytes;
41+
}
42+
43+
try {
44+
final bytes = await read().timeout(deadline);
45+
return jsonDecode(utf8.decode(bytes));
46+
} finally {
47+
if (!abort.isCompleted) abort.complete();
48+
unawaited(body?.cancel());
49+
}
50+
}

‎mobile/lib/shared/relay/relay_session.dart‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -627,7 +627,9 @@ class RelaySessionNotifier extends Notifier<SessionState> {
627627

628628
try {
629629
final auth = ref.read(hostedRelayAuthProvider);
630-
if (auth.protects(config)) socket.headers = await auth.headers(config);
630+
if (auth.protects(config)) {
631+
socket.headers = await auth.headers(config, fresh: true);
632+
}
631633
if (_disposed || generation != _connectionGeneration) return;
632634
await socket.connect();
633635
} on AccountFailure catch (error) {

‎mobile/lib/shared/verified_profiles/verified_profile_discovery_fetch.dart‎

Lines changed: 6 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,10 @@
1-
import 'dart:async';
2-
import 'dart:convert';
3-
41
import 'package:hooks_riverpod/hooks_riverpod.dart';
52
import 'package:http/http.dart' as http;
63

4+
import '../relay/nip11_document.dart';
75
import '../relay/relay.dart';
86
import 'verified_profile.dart';
97

10-
const _maxInfoBytes = 256 * 1024;
11-
const _discoveryTimeout = Duration(seconds: 10);
12-
138
/// Fetches and parses the community's NIP-11 document. Throws on any failure
149
/// or malformed response; a thrown error never changes the last known state.
1510
typedef VerifiedProfileDiscoveryFetch =
@@ -21,42 +16,14 @@ final verifiedProfileHttpClientProvider = Provider<http.Client>((ref) {
2116
return client;
2217
});
2318

24-
/// Reads the NIP-11 document at [uri] with a size cap. One wall-clock
25-
/// deadline covers headers and the whole body, so a relay trickling bytes
26-
/// cannot keep discovery in flight forever.
19+
/// Reads and parses the NIP-11 document at [uri]; see [fetchNip11Document].
2720
Future<VerifiedProfileDiscovery> fetchVerifiedProfileDiscovery(
2821
http.Client client,
2922
Uri uri, {
30-
Duration deadline = _discoveryTimeout,
31-
}) async {
32-
final abort = Completer<void>();
33-
final request = http.AbortableRequest('GET', uri, abortTrigger: abort.future)
34-
..headers['Accept'] = 'application/nostr+json';
35-
StreamIterator<List<int>>? body;
36-
Future<List<int>> read() async {
37-
final response = await client.send(request);
38-
final iterator = body = StreamIterator(response.stream);
39-
if (response.statusCode != 200) {
40-
throw http.ClientException('NIP-11 status ${response.statusCode}', uri);
41-
}
42-
final bytes = <int>[];
43-
while (await iterator.moveNext()) {
44-
if (bytes.length + iterator.current.length > _maxInfoBytes) {
45-
throw const FormatException('NIP-11 exceeds size limit');
46-
}
47-
bytes.addAll(iterator.current);
48-
}
49-
return bytes;
50-
}
51-
52-
try {
53-
final bytes = await read().timeout(deadline);
54-
return parseVerifiedProfileDiscovery(jsonDecode(utf8.decode(bytes)));
55-
} finally {
56-
if (!abort.isCompleted) abort.complete();
57-
unawaited(body?.cancel());
58-
}
59-
}
23+
Duration deadline = nip11Deadline,
24+
}) async => parseVerifiedProfileDiscovery(
25+
await fetchNip11Document(client, uri, deadline: deadline),
26+
);
6027

6128
final verifiedProfileDiscoveryFetchProvider =
6229
Provider<VerifiedProfileDiscoveryFetch>((ref) {

0 commit comments

Comments
 (0)