@@ -6,20 +6,36 @@ import 'package:web_socket_channel/web_socket_channel.dart';
66
77import '../../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+
1325class 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 }
0 commit comments