diff --git a/serverbox/lib/core/ssh_bundle/feishu_setup_policy.dart b/serverbox/lib/core/ssh_bundle/feishu_setup_policy.dart new file mode 100644 index 0000000..0079d65 --- /dev/null +++ b/serverbox/lib/core/ssh_bundle/feishu_setup_policy.dart @@ -0,0 +1,74 @@ +import 'package:server_box/data/model/app/scripts/script_consts.dart'; +import 'package:server_box/data/model/server/custom.dart'; +import 'package:server_box/data/model/server/server_private_info.dart'; + +ServerCustom memberServerCustom([ServerCustom? custom]) { + const scriptDir = ScriptConstants.scriptDirHome; + if (custom == null) return const ServerCustom(scriptDir: scriptDir); + if (custom.scriptDir?.trim().isNotEmpty == true) return custom; + + return ServerCustom( + cmds: custom.cmds, + preferTempDev: custom.preferTempDev, + tempIsCelsius: custom.tempIsCelsius, + logoUrl: custom.logoUrl, + netDev: custom.netDev, + scriptDir: scriptDir, + geo: custom.geo, + diskCountsNetwork: custom.diskCountsNetwork, + ); +} + +Spi? findFeishuServer({ + required Iterable servers, + required Iterable> devices, + required String username, + required String host, + required int port, +}) { + final serversById = {for (final server in servers) server.id: server}; + // An expired lease can still identify the server that should be reauthorized. + for (final device in devices) { + final id = device['server_id']; + if (device['revoked'] == true || + device['username'] != username || + id is! String || + id.isEmpty) { + continue; + } + final server = serversById[id]; + if (server != null) return server; + } + + return servers.where((server) { + final ssh = server.ssh; + return ssh != null && + ssh.ip == host && + ssh.port == port && + ssh.user == username; + }).firstOrNull; +} + +String feishuQueueServerId({ + required String currentId, + required String savedId, + required Iterable servers, +}) { + if (currentId.isEmpty || !servers.any((server) => server.id == currentId)) { + return savedId; + } + return currentId; +} + +String feishuLoginButtonLabel( + Iterable> devices, { + required DateTime now, +}) { + final hasActiveLease = devices.any((device) { + final expiresAt = device['lease_expires_at']; + return device['revoked'] != true && + expiresAt is int && + expiresAt > now.millisecondsSinceEpoch ~/ 1000; + }); + return hasActiveLease ? '重新授权连接' : '飞书登录'; +} diff --git a/serverbox/lib/view/widget/client_bundle_setup.dart b/serverbox/lib/view/widget/client_bundle_setup.dart index 33d34a9..31c2bcf 100644 --- a/serverbox/lib/view/widget/client_bundle_setup.dart +++ b/serverbox/lib/view/widget/client_bundle_setup.dart @@ -6,6 +6,7 @@ import 'package:fl_lib/fl_lib.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:server_box/core/ssh_bundle/bundle.dart'; +import 'package:server_box/core/ssh_bundle/feishu_setup_policy.dart'; import 'package:server_box/core/ssh_bundle/install.dart'; import 'package:server_box/data/model/server/server_private_info.dart'; import 'package:server_box/data/model/server/ssh_credential.dart'; @@ -88,10 +89,18 @@ class _ClientBundleSetupState extends ConsumerState { known['$id::${hostKey.split(' ').first}'] = SshClientBundle.fingerprint(hostKey); // Fail closed: persist the bundled pin before addServer starts connecting. Stores.setting.sshKnownHostFingerprints.putSync(known); - final server = Spi(id: id, name: '${bundle.username} · CPU', ssh: SshCredential( - ip: bundle.cpu['hostname']!, port: int.parse(bundle.cpu['port']!), user: bundle.username, - keyPath: key, proxyCommand: proxy, - )); + final server = Spi( + id: id, + name: '${bundle.username} · CPU', + ssh: SshCredential( + ip: bundle.cpu['hostname']!, + port: int.parse(bundle.cpu['port']!), + user: bundle.username, + keyPath: key, + proxyCommand: proxy, + ), + custom: memberServerCustom(), + ); if (!mounted) { throw const FormatException('导入已取消,请重新打开配置页'); } await ref.read(serversProvider.notifier).addServer(server); if (mounted) setState(() => _saved = true); diff --git a/serverbox/lib/view/widget/feishu_server_setup.dart b/serverbox/lib/view/widget/feishu_server_setup.dart index e217fb6..ac93265 100644 --- a/serverbox/lib/view/widget/feishu_server_setup.dart +++ b/serverbox/lib/view/widget/feishu_server_setup.dart @@ -7,6 +7,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:server_box/core/ssh_bundle/bundle.dart'; import 'package:server_box/core/ssh_bundle/device_login.dart'; +import 'package:server_box/core/ssh_bundle/feishu_setup_policy.dart'; import 'package:server_box/core/ssh_bundle/install.dart'; import 'package:server_box/core/utils/ssh_keygen.dart'; import 'package:server_box/data/model/server/server_private_info.dart'; @@ -165,10 +166,17 @@ class _FeishuServerSetupState extends ConsumerState { if (!bundle.matchesPrivateKey(await SshClientBundle.readPrivateKey(keyPath))) { throw const FormatException('返回的设备公钥不匹配,请重新登录'); } - final existing = Stores.server.fetch().where((server) => - server.ssh?.ip == bundle.cpu['hostname'] && - server.ssh?.port == int.parse(bundle.cpu['port']!) && - server.ssh?.user == bundle.username).firstOrNull; + await _loadDevices(); + if (_cancelled || !mounted) return; + final host = bundle.cpu['hostname']!; + final port = int.parse(bundle.cpu['port']!); + final existing = findFeishuServer( + servers: Stores.server.fetch(), + devices: _devices.map((device) => device.data), + username: bundle.username, + host: host, + port: port, + ); if (existing != null) { final confirmed = await showDialog(context: context, builder: (context) => AlertDialog( title: const Text('更新现有服务器连接?'), @@ -196,17 +204,42 @@ class _FeishuServerSetupState extends ConsumerState { await _writeRecord(directory, {...request.toJson(), 'server_id': id, 'username': bundle.username, 'lease_expires_at': result['expires_at']}); Stores.setting.sshKnownHostFingerprints.putSync(known); - final credential = SshCredential(ip: bundle.cpu['hostname']!, - port: int.parse(bundle.cpu['port']!), user: bundle.username, - keyPath: keyPath, proxyCommand: proxy); + final credential = SshCredential( + ip: host, + port: port, + user: bundle.username, + keyPath: keyPath, + proxyCommand: proxy, + ); final notifier = ref.read(serversProvider.notifier); + final custom = memberServerCustom(existing?.custom); if (existing == null) { - await notifier.addServer(Spi(id: id, name: '${bundle.username} · CPU', ssh: credential)); + await notifier.addServer(Spi( + id: id, + name: '${bundle.username} · CPU', + ssh: credential, + custom: custom, + )); } else { - await notifier.updateServer(existing, existing.copyWith(ssh: credential)); + await notifier.updateServer( + existing, + existing.copyWith(ssh: credential, custom: custom), + ); } _saved = true; if (mounted) setState(() => _message = '${bundle.username} 的个人服务器已配置,正在连接。'); + try { + final queueServer = Stores.setting.gpuQueueServer; + final currentId = queueServer.fetch(); + final selectedId = feishuQueueServerId( + currentId: currentId, + savedId: id, + servers: Stores.server.fetch(), + ); + if (selectedId != currentId) queueServer.putSync(selectedId); + } catch (_) { + if (mounted) setState(() => _error = '服务器已保存。任务服务关联失败,请在任务页选择。'); + } await _retireReplacedDevices(id, directory); } catch (_) { final persisted = Stores.server.fetch().any((s) => s.id == id && s.ssh?.keyPath == keyPath); @@ -286,8 +319,14 @@ class _FeishuServerSetupState extends ConsumerState { const SizedBox(height: 8), const Text('用本人飞书账号授权,自动配置服务器、终端和文件访问。'), const SizedBox(height: 16), - FilledButton.icon(onPressed: _busy ? null : _start, - icon: const Icon(Icons.login), label: Text(_saved ? '重新授权连接' : '飞书登录')), + FilledButton.icon( + onPressed: _busy ? null : _start, + icon: const Icon(Icons.login), + label: Text(feishuLoginButtonLabel( + _devices.map((device) => device.data), + now: DateTime.now(), + )), + ), if (_busy) const Padding(padding: EdgeInsets.symmetric(vertical: 12), child: LinearProgressIndicator()), if (_message != null) Padding(padding: const EdgeInsets.only(top: 12), child: Text(_message!)), if (_busy && request != null) ...[ diff --git a/serverbox/test/unit/ssh/feishu_setup_policy_test.dart b/serverbox/test/unit/ssh/feishu_setup_policy_test.dart new file mode 100644 index 0000000..b65df43 --- /dev/null +++ b/serverbox/test/unit/ssh/feishu_setup_policy_test.dart @@ -0,0 +1,188 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:server_box/core/ssh_bundle/feishu_setup_policy.dart'; +import 'package:server_box/data/model/server/custom.dart'; +import 'package:server_box/data/model/server/geo.dart'; +import 'package:server_box/data/model/server/server_private_info.dart'; +import 'package:server_box/data/model/server/ssh_credential.dart'; + +const _host = 'cpu.example.test'; +const _port = 2222; +const _username = 'test-member'; + +Spi _server( + String id, { + String host = _host, + int port = _port, + String username = _username, +}) => Spi( + id: id, + name: id, + ssh: SshCredential(ip: host, port: port, user: username), +); + +void main() { + group('member server script directory', () { + const homeDir = '~/.config/server_box'; + + test('defaults new servers and existing servers without custom fields', () { + final existing = _server('existing'); + + expect(memberServerCustom().scriptDir, homeDir); + expect(memberServerCustom(existing.custom).scriptDir, homeDir); + }); + + test('fills missing and blank directories while keeping other fields', () { + for (final scriptDir in [null, '', ' ']) { + final custom = ServerCustom( + cmds: const {'example': 'true'}, + preferTempDev: 'sensor-example', + tempIsCelsius: true, + logoUrl: 'https://assets.example.test/icon.png', + netDev: 'eth1', + scriptDir: scriptDir, + geo: GeoCoord.tryNew(0, 0), + diskCountsNetwork: true, + ); + + expect(memberServerCustom(custom).toJson(), { + ...custom.toJson(), + 'scriptDir': homeDir, + }); + } + }); + + test('keeps an explicit directory', () { + const custom = ServerCustom( + scriptDir: '~/.local/share/example', + netDev: 'eth1', + ); + + expect(memberServerCustom(custom), same(custom)); + }); + }); + + group('existing Feishu server', () { + final linked = _server('linked', host: 'old-cpu.example.test'); + final exact = _server('exact'); + final servers = [ + _server('wrong-user', username: 'another-member'), + _server('wrong-port', port: 2200), + linked, + exact, + ]; + + Spi? find(Iterable servers, List> devices) => + findFeishuServer( + servers: servers, + devices: devices, + username: _username, + host: _host, + port: _port, + ); + + test( + 'prefers a linked server even after the lease and SSH address change', + () { + expect( + find(servers, [ + {'username': _username, 'server_id': 'deleted'}, + { + 'username': _username, + 'server_id': linked.id, + 'lease_expires_at': 1, + }, + ]), + same(linked), + ); + }, + ); + + test( + 'falls back to the full SSH tuple if no device links this account', + () { + expect( + find(servers, [ + {'username': 'another-member', 'server_id': linked.id}, + {'username': _username, 'server_id': 'deleted'}, + {'username': _username, 'server_id': linked.id, 'revoked': true}, + {'username': _username}, + ]), + same(exact), + ); + }, + ); + + test('returns no match if the SSH tuple also differs', () { + expect(find(servers.where((server) => server != exact), []), isNull); + }); + }); + + group('default Feishu task service', () { + final servers = [_server('saved'), _server('selected')]; + + for (final (currentId, expectedId) in [ + ('', 'saved'), + ('deleted', 'saved'), + ('saved', 'saved'), + ('selected', 'selected'), + ]) { + test( + 'resolves ${currentId.isEmpty ? 'empty selection' : currentId} to $expectedId', + () { + expect( + feishuQueueServerId( + currentId: currentId, + savedId: 'saved', + servers: servers, + ), + expectedId, + ); + }, + ); + } + }); + + group('Feishu login button', () { + final expiry = DateTime.utc(2030, 1, 1); + final seconds = expiry.millisecondsSinceEpoch ~/ 1000; + + test('offers reauthorization while any unrevoked lease is active', () { + final devices = [ + {'lease_expires_at': seconds - 1}, + {'lease_expires_at': seconds + 1, 'revoked': true}, + {'lease_expires_at': seconds}, + ]; + + expect( + feishuLoginButtonLabel( + devices, + now: expiry.subtract(const Duration(milliseconds: 1)), + ), + '重新授权连接', + ); + expect(feishuLoginButtonLabel(devices, now: expiry), '飞书登录'); + expect( + feishuLoginButtonLabel( + devices, + now: expiry.add(const Duration(milliseconds: 1)), + ), + '飞书登录', + ); + }); + + test( + 'offers login with missing, pending, malformed, or revoked records', + () { + expect(feishuLoginButtonLabel([], now: expiry), '飞书登录'); + expect( + feishuLoginButtonLabel([ + {'expires_at': seconds + 1}, + {'lease_expires_at': '${seconds + 1}'}, + {'lease_expires_at': seconds + 1, 'revoked': true}, + ], now: expiry), + '飞书登录', + ); + }, + ); + }); +}