Skip to content

Commit a008194

Browse files
brownpub1shglkdhngx3hrnhf4gf8vhpqdrmeludctechdvpwd3988zzs7ncq2cmtxu
andauthored
fix(mobile): support open pairing relays (#1939)
Signed-off-by: npub1shglkdhngx3hrnhf4gf8vhpqdrmeludctechdvpwd3988zzs7ncq2cmtxu <85d1fb36f341a371cee9aa12765c2068f79ff1b85e7176b02e6c4a738850f4f0@sprout-oss.stage.blox.sqprod.co> Co-authored-by: npub1shglkdhngx3hrnhf4gf8vhpqdrmeludctechdvpwd3988zzs7ncq2cmtxu <85d1fb36f341a371cee9aa12765c2068f79ff1b85e7176b02e6c4a738850f4f0@sprout-oss.stage.blox.sqprod.co>
1 parent 158259d commit a008194

4 files changed

Lines changed: 424 additions & 39 deletions

File tree

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

Lines changed: 39 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -57,10 +57,34 @@ class PairingState {
5757
);
5858
}
5959

60+
typedef PairingSocketFactory =
61+
PairingSocket Function({
62+
required String wsUrl,
63+
required String ephemeralPrivkey,
64+
required void Function(List<dynamic> message) onMessage,
65+
required void Function(Object? error) onDisconnected,
66+
});
67+
6068
class PairingNotifier extends Notifier<PairingState> {
69+
final PairingSocketFactory _socketFactory;
6170
PairingSocket? _socket;
6271
Timer? _sessionTimeout;
6372

73+
PairingNotifier({PairingSocketFactory? socketFactory})
74+
: _socketFactory = socketFactory ?? _createPairingSocket;
75+
76+
static PairingSocket _createPairingSocket({
77+
required String wsUrl,
78+
required String ephemeralPrivkey,
79+
required void Function(List<dynamic> message) onMessage,
80+
required void Function(Object? error) onDisconnected,
81+
}) => PairingSocket(
82+
wsUrl: wsUrl,
83+
ephemeralPrivkey: ephemeralPrivkey,
84+
onMessage: onMessage,
85+
onDisconnected: onDisconnected,
86+
);
87+
6488
@override
6589
PairingState build() => const PairingState();
6690

@@ -171,20 +195,21 @@ class PairingNotifier extends Notifier<PairingState> {
171195
);
172196

173197
// 4. Connect to relay with ephemeral keys.
174-
_socket = PairingSocket(
198+
final socket = _socketFactory(
175199
wsUrl: relayWsUrl,
176200
ephemeralPrivkey: _ephemeralPrivkey!,
177201
onMessage: _handleRelayMessage,
178202
onDisconnected: _handleDisconnected,
179203
);
180-
await _socket!.connect();
204+
_socket = socket;
205+
await socket.connect();
181206

182-
if (!_socket!.isConnected) {
183-
throw Exception('Failed to connect to pairing relay');
207+
if (!socket.isConnected) {
208+
throw StateError('Pairing socket did not reach the connected state');
184209
}
185210

186211
// 5. Subscribe for kind:24134 events tagged to our ephemeral pubkey.
187-
_socket!.subscribe('pair', 24134, _ephemeralPubkey!);
212+
socket.subscribe('pair', 24134, _ephemeralPubkey!);
188213

189214
// 6. Wait briefly for EOSE, then send offer.
190215
// (In practice, we send the offer immediately — the relay will buffer it.)
@@ -244,11 +269,18 @@ class PairingNotifier extends Notifier<PairingState> {
244269
message.contains('Connection refused') ||
245270
message.contains('Network is unreachable') ||
246271
message.contains('No route to host') ||
247-
message.contains('Failed to connect') ||
248-
message.contains('Null check operator used on a null value')) {
272+
message.contains('Failed to connect')) {
249273
return 'Could not reach the pairing relay. Check your internet '
250274
'connection and VPN, then try again.';
251275
}
276+
if (error is PairingAuthException) {
277+
return 'The pairing relay rejected authentication. Try creating a new '
278+
'pairing code.';
279+
}
280+
if (error is StateError ||
281+
message.contains('Null check operator used on a null value')) {
282+
return 'Pairing stopped because of an internal error. Please try again.';
283+
}
252284
if (message.contains('HandshakeException') ||
253285
message.contains('CERTIFICATE_VERIFY_FAILED')) {
254286
return 'Secure connection failed. Check your network settings '

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

Lines changed: 63 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -6,20 +6,36 @@ import 'package:web_socket_channel/web_socket_channel.dart';
66

77
import '../../shared/relay/nostr_models.dart';
88

9+
const _desktopPairingAuthChallengeGrace = Duration(seconds: 3);
10+
const _pairingAuthOkTimeout = Duration(seconds: 8);
11+
912
/// Ephemeral WebSocket connection for NIP-AB pairing.
1013
///
1114
/// Uses ephemeral keys for NIP-42 auth (not the stored user keys).
1215
/// Single-use — disposed after the pairing session completes.
16+
class PairingAuthException implements Exception {
17+
final String message;
18+
19+
const PairingAuthException(this.message);
20+
21+
@override
22+
String toString() => 'PairingAuthException: $message';
23+
}
24+
1325
class PairingSocket {
1426
final String _wsUrl;
1527
final String _ephemeralPrivkey;
1628
final void Function(List<dynamic> message) _onMessage;
1729
final void Function(Object? error) _onDisconnected;
30+
final Duration _authChallengeTimeout;
31+
final Duration _authResponseTimeout;
32+
final WebSocketChannel Function(Uri uri) _channelFactory;
1833

1934
WebSocketChannel? _channel;
2035
StreamSubscription<dynamic>? _subscription;
2136
Completer<void>? _authCompleter;
22-
Timer? _authTimeout;
37+
Timer? _authChallengeTimer;
38+
Timer? _authResponseTimer;
2339
String? _pendingAuthEventId;
2440
bool _connected = false;
2541

@@ -28,54 +44,52 @@ class PairingSocket {
2844
required String ephemeralPrivkey,
2945
required void Function(List<dynamic> message) onMessage,
3046
required void Function(Object? error) onDisconnected,
47+
Duration authChallengeTimeout = _desktopPairingAuthChallengeGrace,
48+
Duration authResponseTimeout = _pairingAuthOkTimeout,
49+
WebSocketChannel Function(Uri uri) channelFactory =
50+
WebSocketChannel.connect,
3151
}) : _wsUrl = wsUrl,
3252
_ephemeralPrivkey = ephemeralPrivkey,
3353
_onMessage = onMessage,
34-
_onDisconnected = onDisconnected;
54+
_onDisconnected = onDisconnected,
55+
_authChallengeTimeout = authChallengeTimeout,
56+
_authResponseTimeout = authResponseTimeout,
57+
_channelFactory = channelFactory;
3558

3659
bool get isConnected => _connected;
3760

38-
/// Connect and authenticate via NIP-42.
61+
/// Connect and answer a NIP-42 challenge when the relay requires one.
3962
Future<void> connect() async {
40-
try {
41-
_channel = WebSocketChannel.connect(Uri.parse(_wsUrl));
42-
await _channel!.ready;
43-
} catch (e) {
44-
_onDisconnected(e);
45-
return;
46-
}
63+
_channel = _channelFactory(Uri.parse(_wsUrl));
64+
await _channel!.ready;
4765

4866
_authCompleter = Completer<void>();
4967

5068
_subscription = _channel!.stream.listen(
5169
_handleRawMessage,
52-
onError: (Object error) {
53-
_failAuth(error);
54-
_onDisconnected(error);
55-
},
56-
onDone: () {
57-
_failAuth(null);
58-
_onDisconnected(null);
59-
},
70+
onError: _failAuth,
71+
onDone: () => _failAuth(null),
6072
);
6173

62-
// Wait for auth with 8s timeout.
63-
_authTimeout = Timer(const Duration(seconds: 8), () {
64-
if (_authCompleter != null && !_authCompleter!.isCompleted) {
65-
_authCompleter!.completeError(
66-
TimeoutException('NIP-42 auth timed out'),
67-
);
74+
// Dedicated pairing relays may be open and send no NIP-42 challenge.
75+
_authChallengeTimer = Timer(_authChallengeTimeout, () {
76+
if (_pendingAuthEventId == null &&
77+
_authCompleter != null &&
78+
!_authCompleter!.isCompleted) {
79+
_authCompleter!.complete();
6880
}
6981
});
7082

7183
try {
7284
await _authCompleter!.future;
73-
_authTimeout?.cancel();
7485
_connected = true;
75-
} catch (e) {
76-
_authTimeout?.cancel();
86+
} catch (error) {
7787
await disconnect();
78-
_onDisconnected(e);
88+
_onDisconnected(error);
89+
rethrow;
90+
} finally {
91+
_authChallengeTimer?.cancel();
92+
_authResponseTimer?.cancel();
7993
}
8094
}
8195

@@ -105,7 +119,8 @@ class PairingSocket {
105119
_connected = false;
106120
_subscription?.cancel();
107121
_subscription = null;
108-
_authTimeout?.cancel();
122+
_authChallengeTimer?.cancel();
123+
_authResponseTimer?.cancel();
109124
final channel = _channel;
110125
_channel = null;
111126
if (channel != null) {
@@ -118,12 +133,19 @@ class PairingSocket {
118133
_subscription?.cancel();
119134
_channel?.sink.close();
120135
_channel = null;
121-
_authTimeout?.cancel();
136+
_authChallengeTimer?.cancel();
137+
_authResponseTimer?.cancel();
122138
}
123139

124140
void _failAuth(Object? error) {
141+
final authError = error ?? Exception('Connection closed');
125142
if (_authCompleter != null && !_authCompleter!.isCompleted) {
126-
_authCompleter!.completeError(error ?? Exception('Connection closed'));
143+
_authCompleter!.completeError(authError);
144+
return;
145+
}
146+
if (_connected) {
147+
unawaited(disconnect());
148+
_onDisconnected(authError);
127149
}
128150
}
129151

@@ -155,6 +177,14 @@ class PairingSocket {
155177
if (data.length < 2) return;
156178
final challenge = data[1] as String;
157179

180+
_authChallengeTimer?.cancel();
181+
_authResponseTimer?.cancel();
182+
_authResponseTimer = Timer(_authResponseTimeout, () {
183+
_failAuth(
184+
const PairingAuthException('Relay did not confirm authentication'),
185+
);
186+
});
187+
158188
try {
159189
// Build NIP-42 auth event (kind:22242) with ephemeral keys.
160190
final tags = <List<String>>[
@@ -184,6 +214,7 @@ class PairingSocket {
184214

185215
if (_pendingAuthEventId != null && eventId == _pendingAuthEventId) {
186216
_pendingAuthEventId = null;
217+
_authResponseTimer?.cancel();
187218
if (accepted) {
188219
if (_authCompleter != null && !_authCompleter!.isCompleted) {
189220
_authCompleter!.complete();
@@ -192,7 +223,7 @@ class PairingSocket {
192223
final message = data.length > 3
193224
? data[3] as String
194225
: 'Auth rejected by relay';
195-
_failAuth(Exception(message));
226+
_failAuth(PairingAuthException(message));
196227
}
197228
return;
198229
}

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

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import 'dart:convert';
33
import 'package:flutter_test/flutter_test.dart';
44
import 'package:hooks_riverpod/hooks_riverpod.dart';
55
import 'package:buzz/features/pairing/pairing_provider.dart';
6+
import 'package:buzz/features/pairing/pairing_socket.dart';
67
import 'package:buzz/shared/auth/auth.dart';
78

89
/// Tests for [PairingNotifier]'s legacy `buzz://` payload parsing and
@@ -43,6 +44,36 @@ void main() {
4344
expect(state.errorMessage, isNull);
4445
});
4546

47+
test(
48+
'disconnect during connect does not null-dereference the socket',
49+
() async {
50+
final notifier = PairingNotifier(
51+
socketFactory:
52+
({
53+
required wsUrl,
54+
required ephemeralPrivkey,
55+
required onMessage,
56+
required void Function(Object? error) onDisconnected,
57+
}) => _DisconnectingSocket(disconnectCallback: onDisconnected),
58+
);
59+
container = ProviderContainer(
60+
overrides: [pairingProvider.overrideWith(() => notifier)],
61+
);
62+
const code =
63+
'nostrpair://62287897da61e3fa294b4570575f7db8bea147d6631150f2e4656714c645fb1e'
64+
'?secret=abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789'
65+
'&relay=wss%3A%2F%2Fpairing.buzz.xyz&v=1';
66+
67+
await container.read(pairingProvider.notifier).pair(code);
68+
69+
expect(container.read(pairingProvider).status, PairingStatus.error);
70+
expect(
71+
container.read(pairingProvider).errorMessage,
72+
contains('internal error'),
73+
);
74+
},
75+
);
76+
4677
test('payload missing nsec errors before contacting relay', () async {
4778
container = createContainer();
4879

@@ -192,3 +223,21 @@ class FakeAuthNotifier extends AsyncNotifier<AuthState>
192223
);
193224
}
194225
}
226+
227+
class _DisconnectingSocket extends PairingSocket {
228+
final void Function(Object? error) disconnectCallback;
229+
230+
_DisconnectingSocket({required this.disconnectCallback})
231+
: super(
232+
wsUrl: 'ws://unused',
233+
ephemeralPrivkey:
234+
'09b3065e3570a3a4054660dccd66e12774a99a904fdb0ca02dbc6c3136249506',
235+
onMessage: (_) {},
236+
onDisconnected: (_) {},
237+
);
238+
239+
@override
240+
Future<void> connect() async {
241+
disconnectCallback(Exception('Connection closed'));
242+
}
243+
}

0 commit comments

Comments
 (0)