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).
260 lines
8.3 KiB
Dart
260 lines
8.3 KiB
Dart
// Persistence: saved servers in SharedPreferences, device tokens in the
|
|
// platform's secure storage (Android Keystore).
|
|
library;
|
|
|
|
import 'dart:convert';
|
|
|
|
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
|
|
|
class Connection {
|
|
final String id;
|
|
final String label;
|
|
final String url;
|
|
final String proxy;
|
|
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,
|
|
required this.url,
|
|
this.proxy = '',
|
|
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<String, dynamic> j) => Connection(
|
|
id: j['id'] as String? ?? '',
|
|
label: j['label'] as String? ?? '',
|
|
url: j['url'] as String? ?? '',
|
|
proxy: j['proxy'] as String? ?? '',
|
|
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<String, dynamic> toJson() => {
|
|
'id': id,
|
|
'label': label,
|
|
'url': url,
|
|
'proxy': proxy,
|
|
'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({
|
|
String? label,
|
|
String? url,
|
|
String? proxy,
|
|
bool? insecure,
|
|
String? fingerprint,
|
|
int? lastUsedAt,
|
|
String? relayUrl,
|
|
String? serverId,
|
|
String? hostKey,
|
|
String? grant,
|
|
}) =>
|
|
Connection(
|
|
id: id,
|
|
label: label ?? this.label,
|
|
url: url ?? this.url,
|
|
proxy: proxy ?? this.proxy,
|
|
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,
|
|
);
|
|
}
|
|
|
|
/// One remembered terminal tab: the server's session id and the local label.
|
|
class SavedTerminalTab {
|
|
final String id;
|
|
final String label;
|
|
const SavedTerminalTab(this.id, this.label);
|
|
}
|
|
|
|
/// The terminal tabs remembered for one directory, with the tab that was
|
|
/// showing.
|
|
class SavedTerminalTabs {
|
|
final List<SavedTerminalTab> tabs;
|
|
final String? activeId;
|
|
const SavedTerminalTabs(this.tabs, this.activeId);
|
|
}
|
|
|
|
class Storage {
|
|
static const _connsKey = 'openchamber.connections';
|
|
static const _installKey = 'openchamber.installId';
|
|
static const _terminalPrefix = 'openchamber.terminalSessions.';
|
|
// v11 encrypts with AES-GCM and an Android Keystore-wrapped key by default.
|
|
final _secure = const FlutterSecureStorage();
|
|
|
|
Future<List<Connection>> connections() async {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
final raw = prefs.getString(_connsKey);
|
|
if (raw == null || raw.isEmpty) return [];
|
|
try {
|
|
final list = jsonDecode(raw) as List;
|
|
final out = list
|
|
.map((e) => Connection.fromJson(e as Map<String, dynamic>))
|
|
.toList();
|
|
out.sort((a, b) => b.lastUsedAt.compareTo(a.lastUsedAt));
|
|
return out;
|
|
} catch (_) {
|
|
return [];
|
|
}
|
|
}
|
|
|
|
Future<void> saveConnections(List<Connection> list) async {
|
|
final sorted = [...list]..sort((a, b) => b.lastUsedAt.compareTo(a.lastUsedAt));
|
|
final prefs = await SharedPreferences.getInstance();
|
|
await prefs.setString(_connsKey, jsonEncode(sorted.map((e) => e.toJson()).toList()));
|
|
}
|
|
|
|
// ------------------------------------------------------------- terminals
|
|
|
|
// The terminal tabs per directory, so reopening the terminal after an app
|
|
// restart can reattach to the shells the server still holds instead of
|
|
// starting new ones. Ids are meaningless across servers, hence one map per
|
|
// connection.
|
|
|
|
static String _terminalKey(String connectionId) =>
|
|
'$_terminalPrefix$connectionId';
|
|
|
|
Future<Map<String, dynamic>> _terminalMap(String connectionId) async {
|
|
if (connectionId.isEmpty) return {};
|
|
final prefs = await SharedPreferences.getInstance();
|
|
final raw = prefs.getString(_terminalKey(connectionId));
|
|
if (raw == null || raw.isEmpty) return {};
|
|
try {
|
|
final decoded = jsonDecode(raw);
|
|
if (decoded is Map) return Map<String, dynamic>.from(decoded);
|
|
} catch (_) {}
|
|
return {};
|
|
}
|
|
|
|
/// The tabs saved for [directory], or null when there are none. A value
|
|
/// written by 0.4.2 (a bare session id) is read as a single tab.
|
|
Future<SavedTerminalTabs?> terminalTabs(
|
|
String connectionId, String directory) async {
|
|
final entry = (await _terminalMap(connectionId))[directory];
|
|
if (entry is String && entry.isNotEmpty) {
|
|
return SavedTerminalTabs(
|
|
[SavedTerminalTab(entry, '终端 1')], entry);
|
|
}
|
|
if (entry is! Map) return null;
|
|
final rawTabs = entry['tabs'];
|
|
if (rawTabs is! List) return null;
|
|
final tabs = <SavedTerminalTab>[];
|
|
for (final raw in rawTabs) {
|
|
if (raw is! Map) continue;
|
|
final id = raw['id'];
|
|
final label = raw['label'];
|
|
if (id is! String || id.isEmpty) continue;
|
|
tabs.add(SavedTerminalTab(
|
|
id, label is String && label.trim().isNotEmpty ? label : '终端'));
|
|
}
|
|
if (tabs.isEmpty) return null;
|
|
final active = entry['active'];
|
|
return SavedTerminalTabs(tabs, active is String ? active : null);
|
|
}
|
|
|
|
Future<void> saveTerminalTabs(
|
|
String connectionId, String directory, SavedTerminalTabs value) async {
|
|
if (connectionId.isEmpty || directory.isEmpty) return;
|
|
final prefs = await SharedPreferences.getInstance();
|
|
final map = await _terminalMap(connectionId);
|
|
map[directory] = {
|
|
'tabs': [
|
|
for (final tab in value.tabs) {'id': tab.id, 'label': tab.label},
|
|
],
|
|
if (value.activeId != null) 'active': value.activeId,
|
|
};
|
|
await prefs.setString(_terminalKey(connectionId), jsonEncode(map));
|
|
}
|
|
|
|
Future<void> clearTerminalTabs(
|
|
String connectionId, String directory) async {
|
|
if (connectionId.isEmpty) return;
|
|
final prefs = await SharedPreferences.getInstance();
|
|
final map = await _terminalMap(connectionId);
|
|
if (map.remove(directory) == null) return;
|
|
if (map.isEmpty) {
|
|
await prefs.remove(_terminalKey(connectionId));
|
|
} else {
|
|
await prefs.setString(_terminalKey(connectionId), jsonEncode(map));
|
|
}
|
|
}
|
|
|
|
Future<String> installId() async {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
var id = prefs.getString(_installKey);
|
|
if (id == null || id.isEmpty) {
|
|
id = newId();
|
|
await prefs.setString(_installKey, id);
|
|
}
|
|
return id;
|
|
}
|
|
|
|
Future<String?> loadToken(String connectionId) async {
|
|
return _secure.read(key: _tokenKey(connectionId));
|
|
}
|
|
|
|
Future<void> saveToken(String connectionId, String token) async {
|
|
await _secure.write(key: _tokenKey(connectionId), value: token);
|
|
}
|
|
|
|
Future<void> clearToken(String connectionId) async {
|
|
await _secure.delete(key: _tokenKey(connectionId));
|
|
}
|
|
|
|
String _tokenKey(String id) {
|
|
final digest = _sha1(id);
|
|
return 'openchamber.token.$digest';
|
|
}
|
|
|
|
static String newId() =>
|
|
'srv_${DateTime.now().microsecondsSinceEpoch.toRadixString(36)}${(_rand() & 0xffffff).toRadixString(36).padLeft(6, '0')}';
|
|
|
|
static int _rand() => DateTime.now().microsecondsSinceEpoch % 0xffffffff;
|
|
}
|
|
|
|
String _sha1(String s) {
|
|
// A small, dependency-free FNV-ish key is fine for a storage key: it only
|
|
// names the secret, never secures it.
|
|
var h = 0x811c9dc5;
|
|
for (final c in s.codeUnits) {
|
|
h ^= c;
|
|
h = (h * 0x01000193) & 0xffffffff;
|
|
}
|
|
return h.toRadixString(16).padLeft(8, '0');
|
|
}
|