Files
openchamber-android-native/lib/api/relay_tunnel.dart
T
blumia 7b5bccf28f feat: English and Chinese, and selectable chat text
- settings → general → language picks system, Chinese or English; the
  choice is stored on the device and read before the first frame
- our Chinese strings are translated through tr()/trArgs() and AppText,
  with the English in lib/l10n/en_*.dart; a missing entry falls back to
  Chinese and a test checks that every literal in lib has one
- AppText rebuilds on a language change (it depends on the resolved
  locale), so const text and whole pages switch at once; the built-in
  date/time pickers and selection menu follow the same language
- server and user data (titles, messages, prompts, paths) is never
  translated
- the chat list sits in a SelectionArea: long-press selects message text
  and shows the copy/select-all menu
- bump to 0.5.2
2026-11-26 09:04:25 +08:00

635 lines
19 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// The OpenChamber private relay, client side: one outbound WebSocket to the
// relay, an end-to-end encrypted channel to the host (P-256 ECDH + HKDF +
// AES-256-GCM), and a small mux that carries the app's HTTP/SSE requests and
// WebSockets. The relay only forwards ciphertext; the host key from the
// pairing link is the trust anchor.
//
// Wire-compatible with packages/ui/src/lib/relay/ (protocol v1). Batching,
// downstream flow control and response gzip are not negotiated: the host's
// legacy path sends one plain frame per message and plain bodies.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import '../l10n.dart';
import 'relay_crypto.dart';
import 'transport.dart';
const _relayProtocolVersion = 1;
const _tunnelFrameHeaderBytes = 5;
const _tunnelFragmentFlag = 0x80;
const _maxPlaintextFrameBytes = 64 * 1024;
const _maxTunnelPayloadBytes = _maxPlaintextFrameBytes - _tunnelFrameHeaderBytes - 5;
const _connectTimeout = Duration(seconds: 20);
const _handshakeTimeout = Duration(seconds: 30);
const _keepAliveEvery = Duration(seconds: 30);
const _keepAliveDeadAfter = Duration(seconds: 70);
class RelayFrameType {
static const httpRequest = 1;
static const httpBody = 2;
static const httpResponse = 3;
static const streamEnd = 4;
static const streamAbort = 5;
static const wsOpen = 6;
static const wsOpened = 7;
static const wsText = 8;
static const wsBinary = 9;
static const wsClose = 10;
static const ping = 11;
static const pong = 12;
static const deliveryAck = 13;
}
class RelayTunnelException implements Exception {
final String message;
const RelayTunnelException(this.message);
@override
String toString() => message;
}
/// One request over the tunnel. [path] is relative to the server root, [query]
/// the encoded query string (without `?`). The reply's body streams.
class RelayTunnel {
final String relayUrl;
final String serverId;
final Map<String, dynamic> hostKey;
final String? grant;
final String appVersion;
final String platform;
final HttpClient _http = HttpClient()
..connectionTimeout = const Duration(seconds: 20);
_RelayChannel? _channel;
Future<_RelayChannel>? _connecting;
bool _closed = false;
int _failures = 0;
DateTime _retryAfter = DateTime.fromMillisecondsSinceEpoch(0);
RelayTunnel({
required this.relayUrl,
required this.serverId,
required this.hostKey,
this.grant,
this.appVersion = '0.4.4',
this.platform = 'android',
});
Future<TransportResponse> send(TransportRequest request) async {
final channel = await _ensureChannel();
final streamId = channel.nextStreamId();
final body = request.body;
final controller = StreamController<List<int>>();
final response = Completer<TransportResponse>();
var finished = false;
void cleanup() {
channel.streams.remove(streamId);
channel.dropFragments(streamId);
}
void finish({Object? error}) {
if (finished) return;
finished = true;
cleanup();
if (error != null) {
if (!response.isCompleted) {
response.completeError(error);
} else {
controller.addError(error);
controller.close();
}
}
}
void deliveredHead(int status, Map<String, String> headers) {
final noBody = status == 204 || status == 205 || status == 304;
if (noBody) {
finished = true;
cleanup();
controller.close();
}
response.complete(TransportResponse(
status,
headers,
controller.stream,
abort: () {
if (finished) return;
finished = true;
cleanup();
channel.sendJson(RelayFrameType.streamAbort, streamId, {'reason': 'aborted'});
controller.close();
},
));
}
channel.streams[streamId] = _TunnelStream(
onFrame: (type, payload) {
switch (type) {
case RelayFrameType.httpResponse:
if (finished || response.isCompleted) return;
final dynamic decoded;
try {
decoded = jsonDecode(utf8.decode(payload));
} catch (_) {
finish(error: RelayTunnelException(tr('响应头无效')));
return;
}
if (decoded is! Map) {
finish(error: RelayTunnelException(tr('响应头无效')));
return;
}
final status = (decoded['status'] as num?)?.toInt() ?? 0;
final rawHeaders = decoded['headers'];
final headers = <String, String>{};
if (rawHeaders is Map) {
for (final entry in rawHeaders.entries) {
if (entry.key is String && entry.value is String) {
headers[(entry.key as String).toLowerCase()] = entry.value as String;
}
}
}
deliveredHead(status, headers);
break;
case RelayFrameType.httpBody:
if (!finished) controller.add(Uint8List.fromList(payload));
break;
case RelayFrameType.streamEnd:
if (finished) return;
finished = true;
cleanup();
controller.close();
break;
case RelayFrameType.streamAbort:
var reason = tr('传输被中断');
try {
final decoded = jsonDecode(utf8.decode(payload));
if (decoded is Map && decoded['reason'] is String) {
reason = decoded['reason'] as String;
}
} catch (_) {}
finish(error: RelayTunnelException(reason));
break;
}
},
onFail: (error) => finish(error: error),
);
final query = request.rawQuery ??
Uri(queryParameters: request.query.isEmpty ? null : request.query).query;
channel.sendJson(RelayFrameType.httpRequest, streamId, {
'method': request.method,
'path': request.path,
'query': query,
'headers': request.headers,
'hasBody': body != null,
});
if (body != null) {
if (body.isEmpty) {
channel.send(RelayFrameType.httpBody, streamId, Uint8List(0));
} else {
for (var offset = 0; offset < body.length; offset += _maxTunnelPayloadBytes) {
final end = (offset + _maxTunnelPayloadBytes).clamp(0, body.length);
channel.send(RelayFrameType.httpBody, streamId,
Uint8List.fromList(body.sublist(offset, end)));
}
}
}
channel.send(RelayFrameType.streamEnd, streamId, Uint8List(0));
return response.future;
}
/// Opens a server WebSocket over the tunnel. [path] carries no query;
/// [rawQuery] is sent as-is. Outgoing frames are held until the host reports
/// the loopback socket open.
Future<TransportSocket> openWebSocket(
String path, {
String rawQuery = '',
Map<String, String> headers = const {},
}) async {
final channel = await _ensureChannel();
final streamId = channel.nextStreamId();
final socket = _RelaySocket(
channel: channel,
streamId: streamId,
path: path,
query: rawQuery,
);
channel.streams[streamId] = _TunnelStream(
onFrame: socket.onFrame,
onFail: socket.onFail,
);
channel.sendJson(RelayFrameType.wsOpen, streamId, {
'path': path,
'query': rawQuery,
});
return socket;
}
Future<_RelayChannel> _ensureChannel() async {
if (_closed) throw const RelayTunnelException('relay tunnel closed');
final current = _channel;
if (current != null && !current.dead) return current;
final connecting = _connecting;
if (connecting != null) return connecting;
final wait = _retryAfter.difference(DateTime.now());
if (wait > Duration.zero) await Future<void>.delayed(wait);
final future = _connect();
_connecting = future;
try {
final channel = await future;
_channel = channel;
_failures = 0;
return channel;
} catch (error) {
_failures += 1;
final delay = Duration(
milliseconds: (500 * (1 << (_failures.clamp(0, 4)))).clamp(500, 8000));
_retryAfter = DateTime.now().add(delay);
rethrow;
} finally {
_connecting = null;
}
}
Future<_RelayChannel> _connect() async {
final keyPair = newRelayKeyPair();
final nonce = randomBytes(16);
final hello = jsonEncode({
't': 'hello',
'v': _relayProtocolVersion,
'clientPubJwk': publicJwk(keyPair.publicKey),
'nonce': base64UrlEncodeBytes(nonce),
});
final uri = _relayUri();
final WebSocket ws;
try {
ws = await WebSocket.connect(uri.toString(), customClient: _http)
.timeout(_connectTimeout);
} catch (error) {
throw RelayTunnelException(trArgs('无法连接 Relay:{0}', [error]));
}
final channel = _RelayChannel(ws);
final ready = Completer<void>();
var finished = false;
Timer? helloTimer;
Timer? deadline;
StreamSubscription<dynamic>? subscription;
void closeWith(Object error) {
if (finished) return;
finished = true;
helloTimer?.cancel();
deadline?.cancel();
channel.dead = true;
channel.failAll(error);
subscription?.cancel();
try {
ws.close();
} catch (_) {}
if (!ready.isCompleted) ready.completeError(error);
_channel = null;
}
void onData(dynamic raw) {
if (finished) return;
if (raw is String) {
if (raw.contains('relay-retire')) {
// The relay asks the peer to close instead of closing its side.
var code = 1011;
try {
final decoded = jsonDecode(raw);
if (decoded is Map) {
final parsed = decoded['code'];
if (parsed is num) code = parsed.toInt();
}
} catch (_) {}
closeWith(RelayTunnelException('relay closed the tunnel ($code)'));
return;
}
if (!ready.isCompleted) {
dynamic decoded;
try {
decoded = jsonDecode(raw);
} catch (_) {
return;
}
if (decoded is Map && decoded['t'] == 'ready') {
try {
final keys = deriveSessionKeys(
keyPair.privateKey, importPublicJwk(hostKey), nonce);
channel.encryptor = RelayEncryptor(keys.clientToHost);
channel.decryptor = RelayDecryptor(keys.hostToClient);
helloTimer?.cancel();
deadline?.cancel();
ready.complete();
} catch (error) {
closeWith(RelayTunnelException(trArgs('密钥协商失败:{0}', [error])));
}
}
return;
}
// After the channel is up the host may repeat `ready` for a retried
// hello; anything else plaintext is a protocol violation.
if (raw.contains('"ready"')) return;
closeWith(RelayTunnelException(tr('握手后收到明文帧')));
return;
}
if (raw is! List<int>) return;
channel.lastReceived = DateTime.now();
if (!ready.isCompleted) return;
try {
final plaintext = channel.decryptor.decrypt(Uint8List.fromList(raw));
channel.handlePlaintext(plaintext);
} catch (error) {
closeWith(RelayTunnelException(trArgs('解密失败:{0}', [error])));
}
}
subscription = ws.listen(
onData,
onError: (Object error) => closeWith(RelayTunnelException(trArgs('Relay 连接出错:{0}', [error]))),
onDone: () {
if (!finished) {
closeWith(RelayTunnelException(trArgs(
'Relay 连接已关闭({0} {1})',
[ws.closeCode ?? '-', ws.closeReason ?? ''])));
}
},
cancelOnError: true,
);
channel.onClosed = () =>
closeWith(RelayTunnelException(tr('Relay 连接已关闭')));
void sendHello() {
if (finished) return;
try {
ws.add(hello);
} catch (_) {}
}
sendHello();
helloTimer = Timer.periodic(const Duration(seconds: 1), (_) => sendHello());
deadline = Timer(_handshakeTimeout, () {
closeWith(RelayTunnelException(tr('Relay 握手超时')));
});
await ready.future;
if (channel.dead) {
throw RelayTunnelException(trArgs(
'Relay 连接已关闭({0} {1})',
[ws.closeCode ?? '-', ws.closeReason ?? '']));
}
channel.startKeepAlive();
return channel;
}
Uri _relayUri() {
final base = Uri.parse(relayUrl);
final params = <String, String>{
...base.queryParameters,
'v': '$_relayProtocolVersion',
'role': 'client',
'serverId': serverId,
'appId': 'openchamber',
'appVersion': appVersion,
'platform': platform,
};
final relayGrant = grant;
if (relayGrant != null && relayGrant.isNotEmpty) {
params['grant'] = relayGrant;
}
return base.replace(queryParameters: params);
}
void close() {
if (_closed) return;
_closed = true;
final channel = _channel;
_channel = null;
if (channel != null) {
channel.dead = true;
channel.failAll(const RelayTunnelException('relay tunnel closed'));
channel.close();
}
_http.close(force: true);
}
}
class _TunnelStream {
final void Function(int type, Uint8List payload) onFrame;
final void Function(Object error) onFail;
_TunnelStream({required this.onFrame, required this.onFail});
}
class _RelayChannel {
final WebSocket ws;
late final RelayEncryptor encryptor;
late final RelayDecryptor decryptor;
final Map<int, _TunnelStream> streams = {};
final Map<String, BytesBuilder> _fragments = {};
Timer? _keepAlive;
DateTime lastReceived = DateTime.now();
int _nextStreamId = -1;
bool dead = false;
void Function()? onClosed;
_RelayChannel(this.ws);
int nextStreamId() {
_nextStreamId += 2;
return _nextStreamId;
}
void startKeepAlive() {
_keepAlive?.cancel();
_keepAlive = Timer.periodic(_keepAliveEvery, (_) {
if (dead) return;
if (DateTime.now().difference(lastReceived) > _keepAliveDeadAfter) {
dead = true;
_keepAlive?.cancel();
onClosed?.call();
return;
}
send(RelayFrameType.ping, 0, Uint8List(0));
});
}
void send(int type, int streamId, Uint8List payload, {bool more = false}) {
if (dead) return;
final frame = Uint8List(_tunnelFrameHeaderBytes + payload.length);
frame[0] = more ? type | _tunnelFragmentFlag : type;
frame[1] = (streamId >> 24) & 0xff;
frame[2] = (streamId >> 16) & 0xff;
frame[3] = (streamId >> 8) & 0xff;
frame[4] = streamId & 0xff;
frame.setAll(_tunnelFrameHeaderBytes, payload);
try {
ws.add(encryptor.encrypt(frame));
} catch (_) {
dead = true;
onClosed?.call();
}
}
void sendJson(int type, int streamId, Object value) =>
send(type, streamId, Uint8List.fromList(utf8.encode(jsonEncode(value))));
void sendFragmented(int type, int streamId, Uint8List payload) {
if (payload.isEmpty) {
send(type, streamId, Uint8List(0));
return;
}
for (var offset = 0; offset < payload.length; offset += _maxTunnelPayloadBytes) {
final end = (offset + _maxTunnelPayloadBytes).clamp(0, payload.length);
send(type, streamId, Uint8List.sublistView(payload, offset, end),
more: end < payload.length);
}
}
void dropFragments(int streamId) {
_fragments.removeWhere((key, _) => key.startsWith('$streamId:'));
}
void handlePlaintext(Uint8List plaintext) {
if (dead || plaintext.length < _tunnelFrameHeaderBytes) return;
final rawType = plaintext[0];
final more = (rawType & _tunnelFragmentFlag) != 0;
final type = rawType & ~_tunnelFragmentFlag;
final streamId = (plaintext[1] << 24) |
(plaintext[2] << 16) |
(plaintext[3] << 8) |
plaintext[4];
var payload = Uint8List.sublistView(plaintext, _tunnelFrameHeaderBytes);
lastReceived = DateTime.now();
if (type == RelayFrameType.ping) {
send(RelayFrameType.pong, streamId, Uint8List(0));
return;
}
if (type == RelayFrameType.pong) return;
if (type == RelayFrameType.deliveryAck) return;
if (type == RelayFrameType.wsText || type == RelayFrameType.wsBinary) {
if (more || _fragments.containsKey('$streamId:$type')) {
final key = '$streamId:$type';
final builder = _fragments.putIfAbsent(key, BytesBuilder.new);
builder.add(payload);
if (builder.length > 16 * 1024 * 1024) {
dead = true;
onClosed?.call();
return;
}
if (more) return;
payload = builder.takeBytes();
_fragments.remove(key);
}
} else if (more) {
return;
}
final stream = streams[streamId];
if (stream == null) return;
stream.onFrame(type, payload);
}
void failAll(Object error) {
final all = List.of(streams.values);
streams.clear();
for (final stream in all) {
try {
stream.onFail(error);
} catch (_) {}
}
}
void close() {
_keepAlive?.cancel();
try {
ws.close();
} catch (_) {}
}
}
class _RelaySocket implements TransportSocket {
final _RelayChannel channel;
final int streamId;
final String path;
final String query;
final StreamController<List<int>> _messages = StreamController<List<int>>();
final List<Uint8List> _pending = [];
bool _open = false;
bool _closed = false;
_RelaySocket({
required this.channel,
required this.streamId,
required this.path,
required this.query,
});
@override
Stream<List<int>> get messages => _messages.stream;
@override
void add(List<int> data) {
if (_closed) return;
final bytes = Uint8List.fromList(data);
if (!_open) {
_pending.add(bytes);
return;
}
channel.sendFragmented(RelayFrameType.wsBinary, streamId, bytes);
}
void onFrame(int type, Uint8List payload) {
switch (type) {
case RelayFrameType.wsOpened:
if (_open) return;
_open = true;
for (final frame in _pending) {
channel.sendFragmented(RelayFrameType.wsBinary, streamId, frame);
}
_pending.clear();
break;
case RelayFrameType.wsText:
if (!_closed) _messages.add(payload);
break;
case RelayFrameType.wsBinary:
if (!_closed) _messages.add(payload);
break;
case RelayFrameType.wsClose:
_finish();
break;
case RelayFrameType.streamAbort:
_finish(error: RelayTunnelException(tr('WebSocket 子流被中断')));
break;
}
}
void onFail(Object error) => _finish(error: error);
void _finish({Object? error}) {
if (_closed) return;
_closed = true;
channel.streams.remove(streamId);
channel.dropFragments(streamId);
if (error != null) {
_messages.addError(error);
}
_messages.close();
}
@override
Future<void> close([int code = 1000, String reason = '']) async {
if (_closed) return;
// Even before `wsOpened`: the host may be dialing the loopback socket
// already, and this frame tells it to abandon that sub-stream.
channel.sendJson(
RelayFrameType.wsClose, streamId, {'code': code, 'reason': reason});
_finish();
}
}