Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions scripts/test_queue_dart.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--flutter', default='flutter')
parser.add_argument('--widgets', action='store_true', help='Also render production GPU monitor widgets on the CPU Flutter test engine')
parser.add_argument('--ssh-bundle', action='store_true', help='Verify ZIP parsing, private key matching and protected SSH configuration')
parser.add_argument('--ssh-bundle', action='store_true', help='Verify ZIP parsing, private key matching, protected SSH configuration and device leases')
parser.add_argument('--offline', action='store_true', help='Use already cached pub dependencies')
args = parser.parse_args()
build = ROOT/'build'
Expand All @@ -22,7 +22,7 @@ def main():
(harness/'test').mkdir()
ui = ' material_ui: 1.5.0\n cupertino_ui: 1.1.1\n url_launcher: 6.3.2\n clock: ^1.1.3\n' if args.widgets else ''
if args.ssh_bundle:
ui += f' archive: ^4.3.0\n crypto: ^3.0.0\n pointycastle: ^4.0.0\n pinenacl: ^0.6.0\n dartssh2:\n path: "{ROOT / "serverbox/packages/dartssh2"}"\n'
ui += f' archive: ^4.3.0\n crypto: ^3.0.0\n path: ^1.9.1\n pointycastle: ^4.0.0\n pinenacl: ^0.6.0\n dartssh2:\n path: "{ROOT / "serverbox/packages/dartssh2"}"\n'
(harness/'pubspec.yaml').write_text("name: queue_protocol_checks\nenvironment:\n sdk: '>=3.11.0 <4.0.0'\ndependencies:\n flutter:\n sdk: flutter\n"+ui+"dev_dependencies:\n flutter_test:\n sdk: flutter\nflutter:\n uses-material-design: true\n")
names = ['queue_protocol_test.dart', 'queue_session_test.dart', 'queue_presentation_test.dart', 'mac_update_release_test.dart', 'mac_update_bridge_test.dart', 'local_calendar_test.dart', 'result_preview_test.dart']
if args.widgets:
Expand All @@ -31,8 +31,9 @@ def main():
source = (ROOT/'serverbox/test/unit/app'/name).read_text()
(harness/'test'/name).write_text(source)
if args.ssh_bundle:
(harness/'test/client_bundle_test.dart').write_text((ROOT/'serverbox/test/unit/ssh/client_bundle_test.dart').read_text())
(harness/'test/device_login_test.dart').write_text((ROOT/'serverbox/test/unit/ssh/device_login_test.dart').read_text())
for name in ['client_bundle_test.dart', 'device_login_test.dart', 'device_lease_test.dart']:
source = (ROOT/'serverbox/test/unit/ssh'/name).read_text()
(harness/'test'/name).write_text(source)
subprocess.run([args.flutter, 'pub', 'get', *(['--offline'] if args.offline else [])], cwd=harness, check=True)
# Resolve the real production library; no copies, mocks, or native app
# hooks. Only the small declared dependency graph is built by this harness.
Expand Down
84 changes: 84 additions & 0 deletions serverbox/lib/core/ssh_bundle/device_lease.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import 'dart:convert';
import 'dart:io';

import 'package:path/path.dart' as p;

enum DeviceLeaseState { valid, expired, revoked }

/// The displayable part of a locally installed Feishu device record.
class DeviceLease {
const DeviceLease._(this.state, this.expiresAt);

final DeviceLeaseState state;
final DateTime? expiresAt;

static const _maxFileBytes = 8192;
static const _maxEpochSeconds = 8640000000000; // DateTime's range.

/// Returns null when the SSH key has no recognizable device lease.
static DeviceLease? read(
String keyPath, {
required String bundlesRoot,
DateTime? now,
}) {
final root = p.normalize(bundlesRoot);
final device = p.dirname(keyPath);
final name = p.basename(device);
if (!p.isAbsolute(root) ||
keyPath.contains('\u0000') ||
!name.startsWith('device-') ||
name == 'device-' ||
keyPath != p.join(root, name, 'identity')) {
return null;
}
final session = p.join(device, 'session.json');
try {
if (FileSystemEntity.typeSync(root, followLinks: false) !=
FileSystemEntityType.directory ||
FileSystemEntity.typeSync(device, followLinks: false) !=
FileSystemEntityType.directory ||
FileSystemEntity.typeSync(keyPath, followLinks: false) !=
FileSystemEntityType.file ||
FileSystemEntity.typeSync(session, followLinks: false) !=
FileSystemEntityType.file ||
File(keyPath).lengthSync() > _maxFileBytes) {
return null;
}

final record = File(session).openSync();
try {
if (record.lengthSync() > _maxFileBytes) return null;
final bytes = record.readSync(_maxFileBytes + 1);
if (bytes.length > _maxFileBytes) return null;
final data = jsonDecode(utf8.decode(bytes));
if (data is! Map<String, dynamic>) return null;

final seconds = data['lease_expires_at'];
final expiresAt =
seconds is int &&
seconds >= -_maxEpochSeconds &&
seconds <= _maxEpochSeconds
? DateTime.fromMillisecondsSinceEpoch(seconds * 1000)
: null;
final revoked = data['revoked'];
if (revoked == true) {
return DeviceLease._(DeviceLeaseState.revoked, expiresAt);
}
if (expiresAt == null || (revoked != null && revoked is! bool)) {
return null;
}

final state = expiresAt.isAfter(now ?? DateTime.now())
? DeviceLeaseState.valid
: DeviceLeaseState.expired;
return DeviceLease._(state, expiresAt);
} finally {
record.closeSync();
}
} on FileSystemException {
return null;
} on FormatException {
return null;
}
}
}
155 changes: 115 additions & 40 deletions serverbox/lib/view/page/server/card/notices.dart
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
import 'dart:async';
import 'dart:ui' show lerpDouble;

import 'package:fl_lib/fl_lib.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:intl/intl.dart' show DateFormat;
import 'package:material_ui/material_ui.dart';
import 'package:server_box/core/extension/context/locale.dart';
import 'package:server_box/core/extension/server.dart';
import 'package:server_box/core/ssh_bundle/device_lease.dart';
import 'package:server_box/data/model/app/error.dart';
import 'package:server_box/data/model/server/server.dart';
import 'package:server_box/data/model/server/server_private_info.dart';
import 'package:server_box/data/model/server/try_limiter.dart';
import 'package:server_box/data/provider/server/all.dart';
Expand All @@ -15,6 +20,7 @@ import 'package:server_box/view/page/server/card/metric.dart';
import 'package:server_box/view/page/server/card/sizes.dart';
import 'package:server_box/view/page/server/metric_row.dart';
import 'package:server_box/view/page/server/reading_text.dart';
import 'package:server_box/view/widget/feishu_server_setup.dart';

// --- The states that are not a body ---
//
Expand All @@ -37,6 +43,9 @@ enum ServerNoticeKind {
/// Reaching it failed, and the machine said why.
failed,

/// The SSH device authorization has expired or was revoked.
feishuLease,

/// Nothing yet, and something on its way.
connecting,

Expand All @@ -49,8 +58,7 @@ enum ServerNoticeKind {
///
/// One set of words for the card in the list and for the page it opens
/// into, because the block that says them is one widget at two sizes — see
/// [ServerCardNotice]. The actions are the page's alone: they act on the
/// machine, and a card has nowhere to put them.
/// [ServerCardNotice].
class ServerNotice {
const ServerNotice({
required this.kind,
Expand All @@ -59,17 +67,18 @@ class ServerNotice {
this.text = '',
this.mono = '',
this.hint = '',
});
bool feishuAuthFailed = false,
}) : _feishuAuthFailed = feishuAuthFailed;

final ServerNoticeKind kind;
final bool _feishuAuthFailed;

final IconData glyph;

/// What went wrong, in this app's words.
final String title;

/// A sentence under the title, which the page has room for and a card has
/// not.
/// A sentence under the title.
final String text;

/// What the machine said, as it said it — the only part a search engine
Expand All @@ -79,8 +88,12 @@ class ServerNotice {
/// A line under the page's actions.
final String hint;

bool canReloginFeishu({bool? onMacOS}) =>
(onMacOS ?? isMacOS) &&
(kind == ServerNoticeKind.feishuLease || _feishuAuthFailed);

/// Which state this machine is in, and what to say about it.
static ServerNotice of(ServerState srv) {
static ServerNotice of(ServerState srv, {String? deviceBundlesRoot}) {
// Asked before the error is read: a connection this app has not been
// allowed to make has not been tried, so whatever else is on `err` is
// about an earlier address or an earlier setting.
Expand All @@ -103,12 +116,37 @@ class ServerNotice {
);
}
final err = srv.status.err;
final keyPath = srv.spi.sshOn?.keyPath;
final lease =
keyPath != null && (err != null || srv.conn < ServerConn.connected)
? DeviceLease.read(
keyPath,
bundlesRoot: deviceBundlesRoot ?? '${Paths.doc}/ssh-client-bundles',
)
: null;
if (lease != null && lease.state != DeviceLeaseState.valid) {
final revoked = lease.state == DeviceLeaseState.revoked;
final expiresAt = lease.expiresAt;
final expiry = expiresAt == null
? ''
: '${revoked ? '原授权' : '授权'}到期时间:'
'${DateFormat('yyyy-MM-dd HH:mm').format(expiresAt.toLocal())}。';
return ServerNotice(
kind: ServerNoticeKind.feishuLease,
glyph: Icons.lock_outline,
title: revoked ? '此设备的飞书授权已退出' : '飞书登录授权已过期',
text: '$expiry重新通过飞书登录可恢复服务器状态监控。',
mono: err?.message ?? '',
);
}
if (err != null) {
return ServerNotice(
kind: ServerNoticeKind.failed,
glyph: Icons.link_off,
title: err.solution ?? libL10n.fail,
mono: err.message ?? '',
feishuAuthFailed:
lease != null && err is SSHErr && err.type == SSHErrType.auth,
);
}
// `connected` counts as busy: the SSH path sits there through system
Expand Down Expand Up @@ -138,21 +176,37 @@ class ServerNotice {
/// What the card in the list says about this machine, or null when it says
/// nothing.
///
/// Only a failure it has seen. Waiting is said by the spinner beside the
/// name, and a machine that answered with nothing is a name with nothing
/// under it. A prompt from the far end is not a failure to report either:
/// the card offers a lock rather than a retry — see
/// `ServerStateUi.needsInteractiveAuth`.
/// A recorded failure or a device lease that needs attention. Other
/// interactive authentication prompts use the lock beside the name.
///
/// The page asks this too, of the block it holds room for: what the card
/// draws, the page paints only at the handover; what the card does not,
/// the page brings in itself — see `ServerDetailPage.readingsShowing`.
static ServerNotice? onCard(ServerState srv) {
if (srv.status.err == null || srv.needsInteractiveAuth) return null;
return of(srv);
static ServerNotice? onCard(ServerState srv, {String? deviceBundlesRoot}) {
if (srv.status.err == null &&
(!(srv.conn < ServerConn.connected) ||
srv.spi.sshOn?.keyPath == null)) {
return null;
}
final notice = of(srv, deviceBundlesRoot: deviceBundlesRoot);
if (notice.kind == ServerNoticeKind.feishuLease ||
(srv.status.err != null && !srv.needsInteractiveAuth)) {
return notice;
}
return null;
}
}

Widget feishuReloginButton(BuildContext context, {bool inErrorDialog = false}) {
return TextButton(
onPressed: () {
if (inErrorDialog) context.popDialog();
unawaited(FeishuServerSetup.open(context));
},
child: const Text('重新飞书登录'),
);
}

/// What the page draws a notice as, which is where a card's block is going.
///
/// Decided from where the card is going rather than from where it is, the
Expand Down Expand Up @@ -201,7 +255,7 @@ class ServerCardNotice extends StatelessWidget {
/// What a press does once this is the page's, in the
/// [ServerNoticeForm.card] form: the whole error, with what the app was
/// doing and the copy button a bug report needs. Null on a card, where the
/// card's own tap is the one that counts.
/// parent handles navigation and the Feishu button opens sign-in directly.
final VoidCallback? onTap;

/// Around the block at rest.
Expand Down Expand Up @@ -245,6 +299,7 @@ class ServerCardNotice extends StatelessWidget {
/// own.
Widget _page(BuildContext context, double t) {
final scheme = Theme.of(context).colorScheme;
final feishuLease = notice.kind == ServerNoticeKind.feishuLease;
// From the left of a card's block to the middle of the page. The lines
// of a title that wraps follow at the halfway point, by which the card is
// wide enough that none does.
Expand Down Expand Up @@ -334,25 +389,32 @@ class ServerCardNotice extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
title,
// The page's sentence under the title, which a card has no room
// for: it grows in from nothing, so what is under it travels
// rather than arriving lower by its height.
// A device lease explanation is visible at both sizes.
if (notice.text.isNotEmpty)
ServerCardReveal(
shown: t,
shown: feishuLease ? 1 : t,
child: Padding(
padding: const EdgeInsets.only(top: 13),
padding: EdgeInsets.only(
top: feishuLease ? lerpDouble(3, 13, t)! : 13,
),
child: Text(
notice.text,
textAlign: textAlign,
style: UIs.textGrey,
maxLines: feishuLease && t < 1 ? 3 : null,
overflow: feishuLease && t < 1 ? TextOverflow.ellipsis : null,
),
),
),
if (mono != null) ...[
SizedBox(height: lerpDouble(3, 13, t)),
mono,
],
if (mono != null) ...[SizedBox(height: lerpDouble(3, 13, t)), mono],
if (notice.canReloginFeishu() && t < 1)
ServerCardReveal(
shown: 1 - t,
child: Align(
alignment: AlignmentDirectional.centerStart,
child: feishuReloginButton(context),
),
),
],
),
);
Expand Down Expand Up @@ -408,6 +470,10 @@ class ServerCardNotice extends StatelessWidget {
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
if (notice.kind == ServerNoticeKind.feishuLease) ...[
const SizedBox(height: 3),
Text(notice.text, style: UIs.textGrey),
],
if (notice.mono.isNotEmpty) ...[
const SizedBox(height: 3),
Text(
Expand All @@ -421,24 +487,33 @@ class ServerCardNotice extends StatelessWidget {
);
final body = Padding(
padding: EdgeInsets.lerp(_pad, ServerCardSizes.focusPad, t)!,
child: Row(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(child: words),
// The page's card is a way in as well as a line, and says so. On
// a card there is no room to say it and nothing it would lead to
// that tapping the card does not.
SizedBox(width: 9 * t),
SizedBox(
width: 17 * t,
child: Opacity(
opacity: t,
child: const Icon(
Icons.chevron_right,
size: 17,
color: Colors.grey,
),
),
Row(
children: [
Expanded(child: words),
// The page's card is a way in as well as a line, and says so.
if (notice.kind != ServerNoticeKind.feishuLease ||
notice.mono.isNotEmpty ||
onTap != null) ...[
SizedBox(width: 9 * t),
SizedBox(
width: 17 * t,
child: Opacity(
opacity: t,
child: const Icon(
Icons.chevron_right,
size: 17,
color: Colors.grey,
),
),
),
],
],
),
if (notice.canReloginFeishu()) feishuReloginButton(context),
],
),
);
Expand Down
Loading
Loading