diff --git a/PLAN.md b/PLAN.md index d4fdbcd..afabf0e 100644 --- a/PLAN.md +++ b/PLAN.md @@ -5,6 +5,22 @@ --- +## 0.4.4 通过 OpenChamber 私有 Relay 连接(分支 `flutter`) + +| 项 | 结果 | +| --- | --- | +| 配对链接 | 服务器列表新增「配对链接」:粘贴 `openchamber://connect?v=2&p=…`,解析一次性密钥与候选地址(lan / tunnel / relay,按 priority 先直连后 Relay),用第一个能连上的候选兑换设备 token 并保存 | +| 端到端加密 | 新增 `relay_crypto.dart`:P-256 ECDH + HKDF-SHA256(salt = 握手 nonce,info = `openchamber-relay-v1`)派生两条 AES-256-GCM 方向密钥;帧 = 版本 + 12 字节 IV(4 随机前缀 + 8 字节计数器)+ 密文 + GCM tag,计数器严格递增,失败即关闭。与官方 `packages/ui/src/lib/relay/crypto.ts` 字节兼容 | +| 隧道 | 新增 `relay_tunnel.dart`:连 `wss://…/ws?v=1&role=client&serverId=…`,明文 hello/ready 握手,之后是加密的 mux 帧(HttpRequest/Body/Response/StreamEnd/Abort、WsOpen/Opened/Text/Binary/Close、Ping/Pong)。大消息按 64 KiB 分片与重组,断线不自动重拉(下一次请求重连,SSE 自己的重试循环会恢复) | +| Transport | `Transport.webSocket` 改为返回 `TransportSocket`(直连包装 WebSocket,Relay 用子流);新增 `RelayTransport` 实现同一接口,所有 HTTP/SSE 走隧道。Relay 下的终端 WebSocket 先经隧道 `POST /auth/url-token` 换取短时 token,附到 `oc_url_token` 查询参数 | +| 连接模型 | `Connection` 增加 `relayUrl/serverId/hostKey/grant` 与 `isRelay`;直连字段不变。配对成功的连接与设备 token 一起保存,之后启动/重连直接用 token,不再需要配对链接 | +| 未协商 | 不声明 batch、下行 flow control 与响应 gzip,走宿主端的 legacy 路径(一帧一条消息、明文响应体),先保证正确性 | +| 切换 | 已连接时配对会先断开旧服务器(关闭旧 shell、事件流),再切到新连接;`ChatScreen` 现在持有自己的 `ChatState`,不再在 dispose/计时器里读已清空的 `app.chat!`(修掉切换服务器时的一个空指针崩溃) | +| 测试 | `test/relay_crypto_test.dart`(JWK 往返、双方派生一致、方向密钥、重放/篡改失败、base64url)、`test/pairing_test.dart`(直连优先、relay-only、grant、过期/非法/裸 payload);`tool/relay_probe.dart` 对真实 relay 做了握手、兑换、/api/version、会话列表、SSE 与终端快照的端到端验证;模拟器上从「配对链接」粘贴 relay-only 链接、重启后自动重连、终端命令输入输出都通过 | +| 版本 | **0.4.4(code 404)** | + +--- + ## 0.4.3 终端多标签:下拉切换、新建、按标签恢复(分支 `flutter`) | 项 | 结果 | diff --git a/README.md b/README.md index 7f30168..03b731a 100644 --- a/README.md +++ b/README.md @@ -5,8 +5,9 @@ Android first. This branch (`flutter`) is a framework evaluation: the same feature set as the earlier Asuka/Go and MyGo attempts, reimplemented in Flutter to compare mobile UI maturity. -Status: 0.4.3 — servers (passwordless / password login, HTTP/HTTPS and -SOCKS5/socks5h proxy, self-signed certificates and pinning), session list with search and live +Status: 0.4.4 — servers (passwordless / password login, HTTP/HTTPS and +SOCKS5/socks5h proxy, self-signed certificates and pinning, or a pairing link +over the OpenChamber private relay with end-to-end encryption), session list with search and live events, chat with streaming Markdown and full history paging, tool steps grouped per turn (icon, one-line summary, foldable run) with image previews, a context usage ring with a detail sheet, model/agent switching (Build/Plan only, diff --git a/lib/api/client.dart b/lib/api/client.dart index b5dd77c..9b37849 100644 --- a/lib/api/client.dart +++ b/lib/api/client.dart @@ -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 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> sessionStatus() async { final r = await _json('GET', '/auth/session'); return r; diff --git a/lib/api/pairing.dart b/lib/api/pairing.dart new file mode 100644 index 0000000..1c932f7 --- /dev/null +++ b/lib/api/pairing.dart @@ -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? 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 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 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 = []; + 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? _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 _base64UrlDecode(String value) { + final padded = value.padRight((value.length + 3) ~/ 4 * 4, '='); + return base64Url.decode(padded); +} diff --git a/lib/api/relay_crypto.dart b/lib/api/relay_crypto.dart new file mode 100644 index 0000000..04b28c5 --- /dev/null +++ b/lib/api/relay_crypto.dart @@ -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.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 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 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 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); diff --git a/lib/api/relay_transport.dart b/lib/api/relay_transport.dart new file mode 100644 index 0000000..6dee936 --- /dev/null +++ b/lib/api/relay_transport.dart @@ -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? _minting; + + RelayTransport({ + required String relayUrl, + required String serverId, + required Map hostKey, + String? grant, + String version = appVersion, + }) : _tunnel = RelayTunnel( + relayUrl: relayUrl, + serverId: serverId, + hostKey: hostKey, + grant: grant, + appVersion: version, + ); + + @override + Future send(TransportRequest request) => + _tunnel.send(request); + + @override + Future webSocket(String path, + {String? rawQuery, Map 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 _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 _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>([], (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(); +} diff --git a/lib/api/relay_tunnel.dart b/lib/api/relay_tunnel.dart new file mode 100644 index 0000000..f6d4e26 --- /dev/null +++ b/lib/api/relay_tunnel.dart @@ -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 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 send(TransportRequest request) async { + final channel = await _ensureChannel(); + final streamId = channel.nextStreamId(); + final body = request.body; + final controller = StreamController>(); + final response = Completer(); + 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 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 = {}; + 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 openWebSocket( + String path, { + String rawQuery = '', + Map 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.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(); + var finished = false; + Timer? helloTimer; + Timer? deadline; + StreamSubscription? 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) 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 = { + ...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 streams = {}; + final Map _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> _messages = StreamController>(); + final List _pending = []; + bool _open = false; + bool _closed = false; + + _RelaySocket({ + required this.channel, + required this.streamId, + required this.path, + required this.query, + }); + + @override + Stream> get messages => _messages.stream; + + @override + void add(List 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 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(); + } +} diff --git a/lib/api/terminal.dart b/lib/api/terminal.dart index 04fb1a9..bb5baa0 100644 --- a/lib/api/terminal.dart +++ b/lib/api/terminal.dart @@ -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), diff --git a/lib/api/transport.dart b/lib/api/transport.dart index 81d6556..b3a97a2 100644 --- a/lib/api/transport.dart +++ b/lib/api/transport.dart @@ -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> get messages; + void add(List data); + Future 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(String path, + Future webSocket(String path, {String? rawQuery, Map 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(String path, - {String? rawQuery, Map headers = const {}}) { + Future webSocket(String path, + {String? rawQuery, Map 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> get messages => + _socket.where((event) => event is List).cast>(); + + @override + void add(List data) => _socket.add(data); + + @override + Future close([int code = 1000, String reason = '']) => + _socket.close(code, reason); +} + String sha256Hex(List bytes) => _Digest.sha256Hex(bytes); // Minimal SHA-256, so the client has no native dependencies for pinning. diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index a3c7cd3..2191e81 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -43,7 +43,11 @@ class ChatScreen extends StatefulWidget { } class _ChatScreenState extends State { - ChatState get chat => widget.app.chat!; + /// The chat this page shows. Held rather than read from `app.chat` each + /// time: switching servers clears `app.chat` while this widget is still on + /// screen for one frame, and its timers and dispose must not trip on that. + late final ChatState _chat; + ChatState get chat => _chat; final TextEditingController _draftCtrl = TextEditingController(); final FocusNode _inputFocus = FocusNode(); final ScrollController _scroll = ScrollController(); @@ -71,6 +75,7 @@ class _ChatScreenState extends State { @override void initState() { super.initState(); + _chat = widget.app.chat!; chat.addListener(_onChat); _inputFocus.addListener(_onFocusChanged); if (chat.running) _startClock(); diff --git a/lib/screens/servers_screen.dart b/lib/screens/servers_screen.dart index 494faff..bb6cd8b 100644 --- a/lib/screens/servers_screen.dart +++ b/lib/screens/servers_screen.dart @@ -1,4 +1,5 @@ import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import '../state.dart'; import '../storage.dart'; @@ -90,10 +91,24 @@ class _ServersScreenState extends State { children: [ for (final c in conns) _serverCard(c), const SizedBox(height: 12), - OutlinedButton.icon( - onPressed: () => _startEdit(null), - icon: const Icon(Icons.add), - label: const Text('添加服务器'), + Row( + children: [ + Expanded( + child: OutlinedButton.icon( + onPressed: () => _startEdit(null), + icon: const Icon(Icons.add), + label: const Text('添加服务器'), + ), + ), + const SizedBox(width: 8), + Expanded( + child: FilledButton.tonalIcon( + onPressed: _pair, + icon: const Icon(Icons.qr_code_2, size: 18), + label: const Text('配对链接'), + ), + ), + ], ), ], ), @@ -114,8 +129,9 @@ class _ServersScreenState extends State { subtitle: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text(c.url, maxLines: 1, overflow: TextOverflow.ellipsis), - if (c.proxy.isNotEmpty) + Text(c.isRelay ? '经由 Relay · ${c.serverId}' : c.url, + maxLines: 1, overflow: TextOverflow.ellipsis), + if (!c.isRelay && c.proxy.isNotEmpty) Text('经由 ${c.proxy}', maxLines: 1, overflow: TextOverflow.ellipsis, @@ -216,48 +232,57 @@ class _ServersScreenState extends State { decoration: const InputDecoration(hintText: '如 我的电脑', border: OutlineInputBorder()), ), const SizedBox(height: 12), - _labelText('服务器地址'), - TextField( - controller: TextEditingController(text: _url), - onChanged: (v) => _url = v, - keyboardType: TextInputType.url, - decoration: const InputDecoration( - hintText: 'http://192.168.1.10:3000', border: OutlineInputBorder()), - ), - const SizedBox(height: 12), - _labelText('代理(可选)'), - TextField( - controller: TextEditingController(text: _proxy), - onChanged: (v) => _proxy = v, - keyboardType: TextInputType.url, - decoration: const InputDecoration( - hintText: 'http://… 或 socks5://…', border: OutlineInputBorder()), - ), - const SizedBox(height: 12), - _labelText('自签证书指纹(可选)'), - TextField( - controller: TextEditingController(text: _fingerprint), - onChanged: (v) => _fingerprint = v, - decoration: const InputDecoration(hintText: 'SHA-256 十六进制', border: OutlineInputBorder()), - ), - SwitchListTile( - contentPadding: EdgeInsets.zero, - title: const Text('信任自签名证书'), - value: _insecure, - onChanged: (v) => setState(() => _insecure = v), - ), - // Shown for new servers too: a password-protected instance rejects - // the first attempt, and this is where the password goes. - _labelText('密码(如果需要)'), - TextField( - controller: TextEditingController(text: _password), - focusNode: _passwordFocus, - onChanged: (v) => _password = v, - obscureText: true, - decoration: const InputDecoration( - hintText: '服务器密码;服务器未设置可留空', - border: OutlineInputBorder()), - ), + if (_edit?.isRelay == true) ...[ + const ListTile( + contentPadding: EdgeInsets.zero, + leading: Icon(Icons.lock_outline, size: 20), + title: Text('通过 Relay 连接'), + subtitle: Text('端到端加密;服务器与设备令牌保持不变'), + ), + ] else ...[ + _labelText('服务器地址'), + TextField( + controller: TextEditingController(text: _url), + onChanged: (v) => _url = v, + keyboardType: TextInputType.url, + decoration: const InputDecoration( + hintText: 'http://192.168.1.10:3000', border: OutlineInputBorder()), + ), + const SizedBox(height: 12), + _labelText('代理(可选)'), + TextField( + controller: TextEditingController(text: _proxy), + onChanged: (v) => _proxy = v, + keyboardType: TextInputType.url, + decoration: const InputDecoration( + hintText: 'http://… 或 socks5://…', border: OutlineInputBorder()), + ), + const SizedBox(height: 12), + _labelText('自签证书指纹(可选)'), + TextField( + controller: TextEditingController(text: _fingerprint), + onChanged: (v) => _fingerprint = v, + decoration: const InputDecoration(hintText: 'SHA-256 十六进制', border: OutlineInputBorder()), + ), + SwitchListTile( + contentPadding: EdgeInsets.zero, + title: const Text('信任自签名证书'), + value: _insecure, + onChanged: (v) => setState(() => _insecure = v), + ), + // Shown for new servers too: a password-protected instance rejects + // the first attempt, and this is where the password goes. + _labelText('密码(如果需要)'), + TextField( + controller: TextEditingController(text: _password), + focusNode: _passwordFocus, + onChanged: (v) => _password = v, + obscureText: true, + decoration: const InputDecoration( + hintText: '服务器密码;服务器未设置可留空', + border: OutlineInputBorder()), + ), + ], if (_formError != null) Padding( padding: const EdgeInsets.only(top: 8), @@ -287,14 +312,20 @@ class _ServersScreenState extends State { _connecting = true; _formError = null; }); - final c = Connection( - id: _edit?.id ?? _newId(), - label: _label.isEmpty ? _hostOf(_url) : _label, - url: _url, - proxy: _proxy, - insecure: _insecure, - fingerprint: _fingerprint, - ); + final relay = _edit?.isRelay == true ? _edit : null; + final c = relay != null + ? relay.copyWith( + label: _label.isEmpty ? relay.label : _label, + lastUsedAt: DateTime.now().millisecondsSinceEpoch, + ) + : Connection( + id: _edit?.id ?? Storage.newId(), + label: _label.isEmpty ? _hostOf(_url) : _label, + url: _url, + proxy: _proxy, + insecure: _insecure, + fingerprint: _fingerprint, + ); // Only a connection that works is saved (AppState saves it on success), // so failed attempts do not pile up in the server list. await widget.app.connect(c, password: _password); @@ -322,6 +353,12 @@ class _ServersScreenState extends State { }); } + void _pair() { + widget.app.error = null; + widget.app.clearLastError(); + showPairingDialog(context, widget.app); + } + void _confirmDelete(Connection c) { showDialog( context: context, @@ -342,9 +379,6 @@ class _ServersScreenState extends State { ); } - static String _newId() => - 'srv_${DateTime.now().microsecondsSinceEpoch.toRadixString(36)}'; - static String _hostOf(String raw) { try { return Uri.parse(raw).host; @@ -353,3 +387,125 @@ class _ServersScreenState extends State { } } } + +/// Opens the paste-a-pairing-link dialog (also reachable from the connected +/// sidebar's server sheet). +Future showPairingDialog(BuildContext context, AppState app) { + app.error = null; + app.clearLastError(); + return showDialog( + context: context, + builder: (_) => _PairingDialog(app: app), + ); +} + +/// Paste an `openchamber://connect` link and pair. The relay candidate in the +/// link is used when no direct address answers. +class _PairingDialog extends StatefulWidget { + final AppState app; + const _PairingDialog({required this.app}); + + @override + State<_PairingDialog> createState() => _PairingDialogState(); +} + +class _PairingDialogState extends State<_PairingDialog> { + final TextEditingController _text = TextEditingController(); + bool _busy = false; + String? _error; + + @override + void dispose() { + _text.dispose(); + super.dispose(); + } + + Future _paste() async { + final data = await Clipboard.getData(Clipboard.kTextPlain); + final text = data?.text?.trim() ?? ''; + if (text.isEmpty || !mounted) return; + setState(() => _text.text = text); + } + + Future _connect() async { + final link = _text.text.trim(); + if (link.isEmpty || _busy) return; + setState(() { + _busy = true; + _error = null; + }); + final paired = await widget.app.connectWithPairing(link); + if (!mounted) return; + if (paired && widget.app.client != null) { + Navigator.of(context).pop(); + return; + } + setState(() { + _busy = false; + _error = widget.app.lastError ?? '配对失败'; + }); + widget.app.clearLastError(); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return AlertDialog( + title: const Text('配对链接'), + content: SizedBox( + width: 420, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text( + '在 OpenChamber 网页端打开「连接设备」,把生成的链接粘贴到这里。' + '链接里带一次性密钥,以及直连地址或私有 Relay。', + style: TextStyle(fontSize: 12.5, color: theme.hintColor), + ), + const SizedBox(height: 12), + TextField( + controller: _text, + autofocus: true, + minLines: 2, + maxLines: 4, + keyboardType: TextInputType.multiline, + style: const TextStyle(fontFamily: 'monospace', fontSize: 12), + decoration: const InputDecoration( + hintText: 'openchamber://connect?v=2&p=…', + border: OutlineInputBorder(), + ), + ), + if (_error != null) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text(_error!, + style: TextStyle(color: theme.colorScheme.error, fontSize: 12.5)), + ), + Align( + alignment: Alignment.centerLeft, + child: TextButton.icon( + onPressed: _busy ? null : _paste, + icon: const Icon(Icons.content_paste, size: 18), + label: const Text('从剪贴板粘贴'), + ), + ), + ], + ), + ), + actions: [ + TextButton( + onPressed: _busy ? null : () => Navigator.of(context).pop(), + child: const Text('取消'), + ), + FilledButton( + onPressed: _busy ? null : _connect, + child: _busy + ? const SizedBox( + width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 2)) + : const Text('配对并连接'), + ), + ], + ); + } +} diff --git a/lib/screens/sessions_screen.dart b/lib/screens/sessions_screen.dart index 2109cc3..1d6d6ff 100644 --- a/lib/screens/sessions_screen.dart +++ b/lib/screens/sessions_screen.dart @@ -761,8 +761,9 @@ class _SessionListPaneState extends State { for (final c in app.connections) ...[ ListTile( title: Text(c.label), - subtitle: - Text(c.proxy.isEmpty ? c.url : '${c.url}\n经由 ${c.proxy}'), + subtitle: Text(c.isRelay + ? '经由 Relay · ${c.serverId}' + : (c.proxy.isEmpty ? c.url : '${c.url}\n经由 ${c.proxy}')), trailing: app.conn?.id == c.id ? Text('已连接', style: TextStyle( @@ -784,6 +785,15 @@ class _SessionListPaneState extends State { )); }, ), + ListTile( + leading: const Icon(Icons.qr_code_2), + title: const Text('配对链接'), + subtitle: const Text('直连地址或 OpenChamber Relay'), + onTap: () { + Navigator.pop(context); + showPairingDialog(context, app); + }, + ), if (app.client != null) ListTile( leading: const Icon(Icons.link_off), diff --git a/lib/state.dart b/lib/state.dart index c3c5f68..2731726 100644 --- a/lib/state.dart +++ b/lib/state.dart @@ -3,12 +3,15 @@ library; import 'dart:async'; +import 'dart:convert'; import 'dart:io'; import 'package:flutter/foundation.dart'; import 'api/client.dart'; import 'api/models.dart'; +import 'api/pairing.dart'; +import 'api/relay_transport.dart'; import 'storage.dart'; import 'terminal_state.dart'; @@ -190,12 +193,143 @@ class AppState extends ChangeNotifier { } Client _buildClient(Connection c) { + if (c.isRelay) { + // The relay has no reachable origin: every request rides the tunnel. + final transport = RelayTransport( + relayUrl: c.relayUrl, + serverId: c.serverId, + hostKey: jsonDecode(c.hostKey) as Map, + grant: c.grant.isEmpty ? null : c.grant, + ); + return Client(Uri.parse('http://relay.invalid'), transport: transport); + } return Client(Uri.parse(c.url), proxy: c.proxy.isEmpty ? null : c.proxy, insecure: c.insecure, fingerprint: c.fingerprint.isEmpty ? null : c.fingerprint); } + /// Ends a failed pairing attempt's client without touching the app's state. + void _dropClient(Client cl) { + try { + cl.close(); + } catch (_) {} + } + + /// Pairs a device from an `openchamber://connect` link: the one-time secret + /// is redeemed over the first reachable candidate (LAN first, then relay), + /// and the resulting device token is stored for later connections. + Future connectWithPairing(String link) async { + if (busy) return false; + final payload = parsePairingLink(link); + if (payload == null) { + debugPrint('pair: invalid link (${link.length} chars)'); + _lastError = '配对链接无效或已过期'; + notifyListeners(); + return false; + } + busy = true; + error = null; + _lastError = null; + notifyListeners(); + final installId = await storage.installId(); + Object? failure; + for (final candidate in payload.candidates) { + final Client cl; + try { + cl = candidate.isRelay + ? Client(Uri.parse('http://relay.invalid'), + transport: RelayTransport( + relayUrl: candidate.relayUrl, + serverId: candidate.serverId, + hostKey: candidate.hostKey!, + grant: candidate.grant, + )) + : Client(Uri.parse(candidate.url)); + } catch (e) { + failure = e; + continue; + } + try { + final redeemed = await cl + .redeemPairing( + pairingId: payload.pairingId, + secret: payload.secret, + installId: installId, + ) + .timeout(candidate.isRelay + ? const Duration(seconds: 30) + : const Duration(seconds: 15)); + if (redeemed.token.isEmpty) { + throw ApiError(401, '服务器没有返回设备令牌'); + } + final connection = _pairingConnection(candidate, payload, redeemed.response); + await storage.saveToken(connection.id, redeemed.token); + cl.token = redeemed.token; + // Pairing while another server is live switches this app to the paired + // one, exactly like picking it in the server list: close the old + // client, shells and event stream first. + if (client != null) { + await disconnect(); + } + busy = false; + _connected(cl, connection); + notifyListeners(); + return true; + } catch (e) { + failure = e; + _dropClient(cl); + } + } + busy = false; + final message = friendlyConnectError(failure ?? '配对失败'); + debugPrint('pair: failed: $message'); + error = message; + _lastError = message; + notifyListeners(); + return false; + } + + Connection _pairingConnection( + PairingCandidate candidate, PairingPayload payload, Map response) { + final server = response['server']; + final serverLabel = + server is Map ? server['label'] as String? : null; + final label = (payload.label ?? serverLabel ?? '').trim(); + Connection? existing; + for (final c in connections) { + if (candidate.isRelay) { + if (c.isRelay && + c.serverId == candidate.serverId && + c.relayUrl == candidate.relayUrl) { + existing = c; + break; + } + } else if (!c.isRelay && c.url == candidate.url) { + existing = c; + break; + } + } + if (candidate.isRelay) { + return Connection( + id: existing?.id ?? Storage.newId(), + label: label.isNotEmpty ? label : (existing?.label ?? 'Relay 服务器'), + url: 'relay://${candidate.serverId}', + relayUrl: candidate.relayUrl, + serverId: candidate.serverId, + hostKey: jsonEncode(candidate.hostKey), + grant: candidate.grant ?? '', + ); + } + return Connection( + id: existing?.id ?? Storage.newId(), + label: label.isNotEmpty + ? label + : (existing?.label ?? Uri.parse(candidate.url).host), + url: candidate.url, + ); + } + Future connect(Connection c, {String password = '', bool silent = false}) async { if (busy) return; busy = true; @@ -205,6 +339,11 @@ class AppState extends ChangeNotifier { try { var token = await storage.loadToken(c.id); if (token == null || token.isEmpty) { + if (c.isRelay) { + // A relay connection is created by pairing; a missing token means it + // was never stored or was revoked. + throw ApiError(401, '配对已失效,请重新配对'); + } // No saved token: a passwordless server needs none. try { final st = await cl.sessionStatus(); diff --git a/lib/storage.dart b/lib/storage.dart index 7ad8750..1b6a651 100644 --- a/lib/storage.dart +++ b/lib/storage.dart @@ -15,6 +15,14 @@ class Connection { final bool insecure; final String fingerprint; final int lastUsedAt; + + /// Set for a server reached through the private relay. The host's public + /// key (JSON JWK) is the E2EE trust anchor from the pairing link. + final String relayUrl; + final String serverId; + final String hostKey; + final String grant; + Connection({ required this.id, required this.label, @@ -23,8 +31,15 @@ class Connection { this.insecure = false, this.fingerprint = '', this.lastUsedAt = 0, + this.relayUrl = '', + this.serverId = '', + this.hostKey = '', + this.grant = '', }); + bool get isRelay => + relayUrl.isNotEmpty && serverId.isNotEmpty && hostKey.isNotEmpty; + factory Connection.fromJson(Map j) => Connection( id: j['id'] as String? ?? '', label: j['label'] as String? ?? '', @@ -33,6 +48,10 @@ class Connection { insecure: j['insecure'] as bool? ?? false, fingerprint: j['fingerprint'] as String? ?? '', lastUsedAt: (j['lastUsedAt'] as num?)?.toInt() ?? 0, + relayUrl: j['relayUrl'] as String? ?? '', + serverId: j['serverId'] as String? ?? '', + hostKey: j['hostKey'] as String? ?? '', + grant: j['grant'] as String? ?? '', ); Map toJson() => { @@ -43,6 +62,10 @@ class Connection { 'insecure': insecure, 'fingerprint': fingerprint, 'lastUsedAt': lastUsedAt, + if (relayUrl.isNotEmpty) 'relayUrl': relayUrl, + if (serverId.isNotEmpty) 'serverId': serverId, + if (hostKey.isNotEmpty) 'hostKey': hostKey, + if (grant.isNotEmpty) 'grant': grant, }; Connection copyWith({ @@ -52,6 +75,10 @@ class Connection { bool? insecure, String? fingerprint, int? lastUsedAt, + String? relayUrl, + String? serverId, + String? hostKey, + String? grant, }) => Connection( id: id, @@ -61,6 +88,10 @@ class Connection { insecure: insecure ?? this.insecure, fingerprint: fingerprint ?? this.fingerprint, lastUsedAt: lastUsedAt ?? this.lastUsedAt, + relayUrl: relayUrl ?? this.relayUrl, + serverId: serverId ?? this.serverId, + hostKey: hostKey ?? this.hostKey, + grant: grant ?? this.grant, ); } @@ -187,7 +218,7 @@ class Storage { final prefs = await SharedPreferences.getInstance(); var id = prefs.getString(_installKey); if (id == null || id.isEmpty) { - id = _newId(); + id = newId(); await prefs.setString(_installKey, id); } return id; @@ -210,7 +241,7 @@ class Storage { return 'openchamber.token.$digest'; } - static String _newId() => + static String newId() => 'srv_${DateTime.now().microsecondsSinceEpoch.toRadixString(36)}${(_rand() & 0xffffff).toRadixString(36).padLeft(6, '0')}'; static int _rand() => DateTime.now().microsecondsSinceEpoch % 0xffffffff; diff --git a/lib/version.dart b/lib/version.dart new file mode 100644 index 0000000..2aa197c --- /dev/null +++ b/lib/version.dart @@ -0,0 +1,2 @@ +/// The app version sent to the server in pairing and relay handshakes. +const appVersion = '0.4.4'; diff --git a/pubspec.lock b/pubspec.lock index 19034a0..8934611 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -549,6 +549,14 @@ packages: url: "https://pub.flutter-io.cn" source: hosted version: "2.1.8" + pointycastle: + dependency: "direct main" + description: + name: pointycastle + sha256: "92aa3841d083cc4b0f4709b5c74fd6409a3e6ba833ffc7dc6a8fee096366acf5" + url: "https://pub.flutter-io.cn" + source: hosted + version: "4.0.0" pub_semver: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index b4e0156..2f16d16 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -2,7 +2,7 @@ name: openchamber description: "A lightweight OpenChamber client for phones." publish_to: 'none' -version: 0.4.3+403 +version: 0.4.4+404 environment: sdk: ^3.14.0 @@ -19,6 +19,7 @@ dependencies: xterm: ^4.0.0 flutter_slidable: ^5.2.0 archive: ^3.6.1 + pointycastle: ^4.0.0 dev_dependencies: flutter_test: sdk: flutter diff --git a/test/pairing_test.dart b/test/pairing_test.dart new file mode 100644 index 0000000..6e54087 --- /dev/null +++ b/test/pairing_test.dart @@ -0,0 +1,109 @@ +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:openchamber/api/pairing.dart'; + +String _link(Map payload) => + 'openchamber://connect?v=2&p=${base64Url.encode(utf8.encode(jsonEncode(payload))).replaceAll('=', '')}'; + +Map _payload({ + String? expiresAt, + List>? candidates, +}) => + { + 'v': 2, + 'pairingId': 'pair_123', + 'secret': 'secret-abc', + 'label': '我的电脑', + if (expiresAt != null) 'expiresAt': expiresAt, + 'candidates': candidates ?? + [ + {'type': 'lan', 'url': 'http://192.168.1.10:3000', 'priority': 10}, + { + 'type': 'relay', + 'relayUrl': 'wss://relay.openchamber.dev/ws', + 'serverId': 'server-1', + 'hostEncPubJwk': { + 'kty': 'EC', + 'crv': 'P-256', + 'x': 'abc', + 'y': 'def', + }, + 'priority': 30, + }, + ], + }; + +void main() { + test('parses a link with direct and relay candidates, direct first', () { + final payload = parsePairingLink(_link(_payload())); + expect(payload, isNotNull); + expect(payload!.pairingId, 'pair_123'); + expect(payload.secret, 'secret-abc'); + expect(payload.label, '我的电脑'); + expect(payload.candidates, hasLength(2)); + expect(payload.candidates.first.isRelay, isFalse); + expect(payload.candidates.first.url, 'http://192.168.1.10:3000'); + + final relay = payload.candidates.last; + expect(relay.isRelay, isTrue); + expect(relay.relayUrl, 'wss://relay.openchamber.dev/ws'); + expect(relay.serverId, 'server-1'); + expect(relay.hostKey?['x'], 'abc'); + }); + + test('a relay-only link works and keeps the grant', () { + final payload = parsePairingLink(_link(_payload(candidates: [ + { + 'type': 'relay', + 'relayUrl': 'wss://relay.example/ws', + 'serverId': 'srv', + 'hostEncPubJwk': {'kty': 'EC', 'crv': 'P-256', 'x': 'x', 'y': 'y'}, + 'grant': 'g-1', + }, + ]))); + expect(payload, isNotNull); + expect(payload!.candidates.single.isRelay, isTrue); + expect(payload.candidates.single.grant, 'g-1'); + }); + + test('a bare base64url payload is accepted too', () { + final encoded = + base64Url.encode(utf8.encode(jsonEncode(_payload()))).replaceAll('=', ''); + expect(parsePairingLink(encoded), isNotNull); + }); + + test('expired and malformed links are refused', () { + final past = DateTime.now() + .subtract(const Duration(minutes: 1)) + .toUtc() + .toIso8601String(); + expect(parsePairingLink(_link(_payload(expiresAt: past))), isNull); + expect(parsePairingLink('openchamber://connect?v=2&p=not-json'), isNull); + expect(parsePairingLink('https://example.com'), isNull); + + // A candidate with a missing key or a bad scheme invalidates the list. + expect( + parsePairingLink(_link(_payload(candidates: [ + { + 'type': 'relay', + 'relayUrl': 'https://relay.example/ws', + 'serverId': 'srv', + 'hostEncPubJwk': {'kty': 'EC', 'crv': 'P-256', 'x': 'x', 'y': 'y'}, + }, + ]))), + isNull, + ); + expect( + parsePairingLink(_link(_payload(candidates: [ + { + 'type': 'relay', + 'relayUrl': 'wss://relay.example/ws', + 'serverId': 'srv', + 'hostEncPubJwk': {'kty': 'EC', 'crv': 'P-384', 'x': 'x', 'y': 'y'}, + }, + ]))), + isNull, + ); + }); +} diff --git a/test/relay_crypto_test.dart b/test/relay_crypto_test.dart new file mode 100644 index 0000000..43c4d2c --- /dev/null +++ b/test/relay_crypto_test.dart @@ -0,0 +1,67 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:openchamber/api/relay_crypto.dart'; + +Uint8List _bytes(String text) => Uint8List.fromList(utf8.encode(text)); + +void main() { + test('P-256 JWK round-trips and fingerprints stably', () { + final pair = newRelayKeyPair(); + final jwk = publicJwk(pair.publicKey); + expect(jwk['kty'], 'EC'); + expect(jwk['crv'], 'P-256'); + + final imported = importPublicJwk(jwk); + expect(publicJwk(imported), jwk); + expect(jwkFingerprint(jwk), jwkFingerprint(Map.from(jwk))); + expect(jwkFingerprint(jwk), isNot(contains('"d"'))); + }); + + test('both sides derive the same directional keys and can talk', () { + final client = newRelayKeyPair(); + final host = newRelayKeyPair(); + final nonce = randomBytes(16); + + final clientKeys = deriveSessionKeys(client.privateKey, host.publicKey, nonce); + final hostKeys = deriveSessionKeys(host.privateKey, client.publicKey, nonce); + expect(clientKeys.clientToHost, hostKeys.clientToHost); + expect(clientKeys.hostToClient, hostKeys.hostToClient); + expect(clientKeys.clientToHost, isNot(clientKeys.hostToClient)); + + final encryptor = RelayEncryptor(clientKeys.clientToHost); + final decryptor = RelayDecryptor(hostKeys.clientToHost); + final frame = encryptor.encrypt(_bytes('hello over the relay')); + expect(frame.first, encryptedFrameVersion); + expect(utf8.decode(decryptor.decrypt(frame)), 'hello over the relay'); + + // A second frame works; a replayed counter does not. + final second = encryptor.encrypt(_bytes('hello over the relay')); + expect(utf8.decode(decryptor.decrypt(second)), 'hello over the relay'); + expect(() => decryptor.decrypt(second), throwsA(isA())); + + // A different nonce gives different keys. + final otherKeys = + deriveSessionKeys(client.privateKey, host.publicKey, randomBytes(16)); + expect(otherKeys.clientToHost, isNot(clientKeys.clientToHost)); + }); + + test('tampered frames fail closed', () { + final a = newRelayKeyPair(); + final b = newRelayKeyPair(); + final nonce = randomBytes(16); + final keys = deriveSessionKeys(a.privateKey, b.publicKey, nonce); + final frame = RelayEncryptor(keys.clientToHost).encrypt(_bytes('tamper me')); + final bad = Uint8List.fromList(frame)..[frame.length - 1] ^= 0xff; + expect(() => RelayDecryptor(keys.clientToHost).decrypt(bad), + throwsA(isA())); + }); + + test('base64url helpers follow the protocol (no padding)', () { + final bytes = Uint8List.fromList([0, 1, 2, 250, 255]); + final encoded = base64UrlEncodeBytes(bytes); + expect(encoded, isNot(contains('='))); + expect(base64UrlDecodeBytes(encoded), bytes); + }); +} diff --git a/tool/relay_probe.dart b/tool/relay_probe.dart new file mode 100644 index 0000000..4b5c420 --- /dev/null +++ b/tool/relay_probe.dart @@ -0,0 +1,88 @@ +// Exercises the private relay end to end: parse a pairing link, open the E2EE +// tunnel, redeem the one-time secret, then use the client like the app does +// (HTTP, SSE, terminal WebSocket). +// dart run tool/relay_probe.dart 'openchamber://connect?v=2&p=...' +import 'dart:async'; +import 'dart:io'; + +import 'package:openchamber/api/client.dart'; +import 'package:openchamber/api/pairing.dart'; +import 'package:openchamber/api/relay_transport.dart'; +import 'package:openchamber/api/terminal.dart'; + +Future main(List args) async { + if (args.isEmpty) { + print('usage: dart run tool/relay_probe.dart '); + return; + } + final payload = parsePairingLink(args.first); + if (payload == null) { + print('invalid pairing link'); + return; + } + PairingCandidate? relay; + for (final candidate in payload.candidates) { + if (candidate.isRelay) { + relay = candidate; + break; + } + } + if (relay == null) { + print('link has no relay candidate'); + return; + } + print('relay ${relay.relayUrl} server ${relay.serverId}'); + final transport = RelayTransport( + relayUrl: relay.relayUrl, + serverId: relay.serverId, + hostKey: relay.hostKey!, + grant: relay.grant, + version: 'probe', + ); + final client = Client(Uri.parse('http://relay.invalid'), transport: transport); + try { + final redeemed = await client.redeemPairing( + pairingId: payload.pairingId, + secret: payload.secret, + installId: 'relay-probe', + clientLabel: 'relay probe', + ); + print('redeem ${redeemed.token.isEmpty ? 'no token' : 'ok'}: ' + '${redeemed.response['server']}'); + if (redeemed.token.isEmpty) return; + client.token = redeemed.token; + + final status = await client.sessionStatus(); + print('session ${status['authenticated']}'); + final page = await client.listSessions(limit: 1); + print('sessions ${page.data.length}' + '${page.data.isEmpty ? '' : ' first=${page.data.first.id}'}'); + + final sse = []; + final sub = client.streamEvents(types: const ['session.created']).listen( + (event) => sse.add('${event['type']}'), + onError: (Object error) => sse.add('error: $error'), + ); + final dir = page.data.isNotEmpty + ? page.data.first.directory + : Directory.current.path; + final info = await client.createTerminal(cwd: dir, cols: 80, rows: 24); + print('terminal ${info.sessionId}'); + final terminal = TerminalSocket( + transport: transport, + headers: client.eventHeaders, + sessionId: info.sessionId, + onEvent: (event) => + print('terminal event ${event.type} ${event.data.length}'), + onState: (state, {detail}) => print('terminal state $state $detail'), + ); + await terminal.connect(); + await Future.delayed(const Duration(seconds: 3)); + await sub.cancel(); + await terminal.dispose(); + await client.closeTerminal(info.sessionId, directory: dir); + print('sse ${sse.take(3).toList()}'); + } finally { + transport.close(); + } +}