Files
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

301 lines
8.5 KiB
Dart

// The OpenChamber terminal protocol: HTTP commands (create, resize, restart,
// close) plus one WebSocket per host carrying binary control frames (a 0x01
// tag, then JSON). A socket can attach to several terminals; we attach to one.
import 'dart:async';
import 'dart:convert';
import 'transport.dart';
/// What `POST /api/terminal/create` (and restart) answers.
class TerminalSessionInfo {
final String sessionId;
final int cols;
final int rows;
final String status;
const TerminalSessionInfo({
required this.sessionId,
this.cols = 80,
this.rows = 24,
this.status = 'running',
});
factory TerminalSessionInfo.fromJson(Map<String, dynamic> j) =>
TerminalSessionInfo(
sessionId: j['sessionId'] as String? ?? '',
cols: (j['cols'] as num?)?.toInt() ?? 80,
rows: (j['rows'] as num?)?.toInt() ?? 24,
status: j['status'] as String? ?? 'running',
);
}
/// A terminal the server still holds, from `GET /api/terminal/sessions`.
/// The id outlives this app process, so a restart can attach to the same
/// shell instead of making another one.
class ServerTerminal {
final String sessionId;
final String cwd;
final String status; // running | exited
final int? createdAt;
final String mode; // interactive | command
final String purpose; // terminal | project-action (or empty)
const ServerTerminal({
required this.sessionId,
this.cwd = '',
this.status = 'running',
this.createdAt,
this.mode = 'interactive',
this.purpose = '',
});
/// A terminal a person opened. A project action's command runner is also a
/// PTY, but it is not one of the user's tabs.
bool get interactive => mode != 'command' && purpose != 'project-action';
factory ServerTerminal.fromJson(Map<String, dynamic> j) {
final purposeJson = j['purpose'];
return ServerTerminal(
sessionId: j['sessionId'] as String? ?? '',
cwd: j['cwd'] as String? ?? '',
status: j['status'] as String? ?? 'running',
createdAt: (j['createdAt'] as num?)?.toInt(),
mode: j['mode'] as String? ?? 'interactive',
purpose: purposeJson is Map
? purposeJson['type'] as String? ?? ''
: '',
);
}
}
/// One frame from the server: a snapshot (the authoritative screen), output,
/// an exit notice, or an error.
class TerminalEvent {
final String type; // snapshot | output | restarted | exit | error
final String data; // snapshot history / output text
final int sequence;
final int? cols;
final int? rows;
final String? status;
final int? exitCode;
final int? signal;
final String? code;
final String? message;
final bool fatal;
const TerminalEvent(
this.type, {
this.data = '',
this.sequence = 0,
this.cols,
this.rows,
this.status,
this.exitCode,
this.signal,
this.code,
this.message,
this.fatal = false,
});
}
/// The socket's life, for the status bar.
enum TerminalLinkState { idle, creating, connecting, open, reconnecting, exited, error }
/// One attached terminal. Writes made while the socket is down wait in a
/// buffer; a dropped socket reconnects with backoff and reattaches, which
/// begins with a fresh snapshot.
class TerminalSocket {
final Transport transport;
final Map<String, String> headers;
final String sessionId;
final void Function(TerminalEvent event) onEvent;
final void Function(TerminalLinkState state, {String? detail}) onState;
TransportSocket? _socket;
Timer? _keepAlive;
Timer? _reconnect;
final StringBuffer _pending = StringBuffer();
int _failures = 0;
int _generation = 0;
bool _disposed = false;
bool _opened = false;
TerminalSocket({
required this.transport,
required this.headers,
required this.sessionId,
required this.onEvent,
required this.onState,
});
Future<void> connect() async {
if (_disposed) return;
final generation = ++_generation;
onState(_opened ? TerminalLinkState.reconnecting : TerminalLinkState.connecting);
try {
final socket = await transport.webSocket(
'/api/terminal/ws',
headers: headers,
);
if (_disposed || generation != _generation) {
await socket.close();
return;
}
_socket = socket;
_failures = 0;
socket.messages.listen(
_handle,
onError: (_) => _drop(generation),
onDone: () => _drop(generation),
);
_send({'t': 'hello', 'v': 3});
_send({'t': 'attach', 'v': 3, 's': sessionId});
_opened = true;
_keepAlive?.cancel();
_keepAlive = Timer.periodic(
const Duration(seconds: 45), (_) => _send({'t': 'ping', 'v': 3}));
onState(TerminalLinkState.open);
_flushPending();
} catch (error) {
if (_disposed) return;
onState(TerminalLinkState.error, detail: '$error');
_scheduleReconnect();
}
}
void write(String data) {
if (data.isEmpty) return;
if (_socket == null) {
_pending.write(data);
return;
}
_send({'t': 'write', 'v': 3, 's': sessionId, 'd': data});
}
Future<void> dispose() async {
_disposed = true;
_generation++;
_reconnect?.cancel();
_keepAlive?.cancel();
final socket = _socket;
_socket = null;
// Detaching leaves the session running on the server; closing the socket
// is enough for a panel that is going away.
try {
await socket?.close();
} catch (_) {}
}
// ------------------------------------------------------------- internals
void _send(Map<String, Object?> message) {
final socket = _socket;
if (socket == null) return;
final bytes = <int>[1, ...utf8.encode(jsonEncode(message))];
try {
socket.add(bytes);
} catch (_) {
_drop(_generation);
}
}
void _flushPending() {
if (_pending.isEmpty) return;
final data = _pending.toString();
_pending.clear();
write(data);
}
void _drop(int generation) {
if (_disposed || generation != _generation) return;
_generation++;
_keepAlive?.cancel();
_keepAlive = null;
final socket = _socket;
_socket = null;
try {
socket?.close();
} catch (_) {}
onState(TerminalLinkState.reconnecting);
_scheduleReconnect();
}
void _scheduleReconnect() {
if (_disposed || _reconnect != null) return;
_failures += 1;
final delay = Duration(
milliseconds: 500 * (1 << (_failures - 1).clamp(0, 4)));
_reconnect = Timer(delay, () {
_reconnect = null;
if (!_disposed) connect();
});
}
void _handle(dynamic raw) {
if (_disposed || raw is! List<int> || raw.isEmpty) return;
final Map<String, dynamic> message;
try {
final tag = raw.first;
final bytes = tag == 1 ? raw.sublist(1) : raw;
final decoded = jsonDecode(utf8.decode(bytes));
if (decoded is! Map<String, dynamic>) return;
message = decoded;
} catch (_) {
return;
}
final type = message['t'] as String? ?? '';
final sequence = (message['q'] as num?)?.toInt() ?? 0;
switch (type) {
case 'snapshot':
onEvent(TerminalEvent(
'snapshot',
data: message['history'] as String? ?? '',
sequence: sequence,
cols: (message['cols'] as num?)?.toInt(),
rows: (message['rows'] as num?)?.toInt(),
status: message['status'] as String?,
exitCode: (message['exitCode'] as num?)?.toInt(),
signal: (message['signal'] as num?)?.toInt(),
));
break;
case 'output':
// `r` is the replay-safe text (terminal queries removed); `d` the raw
// bytes. Replay text is what the official client renders.
onEvent(TerminalEvent(
'output',
data: (message['r'] ?? message['d'] ?? '') as String,
sequence: sequence,
));
break;
case 'restarted':
onEvent(TerminalEvent(
'restarted',
data: message['history'] as String? ?? '',
sequence: sequence,
));
break;
case 'exit':
onState(TerminalLinkState.exited,
detail: '${(message['exitCode'] as num?)?.toInt() ?? ''}');
onEvent(TerminalEvent(
'exit',
sequence: sequence,
exitCode: (message['exitCode'] as num?)?.toInt(),
signal: (message['signal'] as num?)?.toInt(),
));
break;
case 'error':
onEvent(TerminalEvent(
'error',
sequence: sequence,
code: message['code'] as String?,
message: message['message'] as String?,
fatal: message['fatal'] as bool? ?? false,
));
break;
default:
break;
}
}
}