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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
fix(mobile): pairing times out on a dial that never opens, and keeps a lockout's retry time
dee19de01cf1b4a
diff --git a/mobile/lib/viewer/code_link.dart b/mobile/lib/viewer/code_link.dartindex 095c41127..1042b9a12 100644--- a/mobile/lib/viewer/code_link.dart+++ b/mobile/lib/viewer/code_link.dart@@ -2,7 +2,6 @@ import 'dart:async';import 'dart:convert';import 'dart:typed_data';-import '../e2ee/bytes.dart';import '../e2ee/code_pake.dart';import '../e2ee/cpace.dart';@@ -50,14 +49,16 @@ Future<PasswordLinkResult> linkWithCode({channel.sink.add(jsonEncode({'type': type, 'payload': payload})),);try {- await channel.ready;- return await run- .drive(- channel.stream.map(- (raw) => raw is String ? jsonObjectOf(utf8Bytes(raw)) : null,- ),- )- .timeout(timeout, onTimeout: () => const PasswordLinkFailed('TIMEOUT'));+ // The dial is inside the timeout, as in `linkWithPassword`: a network that swallows packets+ // otherwise holds "Pairing…" on screen for the OS's own TCP timeout.+ return await () async {+ await channel.ready;+ return run.drive(+ channel.stream.map(+ (raw) => raw is String ? jsonObjectOf(utf8Bytes(raw)) : null,+ ),+ );+ }().timeout(timeout, onTimeout: () => const PasswordLinkFailed('TIMEOUT'));} catch (_) {return const PasswordLinkFailed('CONNECTION_ERROR');} finally {diff --git a/mobile/lib/viewer/password_link.dart b/mobile/lib/viewer/password_link.dartindex 5c366f989..289176b78 100644--- a/mobile/lib/viewer/password_link.dart+++ b/mobile/lib/viewer/password_link.dart@@ -46,8 +46,10 @@ final class PasswordLinkFailed extends PasswordLinkResult {final DateTime? retryAt;}-typedef RelaySocketFactory =- WebSocketChannel Function(Uri uri, Iterable<String> protocols);+typedef RelaySocketFactory = WebSocketChannel Function(+ Uri uri,+ Iterable<String> protocols,+);WebSocketChannel defaultRelaySocket(Uri uri, Iterable<String> protocols) =>WebSocketChannel.connect(uri, protocols: protocols);@@ -70,17 +72,24 @@ Future<PasswordLinkResult> linkWithPassword({Duration timeout = const Duration(seconds: 30),}) async {onProgress?.call(PasswordLinkStage.connecting);- final uri = Uri.parse('$wsBaseUrl/api/web-ws').replace(- queryParameters: {'autonomousEnv': autonomousEnv},- );+ 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);+ final run = _PasswordLinkRun(+ machineId,+ password,+ identity,+ channel,+ onProgress,+ );try {- await channel.ready;- return await run.drive().timeout(- timeout,- onTimeout: () => const PasswordLinkFailed('TIMEOUT'),- );+ // ⚠️ The dial is inside the timeout, not in front of it: a socket dialled into a network+ // that swallows packets waits out the OS's own TCP timeout — over a minute on iOS — and the+ // form said "connecting" for all of it.+ return await () async {+ await channel.ready;+ return run.drive();+ }().timeout(timeout, onTimeout: () => const PasswordLinkFailed('TIMEOUT'));} catch (_) {return const PasswordLinkFailed('CONNECTION_ERROR');} finally {@@ -186,7 +195,12 @@ class _PasswordLinkRun {theirs,ours.share,);- final transcript = _transcript = transcriptHash(_sid, _ci, theirs, ours.share);+ final transcript = _transcript = transcriptHash(+ _sid,+ _ci,+ theirs,+ ours.share,+ );onProgress?.call(PasswordLinkStage.verifying);_send('e2e_pw_pake', {'sid': _sidB64,@@ -199,7 +213,9 @@ class _PasswordLinkRun {/// 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 {+ Future<PasswordLinkResult?> _answerIdentity(+ Map<String, dynamic> payload,+ ) async {final isk = _isk, transcript = _transcript;if (isk == null || transcript == null) {return const PasswordLinkFailed('PROTOCOL_ERROR');@@ -209,7 +225,12 @@ class _PasswordLinkRun {return _wrongPassword;}final key = pairKey(isk, _ci);- final opened = aeadOpen(key, 3, utf8Bytes('e2e-id'), b64d(payload['enc'] as String));+ 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;@@ -232,11 +253,12 @@ class _PasswordLinkRun {/// 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.+ ///+ /// A refusal here carries its `retryAt` as one at the intent does: the machine judges its+ /// lockout again at round 2 (manager.ts `onPwPake`), and says until when on round 5.PasswordLinkResult _finish(Map<String, dynamic> payload) {final machinePub = _machinePub;- if (payload['ok'] != true || machinePub == null) {- return PasswordLinkFailed(_codeOr(payload['error'], 'PAIR_FAILED'));- }+ if (payload['ok'] != true || machinePub == null) return _refused(payload);return PasswordLinked(machinePub, fingerprint(machinePub));}@@ -244,7 +266,9 @@ class _PasswordLinkRun {final retryAt = payload['retryAt'];return PasswordLinkFailed(_codeOr(payload['error'], 'PAIR_FAILED'),- retryAt: retryAt is int ? DateTime.fromMillisecondsSinceEpoch(retryAt) : null,+ retryAt: retryAt is int+ ? DateTime.fromMillisecondsSinceEpoch(retryAt)+ : null,);}diff --git a/mobile/test/code_link_test.dart b/mobile/test/code_link_test.dartindex 18f3a03ed..9c94d57b0 100644--- a/mobile/test/code_link_test.dart+++ b/mobile/test/code_link_test.dart@@ -11,6 +11,8 @@ import 'package:harness_mobile/e2ee/primitives.dart';import 'package:harness_mobile/viewer/code_link.dart';import 'package:harness_mobile/viewer/password_link.dart';+import 'viewer/fake_relay_socket.dart';+String _hex(List<int> bytes) =>bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join();@@ -194,4 +196,281 @@ void main() {expect((result as PasswordLinkFailed).code, 'CODE_MISMATCH');expect(machine.pinned, isNull);});++ group('over the relay socket', () {+ late E2eeIdentity phone;+ setUpAll(() async => phone = await E2eeIdentity.generate());++ Future<PasswordLinkResult> link(+ FakeRelaySocket socket, {+ Duration timeout = const Duration(seconds: 10),+ }) => linkWithCode(+ machineId: 'machine-1',+ code: 'K7QM4XPT9D2W',+ label: 'iPhone',+ identity: phone,+ accessToken: 'tok',+ wsBaseUrl: 'wss://relay.invalid',+ autonomousEnv: 'prod',+ socket: socket.factory,+ timeout: timeout,+ );++ /// The machine above, behind a relay socket.+ _Machine behind(FakeRelaySocket socket, {String code = 'K7QM4XPT9D2W'}) {+ final machine = _Machine('machine-1', code, phone);+ machine.frames.stream.listen((frame) {+ if (frame != null) {+ socket.emit(+ frame['type'] as String,+ frame['payload'] as Map<String, Object?>,+ );+ }+ });+ socket.onFrame = (frame) => unawaited(+ machine.receive(+ frame['type'] as String,+ Map<String, Object>.from(frame['payload'] as Map),+ ),+ );+ return machine;+ }++ test('pairs, on the socket it dialled with the session', () async {+ final socket = FakeRelaySocket();+ final machine = behind(socket);+ final result = await link(socket);+ expect(result, isA<PasswordLinked>());+ expect(machine.pinned, phone.pub);+ expect(+ socket.dialled.toString(),+ 'wss://relay.invalid/api/web-ws?autonomousEnv=prod',+ );+ expect(socket.protocols, ['tok']);+ expect(socket.closedByPhone, isTrue);+ final intent = socket.sent.firstWhere(+ (f) => f['type'] == 'e2e_pair_intent',+ );+ expect(intent['payload']['label'], 'iPhone');+ expect(intent['payload']['role'], 'web');+ });++ test('a dial that fails is a connection error', () async {+ final socket = FakeRelaySocket(+ ready: Future<void>.error(StateError('x')),+ );+ expect(+ ((await link(socket)) as PasswordLinkFailed).code,+ 'CONNECTION_ERROR',+ );+ });++ // ⚠️ The timeout used to start only once the socket had opened, so a network that swallowed+ // the dial held "Pairing…" for the OS's own TCP timeout rather than this one.+ test('a dial that never opens times out', () async {+ final socket = FakeRelaySocket(ready: Completer<void>().future);+ final result =+ await link(+ socket,+ timeout: const Duration(milliseconds: 200),+ ).timeout(+ const Duration(seconds: 5),+ onTimeout: () => const PasswordLinkFailed('HUNG'),+ );+ expect((result as PasswordLinkFailed).code, 'TIMEOUT');+ });++ test('a desktop that never answers the intent times out', () async {+ final socket = FakeRelaySocket();+ socket.onFrame = (frame) {+ if (frame['type'] == 'machine_select') {+ socket.emit('connected', {'machineId': 'machine-1'});+ }+ };+ final result = await link(+ socket,+ timeout: const Duration(milliseconds: 300),+ );+ expect((result as PasswordLinkFailed).code, 'TIMEOUT');+ });++ test('a relay that hangs up is CONNECTION_CLOSED', () async {+ final socket = FakeRelaySocket();+ socket.onFrame = (frame) => unawaited(socket.hangUp(1006));+ expect(+ ((await link(socket)) as PasswordLinkFailed).code,+ 'CONNECTION_CLOSED',+ );+ });+ });++ group('one frame at a time', () {+ late E2eeIdentity phone;+ setUpAll(() async => phone = await E2eeIdentity.generate());++ CodeLinkRun run(List<(String, Map<String, Object>)> sent) => CodeLinkRun(+ machineId: 'machine-1',+ code: 'K7QM4XPT9D2W',+ label: 'iPhone',+ identity: phone,+ send: (type, payload) => sent.add((type, payload)),+ pairId: Uint8List(16),+ );++ Map<String, dynamic> frame(String type, Map<String, Object?> payload) => {+ 'type': type,+ 'payload': payload,+ };++ final pairId = b64e(Uint8List(16));++ Future<CodeLinkRun> selected(+ List<(String, Map<String, Object>)> sent,+ ) async {+ final link = run(sent);+ expect(+ await link.step(frame('connected', {'machineId': 'machine-1'})),+ isNull,+ );+ return link;+ }++ test('before the select is acked, only its answer counts', () async {+ final link = run([]);+ expect(await link.step(frame('connected', {'userId': 'u'})), isNull);+ expect(+ await link.step(frame('e2e_pake', {'pairId': pairId, 'round': 5})),+ isNull,+ reason: 'no pairing round is taken before the machine is selected',+ );+ expect(+ await link.step({'type': 'connected', 'payload': 'not a map'}),+ isNull,+ );+ expect(+ await link.step(+ frame('node_status', {'machineId': 'machine-1', 'online': true}),+ ),+ isNull,+ );+ final refused = await link.step(+ frame('machine_select_error', {'machineId': 'machine-1'}),+ );+ expect((refused as PasswordLinkFailed).code, 'SELECT_FAILED');+ });++ test('the intent refused, with its reason or ours', () async {+ final sent = <(String, Map<String, Object>)>[];+ final link = await selected(sent);+ final requestId = sent.single.$2['requestId']!;+ expect(+ await link.step(+ frame('e2e_pair_intent_result', {+ 'requestId': 'not-ours',+ 'error': 'X',+ }),+ ),+ isNull,+ );+ expect(+ ((await link.step(+ frame('e2e_pair_intent_result', {+ 'requestId': requestId,+ 'error': 'PAIRING_BUSY',+ }),+ )) as PasswordLinkFailed).code,+ 'PAIRING_BUSY',+ );+ expect(+ ((await (await selected([]))+ .step(frame('e2e_pair_intent_result', {'requestId': 'x'}))) ??+ 'still waiting'),+ 'still waiting',+ reason: 'another client\'s answer is not this one\'s',+ );+ });++ test('an intent accepted waits for the desktop', () async {+ final sent = <(String, Map<String, Object>)>[];+ final link = await selected(sent);+ expect(+ await link.step(+ frame('e2e_pair_intent_result', {+ 'requestId': sent.single.$2['requestId'],+ 'accepted': true,+ }),+ ),+ isNull,+ );+ final refused = await (await selected(sent)).step(+ frame('e2e_pair_intent_result', {+ 'requestId': sent.last.$2['requestId'],+ }),+ );+ expect((refused as PasswordLinkFailed).code, 'PAIR_REFUSED');+ });++ test('a round with an error ends it with that error', () async {+ final link = await selected([]);+ final failed = await link.step(+ frame('e2e_pake', {'pairId': pairId, 'error': 'EXPIRED'}),+ );+ expect((failed as PasswordLinkFailed).code, 'EXPIRED');+ });++ test(+ 'rounds for another pairing, or of no known number, are not this one\'s',+ () async {+ final link = await selected([]);+ expect(+ await link.step(frame('e2e_pake', {'pairId': 'other', 'round': 1})),+ isNull,+ );+ expect(+ await link.step(frame('e2e_pake', {'pairId': pairId, 'round': 9})),+ isNull,+ );+ },+ );++ test('round 3 before round 1 is a protocol error', () async {+ final link = await selected([]);+ final failed = await link.step(+ frame('e2e_pake', {+ 'pairId': pairId,+ 'round': 3,+ 'mac': b64e(Uint8List(32)),+ 'enc': b64e(Uint8List(32)),+ }),+ );+ expect((failed as PasswordLinkFailed).code, 'PROTOCOL_ERROR');+ });++ test('round 5 with ok but no proven identity pins nothing', () async {+ final link = await selected([]);+ final failed = await link.step(+ frame('e2e_pake', {'pairId': pairId, 'round': 5, 'ok': true}),+ );+ expect((failed as PasswordLinkFailed).code, 'PAIR_FAILED');+ });++ test('garbage in a round is a protocol error, not a crash', () async {+ final link = run([]);+ final result = await link+ .drive(+ Stream.fromIterable([+ null,+ frame('connected', {'machineId': 'machine-1'}),+ // The identity point: a share the CPace must refuse outright.+ frame('e2e_pake', {+ 'pairId': pairId,+ 'round': 1,+ 'ya': b64e(Uint8List(32)),+ }),+ ]),+ )+ .timeout(const Duration(seconds: 5));+ expect((result as PasswordLinkFailed).code, 'PROTOCOL_ERROR');+ });+ });}diff --git a/mobile/test/viewer/fake_relay_socket.dart b/mobile/test/viewer/fake_relay_socket.dartnew file mode 100644index 000000000..13d852e1d--- /dev/null+++ b/mobile/test/viewer/fake_relay_socket.dart@@ -0,0 +1,106 @@+import 'dart:async';+import 'dart:convert';++import 'package:web_socket_channel/web_socket_channel.dart';++/// A relay socket with nothing behind it but the test: frames the phone sends land in [sent] (and+/// [onFrame]), and the test says what comes back with [emit]. Nothing leaves the process.+class FakeRelaySocket implements WebSocketChannel {+ FakeRelaySocket({Future<void>? ready, this.onFrame})+ : ready = ready ?? Future<void>.value();++ /// What the phone sent, decoded.+ final sent = <Map<String, dynamic>>[];++ /// Called with each frame the phone sends, after it is recorded.+ void Function(Map<String, dynamic> frame)? onFrame;++ /// The URL and protocols the phone dialled with, when built through [factory].+ Uri? dialled;+ List<String>? protocols;++ final _down = StreamController<dynamic>();+ late final _FakeSink _sink = _FakeSink(this);++ /// Whether the phone closed its end.+ bool get closedByPhone => _sink.closed;++ @override+ final Future<void> ready;++ @override+ Stream<dynamic> get stream => _down.stream;++ @override+ WebSocketSink get sink => _sink;++ @override+ String? get protocol => null;++ @override+ int? closeCode;++ @override+ String? closeReason;++ /// A frame from the relay (or the machine behind it), as JSON text.+ void emit(String type, Map<String, Object?> payload) =>+ _down.add(jsonEncode({'type': type, 'payload': payload}));++ /// Anything at all, as the socket would hand it over.+ void emitRaw(Object? raw) => _down.add(raw);++ void fail(Object error) => _down.addError(error);++ /// The far end hanging up.+ Future<void> hangUp([int? code]) {+ closeCode = code;+ return _down.close();+ }++ /// A [RelaySocketFactory]-shaped function that hands out this socket.+ WebSocketChannel factory(Uri uri, Iterable<String> protocols) {+ dialled = uri;+ this.protocols = protocols.toList();+ return this;+ }++ // The StreamChannel conveniences (pipe, transform…) are never called on a relay socket.+ @override+ dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);+}++class _FakeSink implements WebSocketSink {+ _FakeSink(this._socket);++ final FakeRelaySocket _socket;+ bool closed = false;+ final _done = Completer<void>();++ @override+ void add(dynamic data) {+ if (closed) throw StateError('sink closed');+ final frame = jsonDecode(data as String) as Map<String, dynamic>;+ _socket.sent.add(frame);+ _socket.onFrame?.call(frame);+ }++ @override+ void addError(Object error, [StackTrace? stackTrace]) {}++ @override+ Future<void> addStream(Stream<dynamic> stream) async {+ await for (final data in stream) {+ add(data);+ }+ }++ @override+ Future<void> close([int? closeCode, String? closeReason]) async {+ closed = true;+ if (!_done.isCompleted) _done.complete();+ }++ @override+ Future<void> get done => _done.future;+}diff --git a/mobile/test/viewer/password_link_test.dart b/mobile/test/viewer/password_link_test.dartnew file mode 100644index 000000000..953b064e0--- /dev/null+++ b/mobile/test/viewer/password_link_test.dart@@ -0,0 +1,568 @@+import 'dart:async';+import 'dart:convert';+import 'dart:typed_data';++import 'package:flutter_test/flutter_test.dart';++import 'package:harness_mobile/e2ee/bytes.dart';+import 'package:harness_mobile/e2ee/cpace.dart';+import 'package:harness_mobile/e2ee/keys.dart';+import 'package:harness_mobile/e2ee/password_pake.dart';+import 'package:harness_mobile/e2ee/primitives.dart';+import 'package:harness_mobile/viewer/password_link.dart';++import 'fake_relay_socket.dart';++const _machineId = 'machine-1';+const _password = 'correct horse fi';++/// The machine's side of the remote-password link, as `manager.ts` `onPwPairIntent` / `onPwPake`+/// run it: round 1 on the intent, check round 2 and answer with round 3, pin on round 4. What it+/// holds is the stretched password (the verifier), never the password.+class _PwMachine {+ _PwMachine(this.socket, this.identity, this.verifier) {+ socket.onFrame = (frame) => unawaited(_receive(frame));+ }++ final FakeRelaySocket socket;+ final E2eeIdentity identity;+ final Uint8List verifier;++ /// When set, every attempt is refused up front, as a locked-out machine does.+ int? lockedUntil;++ /// When set, a lockout that began after the intent: round 2 is refused on round 5.+ int? lockedAtRound2;++ /// Builds what the machine sends instead of its own round 3 — a hostile or broken peer.+ Future<Map<String, Object?>> Function(Uint8List isk, Uint8List th)?+ forgeRound3;++ Uint8List? pinned;+ late Uint8List _sid;+ late String _sidB64;+ late BigInt _y;+ late Uint8List _ya;+ Uint8List? _isk, _th;+ final _ci = pwContext(_machineId);++ Future<void> _receive(Map<String, dynamic> frame) async {+ final payload = frame['payload'] as Map<String, dynamic>;+ switch (frame['type']) {+ case 'machine_select':+ socket.emit('connected', {'machineId': _machineId, 'p2p': null});+ case 'e2e_pw_pair_intent':+ final locked = lockedUntil;+ if (locked != null) {+ socket.emit('e2e_pw_pair_result', {+ 'requestId': payload['requestId'],+ 'ok': false,+ 'error': 'RATE_LIMITED',+ 'retryAt': locked,+ });+ return;+ }+ _sidB64 = payload['sid'] as String;+ _sid = b64d(_sidB64);+ final start = cpaceStart(pwCpaceGenerator(verifier, _sid, _ci));+ _y = start.scalar;+ _ya = start.share;+ socket.emit('e2e_pw_pake', {+ 'sid': _sidB64,+ 'round': 1,+ 'ya': b64e(_ya),+ });+ case 'e2e_pw_pake' when payload['round'] == 2:+ final locked = lockedAtRound2;+ if (locked != null) {+ socket.emit('e2e_pw_pake', {+ 'sid': _sidB64,+ 'round': 5,+ 'error': 'RATE_LIMITED',+ 'retryAt': locked,+ });+ return;+ }+ final yb = b64d(payload['yb'] as String);+ final isk = _isk = cpaceIsk(_sid, cpaceShared(yb, _y), _ya, yb);+ final th = _th = transcriptHash(_sid, _ci, _ya, yb);+ final kc = kcKeys(isk, _ci);+ if (!macVerify(kc.web, th, b64d(payload['mac'] as String))) {+ socket.emit('e2e_pw_pake', {+ 'sid': _sidB64,+ 'round': 5,+ 'error': 'WRONG_PASSWORD',+ });+ return;+ }+ final forge = forgeRound3;+ if (forge != null) {+ socket.emit('e2e_pw_pake', {+ 'sid': _sidB64,+ 'round': 3,+ ...await forge(isk, th),+ });+ return;+ }+ final sealed = aeadSeal(+ pairKey(isk, _ci),+ 3,+ utf8Bytes('e2e-id'),+ utf8Bytes(+ jsonEncode({+ 'id': b64e(identity.pub),+ 'sig': b64e(await pairBindSig(identity, th)),+ }),+ ),+ );+ socket.emit('e2e_pw_pake', {+ 'sid': _sidB64,+ 'round': 3,+ 'mac': b64e(macTag(kc.adapter, th)),+ 'enc': b64e(sealed),+ });+ case 'e2e_pw_pake' when payload['round'] == 4:+ final opened = aeadOpen(+ pairKey(_isk!, _ci),+ 4,+ utf8Bytes('e2e-id'),+ b64d(payload['enc'] as String),+ )!;+ final claim = jsonDecode(utf8.decode(opened)) as Map<String, dynamic>;+ final pub = b64d(claim['id'] as String);+ if (!await pairBindVerify(pub, _th!, b64d(claim['sig'] as String))) {+ return;+ }+ pinned = pub;+ socket.emit('e2e_pw_pake', {+ 'sid': _sidB64,+ 'round': 5,+ 'ok': true,+ // Deliberately NOT this machine's: the phone must compute its own.+ 'fingerprint': 'AAAA·BBBB·CCCC·DDDD',+ });+ }+ }+}++void main() {+ late E2eeIdentity phone;+ late E2eeIdentity machineIdentity;+ late Uint8List verifier;++ setUpAll(() async {+ phone = await E2eeIdentity.generate();+ machineIdentity = await E2eeIdentity.generate();+ verifier = await stretchPassword(_password, _machineId);+ });++ Future<PasswordLinkResult> link(+ FakeRelaySocket socket, {+ String password = _password,+ List<PasswordLinkStage>? stages,+ Duration timeout = const Duration(seconds: 30),+ }) => linkWithPassword(+ machineId: _machineId,+ password: password,+ identity: phone,+ accessToken: 'tok',+ wsBaseUrl: 'wss://relay.invalid',+ autonomousEnv: 'stag',+ onProgress: stages?.add,+ socket: socket.factory,+ timeout: timeout,+ );++ test('the stretch is scrypt as the CLI runs it, NFKC-folded', () async {+ // hashlib.scrypt(nfkc('correct horse fi'), sha256('e2e-remote-password-salt-v1|machine-1'),+ // n=2**17, r=8, p=1, dklen=32) — the parameters passwordPake.ts runs noble's scrypt with.+ expect(+ hexOf(verifier),+ '39b238c0e2f4f28f18c621b19a5bc403867298f894fe4c799a6965772c9bc96a',+ );+ // The folded and unfolded spellings of the same password are one password.+ expect(+ hexOf(await stretchPassword('correct horse fi', _machineId)),+ hexOf(verifier),+ );+ });++ test('the right password pins both sides', () async {+ final socket = FakeRelaySocket();+ final machine = _PwMachine(socket, machineIdentity, verifier);+ final stages = <PasswordLinkStage>[];+ final result = await link(socket, stages: stages);++ expect(result, isA<PasswordLinked>());+ final linked = result as PasswordLinked;+ expect(linked.peerPub, machineIdentity.pub);+ expect(+ linked.fingerprint,+ fingerprint(machineIdentity.pub),+ reason: 'computed from the pinned key, never taken from the clear frame',+ );+ expect(machine.pinned, phone.pub);+ expect(stages, PasswordLinkStage.values);+ expect(stages.map((s) => s.wireName), [+ 'connecting',+ 'deriving_key',+ 'exchanging',+ 'verifying',+ ]);+ expect(+ socket.dialled.toString(),+ 'wss://relay.invalid/api/web-ws?autonomousEnv=stag',+ );+ expect(socket.protocols, ['tok']);+ expect(socket.closedByPhone, isTrue);+ });++ test('a wrong password pins nothing', () async {+ final socket = FakeRelaySocket();+ final machine = _PwMachine(socket, machineIdentity, verifier);+ final result = await link(socket, password: 'wrong');+ expect((result as PasswordLinkFailed).code, 'WRONG_PASSWORD');+ expect(machine.pinned, isNull);+ });++ test('a locked-out machine says until when', () async {+ final socket = FakeRelaySocket();+ final until = DateTime.now().add(const Duration(minutes: 3));+ _PwMachine(socket, machineIdentity, verifier).lockedUntil =+ until.millisecondsSinceEpoch;+ final result = await link(socket) as PasswordLinkFailed;+ expect(result.code, 'RATE_LIMITED');+ expect(+ result.retryAt,+ DateTime.fromMillisecondsSinceEpoch(until.millisecondsSinceEpoch),+ );+ });++ // ⚠️ The machine judges the lockout again at round 2 (manager.ts `onPwPake`) and refuses there+ // with a `retryAt` of its own — dropped here, the person was told to "wait a few minutes" by a+ // machine that had said exactly how long.+ test('a lockout that began mid-attempt still says until when', () async {+ final socket = FakeRelaySocket();+ final until = DateTime.now().add(const Duration(minutes: 5));+ _PwMachine(socket, machineIdentity, verifier).lockedAtRound2 =+ until.millisecondsSinceEpoch;+ final result = await link(socket) as PasswordLinkFailed;+ expect(result.code, 'RATE_LIMITED');+ expect(+ result.retryAt,+ DateTime.fromMillisecondsSinceEpoch(until.millisecondsSinceEpoch),+ );+ });++ test('a machine that cannot be selected says so', () async {+ final socket = FakeRelaySocket();+ socket.onFrame = (frame) {+ if (frame['type'] == 'machine_select') {+ // Another machine's news first: none of this attempt's business.+ socket.emit('machine_select_error', {'machineId': 'other'});+ socket.emit('machine_select_error', {+ 'machineId': _machineId,+ 'error': 'MACHINE_OFFLINE',+ });+ }+ };+ expect(+ ((await link(socket)) as PasswordLinkFailed).code,+ 'MACHINE_OFFLINE',+ );+ });++ test('a select refused with no code of its own is SELECT_FAILED', () async {+ final socket = FakeRelaySocket();+ socket.onFrame = (frame) {+ if (frame['type'] == 'machine_select') {+ socket.emit('machine_select_error', {'machineId': _machineId});+ }+ };+ expect(((await link(socket)) as PasswordLinkFailed).code, 'SELECT_FAILED');+ });++ test('refused at the intent, and at round 1 or 3', () async {+ for (final (type, payload, code) in [+ ('e2e_pw_pair_result', <String, Object?>{'ok': false}, 'PAIR_FAILED'),+ (+ 'e2e_pw_pair_result',+ <String, Object?>{'ok': false, 'error': 'NO_REMOTE_PASSWORD'},+ 'NO_REMOTE_PASSWORD',+ ),+ ('e2e_pw_pake', <String, Object?>{'round': 1, 'error': 'BUSY'}, 'BUSY'),+ (+ 'e2e_pw_pake',+ <String, Object?>{'round': 3, 'error': 'TIMEOUT'},+ 'TIMEOUT',+ ),+ ('e2e_pw_pake', <String, Object?>{'round': 5}, 'PAIR_FAILED'),+ ]) {+ final socket = FakeRelaySocket();+ socket.onFrame = (frame) {+ final sent = frame['payload'] as Map<String, dynamic>;+ switch (frame['type']) {+ case 'machine_select':+ // The socket's own greeting names the user, not a machine: not the select's ack.+ socket.emit('connected', {'userId': 'u'});+ socket.emit('connected', {'machineId': _machineId});+ case 'e2e_pw_pair_intent':+ socket.emit(type, {+ ...payload,+ 'requestId': sent['requestId'],+ 'sid': sent['sid'],+ });+ }+ };+ expect(+ ((await link(socket)) as PasswordLinkFailed).code,+ code,+ reason: '$payload',+ );+ }+ });++ test('frames for somebody else\'s attempt are not this one\'s', () async {+ final socket = FakeRelaySocket();+ final machine = _PwMachine(socket, machineIdentity, verifier);+ final real = socket.onFrame!;+ socket.onFrame = (frame) {+ if (frame['type'] == 'e2e_pw_pair_intent') {+ // Another client's result and another session's round: neither may end this attempt.+ socket.emit('e2e_pw_pair_result', {+ 'requestId': 'someone-else',+ 'ok': false,+ });+ socket.emit('e2e_pw_pake', {'sid': 'someone-else', 'round': 5});+ socket.emit('e2e_pw_pair_result', {+ 'requestId': (frame['payload'] as Map)['requestId'],+ 'ok': true,+ });+ // Nor may a binary frame, or text that is not JSON.+ socket.emitRaw([1, 2, 3]);+ socket.emitRaw('not json');+ }+ real(frame);+ };+ expect(await link(socket), isA<PasswordLinked>());+ expect(machine.pinned, phone.pub);+ });++ test(+ 'a round 5 that says ok before any identity was proven is refused',+ () async {+ final socket = FakeRelaySocket();+ socket.onFrame = (frame) {+ final sent = frame['payload'] as Map<String, dynamic>;+ switch (frame['type']) {+ case 'machine_select':+ socket.emit('connected', {'machineId': _machineId});+ case 'e2e_pw_pair_intent':+ socket.emit('e2e_pw_pake', {+ 'sid': sent['sid'],+ 'round': 5,+ 'ok': true,+ });+ }+ };+ final result = await link(socket) as PasswordLinkFailed;+ expect(result.code, 'PAIR_FAILED');+ },+ );++ test('a round 3 before any round 1 is a protocol error', () async {+ final socket = FakeRelaySocket();+ socket.onFrame = (frame) {+ final sent = frame['payload'] as Map<String, dynamic>;+ switch (frame['type']) {+ case 'machine_select':+ socket.emit('connected', {'machineId': _machineId});+ case 'e2e_pw_pair_intent':+ socket.emit('e2e_pw_pake', {+ 'sid': sent['sid'],+ 'round': 3,+ 'mac': b64e(List.filled(32, 0)),+ 'enc': b64e(List.filled(40, 0)),+ });+ }+ };+ expect(((await link(socket)) as PasswordLinkFailed).code, 'PROTOCOL_ERROR');+ });++ test('a round 1 share that is not a point is a protocol error', () async {+ for (final ya in [+ b64e(List.filled(32, 0)),+ b64e(List.filled(32, 0xff)),+ '!!',+ null,+ ]) {+ final socket = FakeRelaySocket();+ socket.onFrame = (frame) {+ final sent = frame['payload'] as Map<String, dynamic>;+ switch (frame['type']) {+ case 'machine_select':+ socket.emit('connected', {'machineId': _machineId});+ case 'e2e_pw_pair_intent':+ socket.emit('e2e_pw_pake', {+ 'sid': sent['sid'],+ 'round': 1,+ 'ya': ya,+ });+ }+ };+ expect(+ ((await link(socket)) as PasswordLinkFailed).code,+ 'PROTOCOL_ERROR',+ reason: '$ya',+ );+ }+ });++ group('a machine that proves the password but not an identity', () {+ /// A machine that checks round 2 honestly, then answers with a round 3 [forge] builds from+ /// the keys it now shares with the phone.+ Future<PasswordLinkFailed> withRound3(+ Future<Map<String, Object?>> Function(Uint8List isk, Uint8List th) forge,+ ) async {+ final socket = FakeRelaySocket();+ _PwMachine(socket, machineIdentity, verifier).forgeRound3 = forge;+ return await link(socket) as PasswordLinkFailed;+ }++ final ci = pwContext(_machineId);++ test('a MAC only the password could make, but wrong', () async {+ final result = await withRound3(+ (isk, th) async => {+ 'mac': b64e(List.filled(32, 1)),+ 'enc': b64e(List.filled(40, 0)),+ },+ );+ expect(result.code, 'WRONG_PASSWORD');+ });++ test('an identity sealed under some other key', () async {+ final result = await withRound3(+ (isk, th) async => {+ 'mac': b64e(macTag(kcKeys(isk, ci).adapter, th)),+ 'enc': b64e(+ aeadSeal(+ List.filled(32, 9),+ 3,+ utf8Bytes('e2e-id'),+ utf8Bytes('{}'),+ ),+ ),+ },+ );+ expect(result.code, 'WRONG_PASSWORD');+ });++ test('an identity claim with no signature', () async {+ final result = await withRound3(+ (isk, th) async => {+ 'mac': b64e(macTag(kcKeys(isk, ci).adapter, th)),+ 'enc': b64e(+ aeadSeal(+ pairKey(isk, ci),+ 3,+ utf8Bytes('e2e-id'),+ utf8Bytes(jsonEncode({'id': b64e(machineIdentity.pub)})),+ ),+ ),+ },+ );+ expect(result.code, 'WRONG_PASSWORD');+ });++ // The relay cannot swap in an identity of its own: the machine's key signs THIS transcript.+ test('an identity not bound to this transcript', () async {+ final impostor = await E2eeIdentity.generate();+ final result = await withRound3(+ (isk, th) async => {+ 'mac': b64e(macTag(kcKeys(isk, ci).adapter, th)),+ 'enc': b64e(+ aeadSeal(+ pairKey(isk, ci),+ 3,+ utf8Bytes('e2e-id'),+ utf8Bytes(+ jsonEncode({+ 'id': b64e(impostor.pub),+ 'sig': b64e(await pairBindSig(impostor, List.filled(64, 0))),+ }),+ ),+ ),+ ),+ },+ );+ expect(result.code, 'WRONG_PASSWORD');+ });+ });++ group('the network', () {+ test('a dial that fails is a connection error', () async {+ final socket = FakeRelaySocket(+ ready: Future<void>.error(const SocketExceptionLike()),+ );+ expect(+ ((await link(socket)) as PasswordLinkFailed).code,+ 'CONNECTION_ERROR',+ );+ });++ test('a socket that errors mid-link is a connection error', () async {+ final socket = FakeRelaySocket();+ socket.onFrame = (frame) {+ if (frame['type'] == 'machine_select') socket.fail(StateError('reset'));+ };+ expect(+ ((await link(socket)) as PasswordLinkFailed).code,+ 'CONNECTION_ERROR',+ );+ });++ test('a relay that hangs up says with what code', () async {+ final socket = FakeRelaySocket();+ socket.onFrame = (frame) {+ if (frame['type'] == 'machine_select') unawaited(socket.hangUp(4401));+ };+ expect(+ ((await link(socket)) as PasswordLinkFailed).code,+ 'CONNECTION_CLOSED:4401',+ );+ });++ test('a machine that goes quiet mid-link times out', () async {+ final socket = FakeRelaySocket();+ socket.onFrame = (frame) {+ if (frame['type'] == 'machine_select') {+ socket.emit('connected', {'machineId': _machineId});+ }+ };+ final result = await link(socket, timeout: const Duration(seconds: 3));+ expect((result as PasswordLinkFailed).code, 'TIMEOUT');+ });++ // ⚠️ The timeout used to start only once the socket was open. A dial into a network that+ // swallows packets waits out the OS's own TCP timeout — over a minute on iOS — with the form+ // saying "connecting" the whole time, and no way to tell that from a slow machine.+ test('a dial that never opens times out too', () async {+ final socket = FakeRelaySocket(ready: Completer<void>().future);+ final result =+ await link(+ socket,+ timeout: const Duration(milliseconds: 200),+ ).timeout(+ const Duration(seconds: 5),+ onTimeout: () => const PasswordLinkFailed('HUNG'),+ );+ expect((result as PasswordLinkFailed).code, 'TIMEOUT');+ expect(socket.closedByPhone, isTrue);+ });+ });+}++class SocketExceptionLike implements Exception {+ const SocketExceptionLike();+}