Files
openchamber-android-native/lib/screens/servers_screen.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

512 lines
16 KiB
Dart

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../state.dart';
import '../storage.dart';
/// The first screen: the saved servers, or the connect form.
class ServersScreen extends StatefulWidget {
final AppState app;
/// Open the "add server" form straight away (pushed from the server sheet
/// while a connection is live).
final bool startEditing;
const ServersScreen({super.key, required this.app, this.startEditing = false});
@override
State<ServersScreen> createState() => _ServersScreenState();
}
class _ServersScreenState extends State<ServersScreen> {
bool _editing = false;
bool _editNew = true;
Connection? _edit;
String _label = '';
String _url = '';
String _proxy = '';
bool _insecure = false;
String _fingerprint = '';
String _password = '';
bool _connecting = false;
String? _formError;
// A server may ask for a password only after the first attempt; the field
// is always there, but this one takes the focus when it is what is missing.
final FocusNode _passwordFocus = FocusNode();
@override
void initState() {
super.initState();
if (widget.startEditing) _editing = true;
}
@override
void dispose() {
_passwordFocus.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: widget.app,
builder: (context, _) {
if (_editing) return _form();
return _list();
},
);
}
Widget _list() {
final theme = Theme.of(context);
final conns = widget.app.connections;
return Scaffold(
body: SafeArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(20, 20, 20, 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('OpenChamber',
style: theme.textTheme.headlineMedium
?.copyWith(fontWeight: FontWeight.bold)),
const SizedBox(height: 4),
Text('连接你的 OpenChamber 服务器',
style: theme.textTheme.bodyMedium
?.copyWith(color: theme.hintColor)),
],
),
),
if (widget.app.error != null)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
child: Text(widget.app.error!,
style: TextStyle(color: theme.colorScheme.error, fontSize: 13)),
),
Expanded(
child: ListView(
padding: const EdgeInsets.all(16),
children: [
for (final c in conns) _serverCard(c),
const SizedBox(height: 12),
Row(
children: [
Expanded(
child: OutlinedButton.icon(
onPressed: () => _startEdit(null),
icon: const Icon(Icons.add),
label: const Text('添加服务器'),
),
),
const SizedBox(width: 8),
Expanded(
child: FilledButton.tonalIcon(
onPressed: _pair,
icon: const Icon(Icons.qr_code_2, size: 18),
label: const Text('配对链接'),
),
),
],
),
],
),
),
],
),
),
);
}
Widget _serverCard(Connection c) {
final theme = Theme.of(context);
final connected = widget.app.conn?.id == c.id;
return Card(
margin: const EdgeInsets.only(bottom: 10),
child: ListTile(
title: Text(c.label, style: const TextStyle(fontWeight: FontWeight.w600)),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(c.isRelay ? '经由 Relay · ${c.serverId}' : c.url,
maxLines: 1, overflow: TextOverflow.ellipsis),
if (!c.isRelay && c.proxy.isNotEmpty)
Text('经由 ${c.proxy}',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 12, color: theme.hintColor)),
],
),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (connected)
Text('已连接', style: TextStyle(color: theme.colorScheme.primary))
else
TextButton(onPressed: () => _connect(c), child: const Text('连接')),
PopupMenuButton<String>(
onSelected: (v) {
if (v == 'edit') {
_startEdit(c);
} else if (v == 'delete') {
_confirmDelete(c);
}
},
itemBuilder: (_) => const [
PopupMenuItem(value: 'edit', child: Text('编辑')),
PopupMenuItem(value: 'delete', child: Text('删除')),
],
),
],
),
),
);
}
void _connect(Connection c) async {
setState(() {
_connecting = true;
_editNew = false;
_edit = c;
});
await widget.app.connect(c);
if (mounted && widget.app.client == null && widget.app.lastError != null) {
setState(() {
_connecting = false;
_editing = true;
_edit = c;
_label = c.label;
_url = c.url;
_proxy = c.proxy;
_insecure = c.insecure;
_fingerprint = c.fingerprint;
_password = '';
_formError = widget.app.lastError;
});
_focusPasswordIfNeeded(_formError);
widget.app.clearLastError();
} else if (mounted) {
setState(() => _connecting = false);
}
}
void _startEdit(Connection? c) {
widget.app.error = null;
widget.app.clearLastError();
setState(() {
_editing = true;
_editNew = c == null;
_edit = c;
_label = c?.label ?? '';
_url = c?.url ?? '';
_proxy = c?.proxy ?? '';
_insecure = c?.insecure ?? false;
_fingerprint = c?.fingerprint ?? '';
_password = '';
_formError = null;
});
}
Widget _form() {
final theme = Theme.of(context);
return Scaffold(
appBar: AppBar(
leading: IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () {
widget.app.error = null;
widget.app.clearLastError();
setState(() => _editing = false);
},
),
title: Text(_editNew ? '添加服务器' : '连接 ${_edit!.label}'),
),
body: ListView(
padding: const EdgeInsets.all(16),
children: [
_labelText('名称'),
TextField(
controller: TextEditingController(text: _label),
onChanged: (v) => _label = v,
decoration: const InputDecoration(hintText: '如 我的电脑', border: OutlineInputBorder()),
),
const SizedBox(height: 12),
if (_edit?.isRelay == true) ...[
const ListTile(
contentPadding: EdgeInsets.zero,
leading: Icon(Icons.lock_outline, size: 20),
title: Text('通过 Relay 连接'),
subtitle: Text('端到端加密;服务器与设备令牌保持不变'),
),
] else ...[
_labelText('服务器地址'),
TextField(
controller: TextEditingController(text: _url),
onChanged: (v) => _url = v,
keyboardType: TextInputType.url,
decoration: const InputDecoration(
hintText: 'http://192.168.1.10:3000', border: OutlineInputBorder()),
),
const SizedBox(height: 12),
_labelText('代理(可选)'),
TextField(
controller: TextEditingController(text: _proxy),
onChanged: (v) => _proxy = v,
keyboardType: TextInputType.url,
decoration: const InputDecoration(
hintText: 'http://… 或 socks5://…', border: OutlineInputBorder()),
),
const SizedBox(height: 12),
_labelText('自签证书指纹(可选)'),
TextField(
controller: TextEditingController(text: _fingerprint),
onChanged: (v) => _fingerprint = v,
decoration: const InputDecoration(hintText: 'SHA-256 十六进制', border: OutlineInputBorder()),
),
SwitchListTile(
contentPadding: EdgeInsets.zero,
title: const Text('信任自签名证书'),
value: _insecure,
onChanged: (v) => setState(() => _insecure = v),
),
// Shown for new servers too: a password-protected instance rejects
// the first attempt, and this is where the password goes.
_labelText('密码(如果需要)'),
TextField(
controller: TextEditingController(text: _password),
focusNode: _passwordFocus,
onChanged: (v) => _password = v,
obscureText: true,
decoration: const InputDecoration(
hintText: '服务器密码;服务器未设置可留空',
border: OutlineInputBorder()),
),
],
if (_formError != null)
Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(_formError!,
style: TextStyle(color: theme.colorScheme.error)),
),
const SizedBox(height: 16),
FilledButton(
onPressed: _connecting ? null : _submit,
child: _connecting
? const SizedBox(
height: 20, width: 20, child: CircularProgressIndicator(strokeWidth: 2))
: const Text('连接'),
),
],
),
);
}
Widget _labelText(String s) => Padding(
padding: const EdgeInsets.only(bottom: 4),
child: Text(s, style: Theme.of(context).textTheme.bodySmall),
);
Future<void> _submit() async {
setState(() {
_connecting = true;
_formError = null;
});
final relay = _edit?.isRelay == true ? _edit : null;
final c = relay != null
? relay.copyWith(
label: _label.isEmpty ? relay.label : _label,
lastUsedAt: DateTime.now().millisecondsSinceEpoch,
)
: Connection(
id: _edit?.id ?? Storage.newId(),
label: _label.isEmpty ? _hostOf(_url) : _label,
url: _url,
proxy: _proxy,
insecure: _insecure,
fingerprint: _fingerprint,
);
// Only a connection that works is saved (AppState saves it on success),
// so failed attempts do not pile up in the server list.
await widget.app.connect(c, password: _password);
if (mounted) {
if (widget.app.client != null) {
setState(() => _editing = false);
// Pushed on top of a live session list: return there.
if (Navigator.of(context).canPop()) Navigator.of(context).pop();
} else {
setState(() {
_connecting = false;
_formError = widget.app.lastError;
});
_focusPasswordIfNeeded(_formError);
widget.app.clearLastError();
}
}
}
/// The server asked for a password: put the caret where it is typed.
void _focusPasswordIfNeeded(String? message) {
if (message == null || !message.contains('需要密码')) return;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) _passwordFocus.requestFocus();
});
}
void _pair() {
widget.app.error = null;
widget.app.clearLastError();
showPairingDialog(context, widget.app);
}
void _confirmDelete(Connection c) {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text('删除服务器?'),
content: Text('“${c.label}”将从列表移除,设备令牌也会删除。'),
actions: [
TextButton(onPressed: () => Navigator.pop(context), child: const Text('取消')),
FilledButton(
onPressed: () {
Navigator.pop(context);
widget.app.removeConnection(c);
},
child: const Text('删除'),
),
],
),
);
}
static String _hostOf(String raw) {
try {
return Uri.parse(raw).host;
} catch (_) {
return raw;
}
}
}
/// Opens the paste-a-pairing-link dialog (also reachable from the connected
/// sidebar's server sheet).
Future<void> showPairingDialog(BuildContext context, AppState app) {
app.error = null;
app.clearLastError();
return showDialog<void>(
context: context,
builder: (_) => _PairingDialog(app: app),
);
}
/// Paste an `openchamber://connect` link and pair. The relay candidate in the
/// link is used when no direct address answers.
class _PairingDialog extends StatefulWidget {
final AppState app;
const _PairingDialog({required this.app});
@override
State<_PairingDialog> createState() => _PairingDialogState();
}
class _PairingDialogState extends State<_PairingDialog> {
final TextEditingController _text = TextEditingController();
bool _busy = false;
String? _error;
@override
void dispose() {
_text.dispose();
super.dispose();
}
Future<void> _paste() async {
final data = await Clipboard.getData(Clipboard.kTextPlain);
final text = data?.text?.trim() ?? '';
if (text.isEmpty || !mounted) return;
setState(() => _text.text = text);
}
Future<void> _connect() async {
final link = _text.text.trim();
if (link.isEmpty || _busy) return;
setState(() {
_busy = true;
_error = null;
});
final paired = await widget.app.connectWithPairing(link);
if (!mounted) return;
if (paired && widget.app.client != null) {
Navigator.of(context).pop();
return;
}
setState(() {
_busy = false;
_error = widget.app.lastError ?? '配对失败';
});
widget.app.clearLastError();
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return AlertDialog(
title: const Text('配对链接'),
content: SizedBox(
width: 420,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
'在 OpenChamber 网页端打开「连接设备」,把生成的链接粘贴到这里。'
'链接里带一次性密钥,以及直连地址或私有 Relay。',
style: TextStyle(fontSize: 12.5, color: theme.hintColor),
),
const SizedBox(height: 12),
TextField(
controller: _text,
autofocus: true,
minLines: 2,
maxLines: 4,
keyboardType: TextInputType.multiline,
style: const TextStyle(fontFamily: 'monospace', fontSize: 12),
decoration: const InputDecoration(
hintText: 'openchamber://connect?v=2&p=…',
border: OutlineInputBorder(),
),
),
if (_error != null)
Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(_error!,
style: TextStyle(color: theme.colorScheme.error, fontSize: 12.5)),
),
Align(
alignment: Alignment.centerLeft,
child: TextButton.icon(
onPressed: _busy ? null : _paste,
icon: const Icon(Icons.content_paste, size: 18),
label: const Text('从剪贴板粘贴'),
),
),
],
),
),
actions: [
TextButton(
onPressed: _busy ? null : () => Navigator.of(context).pop(),
child: const Text('取消'),
),
FilledButton(
onPressed: _busy ? null : _connect,
child: _busy
? const SizedBox(
width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 2))
: const Text('配对并连接'),
),
],
);
}
}