feat: connect through the OpenChamber private relay
A server can now be added by pasting an openchamber://connect pairing link. The one-time secret is redeemed over the first reachable candidate (direct addresses first, then the relay), and the device token is stored with the connection, so later launches reconnect without the link. The relay candidate carries the relay WebSocket URL, the host's routing id and its P-256 public key. The new transport opens one encrypted tunnel to the relay: P-256 ECDH + HKDF-SHA256 derive one AES-256-GCM key per direction; frames carry a version, a 12-byte IV and the GCM tag; a small mux carries HTTP, SSE and WebSocket sub-streams with fragmentation and ping/pong. Every request and the terminal socket ride it; WebSocket upgrades first mint the short-lived oc_url_token over the tunnel, since upgrades cannot send headers. Only the host's legacy path is negotiated (no batching, downstream flow control or body gzip). Pairing while connected switches servers like picking one in the list, which exposed and fixes a ChatScreen crash when app.chat is cleared during the switch. 0.4.4 (404).
This commit is contained in:
1 parent
a7bc380ac0
commit
902f1e18bb
20 files changed
+1918
-75
No files matched your search
+33
-1
@@ -6,6 +6,7 @@ import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import '../version.dart';
|
||||
import 'models.dart';
|
||||
import 'terminal.dart';
|
||||
import 'transport.dart';
|
||||
@@ -24,7 +25,15 @@ class Client {
|
||||
/// Every request and the event stream go through here; today a direct
|
||||
/// connection, later one that can also be a relay tunnel.
|
||||
final Transport transport;
|
||||
String? token;
|
||||
String? _token;
|
||||
|
||||
/// The bearer this client authenticates with. A relay transport is told too,
|
||||
/// because it must mint URL-scoped tokens for WebSocket upgrades.
|
||||
String? get token => _token;
|
||||
set token(String? value) {
|
||||
_token = value;
|
||||
transport.setBearerToken(value);
|
||||
}
|
||||
|
||||
Client(
|
||||
this.base, {
|
||||
@@ -38,6 +47,29 @@ class Client {
|
||||
|
||||
String get baseUrl => base.toString();
|
||||
|
||||
/// Redeems a pairing link's one-time secret over whichever transport this
|
||||
/// client uses, and returns the device token.
|
||||
Future<({String token, Map<String, dynamic> response})> redeemPairing({
|
||||
required String pairingId,
|
||||
required String secret,
|
||||
required String installId,
|
||||
String clientLabel = 'OpenChamber Native',
|
||||
String clientKind = 'mobile',
|
||||
String? deviceName,
|
||||
}) async {
|
||||
final r = await _json('POST', '/api/client-auth/pairing/redeem', body: {
|
||||
'pairingId': pairingId,
|
||||
'secret': secret,
|
||||
'clientLabel': clientLabel,
|
||||
'clientKind': clientKind,
|
||||
'deviceName': deviceName ?? clientLabel,
|
||||
'devicePlatform': 'android',
|
||||
'dedupeKey': installId,
|
||||
'appVersion': appVersion,
|
||||
});
|
||||
return (token: r['clientToken'] as String? ?? '', response: r);
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>> sessionStatus() async {
|
||||
final r = await _json('GET', '/auth/session');
|
||||
return r;
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
// The pairing link the desktop shows as a QR code: `openchamber://connect?v=2`
|
||||
// with a base64url JSON payload. It carries the one-time secret and the ways
|
||||
// to reach the server — direct URLs and, when enabled, the private relay with
|
||||
// the host's encryption key (the E2EE trust anchor).
|
||||
import 'dart:convert';
|
||||
|
||||
const _maxPayloadLength = 16384;
|
||||
|
||||
class PairingCandidate {
|
||||
final String type; // lan | tunnel | relay
|
||||
final String url; // direct candidates
|
||||
final String relayUrl; // relay candidates
|
||||
final String serverId;
|
||||
final Map<String, dynamic>? hostKey;
|
||||
final String? grant;
|
||||
final int priority;
|
||||
|
||||
const PairingCandidate.direct({
|
||||
required this.type,
|
||||
required this.url,
|
||||
this.priority = 100,
|
||||
}) : relayUrl = '',
|
||||
serverId = '',
|
||||
hostKey = null,
|
||||
grant = null;
|
||||
|
||||
const PairingCandidate.relay({
|
||||
required String this.relayUrl,
|
||||
required this.serverId,
|
||||
required Map<String, dynamic> this.hostKey,
|
||||
this.grant,
|
||||
this.priority = 100,
|
||||
}) : type = 'relay',
|
||||
url = '';
|
||||
|
||||
bool get isRelay => type == 'relay';
|
||||
}
|
||||
|
||||
class PairingPayload {
|
||||
final String pairingId;
|
||||
final String secret;
|
||||
final String? label;
|
||||
final String? fingerprint;
|
||||
final DateTime? expiresAt;
|
||||
final List<PairingCandidate> candidates;
|
||||
|
||||
const PairingPayload({
|
||||
required this.pairingId,
|
||||
required this.secret,
|
||||
this.label,
|
||||
this.fingerprint,
|
||||
this.expiresAt,
|
||||
required this.candidates,
|
||||
});
|
||||
}
|
||||
|
||||
/// Parses a link or payload. Returns null when it is not a valid, unexpired
|
||||
/// pairing link. Direct candidates come before relay, each by priority, so a
|
||||
/// reachable LAN address is tried before the tunnel.
|
||||
PairingPayload? parsePairingLink(String raw) {
|
||||
final text = raw.trim();
|
||||
if (text.isEmpty || text.length > _maxPayloadLength) return null;
|
||||
|
||||
String? encoded;
|
||||
final start = text.indexOf('?');
|
||||
if (start >= 0) {
|
||||
final head = text.substring(0, start);
|
||||
if (RegExp(r'^openchamber://connect/?$', caseSensitive: false)
|
||||
.hasMatch(head)) {
|
||||
for (final part in text.substring(start + 1).split('&')) {
|
||||
final eq = part.indexOf('=');
|
||||
if (eq < 0) continue;
|
||||
final key = part.substring(0, eq);
|
||||
final value = part.substring(eq + 1);
|
||||
if (key == 'p') encoded = value;
|
||||
if (key == 'v' && value != '2') return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
encoded ??= text;
|
||||
if (encoded.length > _maxPayloadLength) return null;
|
||||
final Object? decoded;
|
||||
try {
|
||||
decoded = jsonDecode(utf8.decode(_base64UrlDecode(encoded)));
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
if (decoded is! Map) return null;
|
||||
final pairingId = decoded['pairingId'];
|
||||
final secret = decoded['secret'];
|
||||
if (decoded['v'] != 2 || pairingId is! String || secret is! String) {
|
||||
return null;
|
||||
}
|
||||
if (pairingId.trim().isEmpty || secret.trim().isEmpty) return null;
|
||||
|
||||
DateTime? expiresAt;
|
||||
final rawExpiry = decoded['expiresAt'];
|
||||
if (rawExpiry is String && rawExpiry.isNotEmpty) {
|
||||
expiresAt = DateTime.tryParse(rawExpiry);
|
||||
if (expiresAt != null && !expiresAt.isAfter(DateTime.now())) return null;
|
||||
}
|
||||
|
||||
final rawCandidates = decoded['candidates'];
|
||||
final candidates = <PairingCandidate>[];
|
||||
if (rawCandidates is List) {
|
||||
for (final raw in rawCandidates) {
|
||||
final candidate = _candidate(raw);
|
||||
if (candidate != null) candidates.add(candidate);
|
||||
}
|
||||
}
|
||||
if (candidates.isEmpty) return null;
|
||||
candidates.sort((a, b) {
|
||||
if (a.isRelay != b.isRelay) return a.isRelay ? 1 : -1;
|
||||
return a.priority.compareTo(b.priority);
|
||||
});
|
||||
final label = decoded['label'];
|
||||
final fingerprint = decoded['fingerprint'];
|
||||
return PairingPayload(
|
||||
pairingId: pairingId.trim(),
|
||||
secret: secret.trim(),
|
||||
label: label is String && label.trim().isNotEmpty ? label.trim() : null,
|
||||
fingerprint: fingerprint is String && fingerprint.trim().isNotEmpty
|
||||
? fingerprint.trim()
|
||||
: null,
|
||||
expiresAt: expiresAt,
|
||||
candidates: candidates,
|
||||
);
|
||||
}
|
||||
|
||||
PairingCandidate? _candidate(Object? raw) {
|
||||
if (raw is! Map) return null;
|
||||
final priority = raw['priority'] is num
|
||||
? (raw['priority'] as num).toInt()
|
||||
: 100;
|
||||
final type = raw['type'];
|
||||
if (type == 'lan' || type == 'tunnel') {
|
||||
final url = _httpUrl(raw['url']);
|
||||
if (url == null) return null;
|
||||
return PairingCandidate.direct(type: type as String, url: url, priority: priority);
|
||||
}
|
||||
if (type == 'relay') {
|
||||
final relayUrl = _wsUrl(raw['relayUrl']);
|
||||
final serverId = raw['serverId'];
|
||||
final key = _ecPublicJwk(raw['hostEncPubJwk']);
|
||||
if (relayUrl == null ||
|
||||
serverId is! String ||
|
||||
serverId.trim().isEmpty ||
|
||||
key == null) {
|
||||
return null;
|
||||
}
|
||||
final grant = raw['grant'];
|
||||
return PairingCandidate.relay(
|
||||
relayUrl: relayUrl,
|
||||
serverId: serverId.trim(),
|
||||
hostKey: key,
|
||||
grant: grant is String && grant.trim().isNotEmpty ? grant.trim() : null,
|
||||
priority: priority,
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
String? _httpUrl(Object? raw) {
|
||||
if (raw is! String) return null;
|
||||
final uri = Uri.tryParse(raw.trim());
|
||||
if (uri == null || (uri.scheme != 'http' && uri.scheme != 'https')) {
|
||||
return null;
|
||||
}
|
||||
if (uri.host.isEmpty) return null;
|
||||
return uri.removeFragment().toString().replaceAll(RegExp(r'/+$'), '');
|
||||
}
|
||||
|
||||
String? _wsUrl(Object? raw) {
|
||||
if (raw is! String) return null;
|
||||
final uri = Uri.tryParse(raw.trim());
|
||||
if (uri == null || (uri.scheme != 'ws' && uri.scheme != 'wss')) return null;
|
||||
if (uri.host.isEmpty) return null;
|
||||
return uri.removeFragment().toString();
|
||||
}
|
||||
|
||||
Map<String, dynamic>? _ecPublicJwk(Object? raw) {
|
||||
if (raw is! Map) return null;
|
||||
if (raw['kty'] != 'EC' || raw['crv'] != 'P-256') return null;
|
||||
final x = raw['x'];
|
||||
final y = raw['y'];
|
||||
if (x is! String || y is! String || x.isEmpty || y.isEmpty) return null;
|
||||
return {'kty': 'EC', 'crv': 'P-256', 'x': x, 'y': y};
|
||||
}
|
||||
|
||||
List<int> _base64UrlDecode(String value) {
|
||||
final padded = value.padRight((value.length + 3) ~/ 4 * 4, '=');
|
||||
return base64Url.decode(padded);
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
// E2EE for the OpenChamber private relay (Layer 2). The host holds a
|
||||
// long-lived P-256 key; its public JWK reaches us in the pairing link and is
|
||||
// the trust anchor. An ephemeral P-256 key and a 16-byte nonce per connection
|
||||
// derive two AES-256-GCM keys, one per direction; frames carry a version, a
|
||||
// 12-byte IV (4-byte random prefix + 8-byte counter) and the GCM tag.
|
||||
//
|
||||
// The wire format is the first-party one (packages/ui/src/lib/relay/crypto.ts),
|
||||
// so this must stay byte-compatible.
|
||||
import 'dart:convert';
|
||||
import 'dart:math';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:pointycastle/export.dart';
|
||||
|
||||
const relayHkdfInfo = 'openchamber-relay-v1';
|
||||
const encryptedFrameVersion = 1;
|
||||
const _ivPrefixBytes = 4;
|
||||
const _ivCounterBytes = 8;
|
||||
const _ivBytes = _ivPrefixBytes + _ivCounterBytes;
|
||||
const _tagBytes = 16;
|
||||
const _frameHeaderBytes = 1 + _ivBytes;
|
||||
const _nonceBytes = 16;
|
||||
const _sessionKeyBytes = 32;
|
||||
const _maxPlaintextBytes = 64 * 1024;
|
||||
|
||||
class RelayCryptoError implements Exception {
|
||||
final String message;
|
||||
const RelayCryptoError(this.message);
|
||||
@override
|
||||
String toString() => message;
|
||||
}
|
||||
|
||||
ECDomainParameters get _p256 => ECCurve_prime256v1();
|
||||
|
||||
class RelayKeyPair {
|
||||
final ECPrivateKey privateKey;
|
||||
final ECPublicKey publicKey;
|
||||
RelayKeyPair(this.privateKey, this.publicKey);
|
||||
}
|
||||
|
||||
final Random _secureRandom = Random.secure();
|
||||
Uint8List randomBytes(int length) =>
|
||||
Uint8List.fromList(List<int>.generate(length, (_) => _secureRandom.nextInt(256)));
|
||||
|
||||
RelayKeyPair newRelayKeyPair() {
|
||||
final random = FortunaRandom()
|
||||
..seed(KeyParameter(randomBytes(32)));
|
||||
final generator = ECKeyGenerator()
|
||||
..init(ParametersWithRandom(
|
||||
ECKeyGeneratorParameters(_p256), random));
|
||||
final pair = generator.generateKeyPair();
|
||||
return RelayKeyPair(pair.privateKey, pair.publicKey);
|
||||
}
|
||||
|
||||
/// The four public members only, as the protocol's JWK.
|
||||
Map<String, String> publicJwk(ECPublicKey key) {
|
||||
final point = key.Q;
|
||||
if (point == null || point.isInfinity) {
|
||||
throw const RelayCryptoError('invalid public key');
|
||||
}
|
||||
return {
|
||||
'kty': 'EC',
|
||||
'crv': 'P-256',
|
||||
'x': _base64Url(_bigIntBytes(point.x!.toBigInteger()!, 32)),
|
||||
'y': _base64Url(_bigIntBytes(point.y!.toBigInteger()!, 32)),
|
||||
};
|
||||
}
|
||||
|
||||
ECPublicKey importPublicJwk(Map<String, dynamic> jwk) {
|
||||
if (jwk['kty'] != 'EC' || jwk['crv'] != 'P-256') {
|
||||
throw const RelayCryptoError('invalid ECDH public key JWK');
|
||||
}
|
||||
final x = jwk['x'];
|
||||
final y = jwk['y'];
|
||||
if (x is! String || y is! String) {
|
||||
throw const RelayCryptoError('invalid ECDH public key JWK');
|
||||
}
|
||||
try {
|
||||
final point = _p256.curve.createPoint(
|
||||
_bytesBigInt(_base64UrlDecode(x)),
|
||||
_bytesBigInt(_base64UrlDecode(y)),
|
||||
);
|
||||
return ECPublicKey(point, _p256);
|
||||
} catch (_) {
|
||||
throw const RelayCryptoError('invalid ECDH public key JWK');
|
||||
}
|
||||
}
|
||||
|
||||
String jwkFingerprint(Map<String, dynamic> jwk) =>
|
||||
jsonEncode({'crv': jwk['crv'], 'kty': jwk['kty'], 'x': jwk['x'], 'y': jwk['y']});
|
||||
|
||||
/// The two 32-byte AES keys. The nonce is the handshake salt; the info string
|
||||
/// is fixed, so the host derives the same pair.
|
||||
({Uint8List clientToHost, Uint8List hostToClient}) deriveSessionKeys(
|
||||
ECPrivateKey ownPrivate, ECPublicKey peer, Uint8List nonce) {
|
||||
if (nonce.length != _nonceBytes) {
|
||||
throw const RelayCryptoError('invalid handshake nonce length');
|
||||
}
|
||||
final agreement = ECDHBasicAgreement()..init(ownPrivate);
|
||||
final shared = _bigIntBytes(agreement.calculateAgreement(peer), 32);
|
||||
final hkdf = HKDFKeyDerivator(SHA256Digest())
|
||||
..init(HkdfParameters(
|
||||
shared,
|
||||
_sessionKeyBytes * 2,
|
||||
nonce,
|
||||
Uint8List.fromList(utf8.encode(relayHkdfInfo)),
|
||||
));
|
||||
final material = hkdf.process(Uint8List(0));
|
||||
return (
|
||||
clientToHost: Uint8List.sublistView(material, 0, _sessionKeyBytes),
|
||||
hostToClient: Uint8List.sublistView(material, _sessionKeyBytes),
|
||||
);
|
||||
}
|
||||
|
||||
class RelayEncryptor {
|
||||
final Uint8List _key;
|
||||
final Uint8List _prefix;
|
||||
int _counter = 0;
|
||||
|
||||
RelayEncryptor(this._key) : _prefix = randomBytes(_ivPrefixBytes);
|
||||
|
||||
Uint8List encrypt(Uint8List plaintext) {
|
||||
if (plaintext.length > _maxPlaintextBytes) {
|
||||
throw const RelayCryptoError('plaintext frame exceeds maximum size');
|
||||
}
|
||||
_counter += 1;
|
||||
final iv = Uint8List(_ivBytes)..setAll(0, _prefix);
|
||||
var counter = _counter;
|
||||
for (var i = _ivCounterBytes - 1; i >= 0; i--) {
|
||||
iv[_ivPrefixBytes + i] = counter & 0xff;
|
||||
counter >>= 8;
|
||||
}
|
||||
final cipher = GCMBlockCipher(AESEngine())
|
||||
..init(true, AEADParameters(KeyParameter(_key), _tagBytes * 8, iv, Uint8List(0)));
|
||||
final ciphertext = cipher.process(plaintext);
|
||||
final frame = Uint8List(_frameHeaderBytes + ciphertext.length)
|
||||
..[0] = encryptedFrameVersion
|
||||
..setAll(1, iv)
|
||||
..setAll(_frameHeaderBytes, ciphertext);
|
||||
return frame;
|
||||
}
|
||||
}
|
||||
|
||||
class RelayDecryptor {
|
||||
final Uint8List _key;
|
||||
int _lastCounter = 0;
|
||||
|
||||
RelayDecryptor(this._key);
|
||||
|
||||
Uint8List decrypt(Uint8List frame) {
|
||||
if (frame.length < _frameHeaderBytes + _tagBytes) {
|
||||
throw const RelayCryptoError('encrypted frame too short');
|
||||
}
|
||||
if (frame[0] != encryptedFrameVersion) {
|
||||
throw const RelayCryptoError('unsupported encrypted frame version');
|
||||
}
|
||||
final iv = Uint8List.sublistView(frame, 1, _frameHeaderBytes);
|
||||
var counter = 0;
|
||||
for (var i = 0; i < _ivCounterBytes; i++) {
|
||||
counter = (counter << 8) | iv[_ivPrefixBytes + i];
|
||||
}
|
||||
if (counter <= _lastCounter) {
|
||||
throw const RelayCryptoError('frame counter regression');
|
||||
}
|
||||
try {
|
||||
final cipher = GCMBlockCipher(AESEngine())
|
||||
..init(false,
|
||||
AEADParameters(KeyParameter(_key), _tagBytes * 8, iv, Uint8List(0)));
|
||||
final plaintext =
|
||||
cipher.process(Uint8List.sublistView(frame, _frameHeaderBytes));
|
||||
_lastCounter = counter;
|
||||
return plaintext;
|
||||
} catch (_) {
|
||||
throw const RelayCryptoError('frame decryption failed');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Uint8List _bigIntBytes(BigInt value, int length) {
|
||||
final out = Uint8List(length);
|
||||
var v = value;
|
||||
for (var i = length - 1; i >= 0; i--) {
|
||||
out[i] = (v & BigInt.from(0xff)).toInt();
|
||||
v >>= 8;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
BigInt _bytesBigInt(Uint8List bytes) {
|
||||
var value = BigInt.zero;
|
||||
for (final b in bytes) {
|
||||
value = (value << 8) | BigInt.from(b);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
String _base64Url(Uint8List bytes) =>
|
||||
base64Url.encode(bytes).replaceAll('=', '');
|
||||
|
||||
Uint8List _base64UrlDecode(String value) {
|
||||
if (!RegExp(r'^[A-Za-z0-9_-]*$').hasMatch(value)) {
|
||||
throw const RelayCryptoError('invalid base64url input');
|
||||
}
|
||||
final padded = value.padRight((value.length + 3) ~/ 4 * 4, '=');
|
||||
return base64Url.decode(padded);
|
||||
}
|
||||
|
||||
String base64UrlEncodeBytes(Uint8List bytes) => _base64Url(bytes);
|
||||
Uint8List base64UrlDecodeBytes(String value) => _base64UrlDecode(value);
|
||||
@@ -0,0 +1,110 @@
|
||||
// The server as reached through the private relay: every request and socket
|
||||
// rides the E2EE tunnel started from the pairing link's relay candidate.
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import '../version.dart';
|
||||
import 'relay_tunnel.dart';
|
||||
import 'transport.dart';
|
||||
|
||||
class RelayTransport implements Transport {
|
||||
final RelayTunnel _tunnel;
|
||||
String? _bearer;
|
||||
String? _urlToken;
|
||||
DateTime _urlTokenExpiresAt = DateTime.fromMillisecondsSinceEpoch(0);
|
||||
Future<String>? _minting;
|
||||
|
||||
RelayTransport({
|
||||
required String relayUrl,
|
||||
required String serverId,
|
||||
required Map<String, dynamic> hostKey,
|
||||
String? grant,
|
||||
String version = appVersion,
|
||||
}) : _tunnel = RelayTunnel(
|
||||
relayUrl: relayUrl,
|
||||
serverId: serverId,
|
||||
hostKey: hostKey,
|
||||
grant: grant,
|
||||
appVersion: version,
|
||||
);
|
||||
|
||||
@override
|
||||
Future<TransportResponse> send(TransportRequest request) =>
|
||||
_tunnel.send(request);
|
||||
|
||||
@override
|
||||
Future<TransportSocket> webSocket(String path,
|
||||
{String? rawQuery, Map<String, String> headers = const {}}) async {
|
||||
final token = await _mintUrlToken();
|
||||
final query = [
|
||||
if (rawQuery != null && rawQuery.isNotEmpty) rawQuery,
|
||||
if (token.isNotEmpty) 'oc_url_token=${Uri.encodeQueryComponent(token)}',
|
||||
].join('&');
|
||||
return _tunnel.openWebSocket(path, rawQuery: query, headers: headers);
|
||||
}
|
||||
|
||||
@override
|
||||
void setBearerToken(String? token) {
|
||||
if (_bearer != token) {
|
||||
_bearer = token;
|
||||
_urlToken = null;
|
||||
_urlTokenExpiresAt = DateTime.fromMillisecondsSinceEpoch(0);
|
||||
}
|
||||
}
|
||||
|
||||
/// WebSocket upgrades cannot carry headers, so the host expects a short-lived
|
||||
/// URL-scoped token minted over the same tunnel with the bearer.
|
||||
Future<String> _mintUrlToken() async {
|
||||
final bearer = _bearer;
|
||||
if (bearer == null || bearer.isEmpty) return '';
|
||||
if (_urlToken != null && _urlToken!.isNotEmpty &&
|
||||
DateTime.now().isBefore(_urlTokenExpiresAt)) {
|
||||
return _urlToken!;
|
||||
}
|
||||
final inFlight = _minting;
|
||||
if (inFlight != null) return inFlight;
|
||||
final future = _mint(bearer);
|
||||
_minting = future;
|
||||
try {
|
||||
return await future;
|
||||
} finally {
|
||||
_minting = null;
|
||||
}
|
||||
}
|
||||
|
||||
Future<String> _mint(String bearer) async {
|
||||
final response = await _tunnel.send(TransportRequest(
|
||||
method: 'POST',
|
||||
path: '/auth/url-token',
|
||||
headers: {'authorization': 'Bearer $bearer', 'accept': 'application/json'},
|
||||
));
|
||||
final bytes = await response.body
|
||||
.fold<List<int>>(<int>[], (all, chunk) => all..addAll(chunk));
|
||||
if (response.status < 200 || response.status >= 300) {
|
||||
throw RelayTunnelException('无法获取 WebSocket 令牌(${response.status})');
|
||||
}
|
||||
try {
|
||||
final decoded = jsonDecode(utf8.decode(bytes, allowMalformed: true));
|
||||
if (decoded is! Map) return '';
|
||||
final token = decoded['token'];
|
||||
if (token is! String) return '';
|
||||
final expiresIn = decoded['expiresIn'];
|
||||
final expiresAt = decoded['expiresAt'];
|
||||
final lifetime = expiresIn is num
|
||||
? Duration(seconds: expiresIn.toInt())
|
||||
: expiresAt is num && expiresAt > 0
|
||||
? Duration(milliseconds: expiresAt.toInt())
|
||||
: const Duration(minutes: 4);
|
||||
_urlToken = token.trim();
|
||||
_urlTokenExpiresAt = DateTime.now()
|
||||
.add(lifetime)
|
||||
.subtract(const Duration(seconds: 20));
|
||||
return _urlToken!;
|
||||
} catch (_) {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void close() => _tunnel.close();
|
||||
}
|
||||
@@ -0,0 +1,631 @@
|
||||
// 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 '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: const RelayTunnelException('响应头无效'));
|
||||
return;
|
||||
}
|
||||
if (decoded is! Map) {
|
||||
finish(error: const RelayTunnelException('响应头无效'));
|
||||
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 = '传输被中断';
|
||||
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('无法连接 Relay:$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('密钥协商失败:$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(const RelayTunnelException('握手后收到明文帧'));
|
||||
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('解密失败:$error'));
|
||||
}
|
||||
}
|
||||
|
||||
subscription = ws.listen(
|
||||
onData,
|
||||
onError: (Object error) => closeWith(RelayTunnelException('Relay 连接出错:$error')),
|
||||
onDone: () {
|
||||
if (!finished) {
|
||||
closeWith(RelayTunnelException(
|
||||
'Relay 连接已关闭(${ws.closeCode ?? '-'} ${ws.closeReason ?? ''})'));
|
||||
}
|
||||
},
|
||||
cancelOnError: true,
|
||||
);
|
||||
channel.onClosed = () =>
|
||||
closeWith(const RelayTunnelException('Relay 连接已关闭'));
|
||||
|
||||
void sendHello() {
|
||||
if (finished) return;
|
||||
try {
|
||||
ws.add(hello);
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
sendHello();
|
||||
helloTimer = Timer.periodic(const Duration(seconds: 1), (_) => sendHello());
|
||||
deadline = Timer(_handshakeTimeout, () {
|
||||
closeWith(const RelayTunnelException('Relay 握手超时'));
|
||||
});
|
||||
|
||||
await ready.future;
|
||||
if (channel.dead) {
|
||||
throw RelayTunnelException(
|
||||
'Relay 连接已关闭(${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: const RelayTunnelException('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();
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,6 @@
|
||||
// tag, then JSON). A socket can attach to several terminals; we attach to one.
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'transport.dart';
|
||||
|
||||
@@ -112,7 +111,7 @@ class TerminalSocket {
|
||||
final void Function(TerminalEvent event) onEvent;
|
||||
final void Function(TerminalLinkState state, {String? detail}) onState;
|
||||
|
||||
WebSocket? _socket;
|
||||
TransportSocket? _socket;
|
||||
Timer? _keepAlive;
|
||||
Timer? _reconnect;
|
||||
final StringBuffer _pending = StringBuffer();
|
||||
@@ -144,7 +143,7 @@ class TerminalSocket {
|
||||
}
|
||||
_socket = socket;
|
||||
_failures = 0;
|
||||
socket.listen(
|
||||
socket.messages.listen(
|
||||
_handle,
|
||||
onError: (_) => _drop(generation),
|
||||
onDone: () => _drop(generation),
|
||||
|
||||
+40
-4
@@ -42,6 +42,14 @@ class TransportResponse {
|
||||
const TransportResponse(this.status, this.headers, this.body, {this.abort});
|
||||
}
|
||||
|
||||
/// A binary socket: a direct WebSocket, or one sub-stream of the relay tunnel.
|
||||
/// The terminal speaks binary control frames, so text frames are not surfaced.
|
||||
abstract class TransportSocket {
|
||||
Stream<List<int>> get messages;
|
||||
void add(List<int> data);
|
||||
Future<void> close([int code = 1000, String reason = '']);
|
||||
}
|
||||
|
||||
/// The one seam every request goes through.
|
||||
abstract class Transport {
|
||||
/// Sends [request], completing when the reply head arrives.
|
||||
@@ -49,9 +57,14 @@ abstract class Transport {
|
||||
|
||||
/// Opens a WebSocket on [path] (the terminal stream). Through the same
|
||||
/// sockets as [send], so proxies and certificates keep working.
|
||||
Future<WebSocket> webSocket(String path,
|
||||
Future<TransportSocket> webSocket(String path,
|
||||
{String? rawQuery, Map<String, String> headers = const {}});
|
||||
|
||||
/// The bearer the client authenticates with. A direct transport ignores it;
|
||||
/// a relay must mint URL-scoped tokens from it for WebSocket upgrades, which
|
||||
/// cannot carry headers.
|
||||
void setBearerToken(String? token) {}
|
||||
|
||||
/// Releases whatever sockets the transport holds.
|
||||
void close();
|
||||
}
|
||||
@@ -210,21 +223,44 @@ class DirectTransport implements Transport {
|
||||
}
|
||||
|
||||
@override
|
||||
Future<WebSocket> webSocket(String path,
|
||||
{String? rawQuery, Map<String, String> headers = const {}}) {
|
||||
Future<TransportSocket> webSocket(String path,
|
||||
{String? rawQuery, Map<String, String> headers = const {}}) async {
|
||||
// ws:// is http:// with the upgrade; wss:// checks the same certificates,
|
||||
// so the configured client is reused as it stands.
|
||||
final base = this.base.replace(
|
||||
scheme: this.base.scheme == 'https' ? 'wss' : 'ws');
|
||||
final query = rawQuery ?? '';
|
||||
final uri = base.resolve(path).replace(query: query.isEmpty ? null : query);
|
||||
return WebSocket.connect(uri.toString(), headers: headers, customClient: _http);
|
||||
final socket = await WebSocket.connect(uri.toString(),
|
||||
headers: headers, customClient: _http);
|
||||
return _DirectSocket(socket);
|
||||
}
|
||||
|
||||
@override
|
||||
void setBearerToken(String? token) {}
|
||||
|
||||
@override
|
||||
void close() => _http.close();
|
||||
}
|
||||
|
||||
/// Wraps a direct WebSocket in the transport-agnostic socket shape. The
|
||||
/// terminal only speaks binary frames; text frames are ignored.
|
||||
class _DirectSocket implements TransportSocket {
|
||||
final WebSocket _socket;
|
||||
_DirectSocket(this._socket);
|
||||
|
||||
@override
|
||||
Stream<List<int>> get messages =>
|
||||
_socket.where((event) => event is List<int>).cast<List<int>>();
|
||||
|
||||
@override
|
||||
void add(List<int> data) => _socket.add(data);
|
||||
|
||||
@override
|
||||
Future<void> close([int code = 1000, String reason = '']) =>
|
||||
_socket.close(code, reason);
|
||||
}
|
||||
|
||||
String sha256Hex(List<int> bytes) => _Digest.sha256Hex(bytes);
|
||||
|
||||
// Minimal SHA-256, so the client has no native dependencies for pinning.
|
||||
|
||||
Reference in new issue
Block a user