Files
openchamber-android-native/lib/api/relay_crypto.dart
T
blumia 902f1e18bb 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).
2026-11-22 16:51:44 +08:00

210 lines
6.6 KiB
Dart

// 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);