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

+110
View File
@@ -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();
}