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:
blumia committed 2026-11-22 16:51:44 +08:00
1 parent a7bc380ac0
commit 902f1e18bb
20 files changed
+1918 -75

No files matched your search

+109
View File
@@ -0,0 +1,109 @@
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/api/pairing.dart';
String _link(Map<String, dynamic> payload) =>
'openchamber://connect?v=2&p=${base64Url.encode(utf8.encode(jsonEncode(payload))).replaceAll('=', '')}';
Map<String, dynamic> _payload({
String? expiresAt,
List<Map<String, dynamic>>? 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,
);
});
}
+67
View File
@@ -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<String, dynamic>.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<RelayCryptoError>()));
// 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<RelayCryptoError>()));
});
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);
});
}