mirror of
https://github.com/block/buzz.git
synced 2026-11-28 04:01:45 +00:00
Makes relay errors that nothing catches readable in diagnostic reports. Today an unhandled relay rejection or timeout arrives with its text removed and a stack that stops at the async error handler, so a report can't say which call failed or why. ## Changes - **Typed call and reason:** relay errors now carry the call (`publish`, `query`, `history`, `subscribe`) and a fixed reason class taken from the relay's reason prefix (`invalid`, `rate-limited`, `restricted`, `auth-required`, `blocked`, `duplicate`, `pow`, `unsupported`, `error`, `timeout`, or `other`). Types: - `RelayEventRejectedException` implements the new `RelayCallError`; - new `RelayTimeoutException` extends `TimeoutException`, and `RelayAckTimeoutError` now extends it; - new `RelayClosedException` replaces the plain `Exception` for a closed history or live subscription, with the same `toString`. - new `RelayQueryException` (a `RelayException` that is also a `RelayCallError`) for a non-2xx `/query` answer, with its reason from the status alone; - a one-shot signed event the relay refuses now fails with a typed rejection, with the same text. Existing `TimeoutException` checks and message helpers behave as before. - **Report tags:** before the filter runs, a report whose error is a `RelayCallError` gets `relay.call` and `relay.reason` tags. The relay's own text is never sent. These reports are also grouped by call and reason on top of the default grouping, so a rate limit and an invalid request from the same code become separate issues. - **Call-site stack:** pending publishes, one-shot signed events, and history and live subscriptions keep the stack where they were created, and errors completed later from timers or socket callbacks use it. A report's stack now reaches the calling code. - **Spec:** one bullet on the tags, the grouping and the stack. ## Validation New tests: - a table of reason prefixes to classes; - error types, fields and the existing message helpers; - relay session cases: a rejected publish's call, reason and calling stack, the timeout types, and closed subscriptions; - reports: tags, the grouping key, no relay text, and non-relay errors untouched. - production refusals through a serialized report: `/query` statuses, snapshot `/query` versus discovery, and one-shot rejections and timeouts with the caller's stack. Full-app run on an iOS simulator (signed in, healthy relay): cold start and session restore, channel list, opening channels and DMs, history back to each channel's start, send, react, edit, thread reply, search, channel details and Add Members, Settings > Send test report, and background then foreground followed by a send and a delete. All passed with no new errors in the device log, and no doubled error names in any logged text. Error paths (timeouts, closed connections, relay rejections) weren't triggered on the healthy relay; the unit tests above cover them. --------- Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
321 lines
9.0 KiB
Dart
321 lines
9.0 KiB
Dart
import 'dart:io';
|
|
import 'dart:async';
|
|
import 'dart:convert';
|
|
|
|
import 'package:flutter/foundation.dart';
|
|
import 'package:nostr/nostr.dart' as nostr;
|
|
import 'package:web_socket_channel/io.dart';
|
|
import 'package:web_socket_channel/web_socket_channel.dart';
|
|
|
|
import '../diagnostics/diagnostic_reporter.dart';
|
|
import 'nostr_models.dart';
|
|
import 'relay_call_error.dart';
|
|
import 'relay_websocket.dart';
|
|
import 'package:buzz/shared/crypto/event_signing.dart';
|
|
|
|
/// Low-level websocket connection with NIP-42 authentication.
|
|
///
|
|
/// Handles the raw websocket lifecycle: connect, authenticate via NIP-42
|
|
/// challenge/response, send/receive JSON frames, and disconnect.
|
|
///
|
|
/// Does NOT handle reconnection — that is [RelaySessionNotifier]'s job.
|
|
enum SocketState { disconnected, connecting, authenticating, connected }
|
|
|
|
class RelayAuthRejectedException implements Exception {
|
|
final String message;
|
|
|
|
const RelayAuthRejectedException(this.message);
|
|
|
|
@override
|
|
String toString() => 'Relay authentication rejected: $message';
|
|
}
|
|
|
|
/// The relay answered an EVENT with OK false, so it wasn't stored.
|
|
class RelayEventRejectedException implements RelayCallError {
|
|
final String message;
|
|
|
|
const RelayEventRejectedException(this.message);
|
|
|
|
@override
|
|
RelayCall get call => RelayCall.publish;
|
|
|
|
@override
|
|
RelayReason get reason => RelayReason.fromMessage(message);
|
|
|
|
@override
|
|
String toString() => 'Exception: $message';
|
|
}
|
|
|
|
Exception classifyRelayAuthFailure(String message) {
|
|
if (message.startsWith('error:')) return Exception(message);
|
|
return RelayAuthRejectedException(message);
|
|
}
|
|
|
|
class RelaySocket {
|
|
/// Interval for sending a ping and awaiting its pong before disconnecting.
|
|
static const pingInterval = Duration(seconds: 30);
|
|
|
|
@visibleForTesting
|
|
static Duration debugPingInterval = pingInterval;
|
|
|
|
@visibleForTesting
|
|
static Duration debugConnectTimeout = relayWebSocketConnectTimeout;
|
|
|
|
final String _wsUrl;
|
|
final String? _nsec;
|
|
final void Function(List<dynamic> message) _onMessage;
|
|
final void Function() _onConnected;
|
|
final void Function(Object? error) _onDisconnected;
|
|
|
|
WebSocketChannel? _channel;
|
|
StreamSubscription<dynamic>? _subscription;
|
|
SocketState _state = SocketState.disconnected;
|
|
Completer<void>? _authCompleter;
|
|
Timer? _authTimeout;
|
|
String? _pendingAuthEventId;
|
|
int? _closeCode;
|
|
|
|
SocketState get state => _state;
|
|
|
|
/// The WebSocket close code the relay sent, once it has closed the
|
|
/// connection; null if the connection failed without one.
|
|
int? get closeCode => _closeCode;
|
|
|
|
/// Scoped assertion supplied by the connection owner before connecting.
|
|
Map<String, String> headers = const {};
|
|
|
|
/// Where frames the relay sent that this client can't parse are reported.
|
|
DiagnosticReporter diagnostics = const NoopDiagnosticReporter();
|
|
|
|
RelaySocket({
|
|
required String wsUrl,
|
|
required String? nsec,
|
|
required void Function(List<dynamic> message) onMessage,
|
|
required void Function() onConnected,
|
|
required void Function(Object? error) onDisconnected,
|
|
}) : _wsUrl = wsUrl,
|
|
_nsec = nsec,
|
|
_onMessage = onMessage,
|
|
_onConnected = onConnected,
|
|
_onDisconnected = onDisconnected;
|
|
|
|
/// Connect to the relay and complete NIP-42 authentication.
|
|
Future<void> connect() async {
|
|
if (_state != SocketState.disconnected) return;
|
|
_state = SocketState.connecting;
|
|
|
|
try {
|
|
_channel = IOWebSocketChannel(
|
|
openRelayWebSocket(
|
|
Uri.parse(_wsUrl),
|
|
headers: headers,
|
|
pingInterval: debugPingInterval,
|
|
connectTimeout: debugConnectTimeout,
|
|
),
|
|
);
|
|
await _channel!.ready;
|
|
} catch (e) {
|
|
// A channel that never opened never completes sink.close(), so a later
|
|
// disconnect() must not await it.
|
|
_channel = null;
|
|
_state = SocketState.disconnected;
|
|
_onDisconnected(e);
|
|
return;
|
|
}
|
|
|
|
// The channel may have been disposed while we were awaiting ready
|
|
// (e.g. provider rebuild triggered dispose() concurrently).
|
|
if (_channel == null) {
|
|
_state = SocketState.disconnected;
|
|
return;
|
|
}
|
|
|
|
_state = SocketState.authenticating;
|
|
_authCompleter = Completer<void>();
|
|
|
|
_subscription = _channel!.stream.listen(
|
|
_handleRawMessage,
|
|
onError: (Object error) {
|
|
_failAuth(error);
|
|
_resetConnection();
|
|
_onDisconnected(error);
|
|
},
|
|
onDone: () {
|
|
_closeCode = _channel?.closeCode;
|
|
_failAuth(null);
|
|
_resetConnection();
|
|
_onDisconnected(null);
|
|
},
|
|
);
|
|
|
|
// Wait for auth to complete (or timeout).
|
|
_authTimeout = Timer(const Duration(seconds: 8), () {
|
|
if (_authCompleter != null && !_authCompleter!.isCompleted) {
|
|
_authCompleter!.completeError(
|
|
TimeoutException('NIP-42 auth timed out after 8s'),
|
|
);
|
|
}
|
|
});
|
|
|
|
try {
|
|
await _authCompleter!.future;
|
|
_authTimeout?.cancel();
|
|
_state = SocketState.connected;
|
|
_onConnected();
|
|
} catch (e) {
|
|
_authTimeout?.cancel();
|
|
await disconnect();
|
|
_onDisconnected(e);
|
|
}
|
|
}
|
|
|
|
/// Send a raw JSON array over the websocket.
|
|
void send(List<dynamic> payload) {
|
|
_channel?.sink.add(jsonEncode(payload));
|
|
}
|
|
|
|
/// Upper bound on a graceful close. A channel whose upgrade is still pending
|
|
/// never completes sink.close(), and callers await disconnect() in cleanup.
|
|
static const closeTimeout = Duration(seconds: 2);
|
|
|
|
/// Gracefully close the connection, waiting at most [closeTimeout].
|
|
Future<void> disconnect() async {
|
|
_resetConnection();
|
|
final channel = _channel;
|
|
_channel = null;
|
|
if (channel != null) {
|
|
await channel.sink.close().timeout(closeTimeout, onTimeout: () {});
|
|
}
|
|
}
|
|
|
|
void dispose() {
|
|
_resetConnection();
|
|
_channel?.sink.close();
|
|
_channel = null;
|
|
}
|
|
|
|
void _resetConnection() {
|
|
_state = SocketState.disconnected;
|
|
_subscription?.cancel();
|
|
_subscription = null;
|
|
_authTimeout?.cancel();
|
|
_authTimeout = null;
|
|
_pendingAuthEventId = null;
|
|
}
|
|
|
|
void _failAuth(Object? error) {
|
|
if (_authCompleter != null && !_authCompleter!.isCompleted) {
|
|
_authCompleter!.completeError(error ?? Exception('Connection closed'));
|
|
}
|
|
}
|
|
|
|
void _handleRawMessage(dynamic raw) {
|
|
final String text;
|
|
if (raw is String) {
|
|
text = raw;
|
|
} else {
|
|
return; // Binary frames are not part of the Nostr protocol.
|
|
}
|
|
|
|
final List<dynamic> data;
|
|
try {
|
|
data = jsonDecode(text) as List<dynamic>;
|
|
} catch (error, stackTrace) {
|
|
diagnostics.reportError(
|
|
error,
|
|
stackTrace,
|
|
operation: DiagnosticOperation.relayFrame,
|
|
);
|
|
return;
|
|
}
|
|
|
|
if (data.isEmpty) return;
|
|
final type = data[0] as String;
|
|
|
|
switch (type) {
|
|
case 'AUTH':
|
|
_handleAuthChallenge(data);
|
|
case 'OK':
|
|
_handleOk(data);
|
|
default:
|
|
// Pass EVENT, EOSE, NOTICE, etc. upstream.
|
|
_onMessage(data);
|
|
}
|
|
}
|
|
|
|
/// Handle the relay's AUTH challenge: sign a kind:22242 event and respond.
|
|
void _handleAuthChallenge(List<dynamic> data) {
|
|
if (data.length < 2) return;
|
|
final challenge = data[1] as String;
|
|
|
|
if (_nsec == null) {
|
|
_failAuth(Exception('No nsec available for NIP-42 auth'));
|
|
return;
|
|
}
|
|
|
|
try {
|
|
// Decode bech32 nsec to hex private key.
|
|
final privkeyHex = nostr.Nip19.decode(payload: _nsec).data;
|
|
if (privkeyHex.isEmpty) {
|
|
_failAuth(Exception('Invalid nsec'));
|
|
return;
|
|
}
|
|
|
|
// Build the auth tags.
|
|
final tags = <List<String>>[
|
|
['relay', _wsUrl],
|
|
['challenge', challenge],
|
|
];
|
|
|
|
// Create and sign the kind:22242 AUTH event.
|
|
final event = signNostrEvent(
|
|
kind: EventKind.auth,
|
|
content: '',
|
|
tags: tags,
|
|
secretKey: privkeyHex,
|
|
);
|
|
|
|
_pendingAuthEventId = event.id;
|
|
send(['AUTH', event.toMap()]);
|
|
} catch (e) {
|
|
_failAuth(e);
|
|
}
|
|
}
|
|
|
|
@visibleForTesting
|
|
void debugHandleOkForTest(List<dynamic> data) => _onMessage(data);
|
|
|
|
/// Handle OK frames. During auth, complete the auth flow.
|
|
void _handleOk(List<dynamic> data) {
|
|
if (data.length < 3) return;
|
|
final eventId = data[1] as String;
|
|
final accepted = data[2] as bool;
|
|
|
|
// Check if this OK is for our pending AUTH event.
|
|
if (_pendingAuthEventId != null && eventId == _pendingAuthEventId) {
|
|
_pendingAuthEventId = null;
|
|
if (accepted) {
|
|
if (_authCompleter != null && !_authCompleter!.isCompleted) {
|
|
_authCompleter!.complete();
|
|
}
|
|
} else {
|
|
final message = data.length > 3
|
|
? data[3] as String
|
|
: 'Auth rejected by relay';
|
|
_failAuth(classifyRelayAuthFailure(message));
|
|
}
|
|
return;
|
|
}
|
|
|
|
// Pass non-auth OK frames upstream for pending event tracking.
|
|
_onMessage(data);
|
|
}
|
|
}
|
|
|
|
/// HTTP upgrade failures retain their status through WebSocketChannel.
|
|
bool relayUpgradeRefused(Object? error) {
|
|
if (error is WebSocketChannelException) error = error.inner;
|
|
return error is WebSocketException &&
|
|
(error.httpStatusCode == 401 || error.httpStatusCode == 403);
|
|
}
|