Skip to content

Commit 83d0bd3

Browse files
spenceralclaude
andauthored
fix(mobile): stop QR pairing to organization relays from hanging (#9001)
## Problem Pairing a phone to an organization relay by QR (for example Block's `buzz.block.builderlab.xyz`) never finishes. After the codes match and the phone confirms, it sits on the loading surface. About 2 minutes later it returns to the welcome screen with "Lost connection to pairing relay." The desktop stays on "Finishing pairing on your phone…". This reproduces every time on Buzz 0.27.0, iOS 27.2, with desktop 0.7.7 (internal tracking: AIDA-2420). There are two causes: 1. **Validation can never pass for organization relays.** After the payload arrives, `_validateCredentials` opens a plain `RelaySocket` without a `Nostr-Federated-Identity` assertion. Organization relays refuse that upgrade with HTTP 401 until organization sign-in, which a freshly pairing phone hasn't done. 2. **The failure hangs instead of erroring.** `RelaySocket.connect()` catches the failed `ready` but keeps `_channel`. The validator's `finally` then awaits `disconnect()` → `sink.close()` on a channel that never opened, and that never completes. The phone waits until the pairing relay's 120 s connection cap closes the socket, and `_handleDisconnected` reports that as a lost connection. Standalone repro with `web_socket_channel` 3.0.3 against the real relay: ``` ready failed: ... was not upgraded to websocket, HTTP status code: 401 sink.close() DID NOT COMPLETE within 30s (hang) ``` ## Change - `RelaySocket.connect()` drops a channel whose upgrade failed. - `disconnect()` waits at most `RelaySocket.closeTimeout` (2 s). An upgrade that is still pending (connect timeout 10 s) can outlive pairing's 8 s validation deadline, and its close never completes either. - `PairingNotifier` skips the pre-sign-in check for `OrganizationEnvironment.protects` relays. Admission is left to the saved community's session and the existing organization sign-in banner, which matches how the hosted branch already defers admission. The predicate is injectable (`organizationRelay`) for tests. Other relays are still validated before saving. Trade-off: an identity that the organization relay would reject is now saved, and that rejection only surfaces after organization sign-in. The hosted path has the same property. ## Related issue No existing GitHub issue covers this failure; searched open issues and PRs for pairing relay, lost connection and `_validateCredentials`. Closest: - #8043 / #8060 cover the same `_validateCredentials` path from the other side: a failed connect currently returns normally. They're complementary. With #8060 merged, organization relays would fail pairing with an explicit 401 instead of hanging, and this PR keeps them out of that pre-check. Whichever merges second needs a small rebase in `_validateCredentials`. - #3181 is a different failure in the same flow. ## Testing - New `relay_socket_liveness_test` cases check that `disconnect()` completes in three situations: after a refused (401) upgrade, after a timed-out handshake, and while the upgrade is still pending. - New `pairing_provider_test` case: a malformed key is rejected locally before anything is saved, an organization relay is saved without the relay check, and a non-organization relay is still validated and rejected. - Each new test fails with its fix removed. The failures were "disconnect() hung on a channel that never opened", "disconnect() hung on a pending upgrade", and `validated` being true. - `just mobile-check` and `just mobile-test` pass: 4229 passed, 40 skipped. - **Simulator run (iOS 27.0 simulator, iPhone 18 Pro, Block organization dart-defines) against desktop 0.7.7 on `buzz.block.builderlab.xyz`:** pairing completed (desktop reported the phone paired; identity transferred; community saved) instead of hanging until the pairing relay closed. The app then showed the organization sign-in banner and opened browser sign-in for block.builderlab.xyz, as expected. Okta in the simulator requires FastPass, so the final relay connection after sign-in was not exercised there. - Human device testing is still pending. ## Follow-up - Test on a real phone with an organization build. The simulator couldn't complete Okta FastPass, so the relay connection after organization sign-in still needs checking. --------- Signed-off-by: Spencer Lewis <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 1bef1da commit 83d0bd3

4 files changed

Lines changed: 155 additions & 4 deletions

File tree

‎mobile/lib/features/pairing/pairing_provider.dart‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import '../../shared/auth/auth.dart';
1010
import '../../shared/hosted/hosted_flow_provider.dart';
1111
import '../../shared/hosted/account_identity_store.dart';
1212
import '../../shared/hosted/hosted_environment.dart';
13+
import '../../shared/hosted/organization_environment.dart';
1314
import '../../shared/community/paired_community_landing.dart';
1415
import '../../shared/crypto/ecdh.dart';
1516
import '../../shared/crypto/nip44.dart';
@@ -43,6 +44,7 @@ class PairingNotifier extends Notifier<PairingState> {
4344
final PairingSocketFactory _socketFactory;
4445
final PairingCredentialValidator? _credentialValidator;
4546
final RelaySocketFactory _validationSocketFactory;
47+
final bool Function(Uri relay) _organizationRelay;
4648
RelaySocket? _validationSocket;
4749
PairingSocket? _socket;
4850
Timer? _sessionTimeout;
@@ -56,9 +58,12 @@ class PairingNotifier extends Notifier<PairingState> {
5658
PairingSocketFactory? socketFactory,
5759
PairingCredentialValidator? credentialValidator,
5860
RelaySocketFactory validationSocketFactory = RelaySocket.new,
61+
bool Function(Uri relay) organizationRelay =
62+
OrganizationEnvironment.protects,
5963
}) : _socketFactory = socketFactory ?? _createPairingSocket,
6064
_credentialValidator = credentialValidator,
61-
_validationSocketFactory = validationSocketFactory;
65+
_validationSocketFactory = validationSocketFactory,
66+
_organizationRelay = organizationRelay;
6267

6368
static PairingSocket _createPairingSocket({
6469
required String wsUrl,
@@ -926,7 +931,18 @@ class PairingNotifier extends Notifier<PairingState> {
926931
if (nsec == null || nsec.isEmpty) {
927932
throw const FormatException('Pairing payload missing nsec');
928933
}
934+
// A malformed key could never connect, and the organization branch below
935+
// saves without a relay check, so reject it before anything is stored.
936+
try {
937+
AccountIdentityStore.publicKeyForNsec(nsec);
938+
} on AccountIdentityFailure {
939+
throw const FormatException('Pairing payload has an invalid nsec');
940+
}
929941
final uri = Uri.parse(relayUrl);
942+
// Organization relays refuse the upgrade until organization sign-in
943+
// supplies an assertion, which the saved community's session then offers.
944+
// A check here can only fail, so admission is left to that session.
945+
if (_organizationRelay(uri)) return;
930946
final scheme = uri.scheme == 'https' ? 'wss' : 'ws';
931947
final wsUrl = uri.replace(scheme: scheme).toString();
932948

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

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,9 @@ class RelaySocket {
9494
);
9595
await _channel!.ready;
9696
} catch (e) {
97+
// A channel that never opened never completes sink.close(), so a later
98+
// disconnect() must not await it.
99+
_channel = null;
97100
_state = SocketState.disconnected;
98101
_onDisconnected(e);
99102
return;
@@ -150,13 +153,17 @@ class RelaySocket {
150153
_channel?.sink.add(jsonEncode(payload));
151154
}
152155

153-
/// Gracefully close the connection.
156+
/// Upper bound on a graceful close. A channel whose upgrade is still pending
157+
/// never completes sink.close(), and callers await disconnect() in cleanup.
158+
static const closeTimeout = Duration(seconds: 2);
159+
160+
/// Gracefully close the connection, waiting at most [closeTimeout].
154161
Future<void> disconnect() async {
155162
_resetConnection();
156163
final channel = _channel;
157164
_channel = null;
158165
if (channel != null) {
159-
await channel.sink.close();
166+
await channel.sink.close().timeout(closeTimeout, onTimeout: () {});
160167
}
161168
}
162169

‎mobile/test/features/pairing/pairing_provider_test.dart‎

Lines changed: 62 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ void main() {
5757
utf8.encode(
5858
jsonEncode({
5959
'relayUrl': 'https://relay.example',
60-
'nsec': 'pending-key',
60+
'nsec': nostr.Keys.generate().nsec,
6161
}),
6262
),
6363
);
@@ -110,6 +110,67 @@ void main() {
110110
},
111111
);
112112

113+
test(
114+
'organization relays are admitted by their session, not pre-validated',
115+
() async {
116+
// An organization relay refuses this unauthenticated check until
117+
// organization sign-in, so running it would always fail pairing.
118+
final auth = FakeAuthNotifier();
119+
var validated = false;
120+
final notifier = PairingNotifier(
121+
organizationRelay: (relay) => relay.host == 'org.example',
122+
validationSocketFactory:
123+
({
124+
required wsUrl,
125+
required nsec,
126+
required onMessage,
127+
required onConnected,
128+
required onDisconnected,
129+
}) {
130+
validated = true;
131+
return _ValidationOutcomeSocket(() => false);
132+
},
133+
);
134+
container = ProviderContainer(
135+
overrides: [
136+
pairingProvider.overrideWith(() => notifier),
137+
authProvider.overrideWith(() => auth),
138+
],
139+
);
140+
String input(String relayUrl, {String? nsec}) => base64Url.encode(
141+
utf8.encode(
142+
jsonEncode({
143+
'relayUrl': relayUrl,
144+
'nsec': nsec ?? nostr.Keys.generate().nsec,
145+
}),
146+
),
147+
);
148+
149+
// Skipping the relay check must not admit a key that can never sign.
150+
await container
151+
.read(pairingProvider.notifier)
152+
.pair(input('https://org.example', nsec: 'nsec1notakey'));
153+
expect(container.read(pairingProvider).status, PairingStatus.error);
154+
expect(auth.lastCommunity, isNull);
155+
156+
await container
157+
.read(pairingProvider.notifier)
158+
.pair(input('https://org.example'));
159+
expect(validated, isFalse);
160+
expect(container.read(pairingProvider).status, PairingStatus.success);
161+
expect(auth.lastCommunity?.relayUrl, 'https://org.example');
162+
163+
// Other relays still have to accept the identity before it is saved.
164+
auth.lastCommunity = null;
165+
await container
166+
.read(pairingProvider.notifier)
167+
.pair(input('https://relay.example'));
168+
expect(validated, isTrue);
169+
expect(container.read(pairingProvider).status, PairingStatus.error);
170+
expect(auth.lastCommunity, isNull);
171+
},
172+
);
173+
113174
test('starts in idle state', () {
114175
container = createContainer();
115176
final state = container.read(pairingProvider);

‎mobile/test/shared/relay/relay_socket_liveness_test.dart‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,73 @@ void main() {
115115
});
116116
}
117117

118+
// Pairing validation disconnects in a finally block after a failed connect;
119+
// an unbounded close there stranded pairing until the pairing relay expired.
120+
for (final refusal in [401, null]) {
121+
test(
122+
'disconnect completes after '
123+
'${refusal == null ? 'a timed-out handshake' : 'a refused upgrade ($refusal)'}',
124+
() async {
125+
HttpServer? refusing;
126+
ServerSocket? stalled;
127+
if (refusal == null) {
128+
stalled = (await _stalledHandshakeServer()).$1;
129+
} else {
130+
refusing = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
131+
refusing.listen((request) async {
132+
request.response.statusCode = refusal;
133+
await request.response.close();
134+
});
135+
}
136+
final url = 'ws://127.0.0.1:${(refusing?.port ?? stalled!.port)}';
137+
Object? reported;
138+
final socket = RelaySocket(
139+
wsUrl: url,
140+
nsec: null,
141+
onMessage: (_) {},
142+
onConnected: () {},
143+
onDisconnected: (error) => reported = error,
144+
);
145+
146+
await socket.connect();
147+
expect(socket.state, SocketState.disconnected);
148+
if (refusal != null) expect(relayUpgradeRefused(reported), isTrue);
149+
await socket.disconnect().timeout(
150+
testConnectTimeout * 10,
151+
onTimeout: () =>
152+
fail('disconnect() hung on a channel that never opened'),
153+
);
154+
155+
await refusing?.close(force: true);
156+
await stalled?.close();
157+
},
158+
);
159+
}
160+
161+
test('disconnect is bounded while the upgrade is still pending', () async {
162+
// Pairing's 8s validation deadline can fire before the 10s connect timeout.
163+
RelaySocket.debugConnectTimeout = const Duration(seconds: 30);
164+
final (server, _) = await _stalledHandshakeServer();
165+
final socket = RelaySocket(
166+
wsUrl: 'ws://127.0.0.1:${server.port}',
167+
nsec: null,
168+
onMessage: (_) {},
169+
onConnected: () {},
170+
onDisconnected: (_) {},
171+
);
172+
unawaited(socket.connect());
173+
await Future<void>.delayed(const Duration(milliseconds: 100));
174+
175+
await socket.disconnect().timeout(
176+
RelaySocket.closeTimeout * 2,
177+
onTimeout: () => fail('disconnect() hung on a pending upgrade'),
178+
);
179+
expect(socket.state, SocketState.disconnected);
180+
181+
socket.dispose();
182+
await server.close();
183+
});
184+
118185
test('detects a peer that stops answering pings', () async {
119186
final server = await _silentAfterHandshakeServer();
120187

0 commit comments

Comments
 (0)