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.

fix(security): remote-password lockout holds across concurrent attempts (OH-5) (#353)

0xken15db5b89f2a0df
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index fa0b6479d..8c922b9b3 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -6622,6 +6622,7 @@ function humanizeLinkError(error: string, machine: string, retryAt?: number): st
NO_REMOTE_PASSWORD: `Machine ${machine} has no remote password set. Ask its operator to run \`harness remote-password set\` there first.`,
BAD_INTENT: 'The connection request was malformed — this usually means a version mismatch. Update harness on both machines and try again.',
WRONG_PASSWORD: 'That password is wrong. Check it against the other machine and try again.',
+ BUSY: `Machine ${machine} is already handling another link attempt. Wait a moment and try again.`,
TIMEOUT: `Machine ${machine} didn't respond in time. Make sure it's running \`harness start\` and reachable, then try again.`,
SEND_FAILED: 'Could not reach the relay to start linking. Check your network connection and try again.',
DERIVE_FAILED: 'Could not process the password locally. Try again; if it persists, restart harness and retry.',
diff --git a/cli/src/lib/e2ee/manager.test.ts b/cli/src/lib/e2ee/manager.test.ts
index 1c7ce981d..bb3c6350d 100644
--- a/cli/src/lib/e2ee/manager.test.ts
+++ b/cli/src/lib/e2ee/manager.test.ts
@@ -1,4 +1,4 @@
-import { describe, it, expect, beforeAll, beforeEach } from 'vitest'
+import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest'
import { mkdtempSync, rmSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
@@ -463,6 +463,70 @@ describe('E2eeManager persistent remote-password pairing', () => {
// One scrypt per wrong-password attempt — see PW_SCRYPT_TEST_TIMEOUT_MS.
}, PW_SCRYPT_TEST_TIMEOUT_MS)
+ it('keeps at most two password attempts in flight at once; a third is BUSY until one finishes', async () => {
+ const { mgr, takeLast, lastFor } = machine()
+ await mgr.setRemotePassword(PASSWORD)
+ const a = new PwPeer(), b = new PwPeer(), c = new PwPeer()
+ mgr.handleFrame('slot-a', await a.intent(PASSWORD))
+ mgr.handleFrame('slot-b', await b.intent(PASSWORD))
+ mgr.handleFrame('slot-c', await c.intent(PASSWORD))
+ expect(lastFor('slot-c', 'e2e_pw_pair_result')?.payload).toMatchObject({ ok: false, error: 'BUSY' })
+ expect(lastFor('slot-c', 'e2e_pw_pake')).toBeUndefined()
+ // One finishing frees its place.
+ mgr.handleFrame('slot-a', a.onPake(lastFor('slot-a', 'e2e_pw_pake')!)!)
+ mgr.handleFrame('slot-a', a.onPake(lastFor('slot-a', 'e2e_pw_pake')!)!)
+ expect(lastFor('slot-a', 'e2e_pw_pake')?.payload).toMatchObject({ round: 5, ok: true })
+ const d = new PwPeer()
+ mgr.handleFrame('slot-d', await d.intent(PASSWORD))
+ expect(takeLast('e2e_pw_pake').payload).toMatchObject({ round: 1 })
+ })
+
+ it('judges an attempt against a lockout that began after its intent, without evaluating it', async () => {
+ const { mgr, lastFor } = machine()
+ await mgr.setRemotePassword(PASSWORD)
+ const held = new PwPeer()
+ mgr.handleFrame('held', await held.intent(PASSWORD))
+ const heldRound1 = lastFor('held', 'e2e_pw_pake')!
+ for (let i = 0; i < 5; i++) {
+ const joiner = new PwPeer()
+ const conn = `pwlock-${i}`
+ mgr.handleFrame(conn, await joiner.intent(`wrong-${i}`))
+ mgr.handleFrame(conn, joiner.onPake(lastFor(conn, 'e2e_pw_pake')!)!)
+ }
+ // Now locked. The attempt opened before the lockout — even with the right password — is refused.
+ mgr.handleFrame('held', held.onPake(heldRound1)!)
+ expect(lastFor('held', 'e2e_pw_pake')?.payload).toMatchObject({ round: 5, error: 'RATE_LIMITED', retryAt: expect.any(Number) })
+ expect(mgr.listPaired()).toEqual([])
+ }, PW_SCRYPT_TEST_TIMEOUT_MS)
+
+ it('starts the lockout backoff over after a success, and after a quiet day', async () => {
+ const { mgr, lastFor } = machine()
+ await mgr.setRemotePassword(PASSWORD)
+ const lockNow = async (tag: string): Promise<number> => {
+ for (let i = 0; i < 5; i++) {
+ const joiner = new PwPeer()
+ const conn = `${tag}-${i}`
+ mgr.handleFrame(conn, await joiner.intent(`wrong-${i}`))
+ mgr.handleFrame(conn, joiner.onPake(lastFor(conn, 'e2e_pw_pake')!)!)
+ }
+ const probe = new PwPeer()
+ mgr.handleFrame(`${tag}-probe`, await probe.intent(PASSWORD))
+ return (lastFor(`${tag}-probe`, 'e2e_pw_pair_result')!.payload as { retryAt: number }).retryAt
+ }
+ const FIVE_MIN = 5 * 60_000
+ vi.useFakeTimers({ toFake: ['Date'] })
+ try {
+ let now = Date.now()
+ expect(await lockNow('first') - now).toBeLessThanOrEqual(FIVE_MIN + 1000)
+ // Right after it ends, the next lockout escalates (10 min)…
+ vi.setSystemTime(now += FIVE_MIN + 1000)
+ expect(await lockNow('second') - now).toBeGreaterThan(FIVE_MIN + 1000)
+ // …but a day of quiet since the last one ended starts it over.
+ vi.setSystemTime(now += 10 * FIVE_MIN + 25 * 60 * 60_000)
+ expect(await lockNow('third') - now).toBeLessThanOrEqual(FIVE_MIN + 1000)
+ } finally { vi.useRealTimers() }
+ }, PW_SCRYPT_TEST_TIMEOUT_MS * 3)
+
it('clearRemotePassword removes it — a subsequent intent gets NO_REMOTE_PASSWORD again', async () => {
const { mgr, takeLast } = machine()
await mgr.setRemotePassword(PASSWORD)
diff --git a/cli/src/lib/e2ee/manager.ts b/cli/src/lib/e2ee/manager.ts
index b24a85e7d..bb384f648 100644
--- a/cli/src/lib/e2ee/manager.ts
+++ b/cli/src/lib/e2ee/manager.ts
@@ -86,6 +86,9 @@ const MAX_SESSIONS = 64
// 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
+/** Password-PAKE attempts in flight at once, across every connection. The lockout counts failures as
+ * they are judged, so it bounds guesses only if attempts cannot pile up ahead of it. */
+const MAX_PW_SLOTS = 2
interface PwPairSlot {
connId: string
@@ -582,6 +585,7 @@ export class E2eeManager {
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
+ if (this.pwSlots.size >= MAX_PW_SLOTS) { fail('BUSY'); return true }
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)
@@ -603,6 +607,10 @@ export class E2eeManager {
const ci = pwContext(this.deps.machineId)
try {
if (round === 2) {
+ // Judged against the lockout as it stands NOW, not as it stood at the intent: a lockout that
+ // began meanwhile covers this attempt too, and a refused attempt is not counted or evaluated.
+ const lockedUntil = this.store.pwLockedUntil()
+ if (lockedUntil) { this.failPwPair(connId, 'RATE_LIMITED', false, { retryAt: lockedUntil }); return true }
const Yb = C.b64d(String(p.yb))
const K = C.cpaceShared(Yb, slot.y)
const isk = C.cpaceISK(slot.sid, K, slot.Ya, Yb)
@@ -648,11 +656,11 @@ export class E2eeManager {
/** `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 {
+ private failPwPair(connId: string, error: string, countsAsFailure = false, extra?: Record<string, unknown>): 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 } })
+ this.deps.sendTo(connId, { type: 'e2e_pw_pake', payload: { sid: slot.sidB64, round: 5, error, ...extra } })
if (countsAsFailure) {
const { lockedUntil } = this.store.notePwFailure()
if (lockedUntil) this.notifyRemotePasswordLocked(lockedUntil) // fresh lockout — pwLockedUntil() was
diff --git a/cli/src/lib/e2ee/relayClient.ts b/cli/src/lib/e2ee/relayClient.ts
index ee81734dd..8701e9b69 100644
--- a/cli/src/lib/e2ee/relayClient.ts
+++ b/cli/src/lib/e2ee/relayClient.ts
@@ -281,7 +281,8 @@ export async function connectWithPassword(opts: {
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' })
+ const retryAt = typeof payload.retryAt === 'number' ? payload.retryAt : undefined
+ finish({ ok: false, error: typeof payload.error === 'string' ? payload.error : 'PAIR_FAILED', ...(retryAt !== undefined ? { retryAt } : {}) })
}
}
} catch {
diff --git a/cli/src/lib/e2ee/store.ts b/cli/src/lib/e2ee/store.ts
index 591c4aec3..36ab06052 100644
--- a/cli/src/lib/e2ee/store.ts
+++ b/cli/src/lib/e2ee/store.ts
@@ -179,6 +179,9 @@ export class E2eeStore {
const record = this.remotePassword
if (!record) return { lockedUntil: null }
const now = Date.now()
+ // The backoff escalates across lockouts only while they keep coming: a quiet day since the last one
+ // ended starts it over, so no one is held at the 24h ceiling for good.
+ if (record.lockedUntil && now - record.lockedUntil > PW_LOCKOUT_MAX_MS) record.lockoutCount = 0
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
@@ -190,11 +193,15 @@ export class E2eeStore {
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 */ }
+ /** A successful pairing proves the password is known to its owner's machines: the failures and the
+ * lockout escalation that came before it no longer describe anyone's guessing, so both start over. */
+ notePwSuccess(): void {
+ const record = this.remotePassword
+ if (!record || (record.recentFailures.length === 0 && !record.lockoutCount)) return
+ record.recentFailures = []
+ record.lockoutCount = 0
+ writeSecure(REMOTE_PASSWORD_FILE, record)
+ }
/** 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. */
diff --git a/desktop/lib/auth/link_errors.dart b/desktop/lib/auth/link_errors.dart
index 7b5d20c98..9b1080e91 100644
--- a/desktop/lib/auth/link_errors.dart
+++ b/desktop/lib/auth/link_errors.dart
@@ -24,6 +24,8 @@ String humanizeLinkError(String code, String machineId, {DateTime? retryAt}) {
'Update harness on both machines and try again.',
'WRONG_PASSWORD' =>
'That password is wrong. Check it against the other machine and try again.',
+ 'BUSY' =>
+ 'Machine $machineId is already handling another link attempt. Wait a moment and try again.',
'TIMEOUT' =>
"Machine $machineId didn't respond in time. Make sure it's running `harness start` "
'and reachable, then try again.',
diff --git a/mobile/lib/auth/link_errors.dart b/mobile/lib/auth/link_errors.dart
index 7b5d20c98..9b1080e91 100644
--- a/mobile/lib/auth/link_errors.dart
+++ b/mobile/lib/auth/link_errors.dart
@@ -24,6 +24,8 @@ String humanizeLinkError(String code, String machineId, {DateTime? retryAt}) {
'Update harness on both machines and try again.',
'WRONG_PASSWORD' =>
'That password is wrong. Check it against the other machine and try again.',
+ 'BUSY' =>
+ 'Machine $machineId is already handling another link attempt. Wait a moment and try again.',
'TIMEOUT' =>
"Machine $machineId didn't respond in time. Make sure it's running `harness start` "
'and reachable, then try again.',