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): linking never throws, so Unlock and Pairing cannot hang for good
dee8d3baeca5ef7
diff --git a/mobile/lib/viewer/direct_link.dart b/mobile/lib/viewer/direct_link.dartindex eb52c9042..77d5bccea 100644--- a/mobile/lib/viewer/direct_link.dart+++ b/mobile/lib/viewer/direct_link.dart@@ -31,17 +31,13 @@ class DirectLink implements PeerLinkClient {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 start = await _start();+ if (start.failed != null) return start.failed!;final result = await linkWithPassword(machineId: machineId,password: password,- identity: await keys.identity(),- accessToken: token,+ identity: start.identity!,+ accessToken: start.token!,wsBaseUrl: config.wsBaseUrl,autonomousEnv: config.autonomousEnv,onProgress: (stage) => onProgress?.call(stage.wireName),@@ -49,11 +45,7 @@ class DirectLink implements PeerLinkClient {);switch (result) {case PasswordLinked(:final peerPub, :final fingerprint):- await keys.pin(machineId, peerPub);- return CliLinkConnectResult(- linkedMachineId: machineId,- fingerprint: fingerprint,- );+ return _pin(machineId, peerPub, 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@@ -73,29 +65,21 @@ class DirectLink implements PeerLinkClient {required String label,String? displayName,}) async {- final String token;- try {- token = await auth.accessToken();- } on DirectAuthException catch (error) {- return CliLinkConnectResult(error: error.message);- }+ final start = await _start();+ if (start.failed != null) return start.failed!;final result = await linkWithCode(machineId: machineId,code: code,label: label,- identity: await keys.identity(),- accessToken: token,+ identity: start.identity!,+ accessToken: start.token!,wsBaseUrl: config.wsBaseUrl,autonomousEnv: config.autonomousEnv,socket: socket,);switch (result) {case PasswordLinked(:final peerPub, :final fingerprint):- await keys.pin(machineId, peerPub);- return CliLinkConnectResult(- linkedMachineId: machineId,- fingerprint: fingerprint,- );+ return _pin(machineId, peerPub, fingerprint);case PasswordLinkFailed(:final code):final name = displayName == null || displayName.isEmpty? 'the computer'@@ -113,6 +97,58 @@ class DirectLink implements PeerLinkClient {}}+ // ⚠️ **Both links answer with a result, never an exception** — the same contract `CliLink`+ // keeps. Their callers await them with nothing around them: the password form with its button+ // disabled until an answer comes, the QR's pairing screen under "Pairing…". A state file that+ // was locked or full threw straight through here, and left each of them waiting for good.++ /// The session's token and this device's identity — what either link needs before it dials.+ Future<+ ({String? token, E2eeIdentity? identity, CliLinkConnectResult? failed})+ >+ _start() async {+ try {+ return (+ token: await auth.accessToken(),+ identity: await keys.identity(),+ failed: null,+ );+ } on DirectAuthException catch (error) {+ return (+ token: null,+ identity: null,+ failed: CliLinkConnectResult(error: error.message),+ );+ } catch (_) {+ return (+ token: null,+ identity: null,+ failed: const CliLinkConnectResult(+ error: 'This phone couldn’t read its own keys. Try again.',+ ),+ );+ }+ }++ /// The machine proved itself; remembering it is the one thing left that can fail.+ Future<CliLinkConnectResult> _pin(+ String machineId,+ List<int> peerPub,+ String fingerprint,+ ) async {+ try {+ await keys.pin(machineId, peerPub);+ } catch (_) {+ return const CliLinkConnectResult(+ error: 'Linked, but this phone couldn’t save it. Try again.',+ );+ }+ return CliLinkConnectResult(+ linkedMachineId: machineId,+ fingerprint: fingerprint,+ );+ }+@overrideFuture<CliLinkListResult> list() async => CliLinkListResult(machines: [diff --git a/mobile/test/viewer/direct_link_test.dart b/mobile/test/viewer/direct_link_test.dartnew file mode 100644index 000000000..54385d1d6--- /dev/null+++ b/mobile/test/viewer/direct_link_test.dart@@ -0,0 +1,308 @@+import 'dart:typed_data';++import 'package:flutter_test/flutter_test.dart';++import 'package:harness_mobile/auth/auth_session.dart';+import 'package:harness_mobile/auth/link_errors.dart';+import 'package:harness_mobile/core/config.dart';+import 'package:harness_mobile/core/local_key_value_store.dart';+import 'package:harness_mobile/e2ee/keys.dart';+import 'package:harness_mobile/e2ee/password_pake.dart';+import 'package:harness_mobile/viewer/direct_auth.dart';+import 'package:harness_mobile/viewer/direct_auth_api.dart';+import 'package:harness_mobile/viewer/direct_link.dart';+import 'package:harness_mobile/viewer/email_code_api.dart';+import 'package:harness_mobile/viewer/viewer_key_store.dart';++import '../voice_fakes.dart' show MemoryKeyValueStore;+import 'fake_http.dart';+import 'fake_relay_socket.dart';+import 'pairing_machines.dart';++/// A state file that refuses to be written — full, or locked by another process.+class _ReadOnlyStore implements LocalKeyValueStore {+ final values = <String, String>{};+ bool failReads = false;++ @override+ Future<String?> read(String key) async {+ if (failReads) throw StateError('state.json is locked');+ return values[key];+ }++ @override+ Future<void> write(String key, String value) async =>+ throw StateError('disk full');++ @override+ Future<void> delete(String key) async => values.remove(key);+}++const _config = AppConfig(apiBaseUrl: 'https://h.invalid');++void main() {+ late E2eeIdentity machineIdentity;+ late Uint8List verifier;++ setUpAll(() async {+ machineIdentity = await E2eeIdentity.generate();+ verifier = await stretchPassword('pw', 'machine-1');+ });++ /// A phone signed in with a token it can use as it is.+ Future<DirectAuth> signedIn({bool signedIn = true}) async {+ final auth = DirectAuth(+ session: AuthSession(storage: MemoryKeyValueStore()),+ api: DirectAuthApi(config: _config, dio: FakeHttp({}).dio()),+ emailCodes: EmailCodeApi(config: _config, dio: FakeHttp({}).dio()),+ );+ if (signedIn) await auth.signIn(const IssuedTokens(token: 'tok'));+ return auth;+ }++ Future<(DirectLink, FakeRelaySocket, ViewerKeyStore)> linkClient({+ LocalKeyValueStore? storage,+ bool signedIn_ = true,+ }) async {+ final socket = FakeRelaySocket();+ final keys = ViewerKeyStore(storage: storage ?? MemoryKeyValueStore());+ final link = DirectLink(+ keys: keys,+ auth: await signedIn(signedIn: signedIn_),+ config: _config,+ socket: socket.factory,+ );+ return (link, socket, keys);+ }++ group('by password', () {+ test('pins the machine it proved, and lists it', () async {+ final (link, socket, keys) = await linkClient();+ final machine = PasswordMachine(socket, machineIdentity, verifier);+ final stages = <String>[];++ final result = await link.connect(+ 'machine-1',+ 'pw',+ onProgress: stages.add,+ );+ expect(result.error, isNull);+ expect(result.linkedMachineId, 'machine-1');+ expect(result.fingerprint, fingerprint(machineIdentity.pub));+ expect(stages, ['connecting', 'deriving_key', 'exchanging', 'verifying']);+ expect(machine.pinned, (await keys.identity()).pub);+ expect(socket.protocols, ['tok']);++ final listed = await link.list();+ expect(listed.machines.single.machineId, 'machine-1');+ expect(+ listed.machines.single.fingerprint,+ fingerprint(machineIdentity.pub),+ );+ expect(+ listed.machines.single.linkedAt,+ matches(RegExp(r'^\d{4}-\d\d-\d\d \d\d:\d\d$')),+ );+ });++ test('a wrong password is a sentence naming the machine', () async {+ final (link, socket, keys) = await linkClient();+ PasswordMachine(socket, machineIdentity, verifier);+ final result = await link.connect(+ 'machine-1',+ 'wrong',+ displayName: 'Studio Mac',+ );+ expect(result.error, contains('Studio Mac'));+ expect(result.error, contains('password is wrong'));+ expect(await keys.peers(), isEmpty);+ });++ test('with no name to go on, the id is the name', () async {+ final (link, socket, _) = await linkClient();+ PasswordMachine(socket, machineIdentity, verifier).lockedUntil =+ DateTime.now().add(const Duration(minutes: 2)).millisecondsSinceEpoch;+ final result = await link.connect('machine-1', 'pw', displayName: '');+ expect(result.error, contains('machine-1'));+ expect(result.error, contains('Try again in 2 minutes'));+ });++ test('signed out: said, and nothing dialled', () async {+ final (link, socket, _) = await linkClient(signedIn_: false);+ final result = await link.connect('machine-1', 'pw');+ expect(result.error, 'Not signed in.');+ expect(socket.dialled, isNull);+ });+ });++ group('by the Add Phone code', () {+ test('pins the machine it paired with', () async {+ final (link, socket, keys) = await linkClient();+ final machine = CodeMachine(socket, machineIdentity, 'K7QM-4XPT');+ final result = await link.connectWithCode(+ 'machine-1',+ 'k7qm4xpt',+ label: 'iPhone',+ );+ expect(result.error, isNull);+ expect(result.fingerprint, fingerprint(machineIdentity.pub));+ expect(machine.pinned, (await keys.identity()).pub);+ expect((await keys.peer('machine-1'))!.pub, machineIdentity.pub);+ });++ test('each failure reads as a sentence, never a bare code', () async {+ for (final (code, expected) in [+ (+ 'CODE_MISMATCH',+ 'That code didn’t match. Scan the new one on Studio Mac.',+ ),+ ('TIMEOUT', 'Keep “Add phone” open on Studio Mac, then scan again.'),+ (+ 'PAIRING_BUSY',+ 'Studio Mac is pairing with something else. Try again.',+ ),+ ('EXPIRED', 'Couldn’t connect to Studio Mac (EXPIRED).'),+ ]) {+ final (link, socket, keys) = await linkClient();+ socket.onFrame = (frame) {+ if (frame['type'] == 'machine_select') {+ socket.emit('connected', {'machineId': 'machine-1'});+ } else if (frame['type'] == 'e2e_pair_intent') {+ socket.emit('e2e_pair_intent_result', {+ 'requestId': (frame['payload'] as Map)['requestId'],+ 'error': code,+ });+ }+ };+ final result = await link.connectWithCode(+ 'machine-1',+ 'x',+ label: 'iPhone',+ displayName: 'Studio Mac',+ );+ expect(result.error, expected);+ expect(await keys.peers(), isEmpty);+ }+ });++ test('with no name, it is "the computer"', () async {+ final (link, socket, _) = await linkClient();+ socket.onFrame = (frame) {+ if (frame['type'] == 'machine_select') {+ socket.emit('machine_select_error', {+ 'machineId': 'machine-1',+ 'error': 'CODE_MISMATCH',+ });+ }+ };+ final result = await link.connectWithCode('machine-1', 'x', label: 'i');+ expect(+ result.error,+ 'That code didn’t match. Scan the new one on the computer.',+ );+ });++ test('signed out: said, and nothing dialled', () async {+ final (link, socket, _) = await linkClient(signedIn_: false);+ final result = await link.connectWithCode('machine-1', 'x', label: 'i');+ expect(result.error, 'Not signed in.');+ expect(socket.dialled, isNull);+ });+ });++ // ⚠️ A link client answers with a result, never an exception: the password form awaits it with+ // its button disabled and no catch, so a throw here left "Unlock" spinning for good — and the+ // QR's pairing screen on "Pairing…" with no way on.+ group('a state file that will not cooperate', () {+ test('an identity that cannot be read is an error, not a throw', () async {+ final storage = _ReadOnlyStore()..failReads = true;+ final (link, socket, _) = await linkClient(storage: storage);+ final byPassword = await link.connect('machine-1', 'pw');+ expect(byPassword.error, isNotNull);+ final byCode = await link.connectWithCode('machine-1', 'x', label: 'i');+ expect(byCode.error, isNotNull);+ expect(socket.dialled, isNull);+ });++ test('a pin that cannot be saved is an error, not a throw', () async {+ final storage = _ReadOnlyStore();+ final (link, socket, _) = await linkClient(storage: storage);+ // The identity has to exist to pair at all; the pin is what cannot be written.+ storage.values['viewer_e2ee_identity_seed'] =+ 'AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE=';+ CodeMachine(socket, machineIdentity, 'K7QM');+ final result = await link.connectWithCode(+ 'machine-1',+ 'K7QM',+ label: 'i',+ );+ expect(result.error, isNotNull);+ expect(result.linkedMachineId, isNull);+ });+ });++ test('unlinking a machine that was never linked says so', () async {+ final (link, _, keys) = await linkClient();+ expect(await link.unlink('ghost'), 'ghost is not linked.');+ await keys.pin('m', machineIdentity.pub);+ expect(await link.unlink('m'), isNull);+ expect((await link.list()).machines, isEmpty);+ });++ group('humanizeLinkError', () {+ test('every code the machine or the socket can end on is a sentence', () {+ for (final code in [+ 'NO_REMOTE_PASSWORD',+ 'BAD_INTENT',+ 'WRONG_PASSWORD',+ 'BUSY',+ 'TIMEOUT',+ 'SEND_FAILED',+ 'DERIVE_FAILED',+ 'SELECT_FAILED',+ 'PAIR_FAILED',+ 'PROTOCOL_ERROR',+ 'CONNECTION_ERROR',+ 'SOMETHING_NEW',+ ]) {+ final sentence = humanizeLinkError(code, 'm');+ expect(sentence, isNot(code));+ expect(sentence.length, greaterThan(code.length + 10), reason: code);+ }+ expect(+ humanizeLinkError('SOMETHING_NEW', 'm'),+ contains('SOMETHING_NEW'),+ );+ });++ test('a closed socket says with what code', () {+ expect(+ humanizeLinkError('CONNECTION_CLOSED:4401', 'm'),+ contains('code 4401'),+ );+ });++ test('a lockout counts the minutes, or says now, or says a few', () {+ expect(+ humanizeLinkError('RATE_LIMITED', 'm'),+ contains('Wait a few minutes'),+ );+ expect(+ humanizeLinkError(+ 'RATE_LIMITED',+ 'm',+ retryAt: DateTime.now().add(const Duration(seconds: 30)),+ ),+ contains('Try again in 1 minute.'),+ );+ expect(+ humanizeLinkError(+ 'RATE_LIMITED',+ 'm',+ retryAt: DateTime.now().subtract(const Duration(seconds: 5)),+ ),+ contains('Try again now.'),+ );+ });+ });+}diff --git a/mobile/test/viewer/pairing_machines.dart b/mobile/test/viewer/pairing_machines.dartnew file mode 100644index 000000000..2f0975597--- /dev/null+++ b/mobile/test/viewer/pairing_machines.dart@@ -0,0 +1,238 @@+import 'dart:async';+import 'dart:convert';+import 'dart:typed_data';++import 'package:harness_mobile/e2ee/bytes.dart';+import 'package:harness_mobile/e2ee/code_pake.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 'fake_relay_socket.dart';++/// The machine's side of the remote-password link, as `manager.ts` `onPwPairIntent` / `onPwPake`+/// run it, behind a [FakeRelaySocket]: 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 PasswordMachine {+ PasswordMachine(+ this.socket,+ this.identity,+ this.verifier, {+ this.machineId = 'machine-1',+ }) {+ socket.onFrame = (frame) => unawaited(_receive(frame));+ }++ final FakeRelaySocket socket;+ final E2eeIdentity identity;+ final Uint8List verifier;+ final String machineId;++ /// 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;+ late 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;+ }+ socket.emit('e2e_pw_pake', {+ 'sid': _sidB64,+ 'round': 3,+ 'mac': b64e(macTag(kc.adapter, th)),+ 'enc': b64e(await sealIdentity(identity, pairKey(isk, _ci), th)),+ });+ case 'e2e_pw_pake' when payload['round'] == 4:+ final pub = await openIdentity(+ pairKey(_isk!, _ci),+ _th!,+ payload['enc'] as String,+ );+ if (pub == null) 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',+ });+ }+ }+}++/// The machine's side of the live-code pairing (`manager.ts` `onPairIntent` / `onPake`), behind a+/// [FakeRelaySocket], with the desktop app supplying [code] the moment the intent arrives.+class CodeMachine {+ CodeMachine(+ this.socket,+ this.identity,+ this.code, {+ this.machineId = 'machine-1',+ }) {+ socket.onFrame = (frame) => unawaited(_receive(frame));+ }++ final FakeRelaySocket socket;+ final E2eeIdentity identity;+ final String code;+ final String machineId;++ Uint8List? pinned;+ late Uint8List _pairId;+ late String _pairIdB64;+ late String _ci;+ late BigInt _y;+ late Uint8List _ya;+ Uint8List? _isk, _th;++ 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});+ case 'e2e_pair_intent':+ socket.emit('e2e_pair_intent_result', {+ 'requestId': payload['requestId'],+ 'accepted': true,+ 'ttl': 60,+ });+ _pairIdB64 = payload['pairId'] as String;+ _pairId = b64d(_pairIdB64);+ _ci = pairContext(machineId, role: payload['role'] as String);+ final start = cpaceStart(codeCpaceGenerator(code, _pairId, _ci));+ _y = start.scalar;+ _ya = start.share;+ socket.emit('e2e_pake', {+ 'pairId': _pairIdB64,+ 'round': 1,+ 'ya': b64e(_ya),+ });+ case 'e2e_pake' when payload['round'] == 2:+ final yb = b64d(payload['yb'] as String);+ final isk = _isk = cpaceIsk(_pairId, cpaceShared(yb, _y), _ya, yb);+ final th = _th = transcriptHash(_pairId, _ci, _ya, yb);+ final kc = kcKeys(isk, _ci);+ if (!macVerify(kc.web, th, b64d(payload['mac'] as String))) {+ socket.emit('e2e_pake', {+ 'pairId': _pairIdB64,+ 'round': 5,+ 'error': 'CODE_MISMATCH',+ });+ return;+ }+ socket.emit('e2e_pake', {+ 'pairId': _pairIdB64,+ 'round': 3,+ 'mac': b64e(macTag(kc.adapter, th)),+ 'enc': b64e(await sealIdentity(identity, pairKey(isk, _ci), th)),+ });+ case 'e2e_pake' when payload['round'] == 4:+ final pub = await openIdentity(+ pairKey(_isk!, _ci),+ _th!,+ payload['enc'] as String,+ );+ if (pub == null) return;+ pinned = pub;+ socket.emit('e2e_pake', {'pairId': _pairIdB64, 'round': 5, 'ok': true});+ }+ }+}++/// Round 3's sealed identity claim, bound to the transcript [th].+Future<Uint8List> sealIdentity(+ E2eeIdentity identity,+ Uint8List key,+ Uint8List th,+) async => aeadSeal(+ key,+ 3,+ utf8Bytes('e2e-id'),+ utf8Bytes(+ jsonEncode({+ 'id': b64e(identity.pub),+ 'sig': b64e(await pairBindSig(identity, th)),+ }),+ ),+);++/// Round 4's sealed identity claim opened and checked; null when it does not hold up.+Future<Uint8List?> openIdentity(Uint8List key, Uint8List th, String enc) async {+ final opened = aeadOpen(key, 4, utf8Bytes('e2e-id'), b64d(enc));+ if (opened == null) return null;+ final claim = jsonDecode(utf8.decode(opened)) as Map<String, dynamic>;+ final pub = b64d(claim['id'] as String);+ return await pairBindVerify(pub, th, b64d(claim['sig'] as String))+ ? pub+ : null;+}diff --git a/mobile/test/viewer/password_link_test.dart b/mobile/test/viewer/password_link_test.dartindex 953b064e0..94a15cb80 100644--- a/mobile/test/viewer/password_link_test.dart+++ b/mobile/test/viewer/password_link_test.dart@@ -12,139 +12,11 @@ import 'package:harness_mobile/e2ee/primitives.dart';import 'package:harness_mobile/viewer/password_link.dart';import 'fake_relay_socket.dart';+import 'pairing_machines.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;@@ -189,7 +61,7 @@ void main() {test('the right password pins both sides', () async {final socket = FakeRelaySocket();- final machine = _PwMachine(socket, machineIdentity, verifier);+ final machine = PasswordMachine(socket, machineIdentity, verifier);final stages = <PasswordLinkStage>[];final result = await link(socket, stages: stages);@@ -219,7 +91,7 @@ void main() {test('a wrong password pins nothing', () async {final socket = FakeRelaySocket();- final machine = _PwMachine(socket, machineIdentity, verifier);+ final machine = PasswordMachine(socket, machineIdentity, verifier);final result = await link(socket, password: 'wrong');expect((result as PasswordLinkFailed).code, 'WRONG_PASSWORD');expect(machine.pinned, isNull);@@ -228,7 +100,7 @@ void main() {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 =+ PasswordMachine(socket, machineIdentity, verifier).lockedUntil =until.millisecondsSinceEpoch;final result = await link(socket) as PasswordLinkFailed;expect(result.code, 'RATE_LIMITED');@@ -244,7 +116,7 @@ void main() {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 =+ PasswordMachine(socket, machineIdentity, verifier).lockedAtRound2 =until.millisecondsSinceEpoch;final result = await link(socket) as PasswordLinkFailed;expect(result.code, 'RATE_LIMITED');@@ -324,7 +196,7 @@ void main() {test('frames for somebody else\'s attempt are not this one\'s', () async {final socket = FakeRelaySocket();- final machine = _PwMachine(socket, machineIdentity, verifier);+ final machine = PasswordMachine(socket, machineIdentity, verifier);final real = socket.onFrame!;socket.onFrame = (frame) {if (frame['type'] == 'e2e_pw_pair_intent') {@@ -425,7 +297,7 @@ void main() {Future<Map<String, Object?>> Function(Uint8List isk, Uint8List th) forge,) async {final socket = FakeRelaySocket();- _PwMachine(socket, machineIdentity, verifier).forgeRound3 = forge;+ PasswordMachine(socket, machineIdentity, verifier).forgeRound3 = forge;return await link(socket) as PasswordLinkFailed;}