Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

feat(viewer): implement direct link and login functionality

Dev jacobdfd77c7c380a
diff --git a/desktop/lib/api/access_token_source.dart b/desktop/lib/api/access_token_source.dart
new file mode 100644
index 000000000..f0c9f6dd2
--- /dev/null
+++ b/desktop/lib/api/access_token_source.dart
@@ -0,0 +1,6 @@
+/// Hands out a usable SSO access token — refreshing first when it is stale, when [force]d, or when
+/// the caller just had [failedToken] refused. Only a viewer build holds one; everywhere else the
+/// harness CLI does, and signs the requests itself.
+abstract interface class AccessTokenSource {
+ Future<String> accessToken({bool force = false, String? failedToken});
+}
diff --git a/desktop/lib/api/api_client.dart b/desktop/lib/api/api_client.dart
index 6178fc0c6..00e8d3d23 100644
--- a/desktop/lib/api/api_client.dart
+++ b/desktop/lib/api/api_client.dart
@@ -4,55 +4,57 @@ import '../auth/auth_session.dart';
import '../core/config.dart';
import '../core/models.dart';
import '../logging/http_log.dart';
+import 'access_token_source.dart';
+import 'bearer_auth_interceptor.dart';
-/// Control-plane REST client. Every call here goes to the LOCAL `harness` CLI
-/// (loopback, no credential — see CLAUDE.md's naming/architecture notes for why), which proxies to
-/// the real backend using its own saved SSO session. This app never holds a bearer token itself.
-/// Terminal bytes ride the local WS path (relayed transparently for non-local machines).
+/// Control-plane REST client.
+///
+/// In a desktop build every call goes to the LOCAL `harness` CLI (loopback, no credential — see
+/// CLAUDE.md's naming/architecture notes for why), which proxies to the real backend using its own
+/// saved SSO session, and this app never holds a bearer token itself. A viewer build has no CLI:
+/// given [auth], the same calls go straight to the backend, signed with the session the app holds.
+/// Terminal bytes ride the WS path either way.
class ApiClient {
final AppConfig config;
final AuthSession session;
- late final Dio _dio = attachHttpLog(
- Dio(
- BaseOptions(
- baseUrl: config.localCliBaseUrl,
- connectTimeout: const Duration(seconds: 15),
- receiveTimeout: const Duration(seconds: 30),
- // Let the API wrapper turn HTTP failures into short, user-facing
- // ApiExceptions. Transport failures still surface as DioExceptions.
- validateStatus: (status) =>
- status != null && status >= 200 && status < 600,
- ),
- ),
- );
+ final AccessTokenSource? auth;
+ late final Dio _dio = _buildDio();
- ApiClient({required this.config, required this.session});
+ ApiClient({required this.config, required this.session, this.auth});
- dynamic _unwrap(Response res) {
- final body = res.data;
- if (body is Map && body['success'] == true) {
- return body['data'];
- }
- final error = body is Map ? body['error'] : null;
- final serverMessage = error is Map ? error['message'] : null;
- throw ApiException(
- serverMessage is String && serverMessage.isNotEmpty
- ? serverMessage
- : 'Request failed (${res.statusCode})',
- status: res.statusCode,
+ Dio _buildDio() {
+ final dio = attachHttpLog(
+ Dio(
+ BaseOptions(
+ baseUrl: auth == null ? config.localCliBaseUrl : config.apiBaseUrl,
+ connectTimeout: const Duration(seconds: 15),
+ receiveTimeout: const Duration(seconds: 30),
+ // Let the API wrapper turn HTTP failures into short, user-facing
+ // ApiExceptions. Transport failures still surface as DioExceptions.
+ validateStatus: (status) =>
+ status != null && status >= 200 && status < 600,
+ ),
+ ),
);
+ final source = auth;
+ if (source != null) {
+ dio.interceptors.add(
+ BearerAuthInterceptor(source, dio, autonomousEnv: config.autonomousEnv),
+ );
+ }
+ return dio;
}
// -- auth (proxied by the local CLI — no credential on this leg) --
Future<Map<String, dynamic>?> me() async {
final res = await _dio.get('/api/auth/me');
- return _unwrap(res) as Map<String, dynamic>?;
+ return unwrapApiResponse(res) as Map<String, dynamic>?;
}
// -- machines (control plane, proxied by the local CLI) --
Future<List<Machine>> machines() async {
final res = await _dio.get('/api/machines');
- final data = _unwrap(res) as Map<String, dynamic>;
+ final data = unwrapApiResponse(res) as Map<String, dynamic>;
final list = data['machines'] as List<dynamic>? ?? [];
return list
.map((e) => Machine.fromJson(e as Map<String, dynamic>))
@@ -68,7 +70,7 @@ class ApiClient {
data: {'name': name},
options: Options(headers: {'x-adapter-local': '1'}),
);
- final data = _unwrap(res) as Map<String, dynamic>;
+ final data = unwrapApiResponse(res) as Map<String, dynamic>;
return data['name'] as String?;
}
@@ -77,7 +79,7 @@ class ApiClient {
'/api/machines/$machineId',
options: Options(headers: {'x-adapter-local': '1'}),
);
- _unwrap(res);
+ unwrapApiResponse(res);
}
}
@@ -92,3 +94,21 @@ class ApiException implements Exception {
bool isUnauthorizedError(Object error) =>
error is DioException && error.response?.statusCode == 401 ||
error is ApiException && error.status == 401;
+
+/// Unwraps the backend's `{success, data, error}` envelope, which both legs
+/// speak: the CLI's loopback server mirrors it, and the viewer's own auth calls
+/// (`viewer/direct_auth_api.dart`) read it straight from the backend.
+dynamic unwrapApiResponse(Response res) {
+ final body = res.data;
+ if (body is Map && body['success'] == true) {
+ return body['data'];
+ }
+ final error = body is Map ? body['error'] : null;
+ final serverMessage = error is Map ? error['message'] : null;
+ throw ApiException(
+ serverMessage is String && serverMessage.isNotEmpty
+ ? serverMessage
+ : 'Request failed (${res.statusCode})',
+ status: res.statusCode,
+ );
+}
diff --git a/desktop/lib/api/bearer_auth_interceptor.dart b/desktop/lib/api/bearer_auth_interceptor.dart
new file mode 100644
index 000000000..24f5f4f7f
--- /dev/null
+++ b/desktop/lib/api/bearer_auth_interceptor.dart
@@ -0,0 +1,56 @@
+import 'package:dio/dio.dart';
+
+import 'access_token_source.dart';
+
+/// Signs each request with the SSO bearer and the environment header the backend routes on, and
+/// retries a 401 once with a refreshed token — for a viewer build, what the harness CLI's
+/// `controlPlaneAuth` does for a desktop one.
+class BearerAuthInterceptor extends Interceptor {
+ BearerAuthInterceptor(this._auth, this._dio, {required this.autonomousEnv});
+
+ final AccessTokenSource _auth;
+ final Dio _dio;
+ final String autonomousEnv;
+
+ static const _tokenKey = 'bearer.token';
+ static const _retriedKey = 'bearer.retried';
+
+ @override
+ Future<void> onRequest(
+ RequestOptions options,
+ RequestInterceptorHandler handler,
+ ) async {
+ try {
+ final token = await _auth.accessToken();
+ options.headers['authorization'] = 'Bearer $token';
+ options.headers['x-autonomous-env'] = autonomousEnv;
+ options.extra[_tokenKey] = token;
+ handler.next(options);
+ } catch (error) {
+ handler.reject(DioException(requestOptions: options, error: error));
+ }
+ }
+
+ @override
+ Future<void> onResponse(
+ Response<dynamic> response,
+ ResponseInterceptorHandler handler,
+ ) async {
+ final options = response.requestOptions;
+ if (response.statusCode != 401 || options.extra[_retriedKey] == true) {
+ handler.next(response);
+ return;
+ }
+ try {
+ await _auth.accessToken(
+ force: true,
+ failedToken: options.extra[_tokenKey] as String?,
+ );
+ options.extra[_retriedKey] = true;
+ handler.resolve(await _dio.fetch<dynamic>(options));
+ } catch (_) {
+ // The refresh itself failed, so the 401 is the honest answer to hand back.
+ handler.next(response);
+ }
+ }
+}
diff --git a/desktop/lib/auth/cli_link.dart b/desktop/lib/auth/cli_link.dart
index e86b48469..ec9986d5d 100644
--- a/desktop/lib/auth/cli_link.dart
+++ b/desktop/lib/auth/cli_link.dart
@@ -2,6 +2,7 @@ import 'dart:convert';
import 'dart:io';
import '../core/harness_cli_runner.dart';
+import 'peer_link_client.dart';
/// Result of `harness remote-password set --stdin --json` — sets (or replaces) this machine's
/// persistent remote password, the shared secret another machine's `harness link connect` PAKE
@@ -77,7 +78,7 @@ class CliLinkListResult {
const CliLinkListResult({this.error, this.machines = const []});
}
-class CliLink {
+class CliLink implements PeerLinkClient {
final HarnessCliRunner _runner;
CliLink({HarnessCliRunner? runner}) : _runner = runner ?? HarnessCliRunner();
@@ -149,6 +150,7 @@ class CliLink {
/// `verifying`) as the handshake proceeds; best-effort UI feedback only, never required for
/// correctness. [displayName], when given, is how the CLI's error messages name the machine —
/// otherwise they show the raw [machineId], which is all a terminal user would have.
+ @override
Future<CliLinkConnectResult> connect(
String machineId,
String password, {
@@ -193,6 +195,7 @@ class CliLink {
}
/// Machines this one currently trusts (CLI-to-CLI, not the browser-pairing list).
+ @override
Future<CliLinkListResult> list() async {
final response = await _run(['link', 'list']);
if (response.error != null) {
@@ -218,6 +221,7 @@ class CliLink {
}
/// Removes a linked machine's trust pin. Null on success.
+ @override
Future<String?> unlink(String machineId) async {
final response = await _run(['link', 'unlink', machineId]);
if (response.error != null) return response.error;
diff --git a/desktop/lib/auth/cli_login.dart b/desktop/lib/auth/cli_login.dart
index caf396218..1fbb3af82 100644
--- a/desktop/lib/auth/cli_login.dart
+++ b/desktop/lib/auth/cli_login.dart
@@ -3,6 +3,7 @@ import 'dart:convert';
import 'dart:io';
import '../core/harness_cli_runner.dart';
+import 'sign_in_client.dart';
class CliAuthStatus {
final bool loggedIn;
@@ -39,12 +40,13 @@ class CliNotAvailableException implements Exception {
/// signed-in session, and driving `harness login --json`'s NDJSON event stream when it does not. The
/// CLI owns the SSO session end to end (`~/.harness/auth/session.json`) — this app never sees, stores,
/// or refreshes an access token itself.
-class CliLogin {
+class CliLogin implements SignInClient {
final HarnessCliRunner _runner;
Process? _activeProcess;
CliLogin({HarnessCliRunner? runner}) : _runner = runner ?? HarnessCliRunner();
+ @override
Future<CliAuthStatus> checkStatus() async {
final result = await _run(['auth', 'status', '--json']);
final line = _lastNonEmptyLine(result.stdout as String);
@@ -64,6 +66,7 @@ class CliLogin {
/// flow. Calls [onAuthorizeUrl] as soon as the CLI reports the SSO page to show, then resolves once
/// the CLI's own loopback callback server completes the flow (or throws on failure/cancellation).
/// The process is killed if [cancel] is called while this is in flight.
+ @override
Future<void> login({
required void Function(String url) onAuthorizeUrl,
}) async {
@@ -118,10 +121,12 @@ class CliLogin {
}
/// Aborts an in-flight [login] — used by the embedded sign-in webview's close button.
+ @override
void cancel() {
_activeProcess?.kill();
}
+ @override
Future<void> logout() async {
try {
await _run(['logout']);
diff --git a/desktop/lib/auth/link_errors.dart b/desktop/lib/auth/link_errors.dart
new file mode 100644
index 000000000..7b5d20c98
--- /dev/null
+++ b/desktop/lib/auth/link_errors.dart
@@ -0,0 +1,49 @@
+/// cli.ts `humanizeLinkError`: a password-link failure code as the sentence to show. Every branch,
+/// the fallback included, wraps the code in words — a bare code must never reach the screen.
+String humanizeLinkError(String code, String machineId, {DateTime? retryAt}) {
+ if (code == 'RATE_LIMITED') {
+ if (retryAt == null) {
+ return 'Too many wrong attempts on $machineId. Wait a few minutes and try again.';
+ }
+ final minutes = (retryAt.difference(DateTime.now()).inSeconds / 60).ceil();
+ return minutes > 0
+ ? 'Too many wrong attempts on $machineId. Try again in $minutes minute${minutes == 1 ? '' : 's'}.'
+ : 'Too many wrong attempts on $machineId. Try again now.';
+ }
+ const closedPrefix = 'CONNECTION_CLOSED:';
+ if (code.startsWith(closedPrefix)) {
+ return 'The connection closed unexpectedly (code ${code.substring(closedPrefix.length)}) '
+ 'before linking finished. Try again.';
+ }
+ return switch (code) {
+ 'NO_REMOTE_PASSWORD' =>
+ 'Machine $machineId has no remote password set. Ask its operator to run '
+ '`harness remote-password set` there first.',
+ 'BAD_INTENT' =>
+ 'The connection request was malformed — this usually means a version mismatch. '
+ 'Update harness on both machines and try again.',
+ 'WRONG_PASSWORD' =>
+ 'That password is wrong. Check it against the other machine and try again.',
+ 'TIMEOUT' =>
+ "Machine $machineId didn't respond in time. Make sure it's running `harness start` "
+ 'and reachable, then try again.',
+ 'SEND_FAILED' =>
+ 'Could not reach the relay to start linking. Check your network connection and try again.',
+ 'DERIVE_FAILED' =>
+ 'Could not process the password locally. Try again; if it persists, restart the app and retry.',
+ 'SELECT_FAILED' =>
+ "Could not find machine $machineId, or it isn't reachable right now. Check that it has "
+ 'run `harness start`.',
+ 'PAIR_FAILED' =>
+ "Linking failed on $machineId's side. Try again; if it persists, check its status there "
+ 'with `harness status`.',
+ 'PROTOCOL_ERROR' =>
+ 'Something unexpected happened during the handshake. Try again; if it persists, update '
+ 'harness on the other machine.',
+ 'CONNECTION_ERROR' =>
+ 'Could not reach the relay. Check your network connection and try again.',
+ _ =>
+ 'Linking failed ($code). Try again; if it persists, check the other machine is on the '
+ 'latest harness version.',
+ };
+}
diff --git a/desktop/lib/auth/peer_link_client.dart b/desktop/lib/auth/peer_link_client.dart
new file mode 100644
index 000000000..eb0976fa3
--- /dev/null
+++ b/desktop/lib/auth/peer_link_client.dart
@@ -0,0 +1,21 @@
+import 'cli_link.dart';
+
+/// Linking to another machine by its remote password: `harness link connect/list/unlink` through
+/// [CliLink], or the same exchange run by the app itself in a viewer build
+/// (`viewer/direct_link.dart`).
+abstract interface class PeerLinkClient {
+ /// [onProgress] gets the CLI's stage names (`connecting`, `deriving_key`, `exchanging`,
+ /// `verifying`) — best-effort feedback, never needed for correctness. [displayName] is how an
+ /// error names the machine; without it, all an error has to go on is the raw [machineId].
+ Future<CliLinkConnectResult> connect(
+ String machineId,
+ String password, {
+ void Function(String stage)? onProgress,
+ String? displayName,
+ });
+
+ Future<CliLinkListResult> list();
+
+ /// Null on success.
+ Future<String?> unlink(String machineId);
+}
diff --git a/desktop/lib/auth/sign_in_client.dart b/desktop/lib/auth/sign_in_client.dart
new file mode 100644
index 000000000..70c80835c
--- /dev/null
+++ b/desktop/lib/auth/sign_in_client.dart
@@ -0,0 +1,16 @@
+import 'cli_login.dart';
+
+/// Whether the app is signed in, and how it signs in — the seam between the two kinds of build.
+///
+/// [CliLogin] asks the local harness CLI, which holds the session. A viewer build has no CLI and
+/// holds its own (`viewer/direct_login.dart`).
+abstract interface class SignInClient {
+ Future<CliAuthStatus> checkStatus();
+
+ /// Resolves once signed in; throws on failure or [cancel]. [onAuthorizeUrl] gets the SSO page.
+ Future<void> login({required void Function(String url) onAuthorizeUrl});
+
+ void cancel();
+
+ Future<void> logout();
+}
diff --git a/desktop/lib/bootstrap/environment_provisioner.dart b/desktop/lib/bootstrap/environment_provisioner.dart
index 9dda63396..54855408d 100644
--- a/desktop/lib/bootstrap/environment_provisioner.dart
+++ b/desktop/lib/bootstrap/environment_provisioner.dart
@@ -1,3 +1,4 @@
+import '../core/host_platform.dart';
import 'dart:async';
import 'dart:convert';
import 'dart:io';
@@ -280,7 +281,7 @@ class EnvironmentProvisioner {
if (home != null && home.isNotEmpty) return home;
final profile = Platform.environment['USERPROFILE'];
if (profile != null && profile.isNotEmpty) return profile;
- return null;
+ return containerHome;
}
static String _defaultHarnessHome() {
diff --git a/desktop/lib/core/desktop_window.dart b/desktop/lib/core/desktop_window.dart
index cbbf6b261..e7f720303 100644
--- a/desktop/lib/core/desktop_window.dart
+++ b/desktop/lib/core/desktop_window.dart
@@ -6,6 +6,16 @@ import 'package:flutter/services.dart';
import '../shared/theme/color_palette.dart';
import 'build_identity.dart';
+/// Whether this build runs inside a window the app is allowed to manage.
+///
+/// `window_manager` ships implementations for macOS, Windows and Linux only.
+/// Its Dart surface still compiles everywhere, so on any other platform the
+/// calls below are not a compile error — they are a `MissingPluginException` at
+/// runtime, thrown from `main` before the first frame. The guard therefore has
+/// to live here rather than being left to each call site to remember.
+bool get hasManagedWindow =>
+ Platform.isMacOS || Platform.isWindows || Platform.isLinux;
+
/// Configures the native window before the first Flutter frame.
///
/// On macOS, AppKit places Swarm tabs beside the system traffic lights in a
@@ -14,6 +24,7 @@ import 'build_identity.dart';
Future<void> configureDesktopWindow({
HarnessPalette palette = HarnessPalette.graphite,
}) async {
+ if (!hasManagedWindow) return;
await windowManager.ensureInitialized();
final options = WindowOptions(
size: const Size(1280, 800),
@@ -45,6 +56,7 @@ Future<void> configureDesktopWindow({
/// both run, in that order. Failures are swallowed on purpose: the plugin throws on a platform without a
/// window server (a headless test host), and losing the palette is worse than losing the raise.
Future<void> revealWindow() async {
+ if (!hasManagedWindow) return;
try {
if (await windowManager.isMinimized()) await windowManager.restore();
await windowManager.show();
diff --git a/desktop/lib/core/harness_cli_runner.dart b/desktop/lib/core/harness_cli_runner.dart
index 0fb1073bd..0cbc18d69 100644
--- a/desktop/lib/core/harness_cli_runner.dart
+++ b/desktop/lib/core/harness_cli_runner.dart
@@ -1,3 +1,4 @@
+import 'host_platform.dart';
import 'dart:io';
import '../logging/cli_transcript.dart';
@@ -56,7 +57,9 @@ class HarnessCliRunner {
// before any UI existed to report it.
final home = Platform.environment['HOME'];
final profile = Platform.environment['USERPROFILE'];
- final resolved = home != null && home.isNotEmpty ? home : profile;
+ final resolved = home != null && home.isNotEmpty
+ ? home
+ : (profile != null && profile.isNotEmpty ? profile : containerHome);
if (resolved == null || resolved.isEmpty) {
throw StateError('Could not resolve the current user home directory');
}
diff --git a/desktop/lib/core/harness_file_store.dart b/desktop/lib/core/harness_file_store.dart
index 6d0994fd3..ced3f888d 100644
--- a/desktop/lib/core/harness_file_store.dart
+++ b/desktop/lib/core/harness_file_store.dart
@@ -2,6 +2,8 @@ import 'dart:async';
import 'dart:convert';
import 'dart:io';
+import 'host_platform.dart';
+import 'viewer_mode.dart';
import 'local_key_value_store.dart';
/// Versioned Harness desktop state stored under the user's Harness home.
@@ -12,7 +14,15 @@ import 'local_key_value_store.dart';
class HarnessFileStore implements BatchLocalKeyValueStore {
static const schemaVersion = 1;
// Separate from production; the CLI still owns shared authentication and links.
- static const directoryName = 'desktop-app-v2';
+ //
+ // A viewer build is a different product holding a different session — its own
+ // SSO tokens and its own E2EE identity — so it lives BESIDE the desktop one
+ // rather than in it. On a Mac, where the viewer path is developed with
+ // `--dart-define=HARNESS_VIEWER_MODE=true`, the two would otherwise overwrite
+ // each other's state.
+ static final String directoryName = kViewerMode
+ ? 'viewer-app-v2'
+ : 'desktop-app-v2';
static const fileName = 'state.json';
static const lockFileName = 'state.lock';
@@ -39,6 +49,7 @@ class HarnessFileStore implements BatchLocalKeyValueStore {
if (drive != null && path != null) home = '$drive$path';
}
}
+ if (home == null || home.isEmpty) home = containerHome;
if (home == null || home.isEmpty) {
throw StateError('Could not resolve the current user home directory');
}
@@ -188,8 +199,10 @@ class HarnessFileStore implements BatchLocalKeyValueStore {
Future<void> _makePrivateFile(File file) => _chmod(file.path, '600');
+ /// Windows has no POSIX modes, and a phone neither needs one — the app's
+ /// sandbox is already private to it — nor can spawn `/bin/chmod` at all.
Future<void> _chmod(String path, String mode) async {
- if (Platform.isWindows) return;
+ if (Platform.isWindows || isMobileHost) return;
final result = await Process.run('/bin/chmod', [mode, path]);
if (result.exitCode != 0) {
throw FileSystemException('Could not set mode $mode', path);
diff --git a/desktop/lib/core/host_platform.dart b/desktop/lib/core/host_platform.dart
new file mode 100644
index 000000000..91db6e27e
--- /dev/null
+++ b/desktop/lib/core/host_platform.dart
@@ -0,0 +1,34 @@
+import 'dart:io';
+
+/// True where the app is a guest inside a sandboxed container rather than a
+/// desktop process of its own: iOS and Android.
+bool get isMobileHost => Platform.isIOS || Platform.isAndroid;
+
+/// The app's own container, on the platforms that give a process no `HOME`.
+///
+/// An app on iOS or Android does not live in a user's home directory; it lives
+/// in a private container, and `Platform.environment` there carries no `HOME`
+/// to point at it. The container root is the parent of the temporary directory
+/// the platform DOES name — `NSTemporaryDirectory()` is `<container>/tmp`, and
+/// Android's cache directory is `<data dir>/cache` — which makes it reachable
+/// synchronously, without a plugin.
+///
+/// Synchronously matters: the callers read it from field initializers and from
+/// `installFileLogs`, which is deliberately not `async` so that the first lines
+/// about starting up are not lost to a directory probe. Not adding a plugin
+/// matters too — registering one rewrites the macOS SPM package list for every
+/// desktop build as well (see CLAUDE.md).
+///
+/// `null` off those platforms, so a desktop host with no `HOME` still fails the
+/// way it always has rather than quietly writing somewhere unexpected.
+///
+String? get containerHome {
+ if (!isMobileHost) return null;
+ final container = Directory.systemTemp.parent.path;
+ // An iOS app's container ROOT is not writable; `Library/Application Support`
+ // is, and is where Apple expects state that is not user documents. Android's
+ // data directory root is writable, so it takes the container as it is.
+ return Platform.isIOS
+ ? '$container/Library/Application Support'
+ : container;
+}
diff --git a/desktop/lib/core/viewer_mode.dart b/desktop/lib/core/viewer_mode.dart
new file mode 100644
index 000000000..431d0c562
--- /dev/null
+++ b/desktop/lib/core/viewer_mode.dart
@@ -0,0 +1,17 @@
+import 'dart:io';
+
+/// Whether this build is a VIEWER: a window onto the user's machines and nothing more.
+///
+/// No harness CLI runs beside it and no agent is ever hosted here, so every machine — this computer
+/// included, if it is a Harness machine at all — is reached through the relay, with this app
+/// terminating the end-to-end encryption the CLI terminates everywhere else (see `lib/viewer/`).
+///
+/// True on iOS, Android and Windows, where the CLI cannot run: tmux is not optional to it, and a
+/// phone will not host a Node runtime or spawn a process at all. On macOS and Linux only with
+/// `--dart-define=HARNESS_VIEWER_MODE=true`, which is how the path is developed and tested on a Mac
+/// against real machines.
+final bool kViewerMode =
+ const bool.fromEnvironment('HARNESS_VIEWER_MODE') ||
+ Platform.isIOS ||
+ Platform.isAndroid ||
+ Platform.isWindows;
diff --git a/desktop/lib/e2ee/bytes.dart b/desktop/lib/e2ee/bytes.dart
new file mode 100644
index 000000000..732c55a6e
--- /dev/null
+++ b/desktop/lib/e2ee/bytes.dart
@@ -0,0 +1,63 @@
+import 'dart:convert';
+import 'dart:math';
+import 'dart:typed_data';
+
+/// Byte helpers for the E2EE port — the Dart side of core.ts's "portable helpers".
+
+/// A source of random bytes. Production code takes the default ([secureRandomBytes]); tests pass
+/// the seeded generator core.test.ts uses, so key material matches the CLI's vectors.
+typedef Rng = Uint8List Function(int length);
+
+final Random _secure = Random.secure();
+
+Uint8List secureRandomBytes(int length) {
+ final out = Uint8List(length);
+ for (var i = 0; i < length; i++) {
+ out[i] = _secure.nextInt(256);
+ }
+ return out;
+}
+
+String b64e(List<int> bytes) => base64Encode(bytes);
+
+Uint8List b64d(String text) => base64Decode(text);
+
+Uint8List utf8Bytes(String text) => Uint8List.fromList(utf8.encode(text));
+
+Uint8List concatBytes(List<List<int>> parts) {
+ final builder = BytesBuilder(copy: false);
+ for (final part in parts) {
+ builder.add(part);
+ }
+ return builder.takeBytes();
+}
+
+/// core.ts `lvCat`: every part prefixed with its 4-byte big-endian length, so no two different
+/// transcripts can encode to the same bytes. A [String] part is its UTF-8.
+Uint8List lvCat(List<Object> parts) {
+ final builder = BytesBuilder(copy: false);
+ for (final part in parts) {
+ final bytes = switch (part) {
+ String text => utf8Bytes(text),
+ List<int> raw => raw,
+ _ => throw ArgumentError.value(part, 'part', 'must be a String or bytes'),
+ };
+ builder
+ ..add((ByteData(4)..setUint32(0, bytes.length)).buffer.asUint8List())
+ ..add(bytes);
+ }
+ return builder.takeBytes();
+}
+
+/// Equality that does not stop at the first differing byte — for MAC tags.
+bool ctEqual(List<int> a, List<int> b) {
+ if (a.length != b.length) return false;
+ var diff = 0;
+ for (var i = 0; i < a.length; i++) {
+ diff |= a[i] ^ b[i];
+ }
+ return diff == 0;
+}
+
+String hexOf(List<int> bytes) =>
+ bytes.map((byte) => byte.toRadixString(16).padLeft(2, '0')).join();
diff --git a/desktop/lib/e2ee/cpace.dart b/desktop/lib/e2ee/cpace.dart
new file mode 100644
index 000000000..31bc573b1
--- /dev/null
+++ b/desktop/lib/e2ee/cpace.dart
@@ -0,0 +1,103 @@
+import 'dart:typed_data';
+
+import 'bytes.dart';
+import 'keys.dart';
+import 'primitives.dart';
+import 'ristretto.dart';
+import 'ristretto_field.dart';
+
+/// The CPace-style PAKE over ristretto255 — core.ts's cpace*, kcKeys, pairKey and pairBind*.
+///
+/// Roles as core.ts names them: 'a' is the machine being joined, 'b' is the one joining (this app).
+
+const _cpaceDsi = 'e2e-cpace-ristretto255-v1';
+
+/// core.ts `randScalar`: uniform in [1, L) from 64 random bytes.
+BigInt randScalar(Rng rng) {
+ for (var i = 0; i < 8; i++) {
+ final scalar = bytesToNumberLe(rng(64)) % curveOrder;
+ if (scalar != BigInt.zero) return scalar;
+ }
+ throw StateError('randScalar: exhausted');
+}
+
+/// A CPace half: the secret [scalar] this side keeps, and the [share] it sends (core.ts's y and Y).
+typedef CpaceStart = ({BigInt scalar, Uint8List share});
+
+CpaceStart cpaceStart(RistrettoPoint generator, [Rng rng = secureRandomBytes]) {
+ final scalar = randScalar(rng);
+ return (scalar: scalar, share: generator.multiply(scalar).toBytes());
+}
+
+/// K = peerShare^scalar. Throws on an invalid or identity point — attack input, never a typo.
+Uint8List cpaceShared(List<int> peerShare, BigInt scalar) {
+ final shared = RistrettoPoint.fromBytes(peerShare).multiply(scalar);
+ if (shared.equals(RistrettoPoint.zero)) {
+ throw StateError('cpace: identity shared point');
+ }
+ return shared.toBytes();
+}
+
+Uint8List cpaceIsk(
+ List<int> sid,
+ List<int> shared,
+ List<int> shareA,
+ List<int> shareB,
+) => sha512(
+ lvCat([
+ '${_cpaceDsi}_ISK',
+ sid,
+ shared,
+ lvCat([shareA, 'a']),
+ lvCat([shareB, 'b']),
+ ]),
+);
+
+Uint8List transcriptHash(
+ List<int> sid,
+ String ci,
+ List<int> shareA,
+ List<int> shareB,
+) => sha512(lvCat([sid, ci, lvCat([shareA, 'a']), lvCat([shareB, 'b'])]));
+
+/// Key-confirmation MAC keys: [adapter] proves the joined machine's side, [web] the joiner's.
+({Uint8List adapter, Uint8List web}) kcKeys(List<int> isk, String ci) {
+ final kc = hkdfSha256(
+ isk,
+ salt: utf8Bytes(ci),
+ info: utf8Bytes('e2e-kc-v1'),
+ length: 64,
+ );
+ return (
+ adapter: Uint8List.sublistView(kc, 0, 32),
+ web: Uint8List.sublistView(kc, 32, 64),
+ );
+}
+
+Uint8List macTag(List<int> key, List<int> transcript) =>
+ hmacSha256(key, transcript);
+
+bool macVerify(List<int> key, List<int> transcript, List<int> tag) =>
+ ctEqual(macTag(key, transcript), tag);
+
+/// Seals the identity exchange inside the PAKE.
+Uint8List pairKey(List<int> isk, String ci) => hkdfSha256(
+ isk,
+ salt: utf8Bytes(ci),
+ info: utf8Bytes('e2e-id-v1'),
+ length: 32,
+);
+
+Future<Uint8List> pairBindSig(E2eeIdentity identity, List<int> transcript) =>
+ identity.sign(concatBytes([utf8Bytes('e2e-pair-bind'), transcript]));
+
+Future<bool> pairBindVerify(
+ List<int> pub,
+ List<int> transcript,
+ List<int> sig,
+) =>
+ verifySignature(
+ pub,
+ concatBytes([utf8Bytes('e2e-pair-bind'), transcript]),
+ sig,
+ );
diff --git a/desktop/lib/e2ee/envelope.dart b/desktop/lib/e2ee/envelope.dart
new file mode 100644
index 000000000..a5aa61097
--- /dev/null
+++ b/desktop/lib/e2ee/envelope.dart
@@ -0,0 +1,114 @@
+import 'dart:convert';
+import 'dart:typed_data';
+
+import 'bytes.dart';
+import 'primitives.dart';
+
+/// core.ts's frame-payload envelope: `{__e2e: {v, k, n, ct, epoch?}}` stands in for a frame's
+/// payload while its `type` stays readable, so the relay can route what it cannot read.
+
+const int e2eVersion = 1;
+
+/// Frames this client must send as ciphertext — core.ts `ENCRYPTED_DOWN_TYPES`. test/e2ee/ holds it
+/// to the CLI's own list, because a type missing here fails nowhere: the frame simply leaves in the
+/// clear, and for terminal_* the relay then drops it as TERMINAL_FRAME_REJECTED.
+const Set<String> encryptedDownTypes = {
+ 'message',
+ 'question_response',
+ 'agents_list',
+ 'sessions_list',
+ 'session_get',
+ 'models_list',
+ 'agent_create',
+ 'agent_delete',
+ 'agent_restart',
+ 'agent_recent',
+ 'agent_update',
+ 'agent_files',
+ 'agent_read_file',
+ 'fs_list_dir',
+ 'codex_profiles_list',
+ 'codex_profile_link',
+ 'device_e2ee_pair',
+ 'e2ee_pairings_list',
+ 'e2ee_pairing_unpair',
+ 'e2ee_pairings_unpair_all',
+ 'e2ee_browser_link_create',
+ 'terminal_capabilities',
+ 'terminal_open',
+ 'terminal_alive',
+ 'terminal_ack',
+ 'terminal_input',
+ 'terminal_resize',
+ 'terminal_resync',
+ 'terminal_close',
+ 'terminal_scroll',
+ 'terminal_chunked_upload_begin',
+ 'terminal_chunked_upload_cancel',
+ 'p2p_offer',
+ 'p2p_answer',
+ 'p2p_ice_candidate',
+ 'p2p_abort',
+};
+
+Uint8List _aad(int v, String type, String dbSessionId, String k, String epoch) =>
+ utf8Bytes('$v|$type|$dbSessionId|$k|$epoch');
+
+/// Seals [payload] under [key]: [k] is 'p' (pairwise session) or 'g' (the machine's group key,
+/// which also carries an [epoch]).
+Map<String, Object?> wrapPayload(
+ List<int> key,
+ String k,
+ int counter,
+ String frameType,
+ String? dbSessionId,
+ Object? payload, {
+ String? epoch,
+}) {
+ final aad = _aad(e2eVersion, frameType, dbSessionId ?? '', k, epoch ?? '');
+ final sealed = aeadSeal(key, counter, aad, utf8Bytes(jsonEncode(payload)));
+ return {
+ '__e2e': {
+ 'v': e2eVersion,
+ 'k': k,
+ 'n': counter,
+ 'ct': b64e(sealed),
+ 'epoch': ?epoch,
+ },
+ };
+}
+
+/// The payload object [wrapPayload] sealed; null when it does not open — a wrong key or counter, or
+/// an AAD (type, session, epoch) other than the one it was sealed under.
+Map<String, dynamic>? unwrapPayload(
+ List<int> key,
+ Map<String, dynamic> env,
+ String frameType,
+ String? dbSessionId,
+) {
+ final v = env['v'], k = env['k'], n = env['n'], ct = env['ct'];
+ final epoch = env['epoch'] ?? '';
+ if (v is! int || k is! String || n is! int || ct is! String || epoch is! String) {
+ return null;
+ }
+ final Uint8List sealed;
+ try {
+ sealed = b64d(ct);
+ } on FormatException {
+ return null;
+ }
+ final clear = aeadOpen(key, n, _aad(v, frameType, dbSessionId ?? '', k, epoch), sealed);
+ return clear == null ? null : jsonObjectOf(clear);
+}
+
+bool isWrapped(Object? payload) => payload is Map && payload.containsKey('__e2e');
+
+/// UTF-8 JSON that must be an object; null for anything else.
+Map<String, dynamic>? jsonObjectOf(List<int> utf8Json) {
+ try {
+ final value = jsonDecode(utf8.decode(utf8Json));
+ return value is Map<String, dynamic> ? value : null;
+ } on FormatException {
+ return null;
+ }
+}
diff --git a/desktop/lib/e2ee/keys.dart b/desktop/lib/e2ee/keys.dart
new file mode 100644
index 000000000..63559c859
--- /dev/null
+++ b/desktop/lib/e2ee/keys.dart
@@ -0,0 +1,144 @@
+import 'dart:typed_data';
+
+import 'package:cryptography/cryptography.dart';
+import 'package:cryptography/dart.dart';
+
+import 'bytes.dart';
+import 'primitives.dart';
+
+/// Long-lived identity (Ed25519) and per-connection ephemeral (X25519) keys — core.ts `Identity`,
+/// `Ephemeral` and `sessionKeys`, plus the hello/welcome signatures that bind them.
+///
+/// Signing and verifying are async where core.ts's are not: the pure-Dart Ed25519 has no
+/// synchronous API. Nothing that signs touches a nonce counter — only the handshake and the link
+/// sign anything — so the await costs no ordering guarantee.
+
+final _ed25519 = DartEd25519();
+const _x25519 = DartX25519();
+
+/// This app's Ed25519 identity. [seed] is the 32-byte RFC 8032 private key (core.ts's `priv`).
+///
+/// Every machine this app links to pins [pub], so it is minted once and persisted — a new one
+/// means linking every machine again.
+class E2eeIdentity {
+ E2eeIdentity._(this.seed, this.pub);
+
+ final Uint8List seed;
+ final Uint8List pub;
+
+ static Future<E2eeIdentity> fromSeed(List<int> seed) async {
+ final keyPair = await _ed25519.newKeyPairFromSeed(seed);
+ final pub = await keyPair.extractPublicKey();
+ return E2eeIdentity._(Uint8List.fromList(seed), Uint8List.fromList(pub.bytes));
+ }
+
+ static Future<E2eeIdentity> generate([Rng rng = secureRandomBytes]) =>
+ fromSeed(rng(32));
+
+ Future<Uint8List> sign(List<int> message) async {
+ final signature = await _ed25519.sign(
+ message,
+ keyPair: SimpleKeyPairData(
+ seed,
+ publicKey: SimplePublicKey(pub, type: KeyPairType.ed25519),
+ type: KeyPairType.ed25519,
+ ),
+ );
+ return Uint8List.fromList(signature.bytes);
+ }
+}
+
+/// False for a bad signature AND for input too malformed to check, as core.ts's `verify`.
+Future<bool> verifySignature(
+ List<int> pub,
+ List<int> message,
+ List<int> signature,
+) async {
+ try {
+ return await _ed25519.verify(
+ message,
+ signature: Signature(
+ signature,
+ publicKey: SimplePublicKey(pub, type: KeyPairType.ed25519),
+ ),
+ );
+ } catch (_) {
+ return false;
+ }
+}
+
+/// core.ts `fingerprint`: sha256(pub)'s first 8 bytes as four dot-separated hex groups — what the
+/// person compares against the other machine's `harness remote-password status`.
+String fingerprint(List<int> pub) {
+ final hex = hexOf(sha256(pub).sublist(0, 8)).toUpperCase();
+ return '${hex.substring(0, 4)}·${hex.substring(4, 8)}·'
+ '${hex.substring(8, 12)}·${hex.substring(12, 16)}';
+}
+
+/// A per-connection X25519 key.
+class Ephemeral {
+ Ephemeral._(this._keyPair, this.pub);
+
+ final SimpleKeyPairData _keyPair;
+ final Uint8List pub;
+
+ static Future<Ephemeral> generate([Rng rng = secureRandomBytes]) async {
+ final keyPair =
+ await _x25519.newKeyPairFromSeed(rng(32)) as SimpleKeyPairData;
+ return Ephemeral._(keyPair, Uint8List.fromList(keyPair.publicKey.bytes));
+ }
+
+ Uint8List sharedSecret(List<int> peerPub) {
+ final secret =
+ _x25519.sharedSecretSync(
+ keyPairData: _keyPair,
+ remotePublicKey: SimplePublicKey(
+ peerPub,
+ type: KeyPairType.x25519,
+ ),
+ )
+ as SecretKeyData;
+ return Uint8List.fromList(secret.bytes);
+ }
+}
+
+typedef SessionKeys = ({Uint8List c2s, Uint8List s2c});
+
+/// core.ts `sessionKeys`. Both ends pass the SAME (webEphPub, adapterEphPub) order, whichever end
+/// they are.
+SessionKeys sessionKeys(
+ Ephemeral eph,
+ List<int> peerEphPub,
+ String machineId,
+ List<int> webEphPub,
+ List<int> adapterEphPub,
+) {
+ final session = hkdfSha256(
+ eph.sharedSecret(peerEphPub),
+ salt: lvCat([machineId, webEphPub, adapterEphPub]),
+ info: utf8Bytes('e2e-sess-v1'),
+ length: 64,
+ );
+ return (
+ c2s: Uint8List.sublistView(session, 0, 32),
+ s2c: Uint8List.sublistView(session, 32, 64),
+ );
+}
+
+Future<Uint8List> helloSig(
+ E2eeIdentity identity,
+ String machineId,
+ List<int> ephPub,
+) => identity.sign(lvCat(['e2e-hello-v1', machineId, ephPub]));
+
+Future<bool> welcomeVerify(
+ List<int> peerPub,
+ String machineId,
+ List<int> webEphPub,
+ List<int> adapterEphPub,
+ List<int> sig,
+) => verifySignature(
+ peerPub,
+ lvCat(['e2e-welcome-v1', machineId, webEphPub, adapterEphPub]),
+ sig,
+);
diff --git a/desktop/lib/e2ee/password_pake.dart b/desktop/lib/e2ee/password_pake.dart
new file mode 100644
index 000000000..ae62819dc
--- /dev/null
+++ b/desktop/lib/e2ee/password_pake.dart
@@ -0,0 +1,48 @@
+import 'dart:isolate';
+import 'dart:typed_data';
+
+import 'package:unorm_dart/unorm_dart.dart' as unorm;
+
+import 'bytes.dart';
+import 'primitives.dart';
+import 'ristretto.dart';
+import 'scrypt.dart';
+
+/// passwordPake.ts — the generator and channel binding of the remote-password link: `harness
+/// remote-password set` on the machine, the same password typed on this device.
+
+const _pwDsi = 'e2e-cpace-ristretto255-pw-v1';
+
+// passwordPake.ts's cost parameters. A security control: never lowered to make anything faster.
+const _scryptN = 1 << 17;
+const _scryptR = 8;
+const _scryptP = 1;
+const _scryptDkLen = 32;
+
+/// passwordPake.ts `stretchPassword`: NFKC-fold the password, then scrypt it salted per machine,
+/// so one password set on two machines yields two unrelated keys.
+///
+/// Runs on its own isolate — about a second of CPU and 128 MB, which on the UI isolate would
+/// freeze the very frame telling the person to wait.
+Future<Uint8List> stretchPassword(String password, String machineId) {
+ final secret = utf8Bytes(unorm.nfkc(password));
+ final salt = sha256(utf8Bytes('e2e-remote-password-salt-v1|$machineId'));
+ return Isolate.run(
+ () => scrypt(
+ secret,
+ salt,
+ n: _scryptN,
+ r: _scryptR,
+ p: _scryptP,
+ dkLen: _scryptDkLen,
+ ),
+ );
+}
+
+/// The channel binding. The joiner is always named `machine` — the CLI's own joiner is one, and to
+/// the machine being joined this app must look exactly like it.
+String pwContext(String machineId) =>
+ 'autonomous-e2e-pw-pair|agent:$machineId|a:adapter|b:machine';
+
+RistrettoPoint pwCpaceGenerator(List<int> stretched, List<int> sid, String ci) =>
+ hashToRistretto255(lvCat([_pwDsi, stretched, sid, ci]), utf8Bytes(_pwDsi));
diff --git a/desktop/lib/e2ee/primitives.dart b/desktop/lib/e2ee/primitives.dart
new file mode 100644
index 000000000..3580418c1
--- /dev/null
+++ b/desktop/lib/e2ee/primitives.dart
@@ -0,0 +1,105 @@
+import 'dart:typed_data';
+
+import 'package:cryptography/cryptography.dart';
+import 'package:cryptography/dart.dart';
+
+import 'bytes.dart';
+
+/// Hashes, HMAC, HKDF and the ChaCha20-Poly1305 AEAD — what core.ts takes from noble, each one held
+/// byte-for-byte against the CLI by test/e2ee/.
+///
+/// All synchronous on purpose, like core.ts: a nonce counter read before an `await` and spent after
+/// one is exactly how two frames end up sealed under the same nonce.
+
+const _sha256 = DartSha256();
+const _sha512 = DartSha512();
+const _hmacSha256 = DartHmac(DartSha256());
+const _aead = DartChacha20.poly1305Aead();
+const _aeadTagBytes = 16;
+
+Uint8List sha256(List<int> data) =>
+ Uint8List.fromList(_sha256.hashSync(data).bytes);
+
+Uint8List sha512(List<int> data) =>
+ Uint8List.fromList(_sha512.hashSync(data).bytes);
+
+Uint8List hmacSha256(List<int> key, List<int> data) => Uint8List.fromList(
+ _hmacSha256
+ .calculateMacSync(
+ data,
+ secretKeyData: SecretKeyData(key),
+ nonce: const <int>[],
+ )
+ .bytes,
+);
+
+/// RFC 5869 HKDF-SHA256 — noble's `hkdf(sha256, ikm, salt, info, length)`.
+Uint8List hkdfSha256(
+ List<int> ikm, {
+ List<int> salt = const <int>[],
+ List<int> info = const <int>[],
+ required int length,
+}) {
+ // An empty salt means HashLen zero bytes (RFC 5869 §2.2). HMAC zero-pads its key to the block
+ // size either way, so this is what noble computes for both an absent and an empty salt.
+ final prk = hmacSha256(salt.isEmpty ? Uint8List(32) : salt, ikm);
+ final okm = BytesBuilder(copy: false);
+ var block = Uint8List(0);
+ for (var counter = 1; okm.length < length; counter++) {
+ block = hmacSha256(prk, [...block, ...info, counter]);
+ okm.add(block);
+ }
+ return Uint8List.sublistView(okm.takeBytes(), 0, length);
+}
+
+/// core.ts `counterNonce`: the counter as 8 big-endian bytes, then 4 zero bytes.
+Uint8List counterNonce(int counter) {
+ final nonce = Uint8List(12);
+ ByteData.sublistView(nonce).setUint64(0, counter);
+ return nonce;
+}
+
+/// ChaCha20-Poly1305 under a counter nonce: ciphertext followed by its 16-byte tag, the layout
+/// noble's `encrypt` produces.
+Uint8List aeadSeal(
+ List<int> key,
+ int counter,
+ List<int> aad,
+ List<int> plaintext,
+) {
+ final box = _aead.encryptSync(
+ plaintext,
+ secretKey: SecretKeyData(key),
+ nonce: counterNonce(counter),
+ aad: aad,
+ );
+ return concatBytes([box.cipherText, box.mac.bytes]);
+}
+
+/// The inverse of [aeadSeal]; null when the tag does not verify — a wrong key, counter or AAD, or
+/// a flipped byte.
+Uint8List? aeadOpen(
+ List<int> key,
+ int counter,
+ List<int> aad,
+ List<int> sealed,
+) {
+ if (sealed.length < _aeadTagBytes) return null;
+ final split = sealed.length - _aeadTagBytes;
+ try {
+ final clear = _aead.decryptSync(
+ SecretBox(
+ sealed.sublist(0, split),
+ nonce: counterNonce(counter),
+ mac: Mac(sealed.sublist(split)),
+ ),
+ secretKey: SecretKeyData(key),
+ aad: aad,
+ );
+ return Uint8List.fromList(clear);
+ } on SecretBoxAuthenticationError {
+ return null;
+ } on ArgumentError {
+ return null;
+ }
+}
diff --git a/desktop/lib/e2ee/relay_session_crypto.dart b/desktop/lib/e2ee/relay_session_crypto.dart
new file mode 100644
index 000000000..8970c14d7
--- /dev/null
+++ b/desktop/lib/e2ee/relay_session_crypto.dart
@@ -0,0 +1,195 @@
+import 'dart:typed_data';
+
+import '../terminal/terminal_binary.dart';
+import 'bytes.dart';
+import 'envelope.dart';
+import 'keys.dart';
+import 'primitives.dart';
+import 'replay_window.dart';
+import 'terminal_cipher.dart';
+
+/// The client end of one E2EE session with a remote machine — relayClient.ts `RelaySessionCrypto`.
+///
+/// On macOS and Linux the harness CLI runs this role for the app and hands it plaintext. Where
+/// there is no CLI (iOS, Windows) the app runs it itself, against the same machine code that
+/// answers the CLI and the web client — to the machine, this app IS such a client.
+///
+/// One per connection: `e2e_hello` → `e2e_welcome` sets up the keys, and a reconnect is a new
+/// ephemeral, new keys and fresh counters.
+class RelaySessionCrypto {
+ RelaySessionCrypto._(
+ this.machineId,
+ this._identity,
+ this._peerPub,
+ this._eph,
+ this._helloSig,
+ );
+
+ /// Signs the hello up front, so [helloFrame] is ready the moment the relay acks the select.
+ /// [ephemeral] is for tests; production mints a fresh one per connection.
+ static Future<RelaySessionCrypto> start({
+ required String machineId,
+ required E2eeIdentity identity,
+ required List<int> peerPub,
+ Ephemeral? ephemeral,
+ }) async {
+ final eph = ephemeral ?? await Ephemeral.generate();
+ return RelaySessionCrypto._(
+ machineId,
+ identity,
+ Uint8List.fromList(peerPub),
+ eph,
+ await helloSig(identity, machineId, eph.pub),
+ );
+ }
+
+ final String machineId;
+ final E2eeIdentity _identity;
+ final Uint8List _peerPub;
+ final Ephemeral _eph;
+ final Uint8List _helloSig;
+
+ Uint8List? _c2s;
+ Uint8List? _s2c;
+ Uint8List? _terminalC2s;
+ Uint8List? _terminalS2c;
+ int _c2sCounter = 0;
+ int _terminalC2sCounter = 0;
+ final _s2cRecv = ReplayWindow();
+ final _terminalS2cRecv = ReplayWindow();
+ Uint8List? _groupKey;
+ String _epoch = '';
+ final Map<String, int> _groupRecv = {};
+ int _terminalP2pVersion = 0;
+
+ bool get ready => _c2s != null && _s2c != null;
+
+ /// The machine's `features.terminalP2p` — 0 when it offers no P2P terminal channel.
+ int get terminalP2pVersion => _terminalP2pVersion;
+
+ Map<String, dynamic> helloFrame() => {
+ 'type': 'e2e_hello',
+ 'payload': {
+ 'identityPub': b64e(_identity.pub),
+ 'ephPub': b64e(_eph.pub),
+ 'sig': b64e(_helloSig),
+ },
+ };
+
+ /// Takes the machine's `e2e_welcome`; true once the session is usable. False means the machine
+ /// did not prove it holds the identity this app pinned for it, or the welcome did not open.
+ Future<bool> handleWelcome(Map<String, dynamic> payload) async {
+ try {
+ final adapterEphPub = _bytesField(payload, 'ephPub');
+ final sig = _bytesField(payload, 'sig');
+ final enc = _bytesField(payload, 'enc');
+ if (adapterEphPub == null || sig == null || enc == null) return false;
+ if (!await welcomeVerify(_peerPub, machineId, _eph.pub, adapterEphPub, sig)) {
+ return false;
+ }
+ final keys = sessionKeys(_eph, adapterEphPub, machineId, _eph.pub, adapterEphPub);
+ final opened = aeadOpen(keys.s2c, 0, utf8Bytes('e2e-welcome'), enc);
+ final initial = opened == null ? null : jsonObjectOf(opened);
+ final groupKey = initial?['groupKey'], epoch = initial?['epoch'];
+ if (groupKey is! String || groupKey.isEmpty || epoch is! String || epoch.isEmpty) {
+ return false;
+ }
+ _groupKey = b64d(groupKey);
+ _epoch = epoch;
+ _c2s = keys.c2s;
+ _s2c = keys.s2c;
+ _terminalC2s = deriveTerminalBinaryKey(keys.c2s);
+ _terminalS2c = deriveTerminalBinaryKey(keys.s2c);
+ final features = initial!['features'];
+ final p2p = features is Map ? features['terminalP2p'] : null;
+ _terminalP2pVersion = p2p is int ? p2p : 0;
+ return true;
+ } on FormatException {
+ return false;
+ } on ArgumentError {
+ return false;
+ }
+ }
+
+ /// Takes an `e2e_rekey` — the machine rotated its group key, which it does when it revokes a
+ /// client. False when it does not open.
+ bool handleRekey(Map<String, dynamic> payload) {
+ final s2c = _s2c;
+ final n = payload['n'], enc = payload['enc'];
+ if (s2c == null || n is! int || enc is! String || enc.isEmpty) return false;
+ try {
+ final opened = aeadOpen(s2c, n, utf8Bytes('e2e-rekey'), b64d(enc));
+ final next = opened == null ? null : jsonObjectOf(opened);
+ final groupKey = next?['groupKey'], epoch = next?['epoch'];
+ if (groupKey is! String || groupKey.isEmpty || epoch is! String || epoch.isEmpty) {
+ return false;
+ }
+ _groupKey = b64d(groupKey);
+ _epoch = epoch;
+ return true;
+ } on FormatException {
+ return false;
+ }
+ }
+
+ /// Seals the payload of a frame whose type must not cross the relay in the clear; any other
+ /// frame goes as it is.
+ Map<String, dynamic> wrapOutgoing(Map<String, dynamic> frame) {
+ final type = frame['type'], c2s = _c2s;
+ if (type is! String || c2s == null || !encryptedDownTypes.contains(type)) {
+ return frame;
+ }
+ final payload = wrapPayload(c2s, 'p', _c2sCounter++, type, null, frame['payload']);
+ return {...frame, 'payload': payload};
+ }
+
+ /// The frame with its payload opened; a frame that was never sealed passes as it is. Null means
+ /// drop it — stale, replayed or not authentic — and never hand it on.
+ Map<String, dynamic>? unwrapIncoming(Map<String, dynamic> frame) {
+ final payload = frame['payload'];
+ if (payload is! Map || !isWrapped(payload)) return frame;
+ final env = payload['__e2e'], type = frame['type'];
+ if (env is! Map<String, dynamic> || type is! String) return null;
+ final n = env['n'];
+ if (n is! int) return null;
+ final dbSessionId = frame['dbSessionId'] as String?;
+ if (env['k'] == 'g') {
+ final groupKey = _groupKey, epoch = env['epoch'];
+ if (groupKey == null || epoch != _epoch) return null;
+ if (n <= (_groupRecv[_epoch] ?? -1)) return null;
+ final clear = unwrapPayload(groupKey, env, type, dbSessionId);
+ if (clear == null) return null;
+ _groupRecv[_epoch] = n;
+ return {...frame, 'payload': clear};
+ }
+ final s2c = _s2c;
+ if (s2c == null || !_s2cRecv.allows(n)) return null;
+ final clear = unwrapPayload(s2c, env, type, dbSessionId);
+ if (clear == null) return null;
+ _s2cRecv.commit(n);
+ return {...frame, 'payload': clear};
+ }
+
+ Uint8List? encryptTerminal(TerminalBinaryFrame frame) {
+ final key = _terminalC2s;
+ if (key == null) return null;
+ final sealed = sealTerminalBinary(key, _terminalC2sCounter, frame);
+ if (sealed != null) _terminalC2sCounter++;
+ return sealed;
+ }
+
+ /// Null means drop — stale, replayed or not authentic.
+ TerminalBinaryFrame? decryptTerminal(Uint8List raw) {
+ final key = _terminalS2c;
+ if (key == null) return null;
+ final opened = openTerminalBinary(key, raw);
+ if (opened == null || !_terminalS2cRecv.allows(opened.counter)) return null;
+ _terminalS2cRecv.commit(opened.counter);
+ return opened.frame;
+ }
+}
+
+Uint8List? _bytesField(Map<String, dynamic> payload, String key) {
+ final value = payload[key];
+ return value is String && value.isNotEmpty ? b64d(value) : null;
+}
diff --git a/desktop/lib/e2ee/replay_window.dart b/desktop/lib/e2ee/replay_window.dart
new file mode 100644
index 000000000..3f22ff5a7
--- /dev/null
+++ b/desktop/lib/e2ee/replay_window.dart
@@ -0,0 +1,40 @@
+/// replayWindow.ts: the counters of one key domain are accepted each once, in any order, within
+/// [e2eeReplayWindowSize] of the highest seen. The machine can deliver a stream's frames over two
+/// transports (P2P and the relay) that reorder against each other, so "strictly increasing" would
+/// drop authentic frames.
+const int e2eeReplayWindowSize = 4096;
+
+/// JavaScript's `Number.MAX_SAFE_INTEGER` — the CLI refuses any counter above it, so this does too.
+const int maxSafeInteger = 9007199254740991;
+
+class ReplayWindow {
+ int _highest = -1;
+ int _prunedThrough = -1;
+ final Set<int> _seen = {};
+
+ bool allows(int counter) =>
+ counter >= 0 &&
+ counter <= maxSafeInteger &&
+ !_seen.contains(counter) &&
+ (_highest < 0 || counter > _highest - e2eeReplayWindowSize);
+
+ void commit(int counter) {
+ _seen.add(counter);
+ if (counter <= _highest) return;
+ _highest = counter;
+ final oldest = _highest - e2eeReplayWindowSize;
+ if (oldest <= _prunedThrough) return;
+ // A counter far ahead makes the whole old set stale — clear it rather than walk a gap a
+ // hostile peer chose the size of.
+ if (oldest - _prunedThrough > e2eeReplayWindowSize) {
+ _seen
+ ..clear()
+ ..add(counter);
+ } else {
+ for (var value = _prunedThrough + 1; value <= oldest; value++) {
+ _seen.remove(value);
+ }
+ }
+ _prunedThrough = oldest;
+ }
+}
diff --git a/desktop/lib/e2ee/ristretto.dart b/desktop/lib/e2ee/ristretto.dart
new file mode 100644
index 000000000..72d732f2c
--- /dev/null
+++ b/desktop/lib/e2ee/ristretto.dart
@@ -0,0 +1,178 @@
+import 'dart:typed_data';
+
+import 'bytes.dart';
+import 'primitives.dart';
+import 'ristretto_field.dart';
+
+/// ristretto255 points and hash-to-group — core.ts's `RistrettoPoint` and `hashToRistretto255`,
+/// which both CPace generators (the 6-character code and the remote password) are built from.
+
+/// An edwards25519 point in extended coordinates (a = −1).
+class EdwardsPoint {
+ const EdwardsPoint(this.x, this.y, this.z, this.t);
+
+ final BigInt x, y, z, t;
+
+ static final EdwardsPoint zero = EdwardsPoint(
+ BigInt.zero,
+ BigInt.one,
+ BigInt.one,
+ BigInt.zero,
+ );
+
+ static final BigInt _k = fmod(edwardsD * BigInt.two);
+
+ /// add-2008-hwcd-3.
+ EdwardsPoint add(EdwardsPoint o) {
+ final a = fmod((y - x) * (o.y - o.x));
+ final b = fmod((y + x) * (o.y + o.x));
+ final c = fmod(t * _k * o.t);
+ final d = fmod(z * BigInt.two * o.z);
+ final e = fmod(b - a), f = fmod(d - c), g = fmod(d + c), h = fmod(b + a);
+ return EdwardsPoint(fmod(e * f), fmod(g * h), fmod(f * g), fmod(e * h));
+ }
+
+ /// dbl-2008-hwcd.
+ EdwardsPoint double() {
+ final a = fmod(x * x);
+ final b = fmod(y * y);
+ final c = fmod(BigInt.two * z * z);
+ final d = fmod(-a);
+ final e = fmod((x + y) * (x + y) - a - b);
+ final g = fmod(d + b), f = fmod(g - c), h = fmod(d - b);
+ return EdwardsPoint(fmod(e * f), fmod(g * h), fmod(f * g), fmod(e * h));
+ }
+
+ EdwardsPoint multiply(BigInt scalar) {
+ var result = zero;
+ var addend = this;
+ for (var k = scalar; k > BigInt.zero; k = k >> 1) {
+ if (k.isOdd) result = result.add(addend);
+ addend = addend.double();
+ }
+ return result;
+ }
+}
+
+class RistrettoPoint {
+ const RistrettoPoint(this.ep);
+
+ final EdwardsPoint ep;
+
+ static final RistrettoPoint zero = RistrettoPoint(EdwardsPoint.zero);
+
+ /// Decodes a canonical 32-byte encoding; throws [ArgumentError] on anything else, as noble's
+ /// `fromHex` does — the peer's CPace share is untrusted input.
+ factory RistrettoPoint.fromBytes(List<int> bytes) {
+ if (bytes.length != 32) throw ArgumentError('ristretto255: not 32 bytes');
+ final s = bytes255ToNumberLe(bytes);
+ if (!ctEqual(numberToBytesLe(s, 32), bytes) || isNegativeLe(s)) {
+ throw ArgumentError('ristretto255: non-canonical encoding');
+ }
+ final s2 = fmod(s * s);
+ final u1 = fmod(BigInt.one + edwardsA * s2);
+ final u2 = fmod(BigInt.one - edwardsA * s2);
+ final u2Sq = fmod(u2 * u2);
+ final v = fmod(edwardsA * edwardsD * u1 * u1 - u2Sq);
+ final inv = uvRatio(BigInt.one, fmod(v * u2Sq));
+ final dx = fmod(inv.value * u2);
+ final dy = fmod(inv.value * dx * v);
+ var x = fmod((s + s) * dx);
+ if (isNegativeLe(x)) x = fmod(-x);
+ final y = fmod(u1 * dy);
+ final t = fmod(x * y);
+ if (!inv.isValid || isNegativeLe(t) || y == BigInt.zero) {
+ throw ArgumentError('ristretto255: invalid encoding');
+ }
+ return RistrettoPoint(EdwardsPoint(x, y, BigInt.one, t));
+ }
+
+ Uint8List toBytes() {
+ var x = ep.x, y = ep.y;
+ final z = ep.z, t = ep.t;
+ final u1 = fmod(fmod(z + y) * fmod(z - y));
+ final u2 = fmod(x * y);
+ final invSqrt = uvRatio(BigInt.one, fmod(u1 * u2 * u2)).value;
+ final d1 = fmod(invSqrt * u1);
+ final d2 = fmod(invSqrt * u2);
+ final zInv = fmod(d1 * d2 * t);
+ BigInt d;
+ if (isNegativeLe(t * zInv)) {
+ final rotatedX = fmod(y * sqrtM1);
+ y = fmod(x * sqrtM1);
+ x = rotatedX;
+ d = fmod(d1 * invSqrtAMinusD);
+ } else {
+ d = d2;
+ }
+ if (isNegativeLe(x * zInv)) y = fmod(-y);
+ var s = fmod((z - y) * d);
+ if (isNegativeLe(s)) s = fmod(-s);
+ return numberToBytesLe(s, 32);
+ }
+
+ RistrettoPoint multiply(BigInt scalar) => RistrettoPoint(ep.multiply(scalar));
+
+ RistrettoPoint add(RistrettoPoint other) => RistrettoPoint(ep.add(other.ep));
+
+ bool equals(RistrettoPoint other) {
+ final a = ep, b = other.ep;
+ return fmod(a.x * b.y) == fmod(a.y * b.x) ||
+ fmod(a.y * b.y) == fmod(a.x * b.x);
+ }
+}
+
+/// RFC 9496 Elligator map (noble `calcElligatorRistrettoMap`).
+EdwardsPoint _elligator(BigInt r0) {
+ final r = fmod(sqrtM1 * r0 * r0);
+ final ns = fmod((r + BigInt.one) * oneMinusDSq);
+ var c = fmod(-BigInt.one);
+ final den = fmod((c - edwardsD * r) * fmod(r + edwardsD));
+ final ratio = uvRatio(ns, den);
+ var s = ratio.value;
+ var sPrime = fmod(s * r0);
+ if (!isNegativeLe(sPrime)) sPrime = fmod(-sPrime);
+ if (!ratio.isValid) {
+ s = sPrime;
+ c = r;
+ }
+ final nt = fmod(c * (r - BigInt.one) * dMinusOneSq - den);
+ final s2 = fmod(s * s);
+ final w0 = fmod((s + s) * den);
+ final w1 = fmod(nt * sqrtAdMinusOne);
+ final w2 = fmod(BigInt.one - s2);
+ final w3 = fmod(BigInt.one + s2);
+ return EdwardsPoint(fmod(w0 * w3), fmod(w2 * w1), fmod(w1 * w3), fmod(w0 * w2));
+}
+
+/// noble `hashToRistretto255`: expand_message_xmd(SHA-512) to 64 bytes, then the one-way map.
+RistrettoPoint hashToRistretto255(List<int> message, List<int> dst) {
+ final uniform = expandMessageXmd(message, dst, 64);
+ final r1 = _elligator(bytes255ToNumberLe(uniform.sublist(0, 32)));
+ final r2 = _elligator(bytes255ToNumberLe(uniform.sublist(32, 64)));
+ return RistrettoPoint(r1.add(r2));
+}
+
+/// RFC 9380 §5.3.1 expand_message_xmd with SHA-512 (b_in_bytes 64, s_in_bytes 128).
+Uint8List expandMessageXmd(List<int> message, List<int> dst, int length) {
+ if (dst.length > 255) throw ArgumentError('expand_message_xmd: DST too long');
+ final ell = (length + 63) ~/ 64;
+ final dstPrime = [...dst, dst.length];
+ final b0 = sha512([
+ ...Uint8List(128),
+ ...message,
+ (length >> 8) & 0xff,
+ length & 0xff,
+ 0,
+ ...dstPrime,
+ ]);
+ final out = BytesBuilder(copy: false);
+ var previous = sha512([...b0, 1, ...dstPrime]);
+ out.add(previous);
+ for (var i = 2; i <= ell; i++) {
+ final mixed = [for (var j = 0; j < 64; j++) b0[j] ^ previous[j]];
+ previous = sha512([...mixed, i, ...dstPrime]);
+ out.add(previous);
+ }
+ return Uint8List.sublistView(out.takeBytes(), 0, length);
+}
diff --git a/desktop/lib/e2ee/ristretto_field.dart b/desktop/lib/e2ee/ristretto_field.dart
new file mode 100644
index 000000000..c56925424
--- /dev/null
+++ b/desktop/lib/e2ee/ristretto_field.dart
@@ -0,0 +1,91 @@
+import 'dart:typed_data';
+
+/// Arithmetic over GF(2^255 − 19) for ristretto255 (RFC 9496), ported from the noble-curves code
+/// core.ts runs. Pure BigInt and NOT constant-time: it only ever touches the one-shot CPace
+/// exchange of a link attempt, never a session key or a frame.
+
+final BigInt fieldP = BigInt.parse(
+ '7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed',
+ radix: 16,
+);
+
+/// The prime order L of the ristretto255 group.
+final BigInt curveOrder = BigInt.parse(
+ '1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed',
+ radix: 16,
+);
+
+final BigInt edwardsD = BigInt.parse(
+ '52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3',
+ radix: 16,
+);
+
+/// a = −1, reduced.
+final BigInt edwardsA = fieldP - BigInt.one;
+
+final BigInt sqrtM1 = BigInt.parse(
+ '19681161376707505956807079304988542015446066515923890162744021073123829784752',
+);
+final BigInt sqrtAdMinusOne = BigInt.parse(
+ '25063068953384623474111414158702152701244531502492656460079210482610430750235',
+);
+final BigInt invSqrtAMinusD = BigInt.parse(
+ '54469307008909316920995813868745141605393597292927456921205312896311721017578',
+);
+final BigInt oneMinusDSq = BigInt.parse(
+ '1159843021668779879193775521855586647937357759715417654439879720876111806838',
+);
+final BigInt dMinusOneSq = BigInt.parse(
+ '40440834346308536858101042469323190826248399146238708352240133220865137265952',
+);
+
+final BigInt _mask255 = (BigInt.one << 255) - BigInt.one;
+final BigInt _pMinus5Over8 = (fieldP - BigInt.from(5)) >> 3;
+
+/// Dart's BigInt `%` is Euclidean, so this is always in [0, p).
+BigInt fmod(BigInt n) => n % fieldP;
+
+BigInt bytesToNumberLe(List<int> bytes) {
+ var n = BigInt.zero;
+ for (var i = bytes.length - 1; i >= 0; i--) {
+ n = (n << 8) | BigInt.from(bytes[i]);
+ }
+ return n;
+}
+
+Uint8List numberToBytesLe(BigInt n, int length) {
+ final out = Uint8List(length);
+ var rest = n;
+ for (var i = 0; i < length; i++) {
+ out[i] = (rest & BigInt.from(0xff)).toInt();
+ rest = rest >> 8;
+ }
+ return out;
+}
+
+/// noble `bytes255ToNumberLE`: the low 255 bits, reduced.
+BigInt bytes255ToNumberLe(List<int> bytes) =>
+ fmod(bytesToNumberLe(bytes) & _mask255);
+
+bool isNegativeLe(BigInt n) => fmod(n).isOdd;
+
+typedef SqrtRatio = ({bool isValid, BigInt value});
+
+/// noble `uvRatio`: sqrt(u/v) when it exists. On failure the value is still a root of something,
+/// because the Elligator map below uses it either way.
+SqrtRatio uvRatio(BigInt u, BigInt v) {
+ final v3 = fmod(v * v * v);
+ final v7 = fmod(v3 * v3 * v);
+ final pow = fmod(u * v7).modPow(_pMinus5Over8, fieldP);
+ var x = fmod(u * v3 * pow);
+ final vx2 = fmod(v * x * x);
+ final root1 = x;
+ final root2 = fmod(x * sqrtM1);
+ final useRoot1 = vx2 == fmod(u);
+ final useRoot2 = vx2 == fmod(-u);
+ final noRoot = vx2 == fmod(-u * sqrtM1);
+ if (useRoot1) x = root1;
+ if (useRoot2 || noRoot) x = root2;
+ if (isNegativeLe(x)) x = fmod(-x);
+ return (isValid: useRoot1 || useRoot2, value: x);
+}
diff --git a/desktop/lib/e2ee/scrypt.dart b/desktop/lib/e2ee/scrypt.dart
new file mode 100644
index 000000000..a2f003255
--- /dev/null
+++ b/desktop/lib/e2ee/scrypt.dart
@@ -0,0 +1,167 @@
+import 'dart:typed_data';
+
+import 'bytes.dart';
+import 'primitives.dart';
+
+/// RFC 7914 scrypt — the stretch `harness remote-password` puts on a password (N=2^17, r=8, p=1).
+///
+/// Written over 32-bit words rather than taken from pointycastle, whose Salsa core works byte by
+/// byte: this runs 2^17 × 2 block mixes over 128 MB once per link attempt, on a phone, and that is
+/// the whole of the wait the person sees.
+Uint8List scrypt(
+ List<int> password,
+ List<int> salt, {
+ required int n,
+ required int r,
+ required int p,
+ required int dkLen,
+}) {
+ if (n < 2 || (n & (n - 1)) != 0) throw ArgumentError('scrypt: N must be a power of 2');
+ if (r < 1 || p < 1) throw ArgumentError('scrypt: r and p must be positive');
+ final blockWords = 32 * r;
+ final b = _bytesToWords(_pbkdf2Once(password, salt, 128 * r * p));
+ final v = Uint32List(blockWords * n);
+ final x = Uint32List(blockWords);
+ final y = Uint32List(blockWords);
+ final mix = Uint32List(16);
+ for (var i = 0; i < p; i++) {
+ _roMix(b, i * blockWords, r, n, v, x, y, mix);
+ }
+ return _pbkdf2Once(password, _wordsToBytes(b), dkLen);
+}
+
+/// PBKDF2-HMAC-SHA256 with one iteration — all scrypt ever asks of it.
+Uint8List _pbkdf2Once(List<int> password, List<int> salt, int length) {
+ final out = BytesBuilder(copy: false);
+ for (var block = 1; out.length < length; block++) {
+ out.add(hmacSha256(password, [
+ ...salt,
+ (block >> 24) & 0xff,
+ (block >> 16) & 0xff,
+ (block >> 8) & 0xff,
+ block & 0xff,
+ ]));
+ }
+ return Uint8List.sublistView(out.takeBytes(), 0, length);
+}
+
+void _roMix(
+ Uint32List b,
+ int offset,
+ int r,
+ int n,
+ Uint32List v,
+ Uint32List x,
+ Uint32List y,
+ Uint32List mix,
+) {
+ final words = 32 * r;
+ x.setRange(0, words, b, offset);
+ for (var i = 0; i < n; i++) {
+ v.setRange(i * words, (i + 1) * words, x);
+ _blockMix(x, y, mix, r);
+ }
+ final mask = n - 1;
+ final last = (2 * r - 1) * 16;
+ for (var i = 0; i < n; i++) {
+ final base = (x[last] & mask) * words;
+ for (var k = 0; k < words; k++) {
+ x[k] ^= v[base + k];
+ }
+ _blockMix(x, y, mix, r);
+ }
+ b.setRange(offset, offset + words, x);
+}
+
+/// BlockMix_{Salsa20/8, r}: [b] in, [b] out (shuffled even blocks first), [y] as scratch.
+void _blockMix(Uint32List b, Uint32List y, Uint32List mix, int r) {
+ mix.setRange(0, 16, b, (2 * r - 1) * 16);
+ for (var i = 0; i < 2 * r; i++) {
+ for (var k = 0; k < 16; k++) {
+ mix[k] ^= b[i * 16 + k];
+ }
+ _salsa20x8(mix);
+ final target = ((i & 1) == 0 ? i >> 1 : r + (i >> 1)) * 16;
+ y.setRange(target, target + 16, mix);
+ }
+ b.setRange(0, 32 * r, y);
+}
+
+int _rotl(int value, int shift) {
+ final v = value & 0xffffffff;
+ return ((v << shift) | (v >> (32 - shift))) & 0xffffffff;
+}
+
+/// The Salsa20/8 core of RFC 7914 §3, in place.
+void _salsa20x8(Uint32List b) {
+ var x0 = b[0], x1 = b[1], x2 = b[2], x3 = b[3];
+ var x4 = b[4], x5 = b[5], x6 = b[6], x7 = b[7];
+ var x8 = b[8], x9 = b[9], x10 = b[10], x11 = b[11];
+ var x12 = b[12], x13 = b[13], x14 = b[14], x15 = b[15];
+ for (var i = 0; i < 8; i += 2) {
+ x4 ^= _rotl(x0 + x12, 7);
+ x8 ^= _rotl(x4 + x0, 9);
+ x12 ^= _rotl(x8 + x4, 13);
+ x0 ^= _rotl(x12 + x8, 18);
+ x9 ^= _rotl(x5 + x1, 7);
+ x13 ^= _rotl(x9 + x5, 9);
+ x1 ^= _rotl(x13 + x9, 13);
+ x5 ^= _rotl(x1 + x13, 18);
+ x14 ^= _rotl(x10 + x6, 7);
+ x2 ^= _rotl(x14 + x10, 9);
+ x6 ^= _rotl(x2 + x14, 13);
+ x10 ^= _rotl(x6 + x2, 18);
+ x3 ^= _rotl(x15 + x11, 7);
+ x7 ^= _rotl(x3 + x15, 9);
+ x11 ^= _rotl(x7 + x3, 13);
+ x15 ^= _rotl(x11 + x7, 18);
+ x1 ^= _rotl(x0 + x3, 7);
+ x2 ^= _rotl(x1 + x0, 9);
+ x3 ^= _rotl(x2 + x1, 13);
+ x0 ^= _rotl(x3 + x2, 18);
+ x6 ^= _rotl(x5 + x4, 7);
+ x7 ^= _rotl(x6 + x5, 9);
+ x4 ^= _rotl(x7 + x6, 13);
+ x5 ^= _rotl(x4 + x7, 18);
+ x11 ^= _rotl(x10 + x9, 7);
+ x8 ^= _rotl(x11 + x10, 9);
+ x9 ^= _rotl(x8 + x11, 13);
+ x10 ^= _rotl(x9 + x8, 18);
+ x12 ^= _rotl(x15 + x14, 7);
+ x13 ^= _rotl(x12 + x15, 9);
+ x14 ^= _rotl(x13 + x12, 13);
+ x15 ^= _rotl(x14 + x13, 18);
+ }
+ // A Uint32List store keeps the low 32 bits, which is the mod-2^32 add the spec wants.
+ b[0] += x0;
+ b[1] += x1;
+ b[2] += x2;
+ b[3] += x3;
+ b[4] += x4;
+ b[5] += x5;
+ b[6] += x6;
+ b[7] += x7;
+ b[8] += x8;
+ b[9] += x9;
+ b[10] += x10;
+ b[11] += x11;
+ b[12] += x12;
+ b[13] += x13;
+ b[14] += x14;
+ b[15] += x15;
+}
+
+Uint32List _bytesToWords(Uint8List bytes) {
+ final view = ByteData.sublistView(bytes);
+ return Uint32List.fromList([
+ for (var i = 0; i < bytes.length; i += 4) view.getUint32(i, Endian.little),
+ ]);
+}
+
+Uint8List _wordsToBytes(Uint32List words) {
+ final out = ByteData(words.length * 4);
+ for (var i = 0; i < words.length; i++) {
+ out.setUint32(i * 4, words[i], Endian.little);
+ }
+ return concatBytes([out.buffer.asUint8List()]);
+}
diff --git a/desktop/lib/e2ee/terminal_cipher.dart b/desktop/lib/e2ee/terminal_cipher.dart
new file mode 100644
index 000000000..48302dfab
--- /dev/null
+++ b/desktop/lib/e2ee/terminal_cipher.dart
@@ -0,0 +1,87 @@
+import 'dart:typed_data';
+
+import '../terminal/terminal_binary.dart';
+import 'bytes.dart';
+import 'primitives.dart';
+import 'replay_window.dart';
+
+/// HTRM v3 — terminalBinary.ts's encrypted binary terminal frame, the only form terminal bytes take
+/// on the relay. The plaintext inside is the same one the loopback HTRL frame carries
+/// ([encodeTerminalPlain]), which is what lets the transport convert between the two and leave
+/// every terminal session unaware of which it is on.
+///
+/// Header (20 bytes): `HTRM` | version | kind | flags | 0 | u64 counter | u32 ciphertext length.
+/// The first 16 bytes are the AAD; the counter is the nonce.
+
+const int terminalBinaryVersion = 3;
+const int terminalBinaryHeaderBytes = 20;
+const int _aadBytes = 16;
+const int _tagBytes = 16;
+const int _flagZlib = 1;
+final Uint8List _magic = Uint8List.fromList(const [0x48, 0x54, 0x52, 0x4d]);
+
+/// Binary frames get their own key, so their nonces never collide with the JSON frames'.
+Uint8List deriveTerminalBinaryKey(List<int> sessionKey) => hkdfSha256(
+ sessionKey,
+ info: utf8Bytes('harness-terminal-binary-v3'),
+ length: 32,
+);
+
+Uint8List? sealTerminalBinary(
+ List<int> key,
+ int counter,
+ TerminalBinaryFrame frame,
+) {
+ if (counter < 0 || counter > maxSafeInteger) return null;
+ final plaintext = encodeTerminalPlain(frame);
+ if (plaintext == null) return null;
+ final header = Uint8List(terminalBinaryHeaderBytes)..setRange(0, 4, _magic);
+ header[4] = terminalBinaryVersion;
+ header[5] = frame.kind.code;
+ header[6] = frame.compressed ? _flagZlib : 0;
+ final view = ByteData.sublistView(header)..setUint64(8, counter);
+ final ciphertext = aeadSeal(
+ key,
+ counter,
+ Uint8List.sublistView(header, 0, _aadBytes),
+ plaintext,
+ );
+ if (ciphertext.length > maxTerminalPayloadBytesFor(frame.kind)) return null;
+ view.setUint32(16, ciphertext.length);
+ return concatBytes([header, ciphertext]);
+}
+
+/// The frame inside [raw] and the counter it was sealed under; null for anything malformed or
+/// unauthentic. Replay is the caller's to check — the counter is returned for that.
+({int counter, TerminalBinaryFrame frame})? openTerminalBinary(
+ List<int> key,
+ Uint8List raw,
+) {
+ if (raw.length < terminalBinaryHeaderBytes + _tagBytes) return null;
+ for (var i = 0; i < _magic.length; i++) {
+ if (raw[i] != _magic[i]) return null;
+ }
+ final kind = TerminalBinaryKind.fromCode(raw[5]);
+ if (raw[4] != terminalBinaryVersion || kind == null || raw[7] != 0) {
+ return null;
+ }
+ final view = ByteData.sublistView(raw);
+ final counter = view.getUint64(8);
+ final length = view.getUint32(16);
+ if (counter < 0 ||
+ counter > maxSafeInteger ||
+ length < _tagBytes ||
+ length > maxTerminalPayloadBytesFor(kind) ||
+ raw.length != terminalBinaryHeaderBytes + length) {
+ return null;
+ }
+ final plaintext = aeadOpen(
+ key,
+ counter,
+ Uint8List.sublistView(raw, 0, _aadBytes),
+ Uint8List.sublistView(raw, terminalBinaryHeaderBytes),
+ );
+ if (plaintext == null) return null;
+ final frame = decodeTerminalPlain(kind, raw[6], plaintext);
+ return frame == null ? null : (counter: counter, frame: frame);
+}
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index 4aefbf521..eb0bfe94b 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -39,6 +39,7 @@ import '../widgets/swarm_search_input.dart';
import '../widgets/swarm_project_agents.dart';
import '../widgets/swarm_attention.dart';
import '../widgets/swarm_switcher.dart';
+import '../widgets/swarm_tab_strip.dart';
import '../widgets/swarm_wallpaper.dart';
import '../widgets/swarm_welcome.dart';
import '../widgets/task_palette.dart';
@@ -1064,7 +1065,15 @@ class _SwarmScreenState extends State<SwarmScreen> {
backgroundColor: grid.AppPalette.swarmField,
body: Column(
children: [
- if (!_native) _tabStrip(),
+ if (!_native)
+ SwarmTabStrip(
+ notifier: app,
+ attention: _attention,
+ onRename: _rename,
+ onSearch: _jump,
+ onNewAgent: _newAgent,
+ onNotifications: _notifications,
+ ),
if (_keymap.error != null)
Material(
color: grid.AppPalette.panelBg,
@@ -1222,122 +1231,4 @@ class _SwarmScreenState extends State<SwarmScreen> {
);
},
);
-
- Widget _tabStrip() => Container(
- height: 44,
- color: grid.AppPalette.swarmTabBar,
- child: Row(
- children: [
- const SizedBox(width: 10),
- Expanded(
- child: ReorderableListView.builder(
- scrollDirection: Axis.horizontal,
- shrinkWrap: true,
- buildDefaultDragHandles: false,
- itemCount: app.swarms.length,
- onReorderItem: (old, to) =>
- app.reorderSwarm(app.swarms[old].id, to),
- itemBuilder: (context, index) {
- final swarm = app.swarms[index];
- return ReorderableDragStartListener(
- key: ValueKey(swarm.id),
- index: index,
- child: GestureDetector(
- onDoubleTap: () => _rename(swarm.id),
- child: Container(
- width: 186,
- margin: const EdgeInsets.only(top: 6, right: 2),
- decoration: BoxDecoration(
- color: app.activeSwarmId == swarm.id
- ? grid.AppPalette.swarmField
- : Colors.transparent,
- borderRadius: const BorderRadius.vertical(
- top: Radius.circular(9),
- ),
- ),
- child: Row(
- children: [
- Expanded(
- child: TextButton(
- onPressed: () => app.selectSwarm(swarm.id),
- style: TextButton.styleFrom(
- animationDuration: Duration.zero,
- foregroundColor: app.activeSwarmId == swarm.id
- ? Colors.white
- : Colors.white70,
- ),
- child: Text(
- swarm.name,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: const TextStyle(fontSize: 13),
- ),
- ),
- ),
- IconButton(
- tooltip: 'Close ${swarm.name}',
- onPressed: () => app.closeSwarm(swarm.id),
- icon: const Icon(Icons.close, size: 13),
- constraints: const BoxConstraints.tightFor(
- width: 30,
- height: 30,
- ),
- padding: EdgeInsets.zero,
- ),
- ],
- ),
- ),
- ),
- );
- },
- ),
- ),
- IconButton(
- tooltip: withEffectiveShortcutHint(
- context,
- 'New swarm',
- ShortcutAction.newSwarm,
- ),
- onPressed: app.swarms.length < AppNotifier.maxSwarms
- ? app.newSwarm
- : null,
- icon: const Icon(Icons.add, size: 18),
- ),
- IconButton(
- key: const ValueKey('swarm-search-button'),
- tooltip: withEffectiveShortcutHint(
- context,
- 'Search',
- ShortcutAction.switchAgent,
- ),
- onPressed: _jump,
- icon: const Icon(Icons.search, size: 20),
- ),
- IconButton(
- key: const ValueKey('swarm-new-agent-button'),
- tooltip: withEffectiveShortcutHint(
- context,
- 'New agent',
- ShortcutAction.newAgent,
- ),
- onPressed: _newAgent,
- icon: const Icon(Icons.add, size: 20),
- ),
- IconButton(
- key: const ValueKey('swarm-notifications-button'),
- tooltip: withEffectiveShortcutHint(
- context,
- 'Agents needing input',
- ShortcutAction.showAttention,
- ),
- onPressed: _notifications,
- icon: Badge(
- isLabelVisible: _attention > 0,
- child: const Icon(Icons.notifications_none, size: 20),
- ),
- ),
- const SizedBox(width: 6),
- ],
- ),
- );
}
diff --git a/desktop/lib/shared/layouts/window_size.dart b/desktop/lib/shared/layouts/window_size.dart
new file mode 100644
index 000000000..33bb29101
--- /dev/null
+++ b/desktop/lib/shared/layouts/window_size.dart
@@ -0,0 +1,49 @@
+import 'package:flutter/widgets.dart';
+
+/// The width bands the shell branches on.
+///
+/// One definition, in one place, so "narrow" means the same number to every
+/// piece of chrome rather than each one inventing its own threshold.
+///
+/// These are WINDOW widths, not device classes. A desktop window dragged down
+/// to 500pt is [compact] for the same reason a phone is, and is laid out the
+/// same way — there is no separate mobile build to branch on, and a rule that
+/// asked "is this a phone?" would leave the narrow desktop window broken.
+///
+/// The lower edge is Material's 600. The upper one is this app's own: the pane
+/// grid's floor for a usable terminal tile is about 336pt (`_MinTile` in
+/// `widgets/pane_grid.dart`, 40 columns at the default font), and [expanded]
+/// is meant to mean "two of those side by side, with the chrome around them" —
+/// which 840 does not buy and 1024 does.
+enum WindowSizeClass {
+ /// One thing at a time. Chrome that cannot earn its width collapses.
+ compact,
+
+ /// Everything is present, with less room around it.
+ medium,
+
+ /// The size the app is drawn for.
+ expanded;
+
+ /// First width that is no longer [compact].
+ static const double compactMax = 600;
+
+ /// First width that is [expanded].
+ static const double mediumMax = 1024;
+
+ static WindowSizeClass fromWidth(double width) => switch (width) {
+ < compactMax => WindowSizeClass.compact,
+ < mediumMax => WindowSizeClass.medium,
+ _ => WindowSizeClass.expanded,
+ };
+
+ /// The class of the WINDOW.
+ ///
+ /// Prefer [fromWidth] with a `LayoutBuilder`'s own constraint for anything
+ /// laid out narrower than the window: a strip inside a split should answer
+ /// for the box it was given, not for the screen it happens to sit on.
+ static WindowSizeClass of(BuildContext context) =>
+ fromWidth(MediaQuery.sizeOf(context).width);
+
+ bool get isCompact => this == WindowSizeClass.compact;
+}
diff --git a/desktop/lib/shortcuts/keymap_store.dart b/desktop/lib/shortcuts/keymap_store.dart
index baee76bb0..06982e519 100644
--- a/desktop/lib/shortcuts/keymap_store.dart
+++ b/desktop/lib/shortcuts/keymap_store.dart
@@ -1,3 +1,4 @@
+import '../core/host_platform.dart';
import 'dart:async';
import 'dart:convert';
import 'dart:io';
@@ -44,7 +45,8 @@ class KeymapStore extends ChangeNotifier {
static String defaultPath({Map<String, String>? environment}) {
final env = environment ?? Platform.environment;
final xdg = env['XDG_CONFIG_HOME'];
- final home = env['HOME'] ?? env['USERPROFILE'];
+ var home = env['HOME'] ?? env['USERPROFILE'];
+ if (home == null || home.isEmpty) home = containerHome;
final String root;
if (xdg != null && p.isAbsolute(xdg)) {
root = xdg;
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 0d35d99ca..179abc2c6 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -8,10 +8,14 @@ import 'package:url_launcher/url_launcher.dart';
import '../analytics/analytics.dart';
import '../api/api_client.dart';
+import '../viewer/viewer_services.dart';
import '../auth/auth_session.dart';
+import '../auth/peer_link_client.dart';
+import '../auth/sign_in_client.dart';
import '../auth/cli_link.dart';
import '../auth/cli_login.dart';
import '../bootstrap/environment_provisioner.dart';
+import '../core/viewer_mode.dart';
import '../core/config.dart';
import '../core/agent_preference.dart';
import '../core/build_identity.dart';
@@ -234,8 +238,19 @@ class AppNotifier extends ChangeNotifier {
final AuthSession session;
AppConfig config;
late ApiClient api;
- final CliLogin cliLogin;
+ /// Signs in, and says whether this computer is signed in: the harness CLI in a desktop build,
+ /// [ViewerServices.login] in a viewer build — which has no CLI — under one name, so every call
+ /// site reads the same in both.
+ late final SignInClient cliLogin;
final CliLink cliLink;
+
+ /// Links to other machines by remote password: [cliLink] in a desktop build, the app itself in a
+ /// viewer. THIS machine's own remote password stays on [cliLink] — a viewer is not a machine, and
+ /// has no password for anyone to link to.
+ late final PeerLinkClient peerLinks;
+
+ /// A viewer build's stand-ins for the harness CLI (`lib/viewer/`); null on a desktop build.
+ final ViewerServices? viewer;
final ConfigStore? _store;
/// Spoken tasks waiting for a palette. Broadcast because the screen subscribes and unsubscribes with
@@ -839,8 +854,10 @@ class AppNotifier extends ChangeNotifier {
this.environmentProvisioner,
this.desktopUpdater,
this.connectionForTest,
- CliLogin? cliLogin,
+ SignInClient? cliLogin,
CliLink? cliLink,
+ PeerLinkClient? peerLinks,
+ ViewerServices? viewer,
PaneLayoutStore? paneLayoutStore,
this.turnActivityTimeout = const Duration(seconds: 12),
}) : _paneLayout = paneLayoutStore,
@@ -851,13 +868,26 @@ class AppNotifier extends ChangeNotifier {
agentPreference = AgentPreference(paneLayoutStore?.storage),
session = authSession,
_store = configStore,
- cliLogin = cliLogin ?? CliLogin(),
cliLink = cliLink ?? CliLink(),
- config = configStore?.config ?? config {
+ config = configStore?.config ?? config,
+ viewer =
+ viewer ??
+ (kViewerMode
+ ? ViewerServices(
+ config: configStore?.config ?? config,
+ session: authSession,
+ )
+ : null) {
+ this.cliLogin = cliLogin ?? this.viewer?.login ?? CliLogin();
+ this.peerLinks = peerLinks ?? this.viewer?.links ?? this.cliLink;
_autonomousEnv = this.config.autonomousEnv;
- api = ApiClient(config: this.config, session: session);
+ api = _newApiClient();
}
+ /// Through the local CLI in a desktop build; straight to the backend, signed, in a viewer.
+ ApiClient _newApiClient() =>
+ ApiClient(config: config, session: session, auth: viewer?.auth);
+
String? get lastError => _lastError;
bool get lastErrorRetryable => _lastErrorRetryable;
String? get bootStatusMessage => _bootStatusMessage;
@@ -1380,7 +1410,7 @@ class AppNotifier extends ChangeNotifier {
// history) — a stale `stag` value saved before that removal must
// never silently resurrect it.
_autonomousEnv = 'prod';
- api = ApiClient(config: config, session: session);
+ api = _newApiClient();
_skippedDesktopUpdateVersion = _store.skippedDesktopUpdateVersion;
}
_startUpdateChecking();
@@ -1422,6 +1452,14 @@ class AppNotifier extends ChangeNotifier {
/// runtime were absent; provisioning now makes that a visible, recoverable
/// first-run phase instead.
Future<bool> _prepareEnvironment() async {
+ // A viewer has nothing to provision. The provisioner looks for a shell, the
+ // POSIX tools, tmux and a managed Node runtime under `~/.harness` — all of
+ // which exist to host the local `harness` CLI, which a viewer build does
+ // not have and does not want. Running it on a phone reported every step
+ // missing and parked the app on a setup screen whose two actions, Retry
+ // and Switch to Manual, could not succeed either. Treated as ready so
+ // bootstrap goes on to ask about sign-in, which a viewer can answer.
+ if (viewer != null) return true;
if (_environmentSetupInFlight) return false;
_environmentSetupInFlight = true;
status = AppStatus.checkingEnvironment;
@@ -1496,7 +1534,12 @@ class AppNotifier extends ChangeNotifier {
final revision = _authRevision;
if (!_authWorkCurrent(revision)) return;
_cancelEnvironmentRecheckTimer();
- status = AppStatus.checkingEnvironment;
+ // A viewer skipped the preflight (see [_prepareEnvironment]), so there is no
+ // preflight screen to hold while the sign-in is checked — it stays on the
+ // boot spinner instead.
+ status = viewer == null
+ ? AppStatus.checkingEnvironment
+ : AppStatus.bootstrapping;
notifyListeners();
// Auth now lives entirely with the local `harness` CLI — it owns the SSO session on disk and
// refreshes it itself. This app never reads, stores, or refreshes a token of its own; it just
@@ -1697,7 +1740,7 @@ class AppNotifier extends ChangeNotifier {
void _bootstrapLocalManual(LocalManualFixture fixture) {
_autonomousEnv = 'prod';
config = AppConfig(apiBaseUrl: fixture.apiBaseUrl);
- api = ApiClient(config: config, session: session);
+ api = _newApiClient();
currentUser = const CurrentUserProfile.local();
final machine = Machine(
machineId: fixture.machineId,
@@ -2509,7 +2552,7 @@ class AppNotifier extends ChangeNotifier {
void Function(String stage)? onProgress,
}) async {
if (password.isEmpty) return 'Enter the remote password first';
- final result = await cliLink.connect(
+ final result = await peerLinks.connect(
machineId,
password,
onProgress: onProgress,
@@ -2552,7 +2595,7 @@ class AppNotifier extends ChangeNotifier {
Future<void> refreshLinkedMachines() async {
linkedMachinesLoading = true;
notifyListeners();
- final result = await cliLink.list();
+ final result = await peerLinks.list();
linkedMachinesLoading = false;
linkedMachinesError = result.error;
linkedMachines = result.machines;
@@ -2561,7 +2604,7 @@ class AppNotifier extends ChangeNotifier {
/// Removes a linked machine's trust pin, then refreshes the list. Returns null on success.
Future<String?> unlinkMachine(String machineId) async {
- final error = await cliLink.unlink(machineId);
+ final error = await peerLinks.unlink(machineId);
if (error == null) await refreshLinkedMachines();
return error;
}
diff --git a/desktop/lib/terminal/terminal_binary.dart b/desktop/lib/terminal/terminal_binary.dart
index ccbc32d08..ed51258f1 100644
--- a/desktop/lib/terminal/terminal_binary.dart
+++ b/desktop/lib/terminal/terminal_binary.dart
@@ -57,7 +57,11 @@ enum TerminalBinaryKind {
}
}
-int _maxLocalPayloadBytesFor(TerminalBinaryKind kind) {
+/// The ceiling on one frame of [kind]: the loopback payload here, and equally
+/// the relay's HTRM ciphertext — the CLI's `TERMINAL_BINARY_*_MAX_CIPHERTEXT_BYTES`
+/// are the same numbers, which is why `e2ee/terminal_cipher.dart` reads them from
+/// here rather than restating them.
+int maxTerminalPayloadBytesFor(TerminalBinaryKind kind) {
switch (kind) {
case TerminalBinaryKind.paste:
return terminalLocalPasteMaxPayloadBytes;
@@ -186,7 +190,7 @@ TerminalBinaryFrame? decodeTerminalPlain(
Uint8List? encodeTerminalLocal(TerminalBinaryFrame frame) {
final payload = encodeTerminalPlain(frame);
if (payload == null ||
- payload.length > _maxLocalPayloadBytesFor(frame.kind)) {
+ payload.length > maxTerminalPayloadBytesFor(frame.kind)) {
return null;
}
final header = Uint8List(terminalLocalHeaderBytes)
@@ -209,7 +213,7 @@ TerminalBinaryFrame? decodeTerminalLocal(List<int> raw) {
return null;
}
final length = ByteData.sublistView(bytes).getUint32(8, Endian.big);
- if (length > _maxLocalPayloadBytesFor(kind) ||
+ if (length > maxTerminalPayloadBytesFor(kind) ||
bytes.length != terminalLocalHeaderBytes + length) {
return null;
}
diff --git a/desktop/lib/viewer/direct_auth.dart b/desktop/lib/viewer/direct_auth.dart
new file mode 100644
index 000000000..8f7a9b69e
--- /dev/null
+++ b/desktop/lib/viewer/direct_auth.dart
@@ -0,0 +1,71 @@
+import '../api/access_token_source.dart';
+import '../auth/auth_session.dart';
+import 'direct_auth_api.dart';
+
+/// A viewer build's SSO session — authSession.ts's `AuthSessionManager`, moved into the app because
+/// a device with no harness CLI has nobody else to hold it: the tokens `/api/auth/exchange` issued,
+/// kept in [AuthSession], refreshed [_refreshSkew] before they lapse, one refresh at a time.
+class DirectAuth implements AccessTokenSource {
+ DirectAuth({required this.session, required this.api});
+
+ final AuthSession session;
+ final DirectAuthApi api;
+ Future<String>? _refreshing;
+
+ static const _refreshSkew = Duration(seconds: 60);
+
+ Future<bool> hasSession() async =>
+ ((await session.accessToken()) ?? '').isNotEmpty;
+
+ Future<void> signIn(IssuedTokens tokens) => session.saveLogin(
+ token: tokens.token,
+ refreshToken: tokens.refreshToken,
+ autonomousEnv: tokens.autonomousEnv ?? api.config.autonomousEnv,
+ expiresIn: tokens.expiresIn,
+ );
+
+ Future<void> signOut() => session.clear();
+
+ @override
+ Future<String> accessToken({bool force = false, String? failedToken}) async {
+ final current = await session.accessToken();
+ if (current == null || current.isEmpty) {
+ throw const DirectAuthException('Not signed in.', signedOut: true);
+ }
+ // Someone else already refreshed past the token that failed — use theirs.
+ if (failedToken != null && failedToken != current) return current;
+ if (!force && !await _isStale()) return current;
+ return _refreshing ??= _refresh().whenComplete(() => _refreshing = null);
+ }
+
+ Future<bool> _isStale() async {
+ final expiresAt = await session.accessTokenExpiresAt();
+ return expiresAt != null &&
+ expiresAt.isBefore(DateTime.now().toUtc().add(_refreshSkew));
+ }
+
+ Future<String> _refresh() async {
+ final refreshToken = await session.refreshToken();
+ if (refreshToken == null || refreshToken.isEmpty) {
+ await session.clear();
+ throw const DirectAuthException(
+ 'Your sign-in expired. Sign in again.',
+ signedOut: true,
+ );
+ }
+ try {
+ final autonomousEnv = await session.autonomousEnv();
+ final tokens = await api.refresh(refreshToken, autonomousEnv: autonomousEnv);
+ await session.saveRefresh(
+ token: tokens.token,
+ refreshToken: tokens.refreshToken,
+ autonomousEnv: autonomousEnv,
+ expiresIn: tokens.expiresIn,
+ );
+ return tokens.token;
+ } on DirectAuthException catch (error) {
+ if (error.signedOut) await session.clear();
+ rethrow;
+ }
+ }
+}
diff --git a/desktop/lib/viewer/direct_auth_api.dart b/desktop/lib/viewer/direct_auth_api.dart
new file mode 100644
index 000000000..812bc3e4c
--- /dev/null
+++ b/desktop/lib/viewer/direct_auth_api.dart
@@ -0,0 +1,137 @@
+import 'package:dio/dio.dart';
+
+import '../api/api_client.dart';
+import '../core/config.dart';
+import '../logging/http_log.dart';
+
+/// A sign-in or refresh that produced no usable session.
+class DirectAuthException implements Exception {
+ const DirectAuthException(this.message, {this.signedOut = false});
+
+ final String message;
+
+ /// The session is gone for good: retrying cannot help, only signing in again.
+ final bool signedOut;
+
+ @override
+ String toString() => message;
+}
+
+/// What `/api/auth/exchange` and `/api/auth/refresh` hand back.
+class IssuedTokens {
+ const IssuedTokens({
+ required this.token,
+ this.refreshToken,
+ this.expiresIn,
+ this.autonomousEnv,
+ });
+
+ final String token;
+ final String? refreshToken;
+
+ /// Seconds.
+ final int? expiresIn;
+ final String? autonomousEnv;
+
+ static IssuedTokens? fromData(Object? data) {
+ if (data is! Map) return null;
+ final token = data['token'], refresh = data['refreshToken'];
+ final expiresIn = data['expiresIn'], env = data['autonomousEnv'];
+ if (token is! String || token.isEmpty) return null;
+ return IssuedTokens(
+ token: token,
+ refreshToken: refresh is String && refresh.isNotEmpty ? refresh : null,
+ expiresIn: expiresIn is int && expiresIn > 0 ? expiresIn : null,
+ autonomousEnv: env is String ? env : null,
+ );
+ }
+}
+
+/// The backend's auth endpoints, called by the app itself — in a desktop build the harness CLI
+/// calls them (cli.ts `loginCommand`, authSession.ts `refreshRequest`). No bearer rides these:
+/// they are how one is got.
+class DirectAuthApi {
+ DirectAuthApi({required this.config, Dio? dio})
+ : _dio =
+ dio ??
+ attachHttpLog(
+ Dio(
+ BaseOptions(
+ baseUrl: config.apiBaseUrl,
+ connectTimeout: const Duration(seconds: 15),
+ receiveTimeout: const Duration(seconds: 30),
+ validateStatus: (status) => status != null && status < 600,
+ ),
+ ),
+ );
+
+ final AppConfig config;
+ final Dio _dio;
+
+ static const _unavailable =
+ 'Could not renew your sign-in. That is usually the sign-in service having a moment — '
+ 'if it keeps happening, sign out and sign in again.';
+
+ Future<({String authorizeUrl, String tx})> authorizeNative(
+ String redirectUri,
+ ) async {
+ final data = unwrapApiResponse(
+ await _dio.post(
+ '/api/auth/authorize-native',
+ data: {'redirectUri': redirectUri, 'autonomousEnv': config.autonomousEnv},
+ ),
+ );
+ final url = data is Map ? data['authorizeUrl'] : null;
+ final tx = data is Map ? data['tx'] : null;
+ if (url is! String || url.isEmpty || tx is! String || tx.isEmpty) {
+ throw const DirectAuthException('The server did not return a sign-in page.');
+ }
+ return (authorizeUrl: url, tx: tx);
+ }
+
+ Future<IssuedTokens> exchange({
+ required String code,
+ required String state,
+ required String tx,
+ }) async {
+ final data = unwrapApiResponse(
+ await _dio.post(
+ '/api/auth/exchange',
+ data: {'code': code, 'state': state, 'tx': tx},
+ ),
+ );
+ return IssuedTokens.fromData(data) ??
+ (throw const DirectAuthException('Sign-in returned no access token.'));
+ }
+
+ /// authSession.ts `refreshRequest`, down to its one subtle rule: only a 401 or
+ /// `REFRESH_TOKEN_INVALID` means the session is dead. An unusable refresh token and a real outage
+ /// both come back as the same 503, and reading that as dead would delete a refresh token nothing
+ /// can bring back — on a blip.
+ Future<IssuedTokens> refresh(
+ String refreshToken, {
+ required String autonomousEnv,
+ }) async {
+ final Response<dynamic> res;
+ try {
+ res = await _dio.post(
+ '/api/auth/refresh',
+ data: {'refreshToken': refreshToken, 'autonomousEnv': autonomousEnv},
+ );
+ } on DioException {
+ throw const DirectAuthException(_unavailable);
+ }
+ final body = res.data is Map ? res.data as Map : const {};
+ final error = body['error'] is Map ? body['error'] as Map : const {};
+ if (res.statusCode == 401 || error['code'] == 'REFRESH_TOKEN_INVALID') {
+ throw const DirectAuthException(
+ 'Your sign-in expired. Sign in again.',
+ signedOut: true,
+ );
+ }
+ final tokens = body['success'] == false
+ ? null
+ : IssuedTokens.fromData(body['data']);
+ return tokens ?? (throw const DirectAuthException(_unavailable));
+ }
+}
diff --git a/desktop/lib/viewer/direct_link.dart b/desktop/lib/viewer/direct_link.dart
new file mode 100644
index 000000000..17d0dc13c
--- /dev/null
+++ b/desktop/lib/viewer/direct_link.dart
@@ -0,0 +1,88 @@
+import '../auth/cli_link.dart';
+import '../auth/link_errors.dart';
+import '../auth/peer_link_client.dart';
+import '../core/config.dart';
+import '../e2ee/keys.dart';
+import 'direct_auth.dart';
+import 'direct_auth_api.dart';
+import 'password_link.dart';
+import 'viewer_key_store.dart';
+
+/// `harness link connect/list/unlink` for a device with no harness CLI: the password exchange runs
+/// here ([linkWithPassword]) and the pin lands in [ViewerKeyStore] rather than `machinePeers.json`.
+class DirectLink implements PeerLinkClient {
+ DirectLink({
+ required this.keys,
+ required this.auth,
+ required this.config,
+ this.socket = defaultRelaySocket,
+ });
+
+ final ViewerKeyStore keys;
+ final DirectAuth auth;
+ final AppConfig config;
+ final RelaySocketFactory socket;
+
+ @override
+ Future<CliLinkConnectResult> connect(
+ String machineId,
+ String password, {
+ void Function(String stage)? onProgress,
+ String? displayName,
+ }) async {
+ final String token;
+ try {
+ token = await auth.accessToken();
+ } on DirectAuthException catch (error) {
+ return CliLinkConnectResult(error: error.message);
+ }
+ final result = await linkWithPassword(
+ machineId: machineId,
+ password: password,
+ identity: await keys.identity(),
+ accessToken: token,
+ wsBaseUrl: config.wsBaseUrl,
+ autonomousEnv: config.autonomousEnv,
+ onProgress: (stage) => onProgress?.call(stage.wireName),
+ socket: socket,
+ );
+ switch (result) {
+ case PasswordLinked(:final peerPub, :final fingerprint):
+ await keys.pin(machineId, peerPub);
+ return CliLinkConnectResult(
+ linkedMachineId: machineId,
+ fingerprint: fingerprint,
+ );
+ case PasswordLinkFailed(:final code, :final retryAt):
+ // Named the way the CLI's `--name` names it: the id is all a stranger to this rail sees.
+ final name = displayName == null || displayName.isEmpty
+ ? machineId
+ : displayName;
+ return CliLinkConnectResult(
+ error: humanizeLinkError(code, name, retryAt: retryAt),
+ );
+ }
+ }
+
+ @override
+ Future<CliLinkListResult> list() async => CliLinkListResult(
+ machines: [
+ for (final peer in await keys.peers())
+ LinkedMachine(
+ machineId: peer.machineId,
+ fingerprint: fingerprint(peer.pub),
+ linkedAt: _asCliPrints(peer.linkedAt),
+ ),
+ ],
+ );
+
+ @override
+ Future<String?> unlink(String machineId) async =>
+ await keys.unlink(machineId) ? null : '$machineId is not linked.';
+}
+
+/// `YYYY-MM-DD HH:MM`, the form `harness link list` prints and [LinkedMachine] carries.
+String _asCliPrints(DateTime at) {
+ String two(int n) => n.toString().padLeft(2, '0');
+ return '${at.year}-${two(at.month)}-${two(at.day)} ${two(at.hour)}:${two(at.minute)}';
+}
diff --git a/desktop/lib/viewer/direct_login.dart b/desktop/lib/viewer/direct_login.dart
new file mode 100644
index 000000000..ccddf0284
--- /dev/null
+++ b/desktop/lib/viewer/direct_login.dart
@@ -0,0 +1,107 @@
+import 'dart:async';
+import 'dart:io';
+
+import '../auth/cli_login.dart';
+import '../auth/sign_in_client.dart';
+import 'direct_auth.dart';
+import 'direct_auth_api.dart';
+
+/// Signing in with no harness CLI — cli.ts `loginCommand`, run by the app: a loopback listener for
+/// the SSO redirect, `authorize-native` for the page to show, `exchange` for the tokens.
+///
+/// It deliberately skips the CLI's closing `resolve-computer`, which registers the computer as a
+/// Harness machine. A viewer is not one.
+class DirectLogin implements SignInClient {
+ DirectLogin({required this.auth});
+
+ final DirectAuth auth;
+ _LoopbackCallback? _pending;
+
+ static const _callbackTimeout = Duration(minutes: 5);
+
+ @override
+ Future<CliAuthStatus> checkStatus() async =>
+ CliAuthStatus(loggedIn: await auth.hasSession());
+
+ @override
+ Future<void> login({
+ required void Function(String url) onAuthorizeUrl,
+ }) async {
+ final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
+ final callback = _pending = _LoopbackCallback(server);
+ try {
+ final start = await auth.api.authorizeNative(
+ 'http://127.0.0.1:${server.port}/callback',
+ );
+ onAuthorizeUrl(start.authorizeUrl);
+ final redirect = await callback.result.timeout(
+ _callbackTimeout,
+ onTimeout: () => throw const DirectAuthException('Sign-in timed out.'),
+ );
+ await auth.signIn(
+ await auth.api.exchange(
+ code: redirect.code,
+ state: redirect.state,
+ tx: start.tx,
+ ),
+ );
+ } finally {
+ _pending = null;
+ await server.close(force: true);
+ }
+ }
+
+ @override
+ void cancel() => _pending?.cancel();
+
+ @override
+ Future<void> logout() => auth.signOut();
+}
+
+/// The loopback end of the redirect: the first `/callback` carrying `code` and `state` completes
+/// it and an `error` fails it; anything else the browser asks for (a favicon) is turned away.
+class _LoopbackCallback {
+ _LoopbackCallback(HttpServer server) {
+ server.listen(_onRequest);
+ }
+
+ final _completer = Completer<({String code, String state})>();
+
+ Future<({String code, String state})> get result => _completer.future;
+
+ Future<void> _onRequest(HttpRequest request) async {
+ final response = request.response;
+ if (request.uri.path != '/callback') {
+ response.statusCode = HttpStatus.notFound;
+ await response.close();
+ return;
+ }
+ final query = request.uri.queryParameters;
+ final code = query['code'], state = query['state'], error = query['error'];
+ final signedIn = error == null && code != null && state != null;
+ response
+ ..statusCode = signedIn ? HttpStatus.ok : HttpStatus.badRequest
+ ..headers.contentType = ContentType.html
+ ..write(_page(signedIn ? 'Signed in to Harness' : 'Harness sign-in failed'));
+ await response.close();
+ if (_completer.isCompleted) return;
+ if (signedIn) {
+ _completer.complete((code: code, state: state));
+ } else {
+ _completer.completeError(
+ DirectAuthException('Sign-in failed: ${error ?? 'no code returned'}'),
+ );
+ }
+ }
+
+ void cancel() {
+ if (_completer.isCompleted) return;
+ _completer.completeError(const DirectAuthException('Sign-in was cancelled.'));
+ }
+}
+
+String _page(String title) =>
+ '<!doctype html><meta charset="utf-8"><title>$title</title>'
+ '<body style="font:16px system-ui,sans-serif;text-align:center;padding:4em 1em">'
+ '<h1 style="font-weight:600">$title</h1>'
+ '<p>You can close this window and go back to Harness.</p></body>';
diff --git a/desktop/lib/viewer/e2ee_relay_codec.dart b/desktop/lib/viewer/e2ee_relay_codec.dart
new file mode 100644
index 000000000..1635162ff
--- /dev/null
+++ b/desktop/lib/viewer/e2ee_relay_codec.dart
@@ -0,0 +1,64 @@
+import 'dart:typed_data';
+
+import '../e2ee/envelope.dart';
+import '../e2ee/relay_session_crypto.dart';
+import '../terminal/terminal_binary.dart';
+import '../ws/relay_codec.dart';
+import 'viewer_key_store.dart';
+
+/// [RelaySessionCrypto] as a [RelayCodec]: the conversion the harness CLI's `remoteRelay.ts` does
+/// between the relay's HTRM frames and the loopback HTRL ones, done in the app instead.
+class E2eeRelayCodec implements RelayCodec {
+ E2eeRelayCodec(this._session);
+
+ final RelaySessionCrypto _session;
+
+ @override
+ Map<String, dynamic> helloFrame() => _session.helloFrame();
+
+ @override
+ Future<bool> handleWelcome(Map<String, dynamic> payload) =>
+ _session.handleWelcome(payload);
+
+ @override
+ bool handleRekey(Map<String, dynamic> payload) =>
+ _session.handleRekey(payload);
+
+ @override
+ Map<String, dynamic>? encodeFrame(Map<String, dynamic> frame) {
+ final type = frame['type'];
+ final mustSeal = type is String && encryptedDownTypes.contains(type);
+ if (mustSeal && !_session.ready) return null;
+ return _session.wrapOutgoing(frame);
+ }
+
+ @override
+ Map<String, dynamic>? decodeFrame(Map<String, dynamic> frame) =>
+ _session.unwrapIncoming(frame);
+
+ @override
+ Uint8List? encodeBinary(Uint8List localFrame) {
+ final clear = decodeTerminalLocal(localFrame);
+ return clear == null ? null : _session.encryptTerminal(clear);
+ }
+
+ @override
+ Uint8List? decodeBinary(Uint8List wireFrame) {
+ final clear = _session.decryptTerminal(wireFrame);
+ return clear == null ? null : encodeTerminalLocal(clear);
+ }
+}
+
+/// The viewer's [RelayCodecFactory]: a new session per connection, against the identity this
+/// device pinned for the machine when it linked — or none, when it never has.
+RelayCodecFactory viewerRelayCodecs(ViewerKeyStore keys) => (machineId) async {
+ final peer = await keys.peer(machineId);
+ if (peer == null) return null;
+ return E2eeRelayCodec(
+ await RelaySessionCrypto.start(
+ machineId: machineId,
+ identity: await keys.identity(),
+ peerPub: peer.pub,
+ ),
+ );
+};
diff --git a/desktop/lib/viewer/password_link.dart b/desktop/lib/viewer/password_link.dart
new file mode 100644
index 000000000..5c366f989
--- /dev/null
+++ b/desktop/lib/viewer/password_link.dart
@@ -0,0 +1,256 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:typed_data';
+
+import 'package:web_socket_channel/web_socket_channel.dart';
+
+import '../e2ee/bytes.dart';
+import '../e2ee/cpace.dart';
+import '../e2ee/envelope.dart';
+import '../e2ee/keys.dart';
+import '../e2ee/password_pake.dart';
+import '../e2ee/primitives.dart';
+
+/// How far a password link has got — the stages `harness link connect --json` reports, spelled the
+/// same (see [wireName]) so the link form shows one progress for either build.
+enum PasswordLinkStage {
+ connecting('connecting'),
+ derivingKey('deriving_key'),
+ exchanging('exchanging'),
+ verifying('verifying');
+
+ const PasswordLinkStage(this.wireName);
+
+ final String wireName;
+}
+
+sealed class PasswordLinkResult {
+ const PasswordLinkResult();
+}
+
+final class PasswordLinked extends PasswordLinkResult {
+ const PasswordLinked(this.peerPub, this.fingerprint);
+
+ /// The machine's identity, to pin.
+ final Uint8List peerPub;
+ final String fingerprint;
+}
+
+final class PasswordLinkFailed extends PasswordLinkResult {
+ const PasswordLinkFailed(this.code, {this.retryAt});
+
+ /// The CLI's own code: `WRONG_PASSWORD`, `TIMEOUT`, or whatever the machine refused with.
+ final String code;
+
+ /// When a locked-out password may be tried again, if the machine said.
+ final DateTime? retryAt;
+}
+
+typedef RelaySocketFactory =
+ WebSocketChannel Function(Uri uri, Iterable<String> protocols);
+
+WebSocketChannel defaultRelaySocket(Uri uri, Iterable<String> protocols) =>
+ WebSocketChannel.connect(uri, protocols: protocols);
+
+/// relayClient.ts `connectWithPassword`: over a short-lived relay socket, prove to [machineId] that
+/// this device knows its `harness remote-password`, and learn the identity to pin for it. Nobody
+/// approves anything on the machine — knowing the password is the approval.
+///
+/// [timeout] is twice the CLI's 15s: the stretch inside it is about a second on a laptop and can be
+/// several on a phone, and a link that fails for being slow reads exactly like a wrong password.
+Future<PasswordLinkResult> linkWithPassword({
+ required String machineId,
+ required String password,
+ required E2eeIdentity identity,
+ required String accessToken,
+ required String wsBaseUrl,
+ required String autonomousEnv,
+ void Function(PasswordLinkStage stage)? onProgress,
+ RelaySocketFactory socket = defaultRelaySocket,
+ Duration timeout = const Duration(seconds: 30),
+}) async {
+ onProgress?.call(PasswordLinkStage.connecting);
+ final uri = Uri.parse('$wsBaseUrl/api/web-ws').replace(
+ queryParameters: {'autonomousEnv': autonomousEnv},
+ );
+ final channel = socket(uri, [accessToken]);
+ final run = _PasswordLinkRun(machineId, password, identity, channel, onProgress);
+ try {
+ await channel.ready;
+ return await run.drive().timeout(
+ timeout,
+ onTimeout: () => const PasswordLinkFailed('TIMEOUT'),
+ );
+ } catch (_) {
+ return const PasswordLinkFailed('CONNECTION_ERROR');
+ } finally {
+ unawaited(channel.sink.close());
+ }
+}
+
+const _wrongPassword = PasswordLinkFailed('WRONG_PASSWORD');
+
+/// The joiner ('b') side of the machine's `onPwPairIntent`/`onPwPake` state machine.
+class _PasswordLinkRun {
+ _PasswordLinkRun(
+ this.machineId,
+ this.password,
+ this.identity,
+ this.channel,
+ this.onProgress,
+ );
+
+ final String machineId;
+ final String password;
+ final E2eeIdentity identity;
+ final WebSocketChannel channel;
+ final void Function(PasswordLinkStage stage)? onProgress;
+
+ final Uint8List _sid = secureRandomBytes(16);
+ late final String _sidB64 = b64e(_sid);
+ final String _requestId = b64e(secureRandomBytes(16));
+ late final String _ci = pwContext(machineId);
+ bool _selected = false;
+ Uint8List? _stretched;
+ Uint8List? _isk;
+ Uint8List? _transcript;
+ Uint8List? _machinePub;
+
+ Future<PasswordLinkResult> drive() async {
+ _send('machine_select', {'machineId': machineId});
+ await for (final raw in channel.stream) {
+ final frame = raw is String ? jsonObjectOf(utf8Bytes(raw)) : null;
+ if (frame == null) continue;
+ final PasswordLinkResult? result;
+ try {
+ result = await _step(frame);
+ } catch (_) {
+ // Anything this side cannot parse or verify is the protocol failing, as in the CLI.
+ return const PasswordLinkFailed('PROTOCOL_ERROR');
+ }
+ if (result != null) return result;
+ }
+ return PasswordLinkFailed('CONNECTION_CLOSED:${channel.closeCode}');
+ }
+
+ Future<PasswordLinkResult?> _step(Map<String, dynamic> frame) async {
+ final type = frame['type'];
+ final payload = frame['payload'] is Map<String, dynamic>
+ ? frame['payload'] as Map<String, dynamic>
+ : const <String, dynamic>{};
+ if (!_selected) {
+ if (payload['machineId'] != machineId) return null;
+ if (type == 'connected') return _sendIntent();
+ if (type == 'machine_select_error') {
+ return PasswordLinkFailed(_codeOr(payload['error'], 'SELECT_FAILED'));
+ }
+ return null;
+ }
+ if (type == 'e2e_pw_pair_result' && payload['requestId'] == _requestId) {
+ return payload['ok'] == true ? null : _refused(payload);
+ }
+ if (type != 'e2e_pw_pake' || payload['sid'] != _sidB64) return null;
+ final error = payload['error'];
+ return switch (payload['round']) {
+ 1 when error != null => PasswordLinkFailed('$error'),
+ 1 => _answerShare(payload),
+ 3 when error != null => PasswordLinkFailed('$error'),
+ 3 => await _answerIdentity(payload),
+ 5 => _finish(payload),
+ _ => null,
+ };
+ }
+
+ Future<PasswordLinkResult?> _sendIntent() async {
+ _selected = true;
+ onProgress?.call(PasswordLinkStage.derivingKey);
+ try {
+ _stretched = await stretchPassword(password, machineId);
+ } catch (_) {
+ return const PasswordLinkFailed('DERIVE_FAILED');
+ }
+ onProgress?.call(PasswordLinkStage.exchanging);
+ _send('e2e_pw_pair_intent', {'requestId': _requestId, 'sid': _sidB64});
+ return null;
+ }
+
+ /// Round 1 in, round 2 out: our CPace share, and a MAC only the right password could have made.
+ PasswordLinkResult? _answerShare(Map<String, dynamic> payload) {
+ final stretched = _stretched;
+ if (stretched == null) return null;
+ final theirs = b64d(payload['ya'] as String);
+ final ours = cpaceStart(pwCpaceGenerator(stretched, _sid, _ci));
+ final isk = _isk = cpaceIsk(
+ _sid,
+ cpaceShared(theirs, ours.scalar),
+ theirs,
+ ours.share,
+ );
+ final transcript = _transcript = transcriptHash(_sid, _ci, theirs, ours.share);
+ onProgress?.call(PasswordLinkStage.verifying);
+ _send('e2e_pw_pake', {
+ 'sid': _sidB64,
+ 'round': 2,
+ 'yb': b64e(ours.share),
+ 'mac': b64e(macTag(kcKeys(isk, _ci).web, transcript)),
+ });
+ return null;
+ }
+
+ /// Round 3 in, round 4 out: the machine proves the password too and hands over its identity,
+ /// bound to this transcript; ours goes back the same way.
+ Future<PasswordLinkResult?> _answerIdentity(Map<String, dynamic> payload) async {
+ final isk = _isk, transcript = _transcript;
+ if (isk == null || transcript == null) {
+ return const PasswordLinkFailed('PROTOCOL_ERROR');
+ }
+ final mac = b64d(payload['mac'] as String);
+ if (!macVerify(kcKeys(isk, _ci).adapter, transcript, mac)) {
+ return _wrongPassword;
+ }
+ final key = pairKey(isk, _ci);
+ final opened = aeadOpen(key, 3, utf8Bytes('e2e-id'), b64d(payload['enc'] as String));
+ final claim = opened == null ? null : jsonObjectOf(opened);
+ final id = claim?['id'], sig = claim?['sig'];
+ if (id is! String || sig is! String) return _wrongPassword;
+ final machinePub = b64d(id);
+ if (!await pairBindVerify(machinePub, transcript, b64d(sig))) {
+ return _wrongPassword;
+ }
+ _machinePub = machinePub;
+ final ours = jsonEncode({
+ 'id': b64e(identity.pub),
+ 'sig': b64e(await pairBindSig(identity, transcript)),
+ });
+ _send('e2e_pw_pake', {
+ 'sid': _sidB64,
+ 'round': 4,
+ 'enc': b64e(aeadSeal(key, 4, utf8Bytes('e2e-id'), utf8Bytes(ours))),
+ });
+ return null;
+ }
+
+ /// The fingerprint is computed here rather than taken from the frame, unlike the CLI: round 5
+ /// crosses the relay in the clear, and the pinned key is the thing it must describe.
+ PasswordLinkResult _finish(Map<String, dynamic> payload) {
+ final machinePub = _machinePub;
+ if (payload['ok'] != true || machinePub == null) {
+ return PasswordLinkFailed(_codeOr(payload['error'], 'PAIR_FAILED'));
+ }
+ return PasswordLinked(machinePub, fingerprint(machinePub));
+ }
+
+ PasswordLinkFailed _refused(Map<String, dynamic> payload) {
+ final retryAt = payload['retryAt'];
+ return PasswordLinkFailed(
+ _codeOr(payload['error'], 'PAIR_FAILED'),
+ retryAt: retryAt is int ? DateTime.fromMillisecondsSinceEpoch(retryAt) : null,
+ );
+ }
+
+ void _send(String type, Map<String, Object> payload) =>
+ channel.sink.add(jsonEncode({'type': type, 'payload': payload}));
+}
+
+String _codeOr(Object? value, String fallback) =>
+ value is String && value.isNotEmpty ? value : fallback;
diff --git a/desktop/lib/viewer/sign_in_browser.dart b/desktop/lib/viewer/sign_in_browser.dart
new file mode 100644
index 000000000..8b760ace7
--- /dev/null
+++ b/desktop/lib/viewer/sign_in_browser.dart
@@ -0,0 +1,24 @@
+import 'dart:io';
+
+import 'package:url_launcher/url_launcher.dart';
+
+/// Where the SSO page opens: the system browser, as it always has — except on a phone.
+///
+/// There, handing the person to Safari or Chrome suspends this app and with it the loopback
+/// listener the page redirects back to, so the page opens in-app (SFSafariViewController on iOS,
+/// a Custom Tab on Android), where the app keeps running, and [closeSignInPage] takes it down
+/// once the redirect lands.
+///
+/// ⚠️ Unverified on a device: the SSO page's Google button opens a popup, and whether an in-app
+/// browser view lets that popup post back to its opener is exactly what the first run on a phone
+/// has to answer.
+Future<bool> openSignInPage(Uri url) => launchUrl(
+ url,
+ mode: Platform.isIOS || Platform.isAndroid
+ ? LaunchMode.inAppBrowserView
+ : LaunchMode.externalApplication,
+);
+
+Future<void> closeSignInPage() async {
+ if (Platform.isIOS || Platform.isAndroid) await closeInAppWebView();
+}
diff --git a/desktop/lib/viewer/viewer_key_store.dart b/desktop/lib/viewer/viewer_key_store.dart
new file mode 100644
index 000000000..8514aa9f7
--- /dev/null
+++ b/desktop/lib/viewer/viewer_key_store.dart
@@ -0,0 +1,125 @@
+import 'dart:convert';
+import 'dart:typed_data';
+
+import '../core/harness_file_store.dart';
+import '../core/local_key_value_store.dart';
+import '../e2ee/bytes.dart';
+import '../e2ee/keys.dart';
+
+/// A machine this device linked to by its remote password, and the identity it pinned for it — the
+/// same shape as the harness CLI's `machinePeers.json` rows.
+class MachinePeer {
+ const MachinePeer({
+ required this.machineId,
+ required this.pub,
+ required this.linkedAt,
+ this.label = '',
+ });
+
+ final String machineId;
+ final Uint8List pub;
+ final String label;
+ final DateTime linkedAt;
+
+ /// Null for a row that is not one — a damaged file loses that row, not every link.
+ static MachinePeer? tryParse(Object? json) {
+ if (json is! Map) return null;
+ final machineId = json['machineId'], pub = json['pub'];
+ final linkedAt = json['linkedAt'], label = json['label'];
+ if (machineId is! String || pub is! String || linkedAt is! int) return null;
+ try {
+ return MachinePeer(
+ machineId: machineId,
+ pub: b64d(pub),
+ label: label is String ? label : '',
+ linkedAt: DateTime.fromMillisecondsSinceEpoch(linkedAt),
+ );
+ } on FormatException {
+ return null;
+ }
+ }
+
+ Map<String, Object> toJson() => {
+ 'machineId': machineId,
+ 'pub': b64e(pub),
+ 'label': label,
+ 'linkedAt': linkedAt.millisecondsSinceEpoch,
+ };
+}
+
+/// This device's E2EE identity and the machines it has linked — what the harness CLI keeps under
+/// its `e2e/` directory, kept here where there is no CLI.
+///
+/// TODO(security): the identity seed lives in the state file — 0600 on a desktop, the app sandbox
+/// on iOS — the protection the CLI gives its own and less than Keychain/DPAPI would. Moving it
+/// into the platform keystore is a follow-up.
+class ViewerKeyStore {
+ ViewerKeyStore({LocalKeyValueStore? storage})
+ : _storage = storage ?? HarnessFileStore.shared;
+
+ final LocalKeyValueStore _storage;
+ Future<E2eeIdentity>? _identity;
+
+ static const _seedKey = 'viewer_e2ee_identity_seed';
+ static const _peersKey = 'viewer_e2ee_machine_peers';
+
+ /// Minted on first use and kept: every linked machine has pinned it.
+ Future<E2eeIdentity> identity() => _identity ??= _loadOrMintIdentity();
+
+ Future<E2eeIdentity> _loadOrMintIdentity() async {
+ final stored = await _storage.read(_seedKey);
+ if (stored != null) return E2eeIdentity.fromSeed(b64d(stored));
+ final minted = await E2eeIdentity.generate();
+ await _storage.write(_seedKey, b64e(minted.seed));
+ return minted;
+ }
+
+ /// Newest link first.
+ Future<List<MachinePeer>> peers() async {
+ final raw = await _storage.read(_peersKey);
+ if (raw == null) return const [];
+ final Object? decoded;
+ try {
+ decoded = jsonDecode(raw);
+ } on FormatException {
+ return const [];
+ }
+ if (decoded is! List) return const [];
+ return decoded.map(MachinePeer.tryParse).whereType<MachinePeer>().toList()
+ ..sort((a, b) => b.linkedAt.compareTo(a.linkedAt));
+ }
+
+ Future<MachinePeer?> peer(String machineId) async {
+ for (final peer in await peers()) {
+ if (peer.machineId == machineId) return peer;
+ }
+ return null;
+ }
+
+ Future<void> pin(String machineId, List<int> pub, {String label = ''}) async {
+ await _write([
+ for (final peer in await peers())
+ if (peer.machineId != machineId) peer,
+ MachinePeer(
+ machineId: machineId,
+ pub: Uint8List.fromList(pub),
+ label: label,
+ linkedAt: DateTime.now(),
+ ),
+ ]);
+ }
+
+ /// False when [machineId] was not linked.
+ Future<bool> unlink(String machineId) async {
+ final current = await peers();
+ final remaining = current.where((peer) => peer.machineId != machineId).toList();
+ if (remaining.length == current.length) return false;
+ await _write(remaining);
+ return true;
+ }
+
+ Future<void> _write(List<MachinePeer> peers) => _storage.write(
+ _peersKey,
+ jsonEncode([for (final peer in peers) peer.toJson()]),
+ );
+}
diff --git a/desktop/lib/viewer/viewer_services.dart b/desktop/lib/viewer/viewer_services.dart
new file mode 100644
index 000000000..1c6fb7968
--- /dev/null
+++ b/desktop/lib/viewer/viewer_services.dart
@@ -0,0 +1,45 @@
+import '../auth/auth_session.dart';
+import '../core/config.dart';
+import '../ws/relay_codec.dart';
+import 'direct_auth.dart';
+import 'direct_auth_api.dart';
+import 'direct_link.dart';
+import 'direct_login.dart';
+import 'e2ee_relay_codec.dart';
+import 'viewer_key_store.dart';
+
+/// Everything a viewer build uses in place of the harness CLI, built once and handed to
+/// `AppNotifier`: the SSO session, signing in, the machines this device has linked and the E2EE
+/// sessions to them. A desktop build has none — and where it is null, nothing in the app behaves
+/// any differently than it did before viewers existed.
+class ViewerServices {
+ const ViewerServices._({
+ required this.keys,
+ required this.auth,
+ required this.login,
+ required this.links,
+ required this.relayCodecs,
+ });
+
+ factory ViewerServices({
+ required AppConfig config,
+ required AuthSession session,
+ ViewerKeyStore? keys,
+ }) {
+ final store = keys ?? ViewerKeyStore();
+ final auth = DirectAuth(session: session, api: DirectAuthApi(config: config));
+ return ViewerServices._(
+ keys: store,
+ auth: auth,
+ login: DirectLogin(auth: auth),
+ links: DirectLink(keys: store, auth: auth, config: config),
+ relayCodecs: viewerRelayCodecs(store),
+ );
+ }
+
+ final ViewerKeyStore keys;
+ final DirectAuth auth;
+ final DirectLogin login;
+ final DirectLink links;
+ final RelayCodecFactory relayCodecs;
+}
diff --git a/desktop/lib/widgets/swarm_tab_strip.dart b/desktop/lib/widgets/swarm_tab_strip.dart
new file mode 100644
index 000000000..3209cf6b3
--- /dev/null
+++ b/desktop/lib/widgets/swarm_tab_strip.dart
@@ -0,0 +1,228 @@
+import 'package:flutter/material.dart';
+
+import '../shared/layouts/window_size.dart';
+import '../shared/theme/app_theme.dart' as grid;
+import '../shortcuts/app_keymap.dart';
+import '../shortcuts/app_shortcuts.dart';
+import '../state/app_state.dart';
+
+/// What the overflow menu can run when the strip is too narrow to show the
+/// actions as buttons.
+enum _StripAction { newSwarm, search, newAgent }
+
+/// The swarm tabs, and the shell's global actions beside them.
+///
+/// Split out of `screens/swarm_screen.dart` because it is the one piece of
+/// shell chrome that has to answer for its own width. The grid below it already
+/// measures the window — `_SwarmGeometry` reads the viewport and `auto` picks
+/// its column count from it (`widgets/pane_grid.dart`) — while this strip was
+/// drawn at one fixed size: every tab 186pt whether four or twenty-four were
+/// open, and four icon buttons holding ~176pt of the row no matter how little
+/// was left. Below roughly 700pt that left the tabs a sliver to scroll inside.
+///
+/// Two things move with the width, and nothing else does:
+///
+/// * A tab shrinks, from [maxTabWidth] down to [minTabWidth], before the strip
+/// starts scrolling. A window with room for full-width tabs is laid out
+/// exactly as it was, so nothing changes on the size this was drawn for.
+/// * At [WindowSizeClass.compact] the three actions that are only shortcuts
+/// for something reachable elsewhere fold into one overflow button.
+/// Notifications stays out, because its badge is the only part of this strip
+/// that carries state the user cannot see anywhere else.
+class SwarmTabStrip extends StatelessWidget {
+ const SwarmTabStrip({
+ super.key,
+ required this.notifier,
+ required this.attention,
+ required this.onRename,
+ required this.onSearch,
+ required this.onNewAgent,
+ required this.onNotifications,
+ });
+
+ /// Unchanged by width — only what sits in the strip moves, never its height.
+ static const double height = 44;
+
+ /// What a tab is drawn at when the row has room for it.
+ static const double maxTabWidth = 186;
+
+ /// Past this a tab has no room left for a name, so the strip scrolls rather
+ /// than shrinking into a row of identical stubs.
+ static const double minTabWidth = 112;
+
+ final AppNotifier notifier;
+ final int attention;
+ final ValueChanged<String> onRename;
+ final VoidCallback onSearch;
+ final VoidCallback onNewAgent;
+ final VoidCallback onNotifications;
+
+ @override
+ Widget build(BuildContext context) => Container(
+ height: height,
+ color: grid.AppPalette.swarmTabBar,
+ child: LayoutBuilder(
+ builder: (context, constraints) => Row(
+ children: [
+ const SizedBox(width: 10),
+ // The tabs measure what is left AFTER the actions have taken theirs,
+ // which is why this is an inner LayoutBuilder and not the outer one.
+ Expanded(child: _tabs()),
+ ..._actions(context, WindowSizeClass.fromWidth(constraints.maxWidth)),
+ const SizedBox(width: 6),
+ ],
+ ),
+ ),
+ );
+
+ Widget _tabs() => LayoutBuilder(
+ builder: (context, constraints) {
+ final count = notifier.swarms.length;
+ final width = count == 0
+ ? maxTabWidth
+ : (constraints.maxWidth / count)
+ .clamp(minTabWidth, maxTabWidth)
+ .toDouble();
+ return ReorderableListView.builder(
+ scrollDirection: Axis.horizontal,
+ shrinkWrap: true,
+ buildDefaultDragHandles: false,
+ itemCount: count,
+ onReorderItem: (old, to) =>
+ notifier.reorderSwarm(notifier.swarms[old].id, to),
+ itemBuilder: (context, index) => _tab(index, width),
+ );
+ },
+ );
+
+ Widget _tab(int index, double width) {
+ final swarm = notifier.swarms[index];
+ final active = notifier.activeSwarmId == swarm.id;
+ return ReorderableDragStartListener(
+ key: ValueKey(swarm.id),
+ index: index,
+ child: GestureDetector(
+ onDoubleTap: () => onRename(swarm.id),
+ child: Container(
+ width: width,
+ margin: const EdgeInsets.only(top: 6, right: 2),
+ decoration: BoxDecoration(
+ color: active ? grid.AppPalette.swarmField : Colors.transparent,
+ borderRadius: const BorderRadius.vertical(top: Radius.circular(9)),
+ ),
+ child: Row(
+ children: [
+ Expanded(
+ child: TextButton(
+ onPressed: () => notifier.selectSwarm(swarm.id),
+ style: TextButton.styleFrom(
+ animationDuration: Duration.zero,
+ foregroundColor: active ? Colors.white : Colors.white70,
+ ),
+ child: Text(
+ swarm.name,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: const TextStyle(fontSize: 13),
+ ),
+ ),
+ ),
+ IconButton(
+ tooltip: 'Close ${swarm.name}',
+ onPressed: () => notifier.closeSwarm(swarm.id),
+ icon: const Icon(Icons.close, size: 13),
+ constraints: const BoxConstraints.tightFor(
+ width: 30,
+ height: 30,
+ ),
+ padding: EdgeInsets.zero,
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+
+ List<Widget> _actions(BuildContext context, WindowSizeClass size) => [
+ if (!size.isCompact) ...[
+ IconButton(
+ tooltip: withEffectiveShortcutHint(
+ context,
+ 'New swarm',
+ ShortcutAction.newSwarm,
+ ),
+ onPressed: _canAddSwarm ? notifier.newSwarm : null,
+ icon: const Icon(Icons.add, size: 18),
+ ),
+ IconButton(
+ key: const ValueKey('swarm-search-button'),
+ tooltip: withEffectiveShortcutHint(
+ context,
+ 'Search',
+ ShortcutAction.switchAgent,
+ ),
+ onPressed: onSearch,
+ icon: const Icon(Icons.search, size: 20),
+ ),
+ IconButton(
+ key: const ValueKey('swarm-new-agent-button'),
+ tooltip: withEffectiveShortcutHint(
+ context,
+ 'New agent',
+ ShortcutAction.newAgent,
+ ),
+ onPressed: onNewAgent,
+ icon: const Icon(Icons.add, size: 20),
+ ),
+ ],
+ IconButton(
+ key: const ValueKey('swarm-notifications-button'),
+ tooltip: withEffectiveShortcutHint(
+ context,
+ 'Agents needing input',
+ ShortcutAction.showAttention,
+ ),
+ onPressed: onNotifications,
+ icon: Badge(
+ isLabelVisible: attention > 0,
+ child: const Icon(Icons.notifications_none, size: 20),
+ ),
+ ),
+ if (size.isCompact) _overflow(),
+ ];
+
+ Widget _overflow() => PopupMenuButton<_StripAction>(
+ key: const ValueKey('swarm-overflow-button'),
+ tooltip: 'More',
+ constraints: const BoxConstraints(minWidth: 180),
+ icon: const Icon(Icons.more_vert, size: 20),
+ itemBuilder: (_) => [
+ PopupMenuItem(
+ value: _StripAction.newSwarm,
+ enabled: _canAddSwarm,
+ child: const Text('New swarm'),
+ ),
+ const PopupMenuItem(
+ value: _StripAction.search,
+ child: Text('Search'),
+ ),
+ const PopupMenuItem(
+ value: _StripAction.newAgent,
+ child: Text('New agent'),
+ ),
+ ],
+ onSelected: (action) {
+ switch (action) {
+ case _StripAction.newSwarm:
+ notifier.newSwarm();
+ case _StripAction.search:
+ onSearch();
+ case _StripAction.newAgent:
+ onNewAgent();
+ }
+ },
+ );
+
+ bool get _canAddSwarm => notifier.swarms.length < AppNotifier.maxSwarms;
+}
diff --git a/desktop/lib/widgets/window_chrome.dart b/desktop/lib/widgets/window_chrome.dart
index cdd49bf1d..0af21fd49 100644
--- a/desktop/lib/widgets/window_chrome.dart
+++ b/desktop/lib/widgets/window_chrome.dart
@@ -3,6 +3,7 @@ import 'dart:io' show Platform;
import 'package:flutter/widgets.dart';
import 'package:window_manager/window_manager.dart';
+import '../core/desktop_window.dart';
import '../shared/theme/app_theme.dart' as grid;
/// How far a full-width strip drawn at the very top of the window has to
@@ -90,7 +91,11 @@ class WindowDragArea extends StatelessWidget {
// Translucent, like DragToMoveArea: the drag has to be available from
// the gaps between whatever the region draws.
behavior: HitTestBehavior.translucent,
- onPanStart: (_) => windowManager.startDragging(),
+ // Null off the desktop, so no pan recognizer is registered at all rather
+ // than one that throws the moment someone drags the chrome.
+ onPanStart: hasManagedWindow
+ ? (_) => windowManager.startDragging()
+ : null,
child: child,
);
}
diff --git a/desktop/lib/ws/relay_codec.dart b/desktop/lib/ws/relay_codec.dart
new file mode 100644
index 000000000..900b45f49
--- /dev/null
+++ b/desktop/lib/ws/relay_codec.dart
@@ -0,0 +1,35 @@
+import 'dart:typed_data';
+
+/// What a relay [WsConn] needs from an end-to-end session with the machine behind it.
+///
+/// Where the harness CLI is the transport (macOS, Linux) nothing does — the CLI already opened the
+/// session and hands over plaintext — so only a viewer build supplies one
+/// (`viewer/e2ee_relay_codec.dart`). The codec speaks the loopback formats on the app's side
+/// (plain JSON payloads, HTRL binary frames), so nothing above [WsConn] can tell the two apart.
+abstract interface class RelayCodec {
+ /// Sent once the relay acks `machine_select`.
+ Map<String, dynamic> helloFrame();
+
+ /// True once the machine's `e2e_welcome` has made the session usable.
+ Future<bool> handleWelcome(Map<String, dynamic> payload);
+
+ bool handleRekey(Map<String, dynamic> payload);
+
+ /// The frame as it may cross the relay. Null when it must travel sealed and the session is not
+ /// up yet — it must then not go at all: sent in the clear it leaks, and a terminal frame is
+ /// rejected by the relay outright.
+ Map<String, dynamic>? encodeFrame(Map<String, dynamic> frame);
+
+ /// Null means drop it: stale, replayed or not authentic.
+ Map<String, dynamic>? decodeFrame(Map<String, dynamic> frame);
+
+ /// A loopback (HTRL) frame, sealed for the relay; null when it cannot be.
+ Uint8List? encodeBinary(Uint8List localFrame);
+
+ /// A relay frame, opened back into loopback (HTRL) form; null means drop it.
+ Uint8List? decodeBinary(Uint8List wireFrame);
+}
+
+/// A fresh session for each connection to [machineId]; null when this device has no link to it —
+/// the machine could only answer `e2e_denied`, so there is nothing worth dialing.
+typedef RelayCodecFactory = Future<RelayCodec?> Function(String machineId);
diff --git a/desktop/pubspec.lock b/desktop/pubspec.lock
index f25dae9bd..48c575b11 100644
--- a/desktop/pubspec.lock
+++ b/desktop/pubspec.lock
@@ -588,6 +588,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.1.0"
+ unorm_dart:
+ dependency: "direct main"
+ description:
+ name: unorm_dart
+ sha256: "0c69186b03ca6addab0774bcc0f4f17b88d4ce78d9d4d8f0619e30a99ead58e7"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.3.2"
url_launcher:
dependency: "direct main"
description:
diff --git a/desktop/pubspec.yaml b/desktop/pubspec.yaml
index 01292b708..c0eeb0381 100644
--- a/desktop/pubspec.yaml
+++ b/desktop/pubspec.yaml
@@ -41,6 +41,11 @@ dependencies:
go_router: ^17.5.0
url_launcher: ^6.3.2
cryptography: ^2.9.0
+ # Unicode normalisation for the viewer's password-linking PAKE: the same
+ # password must hash identically whatever form the keyboard produced it in.
+ # Pure Dart, so it registers no native plugin and leaves the macOS SPM
+ # package list untouched — see CLAUDE.md on what a plugin costs here.
+ unorm_dart: ^0.3.2
# Keep the terminal core in-tree until the upstream circular-buffer ownership
# fix is released. See third_party/xterm/lib/src/core/buffer/buffer.dart.
xterm:
diff --git a/desktop/test/swarm_tab_strip_test.dart b/desktop/test/swarm_tab_strip_test.dart
new file mode 100644
index 000000000..1fd3f4418
--- /dev/null
+++ b/desktop/test/swarm_tab_strip_test.dart
@@ -0,0 +1,135 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/layouts/window_size.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/state/app_state.dart';
+import 'package:harness/widgets/swarm_tab_strip.dart';
+
+import 'swarm_state_test.dart' show createApp;
+
+/// A tab carries a 2pt right margin inside its own box, so measuring the tab
+/// measures the margin with it.
+const double _margin = 2;
+
+AppNotifier _appWith(int swarms) {
+ final app = createApp();
+ while (app.swarms.length < swarms) {
+ app.newSwarm();
+ }
+ addTearDown(app.dispose);
+ return app;
+}
+
+/// Sizes the WINDOW rather than wrapping the strip in a box: a `SizedBox` wider
+/// than the test surface is silently clamped back to it, which would have every
+/// wide case here quietly measuring 800pt instead.
+Future<void> _mount(
+ WidgetTester tester,
+ AppNotifier app,
+ double width, {
+ VoidCallback? onNewAgent,
+}) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = Size(width, 200);
+ addTearDown(tester.view.resetPhysicalSize);
+ addTearDown(tester.view.resetDevicePixelRatio);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Scaffold(
+ body: Align(
+ alignment: Alignment.topLeft,
+ child: SwarmTabStrip(
+ notifier: app,
+ attention: 0,
+ onRename: (_) {},
+ onSearch: () {},
+ onNewAgent: onNewAgent ?? () {},
+ onNotifications: () {},
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+}
+
+double _tabWidth(WidgetTester tester, AppNotifier app) =>
+ tester.getSize(find.byKey(ValueKey(app.swarms.first.id)).first).width -
+ _margin;
+
+void main() {
+ testWidgets('a window with room draws every tab at its full width', (
+ tester,
+ ) async {
+ final app = _appWith(2);
+ await _mount(tester, app, 1400);
+
+ expect(_tabWidth(tester, app), SwarmTabStrip.maxTabWidth);
+ });
+
+ testWidgets('tabs give up width before the strip starts scrolling', (
+ tester,
+ ) async {
+ final app = _appWith(8);
+ await _mount(tester, app, 1400);
+
+ final width = _tabWidth(tester, app);
+ expect(width, lessThan(SwarmTabStrip.maxTabWidth));
+ expect(width, greaterThan(SwarmTabStrip.minTabWidth));
+ });
+
+ testWidgets('a tab stops shrinking at the width that still holds a name', (
+ tester,
+ ) async {
+ final app = _appWith(24);
+ await _mount(tester, app, 500);
+
+ expect(_tabWidth(tester, app), SwarmTabStrip.minTabWidth);
+ });
+
+ testWidgets('a wide strip keeps all four actions out as buttons', (
+ tester,
+ ) async {
+ await _mount(tester, _appWith(2), 1400);
+
+ expect(find.byKey(const ValueKey('swarm-search-button')), findsOneWidget);
+ expect(
+ find.byKey(const ValueKey('swarm-new-agent-button')),
+ findsOneWidget,
+ );
+ expect(
+ find.byKey(const ValueKey('swarm-notifications-button')),
+ findsOneWidget,
+ );
+ expect(find.byKey(const ValueKey('swarm-overflow-button')), findsNothing);
+ });
+
+ testWidgets('a compact strip folds the actions away but keeps the badge', (
+ tester,
+ ) async {
+ await _mount(tester, _appWith(2), WindowSizeClass.compactMax - 1);
+
+ expect(find.byKey(const ValueKey('swarm-search-button')), findsNothing);
+ expect(find.byKey(const ValueKey('swarm-new-agent-button')), findsNothing);
+ expect(
+ find.byKey(const ValueKey('swarm-notifications-button')),
+ findsOneWidget,
+ );
+ expect(find.byKey(const ValueKey('swarm-overflow-button')), findsOneWidget);
+ });
+
+ testWidgets('the folded actions still run from the overflow menu', (
+ tester,
+ ) async {
+ var newAgents = 0;
+ await _mount(tester, _appWith(2), 420, onNewAgent: () => newAgents++);
+
+ await tester.tap(find.byKey(const ValueKey('swarm-overflow-button')));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('New agent'));
+ await tester.pumpAndSettle();
+
+ expect(newAgents, 1);
+ });
+}