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: implement password-based PAKE authentication for machine linking to replace token-based setup

0xken15eabf7f461991
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 0048699ad..ce183b1e9 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -413,6 +413,18 @@ export class BackendSocket {
revokeAll(): ReturnType<E2eeManager['revokeAll']> {
return this.e2ee.revokeAll()
}
+ /** `harness remote-password set` — stretch + persist a new persistent remote password. */
+ setRemotePassword(password: string): ReturnType<E2eeManager['setRemotePassword']> {
+ return this.e2ee.setRemotePassword(password)
+ }
+ /** `harness remote-password clear` — remove the persistent remote password. */
+ clearRemotePassword(): void {
+ this.e2ee.clearRemotePassword()
+ }
+ /** `harness remote-password status` — whether one is set, and its fingerprint. */
+ remotePasswordStatus(): ReturnType<E2eeManager['remotePasswordStatus']> {
+ return this.e2ee.remotePasswordStatus()
+ }
connect(): void {
if (this.closed || this.ws || this.connecting) return
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index f99033bd6..781f34233 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -86,9 +86,9 @@ import {
import { setVoiceRouterDeviceConnected, setVoiceRouterSessions, shutdownVoiceRouter } from './lib/voiceRouter.js'
import { tailFile } from './lib/sessions.js'
import { E2eeStore } from './lib/e2ee/store.js'
-import { b64e, verifySetupToken } from './lib/e2ee/core.js'
+import { b64e } from './lib/e2ee/core.js'
import { MachinePeerStore } from './lib/e2ee/machinePeers.js'
-import { claimSetupToken } from './lib/e2ee/relayClient.js'
+import { connectWithPassword } from './lib/e2ee/relayClient.js'
import {
startSelfUpdater, restore as restoreUpdate, confirm as confirmUpdate,
fetchManifest, downloadVerified, canary, stage, semverGt,
@@ -226,11 +226,16 @@ Browser end-to-end encryption:
harness unpair --all unpair every browser
Machine-to-machine linking (lets this machine's relay reach ANOTHER of your machines with the CLI,
-not the app, terminating E2EE):
- harness link create print a token for another machine's \`harness link import\`
- harness link import <token> claim a token printed by another machine's \`harness link create\`
- harness link list list machines this one has linked
- harness link unlink <id> remove a linked machine's trust
+not the app, terminating E2EE). A machine's remote password is persistent — set once, reused for
+every future connect, until you change or clear it:
+ harness remote-password set set/rotate this machine's persistent remote password
+ harness remote-password status show whether one is set, and its fingerprint
+ harness remote-password clear remove this machine's remote password
+ harness link connect <machineId> join a machine using ITS remote password (fully automatic)
+ harness link list list machines this one has linked
+ harness link unlink <id> remove a linked machine's trust
+ (both \`remote-password set\` and \`link connect\` prompt for the password interactively, or read one
+ line from stdin with --stdin; add --json for NDJSON output instead of the human-readable text)
harness --help
@@ -2333,6 +2338,14 @@ async function runForeground(session: AuthSession): Promise<void> {
return { status: r.error === 'AMBIGUOUS' ? 409 : 404, body: { error: r.error } }
},
onRevokeAll: () => ({ status: 200, body: backend.revokeAll() }),
+ // `harness remote-password set|clear|status` — mutate/read the running daemon's live E2EE state
+ // directly, so `harness link connect` from another machine sees a just-set password immediately.
+ onSetRemotePassword: async (password) => {
+ const r = await backend.setRemotePassword(password)
+ return { status: 200, body: r }
+ },
+ onClearRemotePassword: () => { backend.clearRemotePassword(); return { status: 200, body: { ok: true } } },
+ onRemotePasswordStatus: () => ({ status: 200, body: backend.remotePasswordStatus() }),
// Local dashboard (GET /api/status): adapter health + computer fingerprint + local pairings. It
// deliberately does NOT expose chat/transcripts — those live in the cloud web (WEB_URL/commander).
onStatus: () => ({
@@ -2394,8 +2407,9 @@ async function runForeground(session: AuthSession): Promise<void> {
onMachineDelete: (machineId) => proxyBackend('DELETE', `/api/machines/${encodeURIComponent(machineId)}`),
onAuthMe: () => proxyBackend('GET', '/api/auth/me'),
})
- // Same on-disk identity `harness link create`/`import` use (E2eeStore.init() is idempotent per file,
- // so a separate in-memory instance here just reads the one this machine already has).
+ // Same on-disk identity `harness remote-password set`/`link connect` use (E2eeStore.init() is
+ // idempotent per file, so a separate in-memory instance here just reads the one this machine
+ // already has).
const relayIdentityStore = new E2eeStore()
relayIdentityStore.init()
const relayPool = new RemoteRelayPool(
@@ -3065,10 +3079,10 @@ async function runForeground(session: AuthSession): Promise<void> {
backendWsBase: env.BACKEND_WS_URL,
computerId: computerId(),
autonomousEnv: readAuthSession()?.autonomousEnv ?? session.autonomousEnv,
- // The SAME identity `harness link create` publishes and `harness link import` verifies against, so
- // one link ceremony covers the desktop app's relay and the dial's lane alike.
+ // The SAME identity `harness remote-password set` publishes and `harness link connect` proves
+ // knowledge against, so one link ceremony covers the desktop app's relay and the dial's lane alike.
identity: relayIdentityStore.getIdentity(),
- // Read FRESH on every attach: `harness link import` runs as a separate process, so a value captured
+ // Read FRESH on every attach: `harness link connect` runs as a separate process, so a value captured
// at daemon start would keep answering "not linked" until the next restart.
peer: (machineId) => machinePeers.get(machineId),
// Read fresh for the same reason `machineId` above is a thunk: it is '' until the daemon has resolved
@@ -3082,7 +3096,7 @@ async function runForeground(session: AuthSession): Promise<void> {
const fleet = new DeviceFleet({
list: machineList,
link: deviceLink,
- // Read FRESH on every call, never cached: `harness link import` runs as a separate process, so a
+ // Read FRESH on every call, never cached: `harness link connect` runs as a separate process, so a
// cached answer would keep saying "not linked" for as long as this daemon lives.
hasPeerLink: (machineId) => machinePeers.get(machineId) !== null,
log: (line) => console.log(`[device] ${line}`),
@@ -3560,63 +3574,222 @@ async function unpairCommand(id: string | undefined, all: boolean): Promise<void
process.exit(1)
}
-/** `harness link create` — print a reusable setup token this machine's own identity signs, for
- * ANOTHER MACHINE's `harness link import` to consume — the machine-to-machine counterpart of
- * `browser-link` (same token mechanism, different consumer). Kept a distinct verb on purpose: `pair`/
- * `browser-link` stay reserved for the browser↔this-machine relation (see the file header comment). */
-async function linkCreateCommand(): Promise<void> {
+/** Read one line from stdin (used by `--stdin` password input — scripts/GUIs pipe the password in
+ * directly instead of going through the interactive masked prompt below). Resolves '' on EOF with no
+ * line, so callers must treat an empty result as "no password provided". */
+function readStdinLine(): Promise<string> {
+ return new Promise((resolve) => {
+ const rl = createInterface({ input: process.stdin })
+ let settled = false
+ // Order matters: rl.close() fires the 'close' listener SYNCHRONOUSLY (re-entrantly, from inside
+ // this same call), so `settled` must flip to true before calling it — otherwise the 'close'
+ // handler's resolve('') would run (and win, since a Promise only honors the first resolve() call)
+ // before we ever reach our own resolve(line) on the next line.
+ rl.once('line', (line) => { settled = true; rl.close(); resolve(line) })
+ rl.once('close', () => { if (!settled) resolve('') })
+ })
+}
+
+/** Prompt on stdin with the terminal echo suppressed, for a remote password. Falls back to a plain
+ * (echoed) prompt when stdin isn't a TTY (piped input, non-interactive shell) — there's no terminal
+ * to suppress echo on, and readline still works correctly for a single piped line. */
+function promptPassword(prompt: string): Promise<string> {
+ return new Promise((resolve) => {
+ if (!process.stdin.isTTY) {
+ const rl = createInterface({ input: process.stdin, output: process.stdout })
+ rl.question(prompt, (answer) => { rl.close(); resolve(answer) })
+ return
+ }
+ const rl = createInterface({ input: process.stdin, output: process.stdout })
+ // Suppress readline's own echo of typed characters while still letting our prompt text and the
+ // trailing newline through — the standard Node trick for masked input without an extra dependency.
+ const rlWithOutput = rl as unknown as { _writeToOutput?: (s: string) => void }
+ let muted = false
+ rlWithOutput._writeToOutput = (s: string) => { if (!muted) process.stdout.write(s) }
+ process.stdout.write(prompt)
+ muted = true
+ rl.question('', (answer) => {
+ muted = false
+ rl.close()
+ process.stdout.write('\n')
+ resolve(answer)
+ })
+ })
+}
+
+/** `harness remote-password set` — set/rotate this machine's persistent "remote password": the
+ * shared secret `harness link connect <machineId>` on another machine proves knowledge of, to link
+ * to this one. Not single-use and does not expire — stays valid until explicitly changed/cleared.
+ * Prefers the running daemon (so an in-progress `link connect` from elsewhere sees it immediately);
+ * falls back to writing the disk-backed store directly when no daemon is running, same fallback
+ * shape as `browserLinkCommand`. `--stdin` reads one line with no confirmation (for scripts/GUIs);
+ * interactively it prompts twice (masked) and requires the two to match. */
+async function remotePasswordSetCommand(json: boolean, stdin: boolean): Promise<void> {
const session = readAuthSession()
- if (!session?.machineId) { console.error('\n ✗ This computer is not signed in. Run: harness login\n'); process.exit(1) }
- const setup = createSetupToken(session.machineId)
- console.log('\n Machine-link token (valid for 7 days):\n')
- console.log(` ${setup.token}\n`)
- console.log(' Run on the OTHER machine:\n')
- console.log(` harness link import ${setup.token}\n`)
- console.log(` fingerprint ${setup.fingerprint} — verify it matches on the other machine\n`)
+ if (!session?.machineId) {
+ if (json) console.log(JSON.stringify({ ok: false, error: 'NOT_SIGNED_IN' }))
+ else console.error('\n ✗ This computer is not signed in. Run: harness login\n')
+ process.exit(1)
+ return
+ }
+ let password: string
+ if (stdin) {
+ password = (await readStdinLine()).trim()
+ if (!password) {
+ if (json) console.log(JSON.stringify({ ok: false, error: 'EMPTY_PASSWORD' }))
+ else console.error('\n ✗ No password read from stdin.\n')
+ process.exit(1)
+ return
+ }
+ } else {
+ const a = await promptPassword(' New remote password: ')
+ const b = await promptPassword(' Confirm remote password: ')
+ if (!a || a !== b) {
+ if (json) console.log(JSON.stringify({ ok: false, error: 'MISMATCH' }))
+ else console.error('\n ✗ Passwords did not match (or were empty). Nothing changed.\n')
+ process.exit(1)
+ return
+ }
+ password = a
+ }
+ let result: { fingerprint: string } | null = null
+ try {
+ const res = await fetch(`http://127.0.0.1:${daemonPort()}/api/remote-password/set`, {
+ method: 'POST',
+ headers: { 'x-adapter-local': '1', 'content-type': 'application/json' },
+ body: JSON.stringify({ password }),
+ })
+ if (res.ok) {
+ const body = (await res.json().catch(() => null)) as { fingerprint?: unknown } | null
+ if (typeof body?.fingerprint === 'string') result = { fingerprint: body.fingerprint }
+ }
+ } catch { /* fall back to the disk-backed store below */ }
+ if (!result) {
+ const store = new E2eeStore()
+ store.init()
+ result = await store.setRemotePassword(session.machineId, password)
+ }
+ if (json) { console.log(JSON.stringify({ ok: true, fingerprint: result.fingerprint })); process.exit(0) }
+ console.log('\n ✓ Remote password set for this machine.')
+ console.log(` fingerprint ${result.fingerprint} — verify it matches on the joining machine after \`harness link connect\`\n`)
+ console.log(' Anyone with this password can link a machine to this one. Keep it private.\n')
+ if (!readPid()) console.log(' Start the adapter with `harness start` if joins are being rejected.\n')
process.exit(0)
}
-/** `harness link import <token>` — claim another machine's link token, proving THIS machine's own
- * identity to it. Needs only this computer's own SSO session and network — no running daemon
- * required. On success this machine can relay through to that machine's data plane with the CLI (not
- * the app) terminating E2EE — see lib/remoteRelay.ts. */
-async function linkImportCommand(token: string | undefined): Promise<void> {
- if (!token) { console.error('Usage: harness link import <token> (from `harness link create` on the other machine)'); process.exit(1) }
+/** `harness remote-password clear` — remove the persistent remote password. Until a new one is set,
+ * `harness link connect` against this machine always fails with NO_REMOTE_PASSWORD. */
+async function remotePasswordClearCommand(json: boolean): Promise<void> {
+ let cleared = false
+ try {
+ const res = await fetch(`http://127.0.0.1:${daemonPort()}/api/remote-password/clear`, {
+ method: 'POST',
+ headers: { 'x-adapter-local': '1' },
+ })
+ if (res.ok) cleared = true
+ } catch { /* fall back to the disk-backed store below */ }
+ if (!cleared) {
+ const store = new E2eeStore()
+ store.init()
+ store.clearRemotePassword()
+ }
+ if (json) console.log(JSON.stringify({ ok: true }))
+ else console.log('\n ✓ Remote password cleared. This machine can no longer be linked by password until a new one is set.\n')
+ process.exit(0)
+}
+
+/** `harness remote-password status` — whether a remote password is set, and its fingerprint. */
+async function remotePasswordStatusCommand(json: boolean): Promise<void> {
+ let status: { hasPassword: boolean; fingerprint: string | null; setAt: number | null } | null = null
+ try {
+ const res = await fetch(`http://127.0.0.1:${daemonPort()}/api/remote-password/status`, { headers: { 'x-adapter-local': '1' } })
+ if (res.ok) {
+ const body = (await res.json().catch(() => null)) as { hasPassword?: unknown; fingerprint?: unknown; setAt?: unknown } | null
+ if (typeof body?.hasPassword === 'boolean') {
+ status = {
+ hasPassword: body.hasPassword,
+ fingerprint: typeof body.fingerprint === 'string' ? body.fingerprint : null,
+ setAt: typeof body.setAt === 'number' ? body.setAt : null,
+ }
+ }
+ }
+ } catch { /* fall back to the disk-backed store below */ }
+ if (!status) {
+ const store = new E2eeStore()
+ store.init()
+ status = { hasPassword: store.hasRemotePassword(), fingerprint: store.remotePasswordFingerprint(), setAt: store.remotePasswordSetAt() }
+ }
+ if (json) { console.log(JSON.stringify(status)); process.exit(0) }
+ if (!status.hasPassword) { console.log('\n No remote password set.\n Run: harness remote-password set\n'); process.exit(0) }
+ console.log('\n Remote password is set.')
+ console.log(` fingerprint ${status.fingerprint}\n`)
+ process.exit(0)
+}
+
+/** `harness link connect <machineId>` — join another machine using ITS persistent remote password
+ * (`harness remote-password set` on that machine), proving knowledge of the password rather than
+ * possession of a signed token. Needs only this computer's own SSO session and network — no running
+ * daemon required, same as the old `link import`. On success this machine can relay through to that
+ * machine's data plane with the CLI (not the app) terminating E2EE — see lib/remoteRelay.ts. Fully
+ * automatic on success: no approval step runs on the target machine beyond having set the password. */
+async function linkConnectCommand(machineId: string | undefined, stdin: boolean, json: boolean): Promise<void> {
+ if (!machineId) {
+ if (json) console.log(JSON.stringify({ ok: false, error: 'MISSING_MACHINE_ID' }))
+ else console.error('Usage: harness link connect <machineId> (the remote password is set on that machine via `harness remote-password set`)')
+ process.exit(1)
+ return
+ }
const session = readAuthSession()
- if (!session) { console.error('\n ✗ Not signed in. Run: harness login\n'); process.exit(1) }
- const verified = verifySetupToken(token)
- if (!verified || !verified.payload.machineId) {
- console.error('\n ✗ That token is invalid, expired, or missing a machine id.\n')
+ if (!session) {
+ if (json) console.log(JSON.stringify({ ok: false, error: 'NOT_SIGNED_IN' }))
+ else console.error('\n ✗ Not signed in. Run: harness login\n')
process.exit(1)
+ return
+ }
+ let password: string
+ if (stdin) {
+ password = (await readStdinLine()).trim()
+ if (!password) {
+ if (json) console.log(JSON.stringify({ ok: false, error: 'EMPTY_PASSWORD' }))
+ else console.error('\n ✗ No password read from stdin.\n')
+ process.exit(1)
+ return
+ }
+ } else {
+ password = await promptPassword(` Remote password for ${machineId}: `)
}
- const targetMachineId = verified.payload.machineId
const auth = new AuthSessionManager(backendHttpBase())
let accessToken: string
try {
accessToken = await auth.accessToken()
} catch (err) {
- console.error(`\n ✗ Could not refresh this computer's SSO session: ${err instanceof Error ? err.message : err}\n`)
+ const message = `Could not refresh this computer's SSO session: ${err instanceof Error ? err.message : err}`
+ if (json) console.log(JSON.stringify({ ok: false, error: 'AUTH_FAILED', message }))
+ else console.error(`\n ✗ ${message}\n`)
process.exit(1)
return
}
const store = new E2eeStore()
store.init()
- const result = await claimSetupToken({
- token,
- targetMachineId,
+ const result = await connectWithPassword({
+ targetMachineId: machineId,
+ password,
selfIdentity: store.getIdentity(),
accessToken,
backendWsBase: env.BACKEND_WS_URL.replace(/\/$/, ''),
autonomousEnv: session.autonomousEnv,
+ onProgress: json ? (stage) => console.log(JSON.stringify({ stage })) : undefined,
})
if (!result.ok) {
- console.error(`\n ✗ Link failed: ${result.error}\n`)
+ if (json) console.log(JSON.stringify({ ok: false, error: result.error }))
+ else console.error(`\n ✗ Link failed: ${result.error}\n`)
process.exit(1)
return
}
- new MachinePeerStore().pin(targetMachineId, b64e(result.peerPub), 'harness link', Date.now())
- console.log(`\n ✓ Linked machine ${targetMachineId}`)
- console.log(` fingerprint ${result.fingerprint} — verify it matches \`harness link create\`'s output on the other machine\n`)
+ new MachinePeerStore().pin(machineId, b64e(result.peerPub), 'harness link', Date.now())
+ if (json) { console.log(JSON.stringify({ ok: true, fingerprint: result.fingerprint, machineId })); process.exit(0) }
+ console.log(`\n ✓ Linked machine ${machineId}`)
+ console.log(` fingerprint ${result.fingerprint} — verify it matches \`harness remote-password status\`'s output on the other machine\n`)
process.exit(0)
}
@@ -3624,7 +3797,7 @@ async function linkImportCommand(token: string | undefined): Promise<void> {
async function linkListCommand(): Promise<void> {
const peers = new MachinePeerStore().list()
if (!peers.length) {
- console.log('\n No machines linked yet.\n Run `harness link create` on another machine and `harness link import <token>` here.\n')
+ console.log('\n No machines linked yet.\n Run `harness remote-password set` on the other machine and `harness link connect <machineId>` here.\n')
process.exit(0)
}
console.log('\n Linked machines:\n')
@@ -3713,12 +3886,17 @@ switch (cmd) {
pairingsCommand().catch(onError)
break
case 'link':
- if (args[0] === 'create') linkCreateCommand().catch(onError)
- else if (args[0] === 'import') linkImportCommand(args[1]).catch(onError)
+ if (args[0] === 'connect') linkConnectCommand(args[1], flags.includes('--stdin'), flags.includes('--json')).catch(onError)
else if (args[0] === 'list') linkListCommand().catch(onError)
else if (args[0] === 'unlink') linkUnlinkCommand(args[1]).catch(onError)
else { console.error(`Unknown command: link ${args[0] ?? ''}`); usage(1) }
break
+ case 'remote-password':
+ if (args[0] === 'set') remotePasswordSetCommand(flags.includes('--json'), flags.includes('--stdin')).catch(onError)
+ else if (args[0] === 'clear') remotePasswordClearCommand(flags.includes('--json')).catch(onError)
+ else if (args[0] === 'status') remotePasswordStatusCommand(flags.includes('--json')).catch(onError)
+ else { console.error(`Unknown command: remote-password ${args[0] ?? ''}`); usage(1) }
+ break
case 'unpair':
unpairCommand(args[0], flags.includes('--all') || flags.includes('-a')).catch(onError)
break
diff --git a/cli/src/device/deviceFleet.ts b/cli/src/device/deviceFleet.ts
index 71fe7f8ae..9983ca990 100644
--- a/cli/src/device/deviceFleet.ts
+++ b/cli/src/device/deviceFleet.ts
@@ -37,7 +37,7 @@ function toCableAgent(raw: unknown): CableAgent {
export interface DeviceFleetOpts {
list: MachineListCache
link: DeviceLink
- /** Whether this daemon holds a pinned E2EE key for a machine — see `harness link import`. */
+ /** Whether this daemon holds a pinned E2EE key for a machine — see `harness link connect`. */
hasPeerLink: (machineId: string) => boolean
log: (line: string) => void
}
diff --git a/cli/src/device/deviceLink.ts b/cli/src/device/deviceLink.ts
index 34f66f945..fc4d7ebc5 100644
--- a/cli/src/device/deviceLink.ts
+++ b/cli/src/device/deviceLink.ts
@@ -55,9 +55,9 @@ export interface DeviceLinkOpts {
backendWsBase: string
computerId: string
autonomousEnv: string
- /** This daemon's own E2EE identity — the same one `harness link create/import` signs with. */
+ /** This daemon's own E2EE identity — the same one `harness remote-password set`/`link connect` signs with. */
identity: Identity
- /** The pinned key for a machine, read FRESH: `harness link import` runs as a separate process. */
+ /** The pinned key for a machine, read FRESH: `harness link connect` runs as a separate process. */
peer: (machineId: string) => MachinePeer | null
/**
* THIS computer's machineId, or '' before the daemon has resolved one.
@@ -144,7 +144,7 @@ export class DeviceLink {
/**
* Bring up the E2EE session for a machine that needs one, IF it does not already have a live one.
*
- * The trust anchor is the PINNED key from `harness link import`, never anything the backend hands over:
+ * The trust anchor is the PINNED key from `harness link connect`, never anything the backend hands over:
* a key directory would make the relay the trust anchor, which is the exact property end-to-end
* encryption exists to deny it.
*
@@ -420,7 +420,7 @@ export class DeviceLink {
if (frame.type === 'e2e_rekey') { this.sessions.get(from)?.handleRekey((frame.payload ?? {}) as Record<string, unknown>); return }
if (frame.type === 'e2e_denied') {
// The far end knows this daemon's key and rejected it — the pin is stale, not merely missing.
- this.opts.log(`device: e2e denied ${from} — re-run \`harness link import\` for this machine`)
+ this.opts.log(`device: e2e denied ${from} — the remote password may have changed or this machine's link was revoked, re-run \`harness link connect ${from}\``)
this.failCrypto(from, new Error('E2EE_DENIED'))
return
}
diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.ts
index 011bbc695..c2d789b49 100644
--- a/cli/src/hookServer.ts
+++ b/cli/src/hookServer.ts
@@ -83,6 +83,13 @@ export interface HookServerHandlers {
onRevoke?: (id: string) => PairOutcome
/** `harness unpair --all` — unpair every browser. */
onRevokeAll?: () => PairOutcome
+ /** `harness remote-password set` — stretch + persist a new persistent remote password on the
+ * running daemon's live E2EE state. */
+ onSetRemotePassword?: (password: string) => Promise<PairOutcome>
+ /** `harness remote-password clear` — remove the persistent remote password. */
+ onClearRemotePassword?: () => PairOutcome
+ /** `harness remote-password status` — whether one is set, and its fingerprint. */
+ onRemotePasswordStatus?: () => PairOutcome
/** Local dashboard status snapshot (GET /api/status). */
onStatus?: () => Record<string, unknown>
/** Recent adapter log tail (GET /api/logs). */
@@ -518,6 +525,34 @@ export function startHookServer(
const out = handlers.onSetupLink(); json(out.status, out.body); return
}
+ // `harness remote-password set` → stretch + persist a new persistent remote password on the
+ // running daemon's live E2EE state (so an in-progress `harness link connect` from another
+ // machine sees it immediately, with no daemon restart needed).
+ if (req.method === 'POST' && url === '/api/remote-password/set') {
+ if (!localOk) { json(403, { error: 'FORBIDDEN' }); return }
+ if (!handlers.onSetRemotePassword) { json(503, { error: 'UNAVAILABLE' }); return }
+ let body: { password?: string }
+ try { body = JSON.parse(await readBody(req)) as { password?: string } } catch { json(400, { error: 'bad json' }); return }
+ if (!body.password) { json(400, { error: 'MISSING_PASSWORD' }); return }
+ try { const out = await handlers.onSetRemotePassword(body.password); json(out.status, out.body) }
+ catch (e) { json(500, { error: e instanceof Error ? e.message : 'INTERNAL' }) }
+ return
+ }
+
+ // `harness remote-password clear` → remove the persistent remote password.
+ if (req.method === 'POST' && url === '/api/remote-password/clear') {
+ if (!localOk) { json(403, { error: 'FORBIDDEN' }); return }
+ if (!handlers.onClearRemotePassword) { json(503, { error: 'UNAVAILABLE' }); return }
+ const out = handlers.onClearRemotePassword(); json(out.status, out.body); return
+ }
+
+ // `harness remote-password status` → whether one is set, and its fingerprint. Read-only, same
+ // gating tier as /api/pairs.
+ if (req.method === 'GET' && url === '/api/remote-password/status') {
+ if (!handlers.onRemotePasswordStatus) { json(503, { error: 'UNAVAILABLE' }); return }
+ const out = handlers.onRemotePasswordStatus(); json(out.status, out.body); return
+ }
+
// Local GUI clients (e.g. the desktop app): read the full machine list / rename or delete one /
// read the signed-in profile through this daemon's own SSO session, so the local caller never
// holds a bearer token itself — loopback trust does the authenticating. Reads are ungated (same
diff --git a/cli/src/lib/e2ee/machinePeers.ts b/cli/src/lib/e2ee/machinePeers.ts
index 748e9e5de..5b3b8e6f6 100644
--- a/cli/src/lib/e2ee/machinePeers.ts
+++ b/cli/src/lib/e2ee/machinePeers.ts
@@ -1,12 +1,14 @@
/**
* Persistence for the "this machine trusts machine X" relation — a third E2EE trust relation distinct
- * from browser↔this-machine (`E2eeStore`/`paired.json`). Established via `harness link create` (on the
- * peer) + `harness link import <token>` (here), never via the live 6-digit CPace code — see
- * relayClient.ts for the session this pin then bootstraps. Same file-permission conventions as
- * `E2eeStore`: ${ADAPTER_DATA_DIR}/e2e/, 0700 dir / 0600 file.
+ * from browser↔this-machine (`E2eeStore`/`paired.json`). Established via `harness remote-password set`
+ * (on the peer, a persistent shared secret) + `harness link connect <machineId>` (here, which proves
+ * knowledge of that secret via a password-authenticated CPace exchange — see passwordPake.ts), never
+ * via the live 6-digit CPace pairing code — see relayClient.ts for the session this pin then
+ * bootstraps. Same file-permission conventions as `E2eeStore`: ${ADAPTER_DATA_DIR}/e2e/, 0700 dir /
+ * 0600 file.
*
- * Deliberately NOT cached in memory: `harness link import` runs as its own short-lived process,
- * independent of the daemon — the daemon's `RemoteRelayPool` must see a link the moment `link import`
+ * Deliberately NOT cached in memory: `harness link connect` runs as its own short-lived process,
+ * independent of the daemon — the daemon's `RemoteRelayPool` must see a link the moment `link connect`
* writes it, not only after a restart. The file is tiny and read rarely (once per fresh relay dial),
* so reading fresh every time costs nothing.
*/
diff --git a/cli/src/lib/e2ee/manager.test.ts b/cli/src/lib/e2ee/manager.test.ts
index fe12ceae2..bfd529d3a 100644
--- a/cli/src/lib/e2ee/manager.test.ts
+++ b/cli/src/lib/e2ee/manager.test.ts
@@ -8,6 +8,9 @@ import { join } from 'path'
type Frame = Record<string, unknown>
let C: typeof import('./core.js')
let makeManager: typeof import('./manager.js')['E2eeManager']
+let pwCpaceGenerator: typeof import('./passwordPake.js')['pwCpaceGenerator']
+let pwContext: typeof import('./passwordPake.js')['pwContext']
+let stretchPassword: typeof import('./passwordPake.js')['stretchPassword']
const AGENT = 'f2e0383771b734e4fc00f0bc8ccf060f'
@@ -15,6 +18,10 @@ beforeAll(async () => {
process.env.ADAPTER_DATA_DIR = mkdtempSync(join(tmpdir(), 'e2ee-mgr-'))
C = await import('./core.js')
makeManager = (await import('./manager.js')).E2eeManager
+ const pw = await import('./passwordPake.js')
+ pwCpaceGenerator = pw.pwCpaceGenerator
+ pwContext = pw.pwContext
+ stretchPassword = pw.stretchPassword
})
// Fresh persisted store (identity + paired.json) per test — the store is disk-backed and shared by
@@ -91,6 +98,55 @@ class WebPeer {
}
}
+/** A minimal remote-password joiner that runs the CPace 'b' role directly against the manager via
+ * handleFrame — mirrors WebPeer above, but for the persistent remote-password flow: no human "arm"
+ * step (intent() carries the stretched password straight away), and connId-keyed on the manager side
+ * instead of a single slot. */
+class PwPeer {
+ identity = C.newIdentity()
+ peerPub?: Uint8Array
+ private pr?: { sid: Uint8Array; sidB64: string; stretched: Uint8Array; y?: bigint; Ya?: Uint8Array; isk?: Uint8Array; th?: Uint8Array }
+
+ async intent(password: string): Promise<Frame> {
+ const sid = C.newPairId()
+ const stretched = await stretchPassword(password, AGENT)
+ this.pr = { sid, sidB64: C.b64e(sid), stretched }
+ return { type: 'e2e_pw_pair_intent', payload: { requestId: 'pwr1', sid: this.pr.sidB64 } }
+ }
+
+ /** Handle an adapter→joiner e2e_pw_pake frame; return the reply frame to feed back (or null on the
+ * terminal round 5 ok/error). */
+ onPake(frame: Frame): Frame | null {
+ const p = frame.payload as Record<string, unknown>
+ const pr = this.pr!
+ const ci = pwContext(AGENT)
+ const round = Number(p.round)
+ if (round === 1) {
+ const g = pwCpaceGenerator(pr.stretched, pr.sid, ci)
+ const { y, Y } = C.cpaceStart(g)
+ const Ya = C.b64d(String(p.ya))
+ const K = C.cpaceShared(Ya, y)
+ pr.y = y; pr.Ya = Ya
+ pr.isk = C.cpaceISK(pr.sid, K, Ya, Y)
+ pr.th = C.transcriptHash(pr.sid, ci, Ya, Y)
+ const kc = C.kcKeys(pr.isk, ci)
+ return { type: 'e2e_pw_pake', payload: { sid: pr.sidB64, round: 2, yb: C.b64e(Y), mac: C.b64e(C.macTag(kc.web, pr.th)) } }
+ }
+ if (round === 3) {
+ const kc = C.kcKeys(pr.isk!, ci)
+ if (!C.macVerify(kc.adapter, pr.th!, C.b64d(String(p.mac)))) throw new Error('adapter MAC failed')
+ const opened = C.aeadOpen(C.pairKey(pr.isk!, ci), 3, C.utf8('e2e-id'), C.b64d(String(p.enc)))!
+ const adId = JSON.parse(new TextDecoder().decode(opened)) as { id: string; sig: string }
+ 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!)) })))
+ return { type: 'e2e_pw_pake', payload: { sid: pr.sidB64, round: 4, enc: C.b64e(sealed) } }
+ }
+ return null // round 5 (ok/error) — nothing to send
+ }
+}
+
function machine() {
const sent: Array<{ connId: string; frame: Frame }> = []
const mgr = new makeManager({ machineId: AGENT, sendTo: (connId, frame) => sent.push({ connId, frame }), isConnected: () => true })
@@ -342,3 +398,105 @@ describe('E2eeManager revoke', () => {
expect(h.mgr.revoke('ZZZZ')).toEqual({ ok: false, error: 'NOT_FOUND' })
})
})
+
+describe('E2eeManager persistent remote-password pairing', () => {
+ const PASSWORD = 'correct horse battery staple'
+
+ it('NO_REMOTE_PASSWORD when no password has been set', async () => {
+ const { mgr, takeLast } = machine()
+ const joiner = new PwPeer()
+ mgr.handleFrame('pw1', await joiner.intent(PASSWORD))
+ const result = takeLast('e2e_pw_pair_result').payload as Record<string, unknown>
+ expect(result).toMatchObject({ ok: false, error: 'NO_REMOTE_PASSWORD' })
+ })
+
+ it('completes a full password pairing with no human "arm" step, pins the joiner, and reports status', async () => {
+ const { mgr, takeLast } = machine()
+ expect(mgr.remotePasswordStatus()).toEqual({ hasPassword: false, fingerprint: null, setAt: null })
+ const set = await mgr.setRemotePassword(PASSWORD)
+ expect(mgr.remotePasswordStatus()).toMatchObject({ hasPassword: true, fingerprint: set.fingerprint })
+ expect(mgr.remotePasswordStatus().setAt).toEqual(expect.any(Number))
+
+ const joiner = new PwPeer()
+ const conn = 'pw2'
+ mgr.handleFrame(conn, await joiner.intent(PASSWORD)) // → round 1, no local approval needed
+ const r2 = joiner.onPake(takeLast('e2e_pw_pake'))!
+ mgr.handleFrame(conn, r2) // → round 3
+ const r4 = joiner.onPake(takeLast('e2e_pw_pake'))!
+ mgr.handleFrame(conn, r4) // → round 5
+
+ const final = takeLast('e2e_pw_pake').payload as Record<string, unknown>
+ expect(final).toMatchObject({ round: 5, ok: true, fingerprint: mgr.fingerprint() })
+ // Pinned exactly as onSetupClaim pins a browser — same role, same trust surface.
+ const paired = mgr.listPaired()
+ expect(paired.length).toBe(1)
+ expect(paired[0]).toMatchObject({ fingerprint: C.fingerprint(joiner.identity.pub), label: 'harness link', role: 'web' })
+ })
+
+ it('a wrong password fails the confirmation MAC at round 2 and pins nobody', async () => {
+ const { mgr, takeLast } = machine()
+ await mgr.setRemotePassword(PASSWORD)
+ const joiner = new PwPeer()
+ const conn = 'pw3'
+ mgr.handleFrame(conn, await joiner.intent('not the right password'))
+ const r2 = joiner.onPake(takeLast('e2e_pw_pake'))!
+ mgr.handleFrame(conn, r2)
+ const final = takeLast('e2e_pw_pake').payload as Record<string, unknown>
+ expect(final).toMatchObject({ round: 5, error: 'WRONG_PASSWORD' })
+ expect(mgr.listPaired().length).toBe(0)
+ })
+
+ it('locks out after repeated wrong passwords, rejecting further intents before any crypto runs', async () => {
+ const { mgr, takeLast } = machine()
+ await mgr.setRemotePassword(PASSWORD)
+ for (let i = 0; i < 5; i++) {
+ const joiner = new PwPeer()
+ const conn = `pwbad${i}`
+ mgr.handleFrame(conn, await joiner.intent(`wrong-${i}`))
+ const r2 = joiner.onPake(takeLast('e2e_pw_pake'))!
+ mgr.handleFrame(conn, r2)
+ }
+ // The 6th attempt, even with the CORRECT password, must be rejected as RATE_LIMITED with no
+ // e2e_pw_pake round-1 frame ever sent — proving the lockout is checked before any CPace runs.
+ const joiner = new PwPeer()
+ mgr.handleFrame('pwlocked', await joiner.intent(PASSWORD))
+ const result = takeLast('e2e_pw_pair_result').payload as Record<string, unknown>
+ expect(result).toMatchObject({ ok: false, error: 'RATE_LIMITED' })
+ expect(typeof result.retryAt).toBe('number')
+ })
+
+ it('setting a new password clears an existing lockout', async () => {
+ const { mgr, takeLast } = machine()
+ await mgr.setRemotePassword(PASSWORD)
+ for (let i = 0; i < 5; i++) {
+ const joiner = new PwPeer()
+ const conn = `pwbad2-${i}`
+ mgr.handleFrame(conn, await joiner.intent(`wrong-${i}`))
+ const r2 = joiner.onPake(takeLast('e2e_pw_pake'))!
+ mgr.handleFrame(conn, r2)
+ }
+ const stillLocked = new PwPeer()
+ mgr.handleFrame('pwstilllocked', await stillLocked.intent(PASSWORD))
+ expect((takeLast('e2e_pw_pair_result').payload as Record<string, unknown>).error).toBe('RATE_LIMITED')
+
+ await mgr.setRemotePassword('a brand new remote password')
+ const joiner = new PwPeer()
+ const conn = 'pwfresh'
+ mgr.handleFrame(conn, await joiner.intent('a brand new remote password'))
+ const r2 = joiner.onPake(takeLast('e2e_pw_pake'))!
+ mgr.handleFrame(conn, r2)
+ const r4 = joiner.onPake(takeLast('e2e_pw_pake'))!
+ mgr.handleFrame(conn, r4)
+ expect(takeLast('e2e_pw_pake').payload).toMatchObject({ round: 5, ok: true })
+ })
+
+ it('clearRemotePassword removes it — a subsequent intent gets NO_REMOTE_PASSWORD again', async () => {
+ const { mgr, takeLast } = machine()
+ await mgr.setRemotePassword(PASSWORD)
+ mgr.clearRemotePassword()
+ expect(mgr.remotePasswordStatus()).toEqual({ hasPassword: false, fingerprint: null, setAt: null })
+ const joiner = new PwPeer()
+ mgr.handleFrame('pwcleared', await joiner.intent(PASSWORD))
+ expect(takeLast('e2e_pw_pair_result').payload).toMatchObject({ ok: false, error: 'NO_REMOTE_PASSWORD' })
+ })
+})
diff --git a/cli/src/lib/e2ee/manager.ts b/cli/src/lib/e2ee/manager.ts
index 49ca254fd..7d7acc463 100644
--- a/cli/src/lib/e2ee/manager.ts
+++ b/cli/src/lib/e2ee/manager.ts
@@ -5,6 +5,11 @@
* - always-on group key (per process, epoch id) that encrypts 1→many `up` user events (wrapUp);
* - the CPace pairing state machine (single slot): browser sends e2e_pair_intent → user runs
* `harness pair <code>` → onPair() runs CPace toward that connId → pin the browser identity;
+ * - the SEPARATE persistent remote-password CPace state machine (multi-slot, keyed by connId):
+ * another machine sends e2e_pw_pair_intent → onPwPairIntent()/onPwPake() run CPace against
+ * store.remotePasswordVerifier() with no local "arm" step → pin that machine's identity, exactly
+ * as if it were a paired browser session — see passwordPake.ts for why it's a fully separate
+ * generator/context from the live-code flow above;
* - a per-connection session table (X25519 → pairwise keys) established by a signed e2e_hello,
* used to decrypt the down `message` frame and to encrypt targeted RPC replies + the group key.
*
@@ -19,6 +24,7 @@ import {
type TerminalBinaryClear,
} from '../terminalBinary.js'
import { E2eeStore } from './store.js'
+import { pwCpaceGenerator, pwContext } from './passwordPake.js'
type Frame = Record<string, unknown>
@@ -72,6 +78,25 @@ const RATE_WINDOW_MS = 5 * 60_000
const RATE_MAX = 3
const MAX_SESSIONS = 64
+// Persistent remote-password linking (`harness remote-password set` + `harness link connect`) — a
+// SEPARATE state machine from PairSlot above: no human "arm" step (a correct password is the only
+// gate), and it must track multiple concurrent connIds since any other account machine could dial in
+// at any time, not just the one browser/device the user is actively pairing. Round timeout is longer
+// than the live-code flow's (30s vs 15s) since this crosses a machine-to-machine relay hop instead of
+// a browser tab that's already open and watching.
+const PW_ROUND_TIMEOUT_MS = 30_000
+
+interface PwPairSlot {
+ connId: string
+ sid: Uint8Array
+ sidB64: string
+ y: bigint
+ Ya: Uint8Array
+ isk?: Uint8Array
+ th?: Uint8Array
+ roundTimer: ReturnType<typeof setTimeout>
+}
+
export interface E2eeManagerDeps {
machineId: string
/** Send a frame targeted at ONE web connection (adapter→web, sets targetConnId on the wire). */
@@ -90,6 +115,7 @@ export class E2eeManager {
private slot: PairSlot | null = null
private sessions = new Map<string, Session>()
private attempts: number[] = [] // timestamps of FAILED pairings — anti online-guessing rate limit
+ private pwSlots = new Map<string, PwPairSlot>() // connId -> in-progress password-PAKE attempt
private now: () => number
/** Local dashboard port (loopback) — surfaced to the web in e2e_status so it can link there to
* approve pairing. Not sensitive (a localhost port); set by the adapter after the hook server binds. */
@@ -106,6 +132,21 @@ export class E2eeManager {
createSetupToken(machineId = this.deps.machineId): { token: string; expiresAt: number; fingerprint: string } {
return this.store.createSetupToken(machineId)
}
+
+ // ── persistent remote password (`harness remote-password set|clear|status`) ──────────────────────
+ setRemotePassword(password: string): Promise<{ fingerprint: string }> {
+ return this.store.setRemotePassword(this.deps.machineId, password)
+ }
+ clearRemotePassword(): void {
+ this.store.clearRemotePassword()
+ }
+ remotePasswordStatus(): { hasPassword: boolean; fingerprint: string | null; setAt: number | null } {
+ return {
+ hasPassword: this.store.hasRemotePassword(),
+ fingerprint: this.store.remotePasswordFingerprint(),
+ setAt: this.store.remotePasswordSetAt(),
+ }
+ }
hasSession(connId: string): boolean { return this.sessions.has(connId) }
sessionRole(connId: string): C.PairRole | null { return this.sessions.get(connId)?.role ?? null }
deviceConnected(): boolean { return [...this.sessions.values()].some((s) => s.role === 'device') }
@@ -322,6 +363,8 @@ export class E2eeManager {
case 'e2e_pair_intent': return this.onPairIntent(connId, payload)
case 'e2e_pair_cancel': return this.onPairCancel(connId, payload)
case 'e2e_pake': return this.onPake(connId, payload)
+ case 'e2e_pw_pair_intent': return this.onPwPairIntent(connId, payload)
+ case 'e2e_pw_pake': return this.onPwPake(connId, payload)
case 'e2e_hello': return this.onHello(connId, payload)
default: return type.startsWith('e2e_') // consume unknown e2e_* silently
}
@@ -526,6 +569,119 @@ export class E2eeManager {
return true
}
+ // ── persistent remote-password pairing (`e2e_pw_pair_intent` / `e2e_pw_pake`) ────────────────────
+ // Structurally the same 5-round CPace dance as onPairIntent/onPake above, but driven by
+ // store.remotePasswordVerifier() instead of a live human-armed code, keyed by connId (pwSlots) so
+ // any number of joiner machines can be mid-handshake at once, with no local "arm" step at all.
+
+ private onPwPairIntent(connId: string, p: Record<string, unknown>): boolean {
+ const requestId = p.requestId
+ const fail = (error: string, extra?: Record<string, unknown>): void => {
+ this.deps.sendTo(connId, { type: 'e2e_pw_pair_result', payload: { requestId, ok: false, error, ...extra } })
+ }
+ if (!this.store.hasRemotePassword()) { fail('NO_REMOTE_PASSWORD'); return true }
+ // Rejected BEFORE any crypto runs — a locked-out caller gets no oracle at all, not even the cost
+ // of one CPace round, while it waits out the lockout.
+ const lockedUntil = this.store.pwLockedUntil()
+ if (lockedUntil) { fail('RATE_LIMITED', { retryAt: lockedUntil }); return true }
+ const sidB64 = typeof p.sid === 'string' ? p.sid : ''
+ if (!sidB64) { fail('BAD_INTENT'); return true }
+ if (this.pwSlots.has(connId)) this.clearPwSlot(connId) // a retry on the same conn replaces the old attempt
+ const verifier = this.store.remotePasswordVerifier()
+ if (!verifier) { fail('NO_REMOTE_PASSWORD'); return true } // race: cleared between the two checks above
+ const sid = C.b64d(sidB64)
+ const ci = pwContext(this.deps.machineId)
+ const g = pwCpaceGenerator(verifier, sid, ci)
+ const { y, Y } = C.cpaceStart(g)
+ const roundTimer = setTimeout(() => this.failPwPair(connId, 'TIMEOUT'), PW_ROUND_TIMEOUT_MS)
+ this.pwSlots.set(connId, { connId, sid, sidB64, y, Ya: Y, roundTimer })
+ // round 1 → the joiner (targeted), no human interaction required on this side
+ this.deps.sendTo(connId, { type: 'e2e_pw_pake', payload: { sid: sidB64, round: 1, ya: C.b64e(Y) } })
+ return true
+ }
+
+ private onPwPake(connId: string, p: Record<string, unknown>): boolean {
+ const slot = this.pwSlots.get(connId)
+ if (!slot) return true
+ if (typeof p.sid !== 'string' || p.sid !== slot.sidB64) return true // not our attempt
+ const round = Number(p.round)
+ const ci = pwContext(this.deps.machineId)
+ try {
+ if (round === 2) {
+ const Yb = C.b64d(String(p.yb))
+ const K = C.cpaceShared(Yb, slot.y)
+ const isk = C.cpaceISK(slot.sid, K, slot.Ya, Yb)
+ const th = C.transcriptHash(slot.sid, ci, slot.Ya, Yb)
+ const kc = C.kcKeys(isk, ci)
+ // Wrong password → wrong generator → this MAC can never verify. Counts toward the lockout;
+ // the error told to the caller never says more than "wrong password".
+ if (!C.macVerify(kc.web, th, C.b64d(String(p.mac)))) { this.failPwPair(connId, 'WRONG_PASSWORD', true); return true }
+ slot.isk = isk
+ slot.th = th
+ const id = this.store.getIdentity()
+ const sealed = C.aeadSeal(C.pairKey(isk, ci), 3, C.utf8('e2e-id'), C.utf8(JSON.stringify({ id: C.b64e(id.pub), sig: C.b64e(C.pairBindSig(id.priv, th)) })))
+ this.resetPwRoundTimer(slot)
+ this.deps.sendTo(connId, { type: 'e2e_pw_pake', payload: { sid: slot.sidB64, round: 3, mac: C.b64e(C.macTag(kc.adapter, th)), enc: C.b64e(sealed) } })
+ return true
+ }
+ if (round === 4) {
+ 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 }
+ 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')
+ 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 } })
+ this.clearPwSlot(connId)
+ return true
+ }
+ } catch {
+ this.failPwPair(connId, 'WRONG_PASSWORD', true)
+ }
+ return true
+ }
+
+ private resetPwRoundTimer(slot: PwPairSlot): void {
+ clearTimeout(slot.roundTimer)
+ slot.roundTimer = setTimeout(() => this.failPwPair(slot.connId, 'TIMEOUT'), PW_ROUND_TIMEOUT_MS)
+ }
+
+ /** `countsAsFailure` is true only for an actual wrong-password verification failure — a timeout or
+ * protocol hiccup (dropped connection, stale round) doesn't prove anything about a guessing
+ * attempt and shouldn't cost the caller part of their lockout budget. */
+ private failPwPair(connId: string, error: string, countsAsFailure = false): void {
+ const slot = this.pwSlots.get(connId)
+ if (!slot) return
+ this.clearPwSlot(connId)
+ this.deps.sendTo(connId, { type: 'e2e_pw_pake', payload: { sid: slot.sidB64, round: 5, error } })
+ if (countsAsFailure) {
+ const { lockedUntil } = this.store.notePwFailure()
+ if (lockedUntil) this.notifyRemotePasswordLocked(lockedUntil) // fresh lockout — pwLockedUntil() was
+ // null before this call (onPwPairIntent already rejects while locked), so any non-null result
+ // here is a NOT-locked → locked transition, never a re-notify of an existing one.
+ }
+ }
+
+ private clearPwSlot(connId: string): void {
+ const slot = this.pwSlots.get(connId)
+ if (slot) clearTimeout(slot.roundTimer)
+ this.pwSlots.delete(connId)
+ }
+
+ private notifyRemotePasswordLocked(lockedUntil: number): void {
+ const payload = { machineId: this.deps.machineId, lockedUntil }
+ this.deps.sendUser?.({ type: 'remote_password_locked', payload })
+ for (const [connId, session] of this.sessions.entries()) {
+ if (session.role !== 'web') continue
+ const wrapped = this.wrapTarget(connId, 'remote_password_locked', payload)
+ if (wrapped) this.deps.sendTo(connId, wrapped)
+ }
+ }
+
private onHello(connId: string, p: Record<string, unknown>): boolean {
const identityPub = String(p.identityPub ?? '')
const ephPubB64 = String(p.ephPub ?? '')
@@ -579,8 +735,9 @@ export class E2eeManager {
}
/** Drop a session when its web connection closes (called from backendSocket on down close is n/a —
- * connections are relayed; sessions are pruned by LRU + overwrite-on-new-hello). */
- dropSession(connId: string): void { this.sessions.delete(connId) }
+ * connections are relayed; sessions are pruned by LRU + overwrite-on-new-hello). Also cleans up any
+ * in-progress password-PAKE attempt on this connId — the joiner may have disconnected mid-round. */
+ dropSession(connId: string): void { this.sessions.delete(connId); this.clearPwSlot(connId) }
// ── helpers ──────────────────────────────────────────────────────────────────────────────────
diff --git a/cli/src/lib/e2ee/passwordPake.spec.ts b/cli/src/lib/e2ee/passwordPake.spec.ts
new file mode 100644
index 000000000..cf3326341
--- /dev/null
+++ b/cli/src/lib/e2ee/passwordPake.spec.ts
@@ -0,0 +1,120 @@
+import { describe, expect, it } from 'vitest'
+import { RistrettoPoint } from '@noble/curves/ed25519'
+import * as C from './core.js'
+import { pwCpaceGenerator, pwContext, stretchPassword } from './passwordPake.js'
+
+const MACHINE_A = 'f2e0383771b734e4fc00f0bc8ccf060f'
+const MACHINE_B = 'a1b2c3d4e5f60718293a4b5c6d7e8f90'
+
+describe('stretchPassword', () => {
+ it('is deterministic for the same (password, machineId)', async () => {
+ const a = await stretchPassword('correct horse battery staple', MACHINE_A)
+ const b = await stretchPassword('correct horse battery staple', MACHINE_A)
+ expect(C.b64e(a)).toBe(C.b64e(b))
+ expect(a.length).toBe(32)
+ })
+
+ it('differs for a different machineId (same password)', async () => {
+ const a = await stretchPassword('correct horse battery staple', MACHINE_A)
+ const b = await stretchPassword('correct horse battery staple', MACHINE_B)
+ expect(C.b64e(a)).not.toBe(C.b64e(b))
+ })
+
+ it('differs for a different password (same machineId)', async () => {
+ const a = await stretchPassword('correct horse battery staple', MACHINE_A)
+ const b = await stretchPassword('a totally different password', MACHINE_A)
+ expect(C.b64e(a)).not.toBe(C.b64e(b))
+ })
+
+ it('normalizes the password (NFKC) before stretching, so visually-identical inputs match', async () => {
+ // 'é' as one codepoint (U+00E9) vs 'e' + combining acute (U+0065 U+0301) — NFKC folds them to the
+ // same sequence, so a password typed either way must derive the same verifier.
+ const composed = await stretchPassword('café', MACHINE_A)
+ const decomposed = await stretchPassword('café', MACHINE_A)
+ expect(composed).not.toBe(decomposed) // sanity: the raw JS strings really are different
+ expect(C.b64e(composed)).toBe(C.b64e(decomposed))
+ })
+})
+
+describe('pwContext', () => {
+ it('is distinct from core.ts\'s pairContext for the same machineId', () => {
+ expect(pwContext(MACHINE_A)).not.toBe(C.pairContext(MACHINE_A))
+ expect(pwContext(MACHINE_A)).not.toBe(C.pairContext(MACHINE_A, 'device'))
+ })
+
+ it('varies by machineId', () => {
+ expect(pwContext(MACHINE_A)).not.toBe(pwContext(MACHINE_B))
+ })
+})
+
+describe('pwCpaceGenerator', () => {
+ it('produces a valid, non-identity ristretto255 point', async () => {
+ const stretched = await stretchPassword('correct horse battery staple', MACHINE_A)
+ const sid = C.newPairId()
+ const g = pwCpaceGenerator(stretched, sid, pwContext(MACHINE_A))
+ expect(g.equals(RistrettoPoint.ZERO)).toBe(false)
+ // Round-trips through raw bytes cleanly (i.e. is a well-formed group element).
+ expect(RistrettoPoint.fromHex(g.toRawBytes()).equals(g)).toBe(true)
+ })
+
+ it('is deterministic for the same (stretched, sid, ci) and varies with each input', async () => {
+ const stretched = await stretchPassword('correct horse battery staple', MACHINE_A)
+ const sid = C.newPairId()
+ const ci = pwContext(MACHINE_A)
+ const g1 = pwCpaceGenerator(stretched, sid, ci)
+ const g2 = pwCpaceGenerator(stretched, sid, ci)
+ expect(g1.equals(g2)).toBe(true)
+
+ const otherSid = C.newPairId()
+ expect(g1.equals(pwCpaceGenerator(stretched, otherSid, ci))).toBe(false)
+ expect(g1.equals(pwCpaceGenerator(stretched, sid, pwContext(MACHINE_B)))).toBe(false)
+
+ const otherStretched = await stretchPassword('a different password entirely', MACHINE_A)
+ expect(g1.equals(pwCpaceGenerator(otherStretched, sid, ci))).toBe(false)
+ })
+
+ it('never collides with core.ts\'s live-code cpaceGenerator for the same sid/machineId, even if the ' +
+ 'stretched password happens to equal the (padded) code bytes', () => {
+ const sid = C.newPairId()
+ // Feed the SAME raw bytes into both constructions (bypassing stretchPassword/normalizeCode) to
+ // isolate the DSI/context separation as the only thing keeping the two flows apart.
+ const sharedSecretBytes = new Uint8Array(32).fill(7)
+ const pwGenerator = pwCpaceGenerator(sharedSecretBytes, sid, pwContext(MACHINE_A))
+ const codeGenerator = C.cpaceGenerator('AAAAAA', sid, C.pairContext(MACHINE_A))
+ expect(pwGenerator.equals(codeGenerator)).toBe(false)
+ })
+})
+
+describe('full CPace flow with a wrong password', () => {
+ it('the responder\'s confirmation MAC fails to verify when the two sides stretch different passwords', async () => {
+ const sid = C.newPairId()
+ const ciA = pwContext(MACHINE_A)
+
+ // "A" side (has the real password) starts CPace, exactly as manager.ts's onPwPairIntent does.
+ const realStretched = await stretchPassword('correct horse battery staple', MACHINE_A)
+ const gA = pwCpaceGenerator(realStretched, sid, ciA)
+ const { y: yA, Y: Ya } = C.cpaceStart(gA)
+
+ // "B" side (guesses wrong) derives its own generator from a DIFFERENT stretched password — the
+ // two therefore land on different ristretto255 points despite sharing sid/context.
+ const wrongStretched = await stretchPassword('a wrong guess', MACHINE_A)
+ const gB = pwCpaceGenerator(wrongStretched, sid, ciA)
+ const { y: yB, Y: Yb } = C.cpaceStart(gB)
+ expect(gA.equals(gB)).toBe(false)
+
+ const kB = C.cpaceShared(Ya, yB)
+ const iskB = C.cpaceISK(sid, kB, Ya, Yb)
+ const thB = C.transcriptHash(sid, ciA, Ya, Yb)
+ const kcB = C.kcKeys(iskB, ciA)
+ const macFromB = C.macTag(kcB.web, thB)
+
+ // "A" independently derives its own isk/th/kc from ITS shared point — mismatched because gA != gB
+ // means K_A = Yb^y_A != K_B = Ya^y_B in general (different groups' worth of exponentiation).
+ const kA = C.cpaceShared(Yb, yA)
+ const iskA = C.cpaceISK(sid, kA, Ya, Yb)
+ const thA = C.transcriptHash(sid, ciA, Ya, Yb)
+ const kcA = C.kcKeys(iskA, ciA)
+
+ expect(C.macVerify(kcA.web, thA, macFromB)).toBe(false)
+ })
+})
diff --git a/cli/src/lib/e2ee/passwordPake.ts b/cli/src/lib/e2ee/passwordPake.ts
new file mode 100644
index 000000000..7c71d724c
--- /dev/null
+++ b/cli/src/lib/e2ee/passwordPake.ts
@@ -0,0 +1,65 @@
+/**
+ * CPace-over-ristretto255 primitives for the persistent "remote password" machine-to-machine link
+ * (`harness remote-password set/clear/status` on the target machine, `harness link connect
+ * <machineId>` on the joiner) — see manager.ts's onPwPairIntent/onPwPake and relayClient.ts's
+ * connectWithPassword for the state machines that use these.
+ *
+ * This is bookkeeping ONLY: every actual primitive (cpaceStart/cpaceShared/cpaceISK/transcriptHash/
+ * kcKeys/macTag/macVerify/pairKey/pairBindSig/pairBindVerify/aeadSeal/aeadOpen) comes unchanged from
+ * core.ts. core.ts is a byte-pinned crypto twin shared with the web app (see core.test.ts) and must
+ * never be edited for this feature — this module only adds a PARALLEL generator construction and
+ * channel-binding context, built the same way core.ts's own cpaceGenerator()/pairContext() are,
+ * but kept entirely separate from them:
+ *
+ * - Distinct DSI (`PW_DSI` vs core.ts's private `CPACE_DSI`) and a distinct context string
+ * (`pwContext()` vs `pairContext()`) mean the two PAKEs hash into cryptographically unrelated
+ * generator points even given the same machineId/sid — a transcript captured from one flow can
+ * never be replayed or spliced into the other, and the two attempt-counting/lockout regimes
+ * (RATE_MAX=3/5min for the live code, the exponential-backoff lockout here) can never be confused.
+ * - The live pairing code is single-use, ~30 bits of entropy, and expires in 60s, so core.ts's
+ * cpaceGenerator() feeds it through normalizeCode() (uppercase, strip separators, remap look-alike
+ * characters) — correct for a code read off a screen, but WRONG for a password: it would silently
+ * mangle whatever the user actually typed. The remote password is long-lived, human-chosen, and
+ * reused across arbitrarily many attempts, so it needs slow-hash stretching (scrypt) instead —
+ * something the disposable high-entropy code never needed. pwCpaceGenerator() below therefore
+ * takes an already-stretched key and never calls normalizeCode().
+ */
+import { RistrettoPoint, hashToRistretto255 } from '@noble/curves/ed25519'
+import { sha256 } from '@noble/hashes/sha2'
+import { scryptAsync } from '@noble/hashes/scrypt'
+import { lvCat, utf8 } from './core.js'
+
+/** Distinct from core.ts's private `CPACE_DSI` ('e2e-cpace-ristretto255-v1'). */
+const PW_DSI = 'e2e-cpace-ristretto255-pw-v1'
+
+// scrypt cost parameters for stretching a human-chosen, indefinitely-reused password — deliberately
+// expensive (interactive-login class), unlike the disposable high-entropy pairing code, which needs
+// no stretching at all. N=2^17/r=8/p=1 costs roughly ~0.5-1s and ~128MB on typical hardware, in line
+// with common scrypt interactive-login guidance for a secret that lives until explicitly rotated.
+const SCRYPT_N = 2 ** 17
+const SCRYPT_R = 8
+const SCRYPT_P = 1
+const SCRYPT_DKLEN = 32
+
+/** Slow-hash a persistent remote password into a 32-byte verifier/key-material seed, salted per
+ * machineId so the same password chosen on two different machines derives unrelated verifiers (and
+ * therefore unrelated CPace generators). Deterministic for a given (password, machineId) pair. */
+export async function stretchPassword(password: string, machineId: string): Promise<Uint8Array> {
+ const salt = sha256(utf8(`e2e-remote-password-salt-v1|${machineId}`))
+ return scryptAsync(utf8(password.normalize('NFKC')), salt, { N: SCRYPT_N, r: SCRYPT_R, p: SCRYPT_P, dkLen: SCRYPT_DKLEN })
+}
+
+/** Channel-binding string for the password-PAKE — the machine-to-machine counterpart of core.ts's
+ * pairContext(), but permanently distinct from it (never 'web'/'device' roles — the joiner is
+ * always a machine's own CLI identity, not a browser or hardware device). */
+export function pwContext(machineId: string): string {
+ return `autonomous-e2e-pw-pair|agent:${machineId}|a:adapter|b:machine`
+}
+
+/** Generator g = hashToGroup(PW_DSI, stretched, sid, ci). Same construction as core.ts's
+ * cpaceGenerator(code, sid, ci), but over an already-stretched password — never raw user input, and
+ * never routed through normalizeCode(). */
+export function pwCpaceGenerator(stretched: Uint8Array, sid: Uint8Array, ci: string): InstanceType<typeof RistrettoPoint> {
+ const genStr = lvCat(PW_DSI, stretched, sid, ci)
+ return hashToRistretto255(genStr, { DST: PW_DSI })
+}
diff --git a/cli/src/lib/e2ee/relayClient.ts b/cli/src/lib/e2ee/relayClient.ts
index 9a3afa00e..7035658fd 100644
--- a/cli/src/lib/e2ee/relayClient.ts
+++ b/cli/src/lib/e2ee/relayClient.ts
@@ -1,8 +1,9 @@
/**
* The "client" (formerly-browser) role of the E2EE session protocol, run by THIS daemon on behalf of a
- * local app relaying through it to a REMOTE machine it has link-imported a setup token for (see
- * machinePeers.ts). Establishes a session via e2e_hello/e2e_welcome, then encrypts outgoing frames /
- * decrypts incoming ones for the lifetime of the relay connection.
+ * local app relaying through it to a REMOTE machine it has `harness link connect`-ed to via that
+ * machine's persistent remote password (see machinePeers.ts). Establishes a session via
+ * e2e_hello/e2e_welcome, then encrypts outgoing frames / decrypts incoming ones for the lifetime of
+ * the relay connection.
*
* This is bookkeeping only — every actual crypto primitive comes from core.ts (identical to the one
* that used to run this same role inside the Flutter desktop app and still runs it in the web app), so
@@ -11,6 +12,7 @@
import { WebSocket } from 'ws'
import * as C from './core.js'
import { deriveTerminalBinaryKey, openTerminalBinary, sealTerminalBinary, type TerminalBinaryClear } from '../terminalBinary.js'
+import { pwCpaceGenerator, pwContext, stretchPassword } from './passwordPake.js'
type Frame = Record<string, unknown>
@@ -145,32 +147,43 @@ export class RelaySessionCrypto {
}
}
-export type ClaimResult =
+export type PwConnectResult =
| { ok: true; peerPub: Uint8Array; fingerprint: string }
| { ok: false; error: string }
-/** `harness link import <token>`: verify the token offline, open a short-lived authenticated
- * `/api/web-ws` connection to the target machine (same endpoint RemoteRelayPool dials for the real
- * relay), and claim it — proving possession of THIS machine's own long-term identity, bound to the
- * token. On success the caller pins the returned peerPub via MachinePeerStore; no session/relay state
- * is established here, just the one-time trust pin. */
-export async function claimSetupToken(opts: {
- token: string
+export type PwConnectProgress = 'connecting' | 'deriving_key' | 'exchanging' | 'verifying'
+
+/** `harness link connect <machineId>`: open a short-lived authenticated `/api/web-ws` connection to
+ * the target machine (same endpoint RemoteRelayPool dials for the real relay), and run the
+ * password-PAKE against it as the joiner ('b') role — proving knowledge of the target machine's
+ * persistent `harness remote-password set` secret, entirely automatically (no approval step on the
+ * target beyond having set the password). Mirrors manager.ts's onPwPairIntent/onPwPake state machine
+ * from the other side. On success the caller pins the returned peerPub via MachinePeerStore; no
+ * session/relay state is established here, just the one-time trust pin — same contract the old
+ * claimSetupToken() had. */
+export async function connectWithPassword(opts: {
targetMachineId: string
+ password: string
selfIdentity: C.Identity
accessToken: string
backendWsBase: string
autonomousEnv: string
+ onProgress?: (stage: PwConnectProgress) => void
timeoutMs?: number
-}): Promise<ClaimResult> {
- const verified = C.verifySetupToken(opts.token, Date.now(), opts.targetMachineId)
- if (!verified) return { ok: false, error: 'BAD_TOKEN' }
+}): Promise<PwConnectResult> {
const url = `${opts.backendWsBase}/api/web-ws?autonomousEnv=${encodeURIComponent(opts.autonomousEnv)}`
const ws = new WebSocket(url, [opts.accessToken])
+ const sid = C.newPairId()
+ const sidB64 = C.b64e(sid)
const requestId = C.b64e(C.newPairId())
- return new Promise<ClaimResult>((resolve) => {
+ const ci = pwContext(opts.targetMachineId)
+ return new Promise<PwConnectResult>((resolve) => {
let settled = false
- const finish = (result: ClaimResult): void => {
+ let stretched: Uint8Array | null = null
+ let isk: Uint8Array | null = null
+ let th: Uint8Array | null = null
+ let peerPub: Uint8Array | null = null
+ const finish = (result: PwConnectResult): void => {
if (settled) return
settled = true
clearTimeout(timeout)
@@ -178,6 +191,7 @@ export async function claimSetupToken(opts: {
resolve(result)
}
const timeout = setTimeout(() => finish({ ok: false, error: 'TIMEOUT' }), opts.timeoutMs ?? 15_000)
+ opts.onProgress?.('connecting')
let selected = false
ws.once('open', () => {
try { ws.send(JSON.stringify({ type: 'machine_select', payload: { machineId: opts.targetMachineId } })) }
@@ -191,32 +205,68 @@ export async function claimSetupToken(opts: {
if (!selected) {
if (frame.type === 'connected' && payload.machineId === opts.targetMachineId) {
selected = true
- const sig = C.setupClaimSig(opts.selfIdentity.priv, opts.targetMachineId, opts.token, opts.selfIdentity.pub)
- ws.send(JSON.stringify({
- type: 'e2e_setup_claim',
- payload: {
- requestId,
- token: opts.token,
- identityPub: C.b64e(opts.selfIdentity.pub),
- sig: C.b64e(sig),
- label: 'harness link',
- },
- }))
+ void (async () => {
+ try {
+ opts.onProgress?.('deriving_key')
+ // scryptAsync completes strictly before this send — the round-1 reply can only arrive
+ // after a network round trip, so `stretched` is always set before it's read below.
+ stretched = await stretchPassword(opts.password, opts.targetMachineId)
+ opts.onProgress?.('exchanging')
+ ws.send(JSON.stringify({ type: 'e2e_pw_pair_intent', payload: { requestId, sid: sidB64 } }))
+ } catch {
+ finish({ ok: false, error: 'DERIVE_FAILED' })
+ }
+ })()
} else if (frame.type === 'machine_select_error' && payload.machineId === opts.targetMachineId) {
finish({ ok: false, error: typeof payload.error === 'string' ? payload.error : 'SELECT_FAILED' })
}
return
}
- if (frame.type === 'e2e_setup_claim_result' && payload.requestId === requestId) {
- if (payload.ok === true) {
- finish({
- ok: true,
- peerPub: verified.adapterPub,
- fingerprint: typeof payload.fingerprint === 'string' ? payload.fingerprint : C.fingerprint(verified.adapterPub),
- })
- } else {
- finish({ ok: false, error: typeof payload.error === 'string' ? payload.error : 'CLAIM_FAILED' })
+ if (frame.type === 'e2e_pw_pair_result' && payload.requestId === requestId) {
+ if (payload.ok !== true) finish({ ok: false, error: typeof payload.error === 'string' ? payload.error : 'PAIR_FAILED' })
+ return
+ }
+ if (frame.type !== 'e2e_pw_pake' || payload.sid !== sidB64) return
+ const round = Number(payload.round)
+ try {
+ if (round === 1) {
+ if (payload.error) { finish({ ok: false, error: String(payload.error) }); return }
+ if (!stretched) return // shouldn't happen — see the note above
+ const g = pwCpaceGenerator(stretched, sid, ci)
+ const { y, Y } = C.cpaceStart(g)
+ const receivedYa = C.b64d(String(payload.ya))
+ const K = C.cpaceShared(receivedYa, y)
+ isk = C.cpaceISK(sid, K, receivedYa, Y)
+ th = C.transcriptHash(sid, ci, receivedYa, Y)
+ const kc = C.kcKeys(isk, ci)
+ opts.onProgress?.('verifying')
+ ws.send(JSON.stringify({ type: 'e2e_pw_pake', payload: { sid: sidB64, round: 2, yb: C.b64e(Y), mac: C.b64e(C.macTag(kc.web, th)) } }))
+ return
+ }
+ if (round === 3) {
+ if (payload.error) { finish({ ok: false, error: String(payload.error) }); return }
+ if (!isk || !th) { finish({ ok: false, error: 'PROTOCOL_ERROR' }); return }
+ const kc = C.kcKeys(isk, ci)
+ if (!C.macVerify(kc.adapter, th, C.b64d(String(payload.mac)))) { finish({ ok: false, error: 'WRONG_PASSWORD' }); return }
+ const opened = C.aeadOpen(C.pairKey(isk, ci), 3, C.utf8('e2e-id'), C.b64d(String(payload.enc)))
+ if (!opened) { finish({ ok: false, error: 'WRONG_PASSWORD' }); return }
+ const targetId = JSON.parse(new TextDecoder().decode(opened)) as { id: string; sig: string }
+ const targetPub = C.b64d(targetId.id)
+ if (!C.pairBindVerify(targetPub, th, C.b64d(targetId.sig))) { finish({ ok: false, error: 'WRONG_PASSWORD' }); return }
+ peerPub = targetPub
+ const sealed = C.aeadSeal(C.pairKey(isk, ci), 4, C.utf8('e2e-id'), C.utf8(JSON.stringify({ id: C.b64e(opts.selfIdentity.pub), sig: C.b64e(C.pairBindSig(opts.selfIdentity.priv, th)) })))
+ ws.send(JSON.stringify({ type: 'e2e_pw_pake', payload: { sid: sidB64, round: 4, enc: C.b64e(sealed) } }))
+ return
+ }
+ if (round === 5) {
+ if (payload.ok === true && peerPub) {
+ finish({ ok: true, peerPub, fingerprint: typeof payload.fingerprint === 'string' ? payload.fingerprint : C.fingerprint(peerPub) })
+ } else {
+ finish({ ok: false, error: typeof payload.error === 'string' ? payload.error : 'PAIR_FAILED' })
+ }
}
+ } catch {
+ finish({ ok: false, error: 'PROTOCOL_ERROR' })
}
})
ws.once('close', (code) => finish({ ok: false, error: `CONNECTION_CLOSED:${code}` }))
diff --git a/cli/src/lib/e2ee/relayLink.spec.ts b/cli/src/lib/e2ee/relayLink.spec.ts
index cf3a6070b..43fd4042a 100644
--- a/cli/src/lib/e2ee/relayLink.spec.ts
+++ b/cli/src/lib/e2ee/relayLink.spec.ts
@@ -11,11 +11,12 @@ type Frame = Record<string, unknown>
let C: typeof import('./core.js')
let E2eeManagerCtor: typeof import('./manager.js')['E2eeManager']
let RelaySessionCrypto: typeof import('./relayClient.js')['RelaySessionCrypto']
-let claimSetupToken: typeof import('./relayClient.js')['claimSetupToken']
+let connectWithPassword: typeof import('./relayClient.js')['connectWithPassword']
let MachinePeerStore: typeof import('./machinePeers.js')['MachinePeerStore']
let RemoteRelayPool: typeof import('../remoteRelay.js')['RemoteRelayPool']
const MACHINE_ID = 'f2e0383771b734e4fc00f0bc8ccf060f'
+const REMOTE_PASSWORD = 'correct horse battery staple'
beforeAll(async () => {
process.env.ADAPTER_DATA_DIR = mkdtempSync(join(tmpdir(), 'e2ee-link-'))
@@ -23,7 +24,7 @@ beforeAll(async () => {
E2eeManagerCtor = (await import('./manager.js')).E2eeManager
const relayClient = await import('./relayClient.js')
RelaySessionCrypto = relayClient.RelaySessionCrypto
- claimSetupToken = relayClient.claimSetupToken
+ connectWithPassword = relayClient.connectWithPassword
MachinePeerStore = (await import('./machinePeers.js')).MachinePeerStore
RemoteRelayPool = (await import('../remoteRelay.js')).RemoteRelayPool
})
@@ -37,7 +38,7 @@ describe('MachinePeerStore', () => {
const a = new MachinePeerStore()
const identity = C.newIdentity()
a.pin(MACHINE_ID, C.b64e(identity.pub), 'test peer')
- // A second instance must see the write immediately — RemoteRelayPool and `harness link import`
+ // A second instance must see the write immediately — RemoteRelayPool and `harness link connect`
// run as separate processes/instances and must never rely on a stale in-memory cache.
const b = new MachinePeerStore()
expect(b.get(MACHINE_ID)?.pub).toBe(C.b64e(identity.pub))
@@ -49,8 +50,8 @@ describe('MachinePeerStore', () => {
})
})
-describe('link create/import + relay session crypto (interop with the real E2eeManager)', () => {
- it('claimSetupToken pins the correct adapter pubkey, then hello/welcome + frame/terminal round-trip succeed', async () => {
+describe('remote-password link + relay session crypto (interop with the real E2eeManager)', () => {
+ it('connectWithPassword pins the correct adapter pubkey, then hello/welcome + frame/terminal round-trip succeed', async () => {
const inbox: Frame[] = []
// Fakes just enough of backend's `/api/web-ws` (machine_select -> connected, then generic e2e_*
// frame relay) to drive a REAL E2eeManager on the "adapter" side against real client-role code —
@@ -86,16 +87,16 @@ describe('link create/import + relay session crypto (interop with the real E2eeM
const port = (wss.address() as AddressInfo).port
const wsBase = `ws://127.0.0.1:${port}`
const clientIdentity = C.newIdentity()
- const token = manager.createSetupToken(MACHINE_ID).token
+ await manager.setRemotePassword(REMOTE_PASSWORD)
- const result = await claimSetupToken({
- token,
+ const result = await connectWithPassword({
targetMachineId: MACHINE_ID,
+ password: REMOTE_PASSWORD,
selfIdentity: clientIdentity,
accessToken: 'unused-in-this-fake',
backendWsBase: wsBase,
autonomousEnv: 'prod',
- timeoutMs: 2_000,
+ timeoutMs: 5_000,
})
expect(result.ok).toBe(true)
@@ -144,18 +145,144 @@ describe('link create/import + relay session crypto (interop with the real E2eeM
}
})
- it('rejects a token signed for a different machine id', async () => {
- const manager = new E2eeManagerCtor({ machineId: MACHINE_ID, sendTo: () => {}, isConnected: () => true })
- const token = manager.createSetupToken(MACHINE_ID).token
- const result = await claimSetupToken({
- token,
- targetMachineId: 'a-completely-different-machine-id',
- selfIdentity: C.newIdentity(),
- accessToken: 'unused',
- backendWsBase: 'ws://127.0.0.1:1', // never reached — rejected before any connection is opened
- autonomousEnv: 'prod',
+ /** Spin up the same fake `/api/web-ws` (machine_select -> connected, then e2e_* frame relay) used
+ * above, wired to a fresh real E2eeManager, and return both plus a cleanup function. */
+ function fakeMachine(): { manager: InstanceType<typeof E2eeManagerCtor>; wsBase: Promise<string>; close: () => Promise<void> } {
+ const wss = new WebSocketServer({ port: 0 })
+ const manager = new E2eeManagerCtor({
+ machineId: MACHINE_ID,
+ sendTo: (_connId, frame) => { for (const client of wss.clients) client.send(JSON.stringify(frame)) },
+ isConnected: () => true,
})
- expect(result).toEqual({ ok: false, error: 'BAD_TOKEN' })
+ wss.on('connection', (ws) => {
+ let selected = false
+ ws.on('message', (raw) => {
+ let frame: Frame
+ try { frame = JSON.parse(raw.toString()) as Frame } catch { return }
+ if (!selected) {
+ if (frame.type === 'machine_select') {
+ selected = true
+ ws.send(JSON.stringify({ type: 'connected', payload: { machineId: MACHINE_ID } }))
+ }
+ return
+ }
+ const type = frame.type as string
+ if (type.startsWith('e2e_')) manager.handleFrame('fake-conn', frame)
+ })
+ })
+ const wsBase = new Promise<string>((resolve) => {
+ wss.once('listening', () => resolve(`ws://127.0.0.1:${(wss.address() as AddressInfo).port}`))
+ })
+ return { manager, wsBase, close: () => new Promise<void>((resolve) => wss.close(() => resolve())) }
+ }
+
+ it('NO_REMOTE_PASSWORD when the target machine never set one', async () => {
+ const { manager, wsBase, close } = fakeMachine()
+ try {
+ const result = await connectWithPassword({
+ targetMachineId: MACHINE_ID,
+ password: REMOTE_PASSWORD,
+ selfIdentity: C.newIdentity(),
+ accessToken: 'unused',
+ backendWsBase: await wsBase,
+ autonomousEnv: 'prod',
+ timeoutMs: 5_000,
+ })
+ expect(result).toEqual({ ok: false, error: 'NO_REMOTE_PASSWORD' })
+ expect(manager.remotePasswordStatus().hasPassword).toBe(false)
+ } finally {
+ await close()
+ }
+ })
+
+ it('a wrong password fails the MAC check and never pins a peer', async () => {
+ const { manager, wsBase, close } = fakeMachine()
+ try {
+ await manager.setRemotePassword(REMOTE_PASSWORD)
+ const result = await connectWithPassword({
+ targetMachineId: MACHINE_ID,
+ password: 'definitely the wrong password',
+ selfIdentity: C.newIdentity(),
+ accessToken: 'unused',
+ backendWsBase: await wsBase,
+ autonomousEnv: 'prod',
+ timeoutMs: 5_000,
+ })
+ expect(result.ok).toBe(false)
+ if (result.ok) return
+ expect(result.error).toBe('WRONG_PASSWORD')
+ } finally {
+ await close()
+ }
+ })
+
+ it('locks out after repeated wrong passwords, rejecting further attempts before running any crypto', async () => {
+ const { manager, wsBase, close } = fakeMachine()
+ try {
+ await manager.setRemotePassword(REMOTE_PASSWORD)
+ const base = await wsBase
+ // Five wrong attempts cross store.ts's PW_FAIL_THRESHOLD (5) and lock the machine out.
+ for (let i = 0; i < 5; i++) {
+ const attempt = await connectWithPassword({
+ targetMachineId: MACHINE_ID,
+ password: `wrong-${i}`,
+ selfIdentity: C.newIdentity(),
+ accessToken: 'unused',
+ backendWsBase: base,
+ autonomousEnv: 'prod',
+ timeoutMs: 5_000,
+ })
+ expect(attempt.ok).toBe(false)
+ }
+ // The 6th attempt — even with the CORRECT password — must be rejected as RATE_LIMITED, proving
+ // the lockout is checked before any CPace round runs (not just before the final verdict).
+ const locked = await connectWithPassword({
+ targetMachineId: MACHINE_ID,
+ password: REMOTE_PASSWORD,
+ selfIdentity: C.newIdentity(),
+ accessToken: 'unused',
+ backendWsBase: base,
+ autonomousEnv: 'prod',
+ timeoutMs: 5_000,
+ })
+ expect(locked).toEqual({ ok: false, error: 'RATE_LIMITED' })
+ } finally {
+ await close()
+ }
+ })
+
+ it('setting a new password clears an existing lockout', async () => {
+ const { manager, wsBase, close } = fakeMachine()
+ try {
+ await manager.setRemotePassword(REMOTE_PASSWORD)
+ const base = await wsBase
+ for (let i = 0; i < 5; i++) {
+ await connectWithPassword({
+ targetMachineId: MACHINE_ID,
+ password: `wrong-${i}`,
+ selfIdentity: C.newIdentity(),
+ accessToken: 'unused',
+ backendWsBase: base,
+ autonomousEnv: 'prod',
+ timeoutMs: 5_000,
+ })
+ }
+ const stillLocked = await connectWithPassword({
+ targetMachineId: MACHINE_ID, password: REMOTE_PASSWORD, selfIdentity: C.newIdentity(),
+ accessToken: 'unused', backendWsBase: base, autonomousEnv: 'prod', timeoutMs: 5_000,
+ })
+ expect(stillLocked).toEqual({ ok: false, error: 'RATE_LIMITED' })
+
+ const NEW_PASSWORD = 'a brand new remote password'
+ await manager.setRemotePassword(NEW_PASSWORD)
+ const result = await connectWithPassword({
+ targetMachineId: MACHINE_ID, password: NEW_PASSWORD, selfIdentity: C.newIdentity(),
+ accessToken: 'unused', backendWsBase: base, autonomousEnv: 'prod', timeoutMs: 5_000,
+ })
+ expect(result.ok).toBe(true)
+ } finally {
+ await close()
+ }
})
})
@@ -231,15 +358,15 @@ describe('RemoteRelayPool drops a peer the responder no longer trusts', () => {
try {
const port = (wss.address() as AddressInfo).port
const clientIdentity = C.newIdentity()
- const token = manager.createSetupToken(MACHINE_ID).token
- const claim = await claimSetupToken({
- token,
+ await manager.setRemotePassword(REMOTE_PASSWORD)
+ const claim = await connectWithPassword({
targetMachineId: MACHINE_ID,
+ password: REMOTE_PASSWORD,
selfIdentity: clientIdentity,
accessToken: 'unused-in-this-fake',
backendWsBase: `ws://127.0.0.1:${port}`,
autonomousEnv: 'prod',
- timeoutMs: 2_000,
+ timeoutMs: 5_000,
})
expect(claim.ok).toBe(true)
if (!claim.ok) return
@@ -303,15 +430,15 @@ describe('RemoteRelayPool drops a peer the responder no longer trusts', () => {
try {
const port = (wss.address() as AddressInfo).port
const clientIdentity = C.newIdentity()
- const token = manager.createSetupToken(MACHINE_ID).token
- const claim = await claimSetupToken({
- token,
+ await manager.setRemotePassword(REMOTE_PASSWORD)
+ const claim = await connectWithPassword({
targetMachineId: MACHINE_ID,
+ password: REMOTE_PASSWORD,
selfIdentity: clientIdentity,
accessToken: 'unused-in-this-fake',
backendWsBase: `ws://127.0.0.1:${port}`,
autonomousEnv: 'prod',
- timeoutMs: 2_000,
+ timeoutMs: 5_000,
})
expect(claim.ok).toBe(true)
if (!claim.ok) return
@@ -329,7 +456,7 @@ describe('RemoteRelayPool drops a peer the responder no longer trusts', () => {
staleSink,
() => { staleOnClosedFired = true },
)
- expect(selects).toBe(2) // 1 for claimSetupToken's own connection, 1 for the acquire() dial
+ expect(selects).toBe(2) // 1 for connectWithPassword's own connection, 1 for the acquire() dial
pool.invalidate(MACHINE_ID)
// onClosed is a stand-in for the LOCAL app socket's own close() — invalidate() must never call
diff --git a/cli/src/lib/e2ee/store.ts b/cli/src/lib/e2ee/store.ts
index 8968dd4e0..a1cf7de99 100644
--- a/cli/src/lib/e2ee/store.ts
+++ b/cli/src/lib/e2ee/store.ts
@@ -4,16 +4,36 @@
* mode 0600 (pairs are rare — no debounce needed). The identity key is the root of trust; losing it
* forces every browser to re-pair.
*/
-import { mkdirSync, readFileSync, writeFileSync } from 'fs'
+import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs'
import { join } from 'path'
import { env } from '../../config/env.js'
import { newIdentity, newPairId, b64e, b64d, fingerprint, encodeSetupToken, verifySetupToken, type Identity, type PairRole } from './core.js'
+import { stretchPassword } from './passwordPake.js'
const DIR = join(env.ADAPTER_DATA_DIR, 'e2e')
const IDENTITY_FILE = join(DIR, 'identity.json')
const PAIRED_FILE = join(DIR, 'paired.json')
+const REMOTE_PASSWORD_FILE = join(DIR, 'remotePassword.json')
const SETUP_TTL_MS = 7 * 24 * 60 * 60 * 1000
+// Remote-password lockout tuning (anti online-guessing for a reusable, human-memorable secret — see
+// notePwFailure()/pwLockedUntil()). Distinct regime from the live pairing code's RATE_MAX=3/5min in
+// manager.ts: that code is disposable and expires in 60s, so a handful of tries exhausts it quickly;
+// this password is long-lived, so failures need a real, growing lockout instead.
+const PW_FAIL_WINDOW_MS = 30 * 60 * 1000
+const PW_FAIL_THRESHOLD = 5
+const PW_LOCKOUT_BASE_MS = 5 * 60 * 1000 // 5 min
+const PW_LOCKOUT_MAX_MS = 24 * 60 * 60 * 1000 // 24h, cap for the exponential backoff
+
+interface RemotePasswordRecord {
+ v: 1
+ stretched: string // base64 — the 32-byte scrypt output, not the raw password
+ setAt: number
+ recentFailures: number[] // ms-epoch timestamps of recent failed attempts, trimmed to PW_FAIL_WINDOW_MS
+ lockedUntil?: number
+ lockoutCount?: number // consecutive lockouts since the password was last set — drives the backoff
+}
+
export interface PairedClient {
identityPub: string // base64 Ed25519 pubkey — the pin
label: string // UA-derived, for display
@@ -28,8 +48,10 @@ function writeSecure(file: string, data: unknown): void {
export class E2eeStore {
private identity: Identity | null = null
private paired = new Map<string, PairedClient>() // key = identityPub (base64)
+ private remotePassword: RemotePasswordRecord | null = null
- /** Load or create the computer identity keypair; load the paired set. Idempotent. */
+ /** Load or create the computer identity keypair; load the paired set + remote-password state.
+ * Idempotent. */
init(): Identity {
if (this.identity) return this.identity
try {
@@ -46,6 +68,19 @@ export class E2eeStore {
if (p?.identityPub) this.paired.set(p.identityPub, { ...p, role: p.role === 'device' ? 'device' : 'web' })
}
} catch { /* none yet */ }
+ try {
+ const raw = JSON.parse(readFileSync(REMOTE_PASSWORD_FILE, 'utf-8')) as Partial<RemotePasswordRecord>
+ if (raw?.v === 1 && typeof raw.stretched === 'string' && typeof raw.setAt === 'number') {
+ this.remotePassword = {
+ v: 1,
+ stretched: raw.stretched,
+ setAt: raw.setAt,
+ recentFailures: Array.isArray(raw.recentFailures) ? raw.recentFailures.filter((n) => typeof n === 'number') : [],
+ lockedUntil: typeof raw.lockedUntil === 'number' ? raw.lockedUntil : undefined,
+ lockoutCount: typeof raw.lockoutCount === 'number' ? raw.lockoutCount : undefined,
+ }
+ }
+ } catch { /* none yet */ }
return this.identity
}
@@ -107,4 +142,82 @@ export class E2eeStore {
if (b64e(id.pub) !== verified.payload.pub) return { ok: false, error: 'WRONG_ADAPTER' }
return { ok: true, fingerprint: this.fingerprint() }
}
+
+ // ── persistent remote password (machine-to-machine `harness link connect`) ───────────────────────
+ // A fourth, separate trust primitive from the three above: not a browser pairing (paired.json), not
+ // a one-time signed token (createSetupToken), and not the live 6-char CPace code — see
+ // passwordPake.ts for why this needs its own domain-separated CPace generator, and manager.ts's
+ // onPwPairIntent/onPwPake for the state machine that consumes remotePasswordVerifier()/
+ // notePwFailure()/notePwSuccess() below.
+
+ /** Stretch + persist a new remote password (0600, same convention as identity.json/paired.json).
+ * Rotating the password always clears any existing lockout — a fresh secret invalidates whatever
+ * guessing history applied to the old one. */
+ async setRemotePassword(machineId: string, password: string): Promise<{ fingerprint: string }> {
+ const stretched = await stretchPassword(password, machineId)
+ const record: RemotePasswordRecord = { v: 1, stretched: b64e(stretched), setAt: Date.now(), recentFailures: [] }
+ this.remotePassword = record
+ writeSecure(REMOTE_PASSWORD_FILE, record)
+ return { fingerprint: fingerprint(stretched) }
+ }
+
+ /** Remove the remote password. Until a new one is set, `harness link connect` against this machine
+ * always fails with NO_REMOTE_PASSWORD (checked before any crypto runs). */
+ clearRemotePassword(): void {
+ this.remotePassword = null
+ try { rmSync(REMOTE_PASSWORD_FILE, { force: true }) } catch { /* already gone */ }
+ }
+
+ hasRemotePassword(): boolean {
+ return this.remotePassword !== null
+ }
+
+ /** The raw stretched verifier bytes, fed into passwordPake.ts's pwCpaceGenerator(); null if unset. */
+ remotePasswordVerifier(): Uint8Array | null {
+ return this.remotePassword ? b64d(this.remotePassword.stretched) : null
+ }
+
+ remotePasswordFingerprint(): string | null {
+ return this.remotePassword ? fingerprint(b64d(this.remotePassword.stretched)) : null
+ }
+
+ remotePasswordSetAt(): number | null {
+ return this.remotePassword ? this.remotePassword.setAt : null
+ }
+
+ /** Record a failed password-PAKE attempt (anti online-guessing — the password is reusable and
+ * human-memorable, unlike the disposable high-entropy live pairing code, so it needs a real,
+ * growing lockout rather than the code's fixed RATE_MAX/RATE_WINDOW). Failures older than
+ * PW_FAIL_WINDOW_MS don't count. Crossing PW_FAIL_THRESHOLD within the window locks out for an
+ * exponentially growing period (5m, 10m, 20m, ... capped at 24h), tracked by `lockoutCount` so
+ * repeated lockouts (not just repeated failures) escalate the wait. No-op if no password is set —
+ * there is nothing to guess. */
+ notePwFailure(): { lockedUntil: number | null } {
+ const record = this.remotePassword
+ if (!record) return { lockedUntil: null }
+ const now = Date.now()
+ record.recentFailures = [...record.recentFailures.filter((t) => now - t < PW_FAIL_WINDOW_MS), now]
+ if (record.recentFailures.length >= PW_FAIL_THRESHOLD) {
+ const count = (record.lockoutCount ?? 0) + 1
+ record.lockoutCount = count
+ record.lockedUntil = now + Math.min(PW_LOCKOUT_BASE_MS * 2 ** (count - 1), PW_LOCKOUT_MAX_MS)
+ record.recentFailures = [] // fresh window once locked — it takes another full THRESHOLD after unlock
+ }
+ writeSecure(REMOTE_PASSWORD_FILE, record)
+ return { lockedUntil: record.lockedUntil ?? null }
+ }
+
+ /** Successful attempts don't affect the failure count — mirrors manager.ts's `attempts` convention
+ * for the live pairing code (only failed handshakes count toward its rate limit). Kept as an
+ * explicit no-op call site (rather than omitted) so the success path in manager.ts reads the same
+ * shape as the failure path, and so a future policy change has one place to land. */
+ notePwSuccess(): void { /* deliberately no-op — see doc comment */ }
+
+ /** Current lockout, or null if unset/expired. An expired `lockedUntil` is treated as not-locked
+ * without rewriting the file — the next real failure (if any) will naturally recompute it. */
+ pwLockedUntil(): number | null {
+ const until = this.remotePassword?.lockedUntil
+ if (!until || until <= Date.now()) return null
+ return until
+ }
}
diff --git a/cli/src/lib/remoteRelay.ts b/cli/src/lib/remoteRelay.ts
index 782f27f50..6c3f14707 100644
--- a/cli/src/lib/remoteRelay.ts
+++ b/cli/src/lib/remoteRelay.ts
@@ -6,10 +6,11 @@
*
* This daemon now TERMINATES E2EE on the relay itself (see lib/e2ee/relayClient.ts), playing the
* "client" role a browser (or the old Flutter app) used to play, toward whichever remote machine
- * `lib/e2ee/machinePeers.ts` has a pinned trust for (established out of band via `harness link
- * create`/`harness link import`). The local app therefore only ever sees plaintext — the exact same
- * shape it already gets for this daemon's own machine — for every machine, relayed or not. A machine
- * with no pinned peer fails the relay with `NO_PEER_LINK` instead of ever reaching pipe mode.
+ * `lib/e2ee/machinePeers.ts` has a pinned trust for (established out of band via `harness
+ * remote-password set` on the target machine + `harness link connect` here). The local app therefore
+ * only ever sees plaintext — the exact same shape it already gets for this daemon's own machine — for
+ * every machine, relayed or not. A machine with no pinned peer fails the relay with `NO_PEER_LINK`
+ * instead of ever reaching pipe mode.
*/
import { WebSocket, type RawData } from 'ws'
import type { Frame, LocalClientSink } from '../backendSocket.js'