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: "Paired with this Mac" in Add Phone — see who can reach this computer, remove any of them

dee5d6cc5fd9218
diff --git a/cli/src/lib/e2ee/manager.test.ts b/cli/src/lib/e2ee/manager.test.ts
index bb3c6350d..a6bca6caf 100644
--- a/cli/src/lib/e2ee/manager.test.ts
+++ b/cli/src/lib/e2ee/manager.test.ts
@@ -111,6 +111,8 @@ class WebPeer {
class PwPeer {
identity = C.newIdentity()
peerPub?: Uint8Array
+ /** What this joiner calls itself in its sealed identity; unset is a joiner that predates the field. */
+ label?: string
private pr?: { sid: Uint8Array; sidB64: string; stretched: Uint8Array; y?: bigint; Ya?: Uint8Array; isk?: Uint8Array; th?: Uint8Array }
async intent(password: string): Promise<Frame> {
@@ -146,7 +148,8 @@ class PwPeer {
if (!C.pairBindVerify(C.b64d(adId.id), pr.th!, C.b64d(adId.sig))) throw new Error('adapter bind sig failed')
this.peerPub = C.b64d(adId.id) // pin
- const sealed = C.aeadSeal(C.pairKey(pr.isk!, ci), 4, C.utf8('e2e-id'), C.utf8(JSON.stringify({ id: C.b64e(this.identity.pub), sig: C.b64e(C.pairBindSig(this.identity.priv, pr.th!)) })))
+ const claim = { id: C.b64e(this.identity.pub), sig: C.b64e(C.pairBindSig(this.identity.priv, pr.th!)), ...(this.label !== undefined ? { label: this.label } : {}) }
+ const sealed = C.aeadSeal(C.pairKey(pr.isk!, ci), 4, C.utf8('e2e-id'), C.utf8(JSON.stringify(claim)))
return { type: 'e2e_pw_pake', payload: { sid: pr.sidB64, round: 4, enc: C.b64e(sealed) } }
}
return null // round 5 (ok/error) — nothing to send
@@ -404,6 +407,24 @@ describe('E2eeManager persistent remote-password pairing', () => {
expect(paired[0]).toMatchObject({ fingerprint: C.fingerprint(joiner.identity.pub), label: 'harness link', role: 'web' })
})
+ it('a joiner that names itself is listed by that name — one clean line of it', async () => {
+ const { mgr, takeLast } = machine()
+ await mgr.setRemotePassword(PASSWORD)
+ for (const [conn, label, shown] of [
+ ['pw-a', "Dee's iPhone", "Dee's iPhone"],
+ ['pw-b', ' two\nlines\u0007 ', 'two lines'],
+ ['pw-c', 'x'.repeat(90), 'x'.repeat(60)],
+ ['pw-d', ' ', 'harness link'],
+ ] as const) {
+ const joiner = new PwPeer()
+ joiner.label = label
+ mgr.handleFrame(conn, await joiner.intent(PASSWORD))
+ mgr.handleFrame(conn, joiner.onPake(takeLast('e2e_pw_pake'))!)
+ mgr.handleFrame(conn, joiner.onPake(takeLast('e2e_pw_pake'))!)
+ expect(mgr.listPaired().find((p) => p.fingerprint === C.fingerprint(joiner.identity.pub))?.label).toBe(shown)
+ }
+ })
+
it('a wrong password fails the confirmation MAC at round 2 and pins nobody', async () => {
const { mgr, takeLast } = machine()
await mgr.setRemotePassword(PASSWORD)
diff --git a/cli/src/lib/e2ee/manager.ts b/cli/src/lib/e2ee/manager.ts
index bb384f648..8f635c1d1 100644
--- a/cli/src/lib/e2ee/manager.ts
+++ b/cli/src/lib/e2ee/manager.ts
@@ -631,11 +631,15 @@ export class E2eeManager {
if (!slot.isk || !slot.th) { this.failPwPair(connId, 'TIMEOUT'); return true }
const opened = C.aeadOpen(C.pairKey(slot.isk, ci), 4, C.utf8('e2e-id'), C.b64d(String(p.enc)))
if (!opened) { this.failPwPair(connId, 'WRONG_PASSWORD', true); return true }
- const joinerId = JSON.parse(new TextDecoder().decode(opened)) as { id: string; sig: string }
+ const joinerId = JSON.parse(new TextDecoder().decode(opened)) as { id: string; sig: string; label?: unknown }
if (!C.pairBindVerify(C.b64d(joinerId.id), slot.th, C.b64d(joinerId.sig))) { this.failPwPair(connId, 'WRONG_PASSWORD', true); return true }
// Full success: trust the joiner exactly as if it were a paired browser session (same call/role
// onSetupClaim uses) — this is what lets it relay through this machine's data plane.
- this.store.addPaired(joinerId.id, 'harness link', this.now(), 'web')
+ //
+ // Named by the joiner when it says who it is ("Dee's iPhone"), inside the sealed identity, so the
+ // name is as authenticated as the key — and so the Mac's list of paired devices reads as devices.
+ // A joiner that predates the field (`harness link connect`, an older phone) stays "harness link".
+ this.store.addPaired(joinerId.id, pairedLabel(joinerId.label) ?? 'harness link', this.now(), 'web')
this.store.notePwSuccess()
const fp = this.fingerprint()
this.deps.sendTo(connId, { type: 'e2e_pw_pake', payload: { sid: slot.sidB64, round: 5, ok: true, fingerprint: fp } })
@@ -795,3 +799,10 @@ function hex8(): string {
for (let i = 0; i < 4; i++) s += b[i].toString(16).padStart(2, '0')
return s
}
+
+/** A joiner's name for itself, fit to show in a list: text only, one line, 60 characters at most. */
+function pairedLabel(raw: unknown): string | null {
+ if (typeof raw !== 'string') return null
+ const label = raw.replace(/[\u0000-\u001f\u007f]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 60)
+ return label || null
+}
diff --git a/desktop/lib/api/api_client.dart b/desktop/lib/api/api_client.dart
index 93e6bb36a..62922e77b 100644
--- a/desktop/lib/api/api_client.dart
+++ b/desktop/lib/api/api_client.dart
@@ -217,6 +217,39 @@ class ApiClient {
}
}
+ /// What this computer trusts to read and drive its terminals — every phone
+ /// paired by QR or password, and every computer linked to it — as the
+ /// daemon keeps them (`GET /api/pairs`, the list `harness pairings` prints).
+ /// Null when the daemon cannot say; the dialog then shows no list.
+ Future<List<PairedDevice>?> pairedDevices() async {
+ try {
+ final res = await _dio.get('/api/pairs');
+ final data = res.data;
+ final pairs = data is Map ? data['pairs'] : null;
+ if (res.statusCode != 200 || pairs is! List) return null;
+ return [for (final raw in pairs) ?PairedDevice.fromJson(raw)];
+ } catch (_) {
+ return null;
+ }
+ }
+
+ /// Take [fingerprint]'s trust away: it can no longer read or drive this
+ /// computer, and any session it has open is dropped (`POST /api/revoke`,
+ /// what `harness unpair` sends). True when the daemon did it.
+ Future<bool> removePairedDevice(String fingerprint) async {
+ try {
+ final res = await _dio.post(
+ '/api/revoke',
+ data: {'id': fingerprint},
+ options: Options(headers: {'x-adapter-local': '1'}),
+ );
+ final data = res.data;
+ return res.statusCode == 200 && !(data is Map && data['error'] != null);
+ } catch (_) {
+ return false;
+ }
+ }
+
// -- the Harness Store: ratings and reviews (control plane, proxied by the local CLI) --
Future<Map<String, dynamic>?> storeRatings() async {
final res = await _dio.get('/api/store/ratings');
@@ -422,3 +455,47 @@ String describeApiError(Object error) {
}
return '$error';
}
+
+/// One entry of [ApiClient.pairedDevices].
+class PairedDevice {
+ const PairedDevice({
+ required this.fingerprint,
+ required this.label,
+ required this.pairedAt,
+ required this.online,
+ });
+
+ final String fingerprint;
+
+ /// What the device called itself ("Dee's iPhone"). An older phone, or a
+ /// computer linked with `harness link connect`, is `harness link` — which
+ /// says nothing, so [name] says "Linked device" for it instead.
+ final String label;
+ final DateTime pairedAt;
+ final bool online;
+
+ String get name {
+ final trimmed = label.trim();
+ return trimmed.isEmpty || trimmed == 'harness link' || trimmed == 'browser'
+ ? 'Linked device'
+ : trimmed;
+ }
+
+ /// A `web` pairing: a phone or another computer. The dial (`device`) has
+ /// its own place, in Settings.
+ static PairedDevice? fromJson(Object? raw) {
+ if (raw is! Map) return null;
+ final fingerprint = raw['fingerprint'], label = raw['label'];
+ final pairedAt = raw['pairedAt'], role = raw['role'];
+ if (fingerprint is! String || fingerprint.isEmpty) return null;
+ if (role != null && role != 'web') return null;
+ return PairedDevice(
+ fingerprint: fingerprint,
+ label: label is String ? label : '',
+ pairedAt: pairedAt is num
+ ? DateTime.fromMillisecondsSinceEpoch(pairedAt.toInt())
+ : DateTime.fromMillisecondsSinceEpoch(0),
+ online: raw['online'] == true,
+ );
+ }
+}
diff --git a/desktop/lib/widgets/add_phone_dialog.dart b/desktop/lib/widgets/add_phone_dialog.dart
index 11a7700d1..0f549d847 100644
--- a/desktop/lib/widgets/add_phone_dialog.dart
+++ b/desktop/lib/widgets/add_phone_dialog.dart
@@ -17,6 +17,7 @@ import '../terminal/terminal_theme.dart';
import '../terminal/terminal_theme_store.dart';
import 'box_chrome.dart';
import 'terminal_prompt.dart';
+import 'terminal_text_action.dart';
/// Harness ▸ Add Phone… — a QR the phone scans to sign in to this account AND
/// pair with this computer, end to end encrypted, with no password typed.
@@ -45,6 +46,8 @@ Future<void> showAddPhoneDialog(
AppKeymap? keymap,
PhonePairCall? pair,
PhoneSignInCodeCall? signInCode,
+ PairedDevicesCall? listDevices,
+ RemovePairedDeviceCall? removeDevice,
}) => showTerminalPrompt<void>(
context,
keymap: keymap,
@@ -52,6 +55,8 @@ Future<void> showAddPhoneDialog(
app: app,
pair: pair ?? phonePairOverDaemon(app.api),
signInCode: signInCode ?? app.api.phoneSignInCode,
+ listDevices: listDevices ?? app.api.pairedDevices,
+ removeDevice: removeDevice ?? app.api.removePairedDevice,
),
);
@@ -193,18 +198,32 @@ PhonePairCall phonePairOverDaemon(ApiClient api) => (code, cancel) async {
/// null when there is none to be had (see [ApiClient.phoneSignInCode]).
typedef PhoneSignInCodeCall = Future<({String code, Duration ttl})?> Function();
+/// The devices paired with this computer, or null when the daemon cannot say
+/// (see [ApiClient.pairedDevices]).
+typedef PairedDevicesCall = Future<List<PairedDevice>?> Function();
+
+/// Unpair one device by its fingerprint; true when it is done.
+typedef RemovePairedDeviceCall = Future<bool> Function(String fingerprint);
+
class AddPhoneDialog extends StatefulWidget {
const AddPhoneDialog({
super.key,
required this.app,
required this.pair,
required this.signInCode,
+ this.listDevices,
+ this.removeDevice,
});
final AppNotifier app;
final PhonePairCall pair;
final PhoneSignInCodeCall signInCode;
+ /// The list under the QR — who can already reach this computer — with a way
+ /// to take a device's access back. Null shows no list.
+ final PairedDevicesCall? listDevices;
+ final RemovePairedDeviceCall? removeDevice;
+
@override
State<AddPhoneDialog> createState() => _AddPhoneDialogState();
}
@@ -247,6 +266,16 @@ class _AddPhoneDialogState extends State<AddPhoneDialog> {
bool _signInAsked = false;
Timer? _signInTimer;
+ /// The devices paired with this computer, newest first; null until the
+ /// daemon answers, or when it cannot.
+ List<PairedDevice>? _devices;
+ bool _allDevices = false;
+ final _removing = <String>{};
+
+ /// How many devices show before "+ N more": the dialog is the QR and a
+ /// line, and the list must not outweigh it.
+ static const _devicesShown = 3;
+
/// No pairing to be had from this daemon — asking stopped for good.
bool _stopped = false;
String? _connected;
@@ -263,6 +292,7 @@ class _AddPhoneDialogState extends State<AddPhoneDialog> {
app.addListener(_appChanged);
_syncLoop();
unawaited(_renewSignIn());
+ unawaited(_loadDevices());
}
@override
@@ -333,6 +363,8 @@ class _AddPhoneDialogState extends State<AddPhoneDialog> {
_connected = label;
_message = null;
});
+ // The phone that just joined is on the list now.
+ unawaited(_loadDevices());
if (await _sleep(_connectedHold) && mounted) {
Navigator.of(context).pop();
}
@@ -403,6 +435,45 @@ class _AddPhoneDialogState extends State<AddPhoneDialog> {
);
}
+ Future<void> _loadDevices() async {
+ final list = widget.listDevices;
+ if (list == null) return;
+ List<PairedDevice>? devices;
+ try {
+ devices = await list();
+ } catch (_) {
+ devices = null;
+ }
+ if (_closed || !mounted) return;
+ setState(() => _devices = devices);
+ }
+
+ /// Takes [device]'s access away. One click, no confirmation: undoing it is
+ /// scanning the QR above again, and a device that is not yours should be
+ /// gone in one move.
+ Future<void> _remove(PairedDevice device) async {
+ final remove = widget.removeDevice;
+ if (remove == null || _removing.contains(device.fingerprint)) return;
+ setState(() => _removing.add(device.fingerprint));
+ bool removed;
+ try {
+ removed = await remove(device.fingerprint);
+ } catch (_) {
+ removed = false;
+ }
+ if (_closed || !mounted) return;
+ setState(() {
+ _removing.remove(device.fingerprint);
+ if (removed) {
+ _devices = [
+ for (final kept in _devices ?? const <PairedDevice>[])
+ if (kept.fingerprint != device.fingerprint) kept,
+ ];
+ }
+ });
+ if (!removed) _say("Couldn't remove ${device.name}. Try again.");
+ }
+
void _say(String message, {bool sticky = false}) => setState(() {
_message = message;
_sticky = sticky;
@@ -534,9 +605,65 @@ class _AddPhoneDialogState extends State<AddPhoneDialog> {
// One line, and it is the status too: what to do, then that it worked.
// The phone's own screen says the rest (Yes — scan to connect).
_status(),
+ ..._devicesList(row),
+ ];
+ }
+
+ /// Who can already reach this computer, with a way to take it back: the
+ /// safety net for a QR somebody else scanned.
+ List<Widget> _devicesList(double row) {
+ final devices = _devices;
+ if (devices == null || devices.isEmpty) return const [];
+ final shown = _allDevices ? devices : devices.take(_devicesShown).toList();
+ final more = devices.length - shown.length;
+ return [
+ SizedBox(height: row),
+ Text(
+ 'Paired with this ${_thisComputer()}',
+ key: const ValueKey('add-phone-devices'),
+ style: _ink(_faint),
+ ),
+ for (final device in shown) _deviceRow(device),
+ if (more > 0)
+ Align(
+ alignment: Alignment.centerLeft,
+ child: TerminalTextAction(
+ key: const ValueKey('add-phone-more-devices'),
+ label: '+ $more more',
+ padding: EdgeInsets.zero,
+ onPressed: () => setState(() => _allDevices = true),
+ ),
+ ),
];
}
+ Widget _deviceRow(PairedDevice device) {
+ final removing = _removing.contains(device.fingerprint);
+ return Row(
+ key: ValueKey('add-phone-device-${device.fingerprint}'),
+ children: [
+ Expanded(
+ child: Text(
+ device.name,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: _ink(),
+ ),
+ ),
+ Text(
+ device.online ? 'online' : _pairedAgo(device.pairedAt),
+ style: _ink(device.online ? _theme.green : _faint),
+ ),
+ TerminalTextAction(
+ label: removing ? 'removing…' : 'remove',
+ onPressed: removing || widget.removeDevice == null
+ ? null
+ : () => unawaited(_remove(device)),
+ ),
+ ],
+ );
+ }
+
Widget _status() {
final connected = _connected;
final (text, color) = connected != null
@@ -556,6 +683,16 @@ class _AddPhoneDialogState extends State<AddPhoneDialog> {
}
}
+/// How long ago [at] was, in one short word: `now`, `5m`, `3h`, `2d`, `6w`.
+String _pairedAgo(DateTime at) {
+ final ago = DateTime.now().difference(at);
+ if (ago.inMinutes < 1) return 'now';
+ if (ago.inHours < 1) return '${ago.inMinutes}m';
+ if (ago.inDays < 1) return '${ago.inHours}h';
+ if (ago.inDays < 14) return '${ago.inDays}d';
+ return '${ago.inDays ~/ 7}w';
+}
+
/// "Mac" where the menu says Harness ▸ Add Phone…; the command palette also
/// reaches this dialog on Linux, where "this Mac" would be wrong.
String _thisComputer() =>
diff --git a/desktop/test/add_phone_dialog_test.dart b/desktop/test/add_phone_dialog_test.dart
index 14a142f3e..df5ca62e8 100644
--- a/desktop/test/add_phone_dialog_test.dart
+++ b/desktop/test/add_phone_dialog_test.dart
@@ -5,6 +5,7 @@ import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/api/api_client.dart';
import 'package:harness/core/models.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/state/app_state.dart';
@@ -65,6 +66,8 @@ Future<void> _open(
AppNotifier app,
PhonePairCall pair, {
PhoneSignInCodeCall? signInCode,
+ PairedDevicesCall? listDevices,
+ RemovePairedDeviceCall? removeDevice,
}) async {
tester.view.devicePixelRatio = 1;
tester.view.physicalSize = const Size(1280, 800);
@@ -82,6 +85,8 @@ Future<void> _open(
app,
pair: pair,
signInCode: signInCode ?? _FakeSignIn().call,
+ listDevices: listDevices ?? () async => null,
+ removeDevice: removeDevice ?? (_) async => false,
),
);
await tester.pump();
@@ -222,6 +227,132 @@ void main() {
});
});
+ group('the devices already paired', () {
+ PairedDevice device(String id, String label, {bool online = false}) =>
+ PairedDevice(
+ fingerprint: id,
+ label: label,
+ pairedAt: DateTime.now().subtract(const Duration(days: 2)),
+ online: online,
+ );
+
+ testWidgets('are listed under the QR, and one click takes one away', (
+ tester,
+ ) async {
+ final app = _signedInApp();
+ addTearDown(app.dispose);
+ final removed = <String>[];
+ await _open(
+ tester,
+ app,
+ _FakeDaemon(List.filled(20, _failed('NO_INTENT'))).call,
+ listDevices: () async => [
+ device('AAAA', "Dee's iPhone", online: true),
+ device('BBBB', 'harness link'),
+ device('CCCC', 'Old phone'),
+ device('DDDD', 'Older phone'),
+ device('EEEE', 'Oldest phone'),
+ ],
+ removeDevice: (id) async {
+ removed.add(id);
+ return true;
+ },
+ );
+ await tester.pump();
+ expect(find.byKey(const ValueKey('add-phone-devices')), findsOneWidget);
+ expect(find.text("Dee's iPhone"), findsOneWidget);
+ expect(find.text('online'), findsOneWidget);
+ // A pairing that never said who it is says so in plain words.
+ expect(find.text('Linked device'), findsOneWidget);
+ expect(find.text('2d'), findsNWidgets(2));
+ // Three, then the rest on request: the list must not outweigh the QR.
+ expect(find.text('Older phone'), findsNothing);
+ await tester.tap(find.text('[ + 2 more ]'));
+ await tester.pump();
+ expect(find.text('Oldest phone'), findsOneWidget);
+
+ await tester.tap(
+ find.descendant(
+ of: find.byKey(const ValueKey('add-phone-device-BBBB')),
+ matching: find.text('[ remove ]'),
+ ),
+ );
+ await tester.pump();
+ await tester.pump();
+ expect(removed, ['BBBB']);
+ expect(find.text('Linked device'), findsNothing);
+
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ await tester.pump(const Duration(seconds: 10));
+ });
+
+ testWidgets('a removal the daemon refuses keeps the row and says so', (
+ tester,
+ ) async {
+ final app = _signedInApp();
+ addTearDown(app.dispose);
+ await _open(
+ tester,
+ app,
+ _FakeDaemon(List.filled(20, _failed('NO_INTENT'))).call,
+ listDevices: () async => [device('AAAA', "Dee's iPhone")],
+ removeDevice: (_) async => false,
+ );
+ await tester.pump();
+ await tester.tap(find.text('[ remove ]'));
+ await tester.pump();
+ await tester.pump();
+ expect(find.text("Dee's iPhone"), findsOneWidget);
+ expect(_status(tester), "Couldn't remove Dee's iPhone. Try again.");
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ await tester.pump(const Duration(seconds: 10));
+ });
+
+ testWidgets('no list when nothing is paired, or the daemon cannot say', (
+ tester,
+ ) async {
+ final app = _signedInApp();
+ addTearDown(app.dispose);
+ await _open(
+ tester,
+ app,
+ _FakeDaemon(List.filled(20, _failed('NO_INTENT'))).call,
+ listDevices: () async => const [],
+ );
+ await tester.pump();
+ expect(find.byKey(const ValueKey('add-phone-devices')), findsNothing);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ await tester.pump(const Duration(seconds: 10));
+ });
+
+ test('reads the daemon\'s list: web pairings only, named plainly', () {
+ final phone = PairedDevice.fromJson({
+ 'fingerprint': 'AB12',
+ 'label': "Dee's iPhone",
+ 'pairedAt': 1790523878148,
+ 'online': true,
+ 'role': 'web',
+ 'current': false,
+ })!;
+ expect(phone.name, "Dee's iPhone");
+ expect(phone.online, isTrue);
+ expect(
+ PairedDevice.fromJson({'fingerprint': 'X', 'role': 'device'}),
+ isNull,
+ reason: 'the dial is managed in Settings',
+ );
+ expect(PairedDevice.fromJson({'label': 'no id'}), isNull);
+ expect(
+ PairedDevice.fromJson({'fingerprint': 'X', 'label': 'harness link'})!
+ .name,
+ 'Linked device',
+ );
+ });
+ });
+
group('arming the daemon', () {
testWidgets('retries while no phone is waiting and closes once paired', (
tester,