The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Devices: a linked Mac's daemon restart renews the dial's E2EE session; refused turns show as not delivered (#2356)
0xken15c128b1a995c4
diff --git a/cli/src/core/api.ts b/cli/src/core/api.tsindex b84ddfbec..e8457de71 100644--- a/cli/src/core/api.ts+++ b/cli/src/core/api.ts@@ -1716,13 +1716,15 @@ export interface LaneSeal {rekey(machineId: string, payload: Record<string, unknown>): Promise<void>/** A frame for the machine, sealed as its session seals that type (a type it does not seal goes as it is). */seal(machineId: string, frame: Record<string, unknown>): Promise<LaneSealed>- /** A sealed frame from the machine, opened; `unreadable` when it does not open (stale, forged, garbled). */+ /** A sealed frame from the machine, opened; `unreadable` when it does not open (stale, forged, garbled);+ * `unknownEpoch` when it is sealed under a group epoch none of the machine's sessions here ever held: the+ * far daemon restarted, and the session here is with a process that is gone. */open(machineId: string, frame: Record<string, unknown>): Promise<LaneOpened>/** The lane is done with the machine's session. */drop(machineId: string): void}export type LaneSealed = { frame: Record<string, unknown> } | { lost: true }-export type LaneOpened = { frame: Record<string, unknown> } | { unreadable: true } | { lost: true }+export type LaneOpened = { frame: Record<string, unknown> } | { unreadable: true } | { unknownEpoch: true } | { lost: true }/** A service with no lane of the core's: it starts no session and seals nothing, never sends in the clear. */export const LANE_OFF: LaneSeal = {hello: () => Promise.reject(new Error('no lane: this process holds no E2EE identity')),diff --git a/cli/src/core/gatewayLink.spec.ts b/cli/src/core/gatewayLink.spec.tsindex bb52b3771..9e44eb5bc 100644--- a/cli/src/core/gatewayLink.spec.ts+++ b/cli/src/core/gatewayLink.spec.ts@@ -479,6 +479,9 @@ describe('the gateway in its own process, as the core sees it', () => {expect(await lane.open('m2', { type: 'agents_list_result' })).toEqual({ frame: { type: 'agents_list_result', payload: {} } })answer = { unreadable: true }expect(await lane.open('m2', { type: 'agents_list_result' })).toEqual({ unreadable: true })+ // A new epoch is the far daemon restarted, not a frame that does not open: the lane renews for it.+ answer = { unknownEpoch: true, unreadable: true }+ expect(await lane.open('m2', { type: 'commander_question' })).toEqual({ unknownEpoch: true })lane.drop('m2')expect(call).toHaveBeenLastCalledWith(GATEWAY_CALLS.lane, { op: 'drop', machineId: 'm2' }, LANE_WAIT_MS)// The gateway not there (or failed): no session is started, nothing is sealed or opened.diff --git a/cli/src/core/gatewayLink.ts b/cli/src/core/gatewayLink.tsindex bfa64791b..7357e3f19 100644--- a/cli/src/core/gatewayLink.ts+++ b/cli/src/core/gatewayLink.ts@@ -242,6 +242,7 @@ export function createGatewayLink(deps: GatewayLinkDeps) {open: async (machineId, frame) => {const answer = await lane('open', { machineId, frame })if (answer.frame && typeof answer.frame === 'object') return { frame: record(answer.frame) }+ if (answer.unknownEpoch === true) return { unknownEpoch: true }return answer.unreadable === true ? { unreadable: true } : { lost: true }},drop: (machineId) => { void lane('drop', { machineId }) },diff --git a/cli/src/device/deviceFleet.spec.ts b/cli/src/device/deviceFleet.spec.tsindex a7bced782..419999d80 100644--- a/cli/src/device/deviceFleet.spec.ts+++ b/cli/src/device/deviceFleet.spec.ts@@ -7,7 +7,7 @@ import { describe, expect, it, vi } from 'vitest'import { DeviceFleet } from './deviceFleet.js'import { FleetError, type FleetEvent } from '../cable/machineFleet.js'-import type { DeviceFrame } from './deviceLink.js'+import { SESSION_GONE, type DeviceFrame, type Undelivered } from './deviceLink.js'type Listed = { machineId: string; name: string; state: string; agentCount: number; authMode: string; local: boolean }@@ -20,11 +20,13 @@ function listOf(rows: Partial<Listed>[]): Listed[] {function make(over: { rows?: Partial<Listed>[]; linked?: string[]; rpc?: (t: string, p: Record<string, unknown>) => Promise<Record<string, unknown>> } = {}) {const rows = listOf(over.rows ?? [{}])let frameCb: ((f: DeviceFrame) => void) | null = null+ let undeliveredCb: ((what: Undelivered) => void) | null = nullconst sent: DeviceFrame[] = []const resets: string[] = []const link = {selectedMachine: 'm1',onFrame: (cb: (f: DeviceFrame) => void) => { frameCb = cb; return () => {} },+ onUndelivered: (cb: (what: Undelivered) => void) => { undeliveredCb = cb; return () => {} },attach: vi.fn(async () => {}),online: vi.fn(async () => {}),detach: vi.fn(),@@ -43,7 +45,7 @@ function make(over: { rows?: Partial<Listed>[]; linked?: string[]; rpc?: (t: strhasPeerLink: (id: string) => (over.linked ?? ['m1']).includes(id),log: () => {},})- return { fleet, link, sent, resets, say: (f: DeviceFrame) => frameCb?.(f) }+ return { fleet, link, sent, resets, say: (f: DeviceFrame) => frameCb?.(f), undelivered: (what: Undelivered) => undeliveredCb?.(what) }}describe('DeviceFleet', () => {@@ -106,6 +108,47 @@ describe('DeviceFleet', () => {expect(resets).toEqual([])})+ it('shows a turn, a stop or an answer that may not have reached its machine on that agent\'s tile, never inviting a blind resend', async () => {+ // Diego, 10-30: after the far daemon restarted, a dial turn vanished with nothing on the dial to say so.+ const { fleet, undelivered } = make()+ const seen: FleetEvent[] = []+ fleet.onEvent((e) => seen.push(e))+ undelivered({ machineId: 'm1', type: 'message', agentId: 'a1' })+ undelivered({ machineId: 'm1', type: 'cancel', agentId: 'a2' })+ undelivered({ machineId: 'm1', type: 'question_response', agentId: 'a3', requestId: 'q1' })+ // With no agent to put it on there is no tile to tell.+ undelivered({ machineId: 'm1', type: 'message' })+ undelivered({ machineId: 'gone', type: 'message', agentId: 'a4' })+ expect(seen).toEqual([+ { machineId: 'm1', kind: 'error', agentId: 'a1', text: 'May not have reached office-imac. Check before sending again.', recap: 'May not have arrived' },+ { machineId: 'm1', kind: 'error', agentId: 'a2', text: 'Stop may not have reached office-imac. Check before stopping again.', recap: 'May not have arrived' },+ { machineId: 'm1', kind: 'error', agentId: 'a3', text: 'Answer may not have reached office-imac. Check before answering again.', recap: 'May not have arrived' },+ { machineId: 'gone', kind: 'error', agentId: 'a4', text: 'May not have reached that computer. Check before sending again.', recap: 'May not have arrived' },+ ])+ })++ it('asks a read again once when its machine\'s session went before the answer came, and counts no miss for it', async () => {+ // The far daemon restarted mid-request: it never saw the request, so asking again is safe for a read.+ const asked: string[] = []+ let fail = 1+ const { fleet, resets } = make({+ rpc: async (type) => { asked.push(type); if (fail-- > 0) throw new Error(SESSION_GONE); return { agents: [{ id: 'c1', engine: 'claude' }] } },+ })+ expect((await fleet.listAgents('m1')).map((a) => a.id)).toEqual(['c1'])+ expect(asked).toEqual(['agents_list', 'agents_list'])+ expect(fleet.reachable('m1')).toMatchObject({ ok: true })+ // Only once: a second loss is a failure like any other.+ fail = 2+ await expect(fleet.listAgents('m1')).rejects.toThrow(SESSION_GONE)+ expect(asked).toHaveLength(4)+ expect(resets).toEqual([])+ // A write is never asked twice: the far side may have run it.+ const writes: string[] = []+ const w = make({ rpc: async (type) => { writes.push(type); throw new Error(SESSION_GONE) } })+ await expect(w.fleet.forkAgent('m1', 'a1')).rejects.toThrow(SESSION_GONE)+ expect(writes).toEqual(['agent_fork'])+ })+it('says nothing about a machine nobody has asked', async () => {// Callers refuse to deliver on a NEGATIVE verdict. Answering "unreachable" for a machine that has// simply never been called would turn every cold start into a refusal.@@ -248,7 +291,7 @@ describe('DeviceFleet', () => {find: (id: string) => rows.find((r) => r.machineId === id),applyLive: (r: unknown) => { applied.push(r); return true },} as never,- link: { selectedMachine: 'm1', onFrame: (cb: never) => { frameCb = cb; return () => {} } } as never,+ link: { selectedMachine: 'm1', onFrame: (cb: never) => { frameCb = cb; return () => {} }, onUndelivered: () => () => {} } as never,hasPeerLink: () => true,log: () => {},})@@ -265,7 +308,7 @@ describe('DeviceFleet', () => {let frameCb!: (f: { type?: string; machineId?: string; payload?: Record<string, unknown> }) => voidconst fleet = new DeviceFleet({list: { list: () => ({ machines: [], source: 'backend' as const }), find: () => undefined, applyLive: () => true } as never,- link: { selectedMachine: 'm1', onFrame: (cb: never) => { frameCb = cb; return () => {} } } as never,+ link: { selectedMachine: 'm1', onFrame: (cb: never) => { frameCb = cb; return () => {} }, onUndelivered: () => () => {} } as never,hasPeerLink: () => true,log: () => {},})diff --git a/cli/src/device/deviceFleet.ts b/cli/src/device/deviceFleet.tsindex c24c52570..ada45f9a4 100644--- a/cli/src/device/deviceFleet.ts+++ b/cli/src/device/deviceFleet.ts@@ -10,7 +10,7 @@ import { FleetError, type FleetEvent, type FleetMachine, type MachineFleet } froimport type { CableAgent } from '../cable/cableSession.js'import type { RecentTurn } from '../cable/cableHost.js'import type { MachineListCache } from './machineList.js'-import type { DeviceFrame, DeviceLink } from './deviceLink.js'+import { SESSION_GONE, type DeviceFrame, type DeviceLink, type Undelivered } from './deviceLink.js'/** How long the socket lingers after the dial goes back to local, so flicking between two machines does* not pay a full dial each way. Mirrors RemoteRelayPool's own linger for the same reason. */@@ -19,6 +19,25 @@ const LINGER_MS = 60_000/** Consecutive failed round trips before a machine's E2EE session is thrown away — see `rpc()`. */const RESET_AFTER_FAILURES = 2+/**+ * Requests that only read, asked once more when their machine's session went before the answer came. The+ * far daemon restarted and never saw them, so a second ask is the same question; a write is never repeated.+ */+const READS = new Set(['agents_list', 'agent_recent', 'models_list'])++/**+ * What the dial's tile says for a turn, stop or answer that may not have reached its machine.+ *+ * "May not", never "not": the refusal behind most of these is a clear frame from the relay, which could+ * forge one for a turn the far side did run. Telling the person to send it again would invite the very+ * double run that re-sending automatically was ruled out for (security review 1 on #2356).+ */+function notDelivered(type: string, name: string): string {+ if (type === 'cancel') return `Stop may not have reached ${name}. Check before stopping again.`+ if (type === 'question_response') return `Answer may not have reached ${name}. Check before answering again.`+ return `May not have reached ${name}. Check before sending again.`+}+/** Split `runtime-v1:<sid>:<engine>:<model>@<effort>` into the two words the dial's chips show. */function chipsFromProfile(profile: unknown): { model?: string; effort?: string } {if (typeof profile !== 'string' || !profile.startsWith('runtime-v1:')) return {}@@ -73,6 +92,7 @@ export class DeviceFleet implements MachineFleet {constructor(private readonly opts: DeviceFleetOpts) {this.opts.link.onFrame((frame) => this.onFrame(frame))+ this.opts.link.onUndelivered((what) => this.onUndelivered(what))}async list(): Promise<{ machines: FleetMachine[]; source: 'backend' | 'local' | 'signed-out' }> {@@ -177,13 +197,16 @@ export class DeviceFleet implements MachineFleet {* Every RPC goes through here so `reachable()` reads a fact rather than a guess. It rethrows* untouched — this is a witness, not a handler.*/- private async rpc(machineId: string, type: string, payload: Record<string, unknown>): Promise<Record<string, unknown>> {+ private async rpc(machineId: string, type: string, payload: Record<string, unknown>, again = false): Promise<Record<string, unknown>> {try {const res = await this.opts.link.rpc(type, payload, machineId)this.health.set(machineId, { ok: true, at: Date.now() })this.misses.delete(machineId)return res} catch (err) {+ // Its session went before the answer came (the far daemon restarted): a read is asked once more, on+ // the new session, and is no miss — nothing about the machine is known yet.+ if (!again && (err as Error).message === SESSION_GONE && READS.has(type)) return this.rpc(machineId, type, payload, true)this.health.set(machineId, { ok: false, at: Date.now() })const missed = (this.misses.get(machineId) ?? 0) + 1this.misses.set(machineId, missed)@@ -403,6 +426,16 @@ export class DeviceFleet implements MachineFleet {}}+ /**+ * A turn, stop or answer that did not reach its machine — said on that agent's tile, where the person+ * would otherwise go on believing it was sent (Diego, 10-30: the far daemon restarted and they vanished).+ */+ private onUndelivered(what: Undelivered): void {+ if (!what.agentId) return+ const name = this.opts.list.find(what.machineId)?.name || 'that computer'+ this.emit({ machineId: what.machineId, kind: 'error', agentId: what.agentId, text: notDelivered(what.type, name), recap: 'May not have arrived' })+ }+private emit(event: FleetEvent): void {for (const cb of this.listeners) cb(event)}diff --git a/cli/src/device/deviceLink.spec.ts b/cli/src/device/deviceLink.spec.tsindex e66036592..92103d32e 100644--- a/cli/src/device/deviceLink.spec.ts+++ b/cli/src/device/deviceLink.spec.ts@@ -19,6 +19,7 @@ import type { LaneOpened, LaneSeal, LaneSealed } from '../core/api.js'import { DeviceLink, type DeviceFrame } from './deviceLink.js'const LINKED = 'linked-machine'+const LINKED_2 = 'second-linked-machine'const CLOUD = 'cloud-machine'type Frame = Record<string, unknown>@@ -61,7 +62,13 @@ async function fakeDeviceWs(opts: { refuseToken?: string } = {}) {/** The gateway's side of the lane, faked: each seal marks the frame, and a test can make it slow or lost. */function fakeSeal() {- const sealed = vi.fn(async (_machineId: string, frame: Frame): Promise<LaneSealed> => ({ frame: { ...frame, payload: { __e2e: { of: frame.type } } } }))+ // Each sealed frame carries its counter, as a real envelope does (`__e2e.n`): a refusal names it.+ const counters = new Map<string, number>()+ const sealed = vi.fn(async (machineId: string, frame: Frame): Promise<LaneSealed> => {+ const n = counters.get(machineId) ?? 0+ counters.set(machineId, n + 1)+ return { frame: { ...frame, payload: { __e2e: { of: frame.type, n } } } }+ })const opened = vi.fn(async (_machineId: string, frame: Frame): Promise<LaneOpened> =>({ frame: { ...frame, payload: { opened: (frame.payload as { __e2e: unknown }).__e2e } } }))const seal = {@@ -82,29 +89,36 @@ afterEach(async () => {for (const server of servers.splice(0)) await server.close()})-async function lane(over: { refuseToken?: string; auth?: { accessToken(options?: { force?: boolean; failedToken?: string }): Promise<string> } } = {}) {+async function lane(over: { refuseToken?: string; auth?: { accessToken(options?: { force?: boolean; failedToken?: string }): Promise<string> }; welcome?: boolean; now?: () => number; linked?: Set<string>; handshakeMs?: number; renewEveryMs?: number } = {}) {const server = await fakeDeviceWs({ refuseToken: over.refuseToken })servers.push(server)const seal = fakeSeal()const lines: string[] = []+ const peerReads: string[] = []const auth = over.auth ?? { accessToken: vi.fn(async () => 'token-1') }const link = new DeviceLink({auth, backendWsBase: server.url, computerId: 'computer-1', autonomousEnv: 'test', seal,- peer: (machineId) => (machineId === LINKED ? { machineId, pub: 'LINKED-PUB', label: 'linked', linkedAt: 1 } as never : null),+ peer: (machineId) => {+ peerReads.push(machineId)+ return (over.linked ?? new Set([LINKED, LINKED_2])).has(machineId) ? { machineId, pub: 'LINKED-PUB', label: 'linked', linkedAt: 1 } as never : null+ },localMachineId: () => 'this-machine',log: (line) => { lines.push(line) },+ ...(over.now ? { now: over.now } : {}),+ ...(over.handshakeMs ? { handshakeTimeoutMs: over.handshakeMs } : {}),+ ...(over.renewEveryMs ? { renewEveryMs: over.renewEveryMs } : {}),})links.push(link)// The far machine answers every hello with a welcome, as a linked daemon does.server.on((frame) => {- if (frame.type === 'e2e_hello') server.send({ type: 'e2e_welcome', machineId: frame.machineId, payload: { ephPub: 'E' } })+ if (frame.type === 'e2e_hello' && over.welcome !== false) server.send({ type: 'e2e_welcome', machineId: frame.machineId, payload: { ephPub: 'E' } })})const heard: DeviceFrame[] = []link.onFrame((frame) => { heard.push(frame) })- return { server, seal, link, lines, auth, heard }+ return { server, seal, link, lines, auth, heard, peerReads }}-const until = async (what: string, check: () => boolean, ms = 5_000): Promise<void> => {+const until = async (what: string, check: () => boolean, ms = 4_000): Promise<void> => {const deadline = Date.now() + mswhile (!check()) {if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}`)@@ -191,11 +205,13 @@ describe('the fleet\'s lane, sealed by the gateway', () => {seal.open.mockResolvedValueOnce({ unreadable: true })server.send({ type: 'card', machineId: LINKED, payload: { __e2e: { n: 2 } } })await until('the drop to be said', () => lines.some((line) => line === 'device: could not decrypt card — dropped'))- // The gateway lost the session: nothing passed on, and the next call starts one again.+ // The gateway lost the session: the frame is not passed on as it came, but held, a session started+ // again for it, and read under that one.seal.open.mockResolvedValueOnce({ lost: true })server.send({ type: 'card', machineId: LINKED, payload: { __e2e: { n: 3 } } })await until('the loss to be said', () => lines.some((line) => line.includes('the E2EE session with linked-machine is gone')))- expect(heard).toHaveLength(2)+ await until('the card, under the new session', () => heard.length === 3)+ expect(heard[2]).toEqual({ type: 'card', machineId: LINKED, payload: { opened: { n: 3 } } })await link.establish(LINKED)expect(seal.hello).toHaveBeenCalledTimes(2)})@@ -205,7 +221,7 @@ describe('the fleet\'s lane, sealed by the gateway', () => {await link.online()const answer = link.rpc('agents_list', { scope: 'all' }, LINKED)await until('the request', () => server.forMachines().some((frame) => frame.type === 'agents_list'))- expect(server.forMachines().find((frame) => frame.type === 'agents_list')!.payload).toEqual({ __e2e: { of: 'agents_list' } })+ expect(server.forMachines().find((frame) => frame.type === 'agents_list')!.payload).toEqual({ __e2e: { of: 'agents_list', n: 0 } })// What the gateway sealed carried the request id; the reply that comes back sealed is opened to it.const asked = seal.seal.mock.calls.find(([, frame]) => frame.type === 'agents_list')![1] as { payload: { requestId: string } }seal.open.mockResolvedValueOnce({ frame: { type: 'agents_list_result', machineId: LINKED, payload: { requestId: asked.payload.requestId, agents: ['on B'] } } })@@ -214,7 +230,7 @@ describe('the fleet\'s lane, sealed by the gateway', () => {})it('a machine that refuses this one\'s key fails its session, and it ends at the gateway', async () => {- const { server, seal, link } = await lane()+ const { server, seal, link } = await lane({ handshakeMs: 300 })await link.online()await link.establish(LINKED)server.send({ type: 'e2e_rekey', machineId: LINKED, payload: { epoch: 'next' } })@@ -226,9 +242,9 @@ describe('the fleet\'s lane, sealed by the gateway', () => {await until('the session to end at the gateway', () => seal.drop.mock.calls.length === 1)expect(seal.drop).toHaveBeenCalledWith(LINKED)expect(seal.rekey).toHaveBeenCalledTimes(1)- // A welcome the gateway turns down fails the handshake.+ // A welcome the gateway turns down is ignored, and the hello it answered times out with nothing in its place.seal.welcome.mockResolvedValueOnce(false)- await expect(link.establish(LINKED)).rejects.toThrow('E2EE_HANDSHAKE_FAILED')+ await expect(link.establish(LINKED)).rejects.toThrow('did not answer the E2EE hello')// A reset says so to the gateway too, and the lane stopping ends every session it has there.await link.establish(LINKED)expect(link.resetSession(LINKED)).toBe(true)@@ -248,3 +264,415 @@ describe('the fleet\'s lane, sealed by the gateway', () => {expect(server.tokens).toEqual(['token-1', 'token-2'])})})++/** The request id the gateway was handed to seal for a machine's `type`, the nth such. */+function askedId(seal: ReturnType<typeof fakeSeal>, machineId: string, type: string, nth = 0): string {+ const asked = seal.seal.mock.calls.filter(([m, frame]) => m === machineId && frame.type === type)[nth]![1] as { payload: { requestId: string } }+ return asked.payload.requestId+}++/** The counter the gateway sealed a machine's `type` under, the nth such: what a refusal names. */+async function sealedCounter(seal: ReturnType<typeof fakeSeal>, machineId: string, type: string, nth = 0): Promise<number> {+ const at = seal.seal.mock.calls.findIndex(([m, frame], i) => m === machineId && frame.type === type+ && seal.seal.mock.calls.slice(0, i).filter(([m2, f2]) => m2 === machineId && f2.type === type).length === nth)+ const result = await seal.seal.mock.results[at]!.value as { frame: { payload: { __e2e: { n: number } } } }+ return result.frame.payload.__e2e.n+}++// Diego, 10-30: every CLI release restarts the far daemon. This Mac kept using the session the old process had+// agreed to, so a dial turn, a stop or an answer for its agents vanished, its open questions with them, and the+// log filled with "could not decrypt" until two agents_list timeouts happened to reset it.+describe('a linked machine\'s daemon restarts', () => {+ it('its "session unknown" drops that session at once: only its requests fail, and the next call says hello again', async () => {+ const { server, seal, link, lines } = await lane()+ await link.online()+ await link.establish(LINKED)+ await link.establish(LINKED_2)+ expect(seal.hello).toHaveBeenCalledTimes(2)+ const toLinked = link.rpc('agents_list', {}, LINKED)+ const toOther = link.rpc('agents_list', {}, LINKED_2)+ await until('both requests', () => server.forMachines().filter((frame) => frame.type === 'agents_list').length === 2)+ const n = await sealedCounter(seal, LINKED, 'agents_list')+ const asked = Date.now()+ server.send({ type: 'e2e_session_unknown', machineId: LINKED, payload: { refused: { type: 'agents_list', n } } })+ // At once, not after the request's own 15-second timeout.+ await expect(toLinked).rejects.toThrow('E2EE_SESSION_GONE')+ expect(Date.now() - asked).toBeLessThan(2_000)+ expect(seal.drop).toHaveBeenCalledWith(LINKED)+ expect(seal.drop).not.toHaveBeenCalledWith(LINKED_2)+ expect(lines.some((line) => line.includes(`${LINKED} restarted (it no longer knows this session)`))).toBe(true)+ // The other machine's request is still waiting, and is answered.+ seal.open.mockResolvedValueOnce({ frame: { type: 'agents_list_result', machineId: LINKED_2, payload: { requestId: askedId(seal, LINKED_2, 'agents_list'), agents: ['still here'] } } })+ server.send({ type: 'agents_list_result', machineId: LINKED_2, payload: { __e2e: { n: 1 } } })+ expect(await toOther).toMatchObject({ agents: ['still here'] })+ // The next sealed frame for the restarted machine starts a new session first.+ await link.sendSealed({ type: 'message', machineId: LINKED, payload: { agentId: 'a1', content: 'after the restart' } })+ await until('the message', () => server.forMachines().some((frame) => frame.type === 'message'))+ expect(seal.hello).toHaveBeenCalledTimes(3)+ expect(server.forMachines().filter((frame) => frame.machineId === LINKED).map((frame) => frame.type)).toEqual(['e2e_hello', 'agents_list', 'e2e_hello', 'message'])+ })++ it('a turn, a stop or an answer it refused is reported not delivered, never re-sent; one it took before is not', async () => {+ let now = 1_000_000+ const { server, seal, link } = await lane({ now: () => now })+ const undelivered: Array<Record<string, unknown>> = []+ link.onUndelivered((what) => { undelivered.push({ ...what }) })+ await link.online()+ await link.sendSealed({ type: 'message', machineId: LINKED, payload: { agentId: 'a0', content: 'before the restart' } })+ await link.sendSealed({ type: 'message', machineId: LINKED, payload: { agentId: 'a1', content: 'run the tests' } })+ await link.sendSealed({ type: 'cancel', machineId: LINKED, payload: { agentId: 'a2' } })+ await link.sendSealed({ type: 'question_response', machineId: LINKED, payload: { agentId: 'a3', requestId: 'q1', answers: { k: 'v' } } })+ await until('all four', () => server.forMachines().filter((frame) => frame.type !== 'e2e_hello').length === 4)+ // The far side restarted after the first: it refuses the second, the first it never saw refused.+ const n = await sealedCounter(seal, LINKED, 'message', 1)+ server.send({ type: 'e2e_session_unknown', machineId: LINKED, payload: { refused: { type: 'message', n } } })+ await until('the three reports', () => undelivered.length === 3)+ expect(undelivered).toEqual([+ { machineId: LINKED, type: 'message', agentId: 'a1' },+ { machineId: LINKED, type: 'cancel', agentId: 'a2' },+ { machineId: LINKED, type: 'question_response', agentId: 'a3', requestId: 'q1' },+ ])+ // Nothing went out again: the refusal is a clear frame the relay could have written, and re-sending on its+ // word would let it replay a turn into a fresh session.+ await new Promise((resolve) => setTimeout(resolve, 100))+ expect(server.forMachines().filter((frame) => frame.type !== 'e2e_hello')).toHaveLength(4)+ expect(seal.hello).toHaveBeenCalledTimes(1)+ // The next turn starts a new session. A refusal of it moments later is still reported (only the drop+ // waits for the limit), and one with no counter names what that session sealed in the last minute.+ await link.sendSealed({ type: 'message', machineId: LINKED, payload: { agentId: 'a4', content: 'again' } })+ await until('the fifth', () => server.forMachines().filter((frame) => frame.type !== 'e2e_hello').length === 5)+ server.send({ type: 'e2e_session_unknown', machineId: LINKED, payload: { refused: { type: 'message' } } })+ await until('the fourth report', () => undelivered.length === 4)+ expect(undelivered[3]).toEqual({ machineId: LINKED, type: 'message', agentId: 'a4' })+ expect(seal.drop).toHaveBeenCalledTimes(1)+ // Nothing is reported twice.+ now += 30_001+ server.send({ type: 'e2e_session_unknown', machineId: LINKED, payload: { refused: { type: 'message' } } })+ await until('the second drop', () => seal.drop.mock.calls.length === 2)+ expect(undelivered).toHaveLength(4)+ })++ it('a turn that could not be sealed at all is reported not delivered too', async () => {+ const { seal, link } = await lane()+ const undelivered: Array<Record<string, unknown>> = []+ link.onUndelivered((what) => { undelivered.push({ ...what }) })+ await link.online()+ seal.hello.mockRejectedValueOnce(new Error('the gateway could not start an E2EE session: it is not running'))+ await link.sendSealed({ type: 'message', machineId: LINKED, payload: { agentId: 'a1', content: 'x' } })+ expect(undelivered).toEqual([{ machineId: LINKED, type: 'message', agentId: 'a1' }])+ // The gateway lost the session as it sealed.+ await link.establish(LINKED)+ seal.seal.mockResolvedValueOnce({ lost: true })+ await link.sendSealed({ type: 'cancel', machineId: LINKED, payload: { agentId: 'a2' } })+ await until('the second report', () => undelivered.length === 2)+ expect(undelivered[1]).toEqual({ machineId: LINKED, type: 'cancel', agentId: 'a2' })+ })++ it('a refusal that lands while the new hello is out is about the old session, and kills nothing', async () => {+ let now = 1_000_000+ const { server, seal, link } = await lane({ welcome: false, now: () => now })+ await link.online()+ const first = link.establish(LINKED)+ await until('the hello', () => server.forMachines().some((frame) => frame.type === 'e2e_hello'))+ // Refusals of what the old session sealed come back before the welcome to the new hello.+ server.send({ type: 'e2e_session_unknown', machineId: LINKED, payload: { refused: { type: 'message', n: 7 } } })+ server.send({ type: 'e2e_welcome', machineId: LINKED, payload: { ephPub: 'E' } })+ await first+ expect(seal.drop).not.toHaveBeenCalled()+ // Once the session is up, a refusal is believed and drops it.+ server.send({ type: 'e2e_session_unknown', machineId: LINKED, payload: { refused: { type: 'message', n: 0 } } })+ await until('the drop', () => seal.drop.mock.calls.length === 1)+ // But another right after a forced drop waits for the limit: a relay repeating it cannot make re-handshakes cheap.+ const again = link.establish(LINKED)+ await until('the second hello', () => server.forMachines().filter((frame) => frame.type === 'e2e_hello').length === 2)+ server.send({ type: 'e2e_welcome', machineId: LINKED, payload: { ephPub: 'E' } })+ await again+ server.send({ type: 'e2e_session_unknown', machineId: LINKED, payload: { refused: { type: 'message', n: 0 } } })+ await new Promise((resolve) => setTimeout(resolve, 100))+ expect(seal.drop).toHaveBeenCalledTimes(1)+ // Half a minute on, it is believed again.+ now += 30_001+ server.send({ type: 'e2e_session_unknown', machineId: LINKED, payload: { refused: { type: 'message', n: 0 } } })+ await until('the second drop', () => seal.drop.mock.calls.length === 2)+ })++ it('a machine the backend says went offline loses its session at once; when it is back the next request says hello', async () => {+ const { server, seal, link, heard } = await lane()+ await link.online()+ await link.establish(LINKED)+ await link.establish(LINKED_2)+ const pending = link.rpc('agents_list', {}, LINKED)+ await until('the request', () => server.forMachines().some((frame) => frame.type === 'agents_list'))+ server.send({ type: 'node_status', machineId: LINKED, payload: { online: false } })+ await expect(pending).rejects.toThrow('E2EE_SESSION_GONE')+ expect(seal.drop).toHaveBeenCalledWith(LINKED)+ server.send({ type: 'node_status', machineId: LINKED, payload: { online: true } })+ // The fleet still hears both: they are the wheel's dots.+ await until('both statuses', () => heard.filter((frame) => frame.type === 'node_status').length === 2)+ const listed = link.rpc('agents_list', {}, LINKED)+ await until('the new hello', () => seal.hello.mock.calls.length === 3)+ await until('the request, sealed', () => seal.seal.mock.calls.filter(([m, frame]) => m === LINKED && frame.type === 'agents_list').length === 2)+ seal.open.mockResolvedValueOnce({ frame: { type: 'agents_list_result', machineId: LINKED, payload: { requestId: askedId(seal, LINKED, 'agents_list', 1), agents: [] } } })+ server.send({ type: 'agents_list_result', machineId: LINKED, payload: { __e2e: { n: 0 } } })+ expect(await listed).toMatchObject({ agents: [] })+ // The live machine list says the same for the other machine; a row still online changes nothing.+ server.send({ type: 'machines_status', payload: { statuses: [{ machineId: LINKED, online: true }, { machineId: LINKED_2, online: false }] } })+ await until('the second drop', () => seal.drop.mock.calls.length === 2)+ expect(seal.drop).toHaveBeenLastCalledWith(LINKED_2)+ })++ it('the restarted daemon\'s replay is held, a new session made by itself, and the replay read after its welcome, in order', async () => {+ const { server, seal, link, heard, lines } = await lane()+ await link.online()+ await link.establish(LINKED)+ // The first frame of the replay is sealed under the new process's epoch.+ seal.open.mockResolvedValueOnce({ unknownEpoch: true })+ server.send({ type: 'commander_question', machineId: LINKED, agentId: 'a1', payload: { __e2e: { n: 0, k: 'g' } } })+ server.send({ type: 'commander_event', machineId: LINKED, agentId: 'a1', payload: { __e2e: { n: 1, k: 'g' } } })+ await until('both, after the new welcome', () => heard.length === 2)+ expect(seal.hello).toHaveBeenCalledTimes(2)+ expect(seal.drop).toHaveBeenCalledWith(LINKED)+ expect(heard.map((frame) => frame.type)).toEqual(['commander_question', 'commander_event'])+ expect(heard[0].payload).toEqual({ opened: { n: 0, k: 'g' } })+ expect(lines.some((line) => line.includes(`${LINKED} restarted`))).toBe(true)+ expect(lines.some((line) => line.includes('could not decrypt'))).toBe(false)+ // A frame after them is read as before.+ server.send({ type: 'commander_event', machineId: LINKED, agentId: 'a1', payload: { __e2e: { n: 2, k: 'g' } } })+ await until('the third', () => heard.length === 3)+ })++ it('a sealed frame from a linked machine with no session is held and a session started for it', async () => {+ const { server, seal, link, heard } = await lane()+ await link.online()+ server.send({ type: 'commander_question', machineId: LINKED, agentId: 'a1', payload: { __e2e: { n: 0, k: 'g' } } })+ await until('the question, opened', () => heard.length === 1)+ expect(seal.hello).toHaveBeenCalledTimes(1)+ expect(heard[0]).toEqual({ type: 'commander_question', machineId: LINKED, agentId: 'a1', payload: { opened: { n: 0, k: 'g' } } })+ // A machine with no pinned key is not one this daemon makes sessions with: its frame passes as before.+ server.send({ type: 'commander_event', machineId: CLOUD, agentId: 'c1', payload: { __e2e: { n: 0, k: 'g' } } })+ await until('the cloud frame', () => heard.length === 2)+ expect(seal.hello).toHaveBeenCalledTimes(1)+ })++ it('a relay forging new epochs gets one new session per machine per half minute, and nothing it forged is read', async () => {+ let now = 1_000_000+ const { server, seal, link, heard, lines } = await lane({ now: () => now })+ await link.online()+ await link.establish(LINKED)+ seal.open.mockResolvedValue({ unknownEpoch: true })+ server.send({ type: 'commander_event', machineId: LINKED, agentId: 'a1', payload: { __e2e: { n: 0, k: 'g', epoch: 'forged-1' } } })+ await until('the one renewal', () => seal.hello.mock.calls.length === 2)+ // Under the new session it still does not open: thrown away, not held again, no third hello.+ await until('the forged frame dropped', () => lines.some((line) => line.includes('not from the session it renewed — dropped')))+ server.send({ type: 'commander_event', machineId: LINKED, agentId: 'a1', payload: { __e2e: { n: 1, k: 'g', epoch: 'forged-2' } } })+ server.send({ type: 'commander_event', machineId: LINKED, agentId: 'a1', payload: { __e2e: { n: 2, k: 'g', epoch: 'forged-3' } } })+ await until('the limit said', () => lines.filter((line) => line.includes('renewed its session moments ago — held')).length === 2)+ expect(seal.hello).toHaveBeenCalledTimes(2)+ expect(heard).toEqual([])+ now += 30_001+ server.send({ type: 'commander_event', machineId: LINKED, agentId: 'a1', payload: { __e2e: { n: 3, k: 'g', epoch: 'forged-4' } } })+ await until('one more renewal', () => seal.hello.mock.calls.length === 3)+ })++ it('never asks a linked machine in the clear: a request with no session up fails as session gone', async () => {+ // A machine linked between the handshake and the send (`harness link connect` runs as its own process):+ // establish() saw no pin and made no session, and the request must not go out unsealed.+ const linked = new Set<string>()+ const { server, seal, link } = await lane({ linked })+ await link.online()+ const peerAppears = vi.spyOn(link, 'establish').mockImplementationOnce(async () => { linked.add(LINKED) })+ await expect(link.rpc('agents_list', { scope: 'all' }, LINKED)).rejects.toThrow('E2EE_SESSION_GONE')+ peerAppears.mockRestore()+ await new Promise((resolve) => setTimeout(resolve, 50))+ expect(server.forMachines()).toEqual([])+ expect(seal.seal).not.toHaveBeenCalled()+ })++ it('access revoked mid-renewal: nothing held is read afterwards, and every waiting request fails at once', async () => {+ const { server, seal, link, heard } = await lane({ welcome: false })+ await link.online()+ server.send({ type: 'commander_question', machineId: LINKED, agentId: 'a1', payload: { __e2e: { n: 0, k: 'g' } } })+ await until('the renewal', () => seal.hello.mock.calls.length === 1)+ const pending = link.rpc('agents_list', {}, LINKED_2)+ pending.catch(() => {})+ await until('the other machine\'s hello', () => seal.hello.mock.calls.length === 2)+ server.send({ type: 'device_revoked', payload: {} })+ await expect(pending).rejects.toThrow()+ // A welcome that lands after the revocation opens nothing that was held before it.+ server.send({ type: 'e2e_welcome', machineId: LINKED, payload: { ephPub: 'E' } })+ await new Promise((resolve) => setTimeout(resolve, 100))+ expect(heard).toEqual([])+ expect(seal.open).not.toHaveBeenCalled()+ })++ it('a welcome no hello is waiting for is ignored: forged or replayed ones cannot drop a healthy session', async () => {+ // Security review 1 on #2356: three forged welcomes in 30 s cost three drops and four hellos.+ const { server, seal, link, lines } = await lane()+ await link.online()+ await link.establish(LINKED)+ seal.welcome.mockResolvedValue(false)+ for (let i = 0; i < 3; i++) server.send({ type: 'e2e_welcome', machineId: LINKED, payload: { ephPub: 'replayed' } })+ await until('the three said', () => lines.filter((line) => line.includes('no hello of this daemon is waiting')).length === 3)+ expect(seal.welcome).toHaveBeenCalledTimes(1)+ expect(seal.drop).not.toHaveBeenCalled()+ expect(seal.hello).toHaveBeenCalledTimes(1)+ // The session is still the one in use.+ await link.sendSealed({ type: 'message', machineId: LINKED, payload: { agentId: 'a1', content: 'still sealed' } })+ await until('the message', () => server.forMachines().some((frame) => frame.type === 'message'))+ expect(seal.hello).toHaveBeenCalledTimes(1)+ })++ it('while a hello waits, a welcome that does not verify is ignored, and the real one still brings the held replay', async () => {+ const { server, seal, link, heard, lines } = await lane({ welcome: false })+ await link.online()+ server.send({ type: 'commander_question', machineId: LINKED, agentId: 'a1', payload: { __e2e: { n: 0, k: 'g' } } })+ await until('the hello', () => seal.hello.mock.calls.length === 1)+ seal.welcome.mockResolvedValueOnce(false)+ server.send({ type: 'e2e_welcome', machineId: LINKED, payload: { ephPub: 'forged' } })+ await until('the forged one said', () => lines.some((line) => line.includes('does not verify')))+ expect(seal.drop).not.toHaveBeenCalled()+ server.send({ type: 'e2e_welcome', machineId: LINKED, payload: { ephPub: 'E' } })+ await until('the replay, read', () => heard.length === 1)+ expect(heard[0]).toMatchObject({ type: 'commander_question', payload: { opened: { n: 0, k: 'g' } } })+ expect(seal.hello).toHaveBeenCalledTimes(1)+ })++ it('an offline notice drops a machine\'s session at most once per half minute', async () => {+ let now = 1_000_000+ const { server, seal, link, lines } = await lane({ now: () => now })+ await link.online()+ await link.establish(LINKED)+ server.send({ type: 'node_status', machineId: LINKED, payload: { online: false } })+ await until('the drop', () => seal.drop.mock.calls.length === 1)+ await link.establish(LINKED)+ // Repeated at once (by the relay, or a flapping machine): the new session is kept.+ server.send({ type: 'node_status', machineId: LINKED, payload: { online: false } })+ server.send({ type: 'machines_status', payload: { statuses: [{ machineId: LINKED, online: false }] } })+ await until('the two said', () => lines.filter((line) => line.includes('reported offline again')).length === 2)+ expect(seal.drop).toHaveBeenCalledTimes(1)+ now += 30_001+ server.send({ type: 'node_status', machineId: LINKED, payload: { online: false } })+ await until('the second drop', () => seal.drop.mock.calls.length === 2)+ })++ it('counts the size cap in bytes as they came, not characters', async () => {+ const { server, link, lines } = await lane({ welcome: false })+ await link.online()+ // 300 Ki characters of a three-byte character: 900 KiB a frame, so two fit under 2 MiB.+ const wide = '€'.repeat(300 * 1024)+ for (let n = 0; n < 4; n++) server.send({ type: 'commander_event', machineId: LINKED, agentId: 'a1', payload: { __e2e: { n, k: 'g', ct: wide } } })+ await until('the excess said', () => lines.filter((line) => line.includes('held too much')).length === 2)+ })++ it('holds frames up to a size as well as a count', async () => {+ const { server, seal, link, heard, lines } = await lane({ welcome: false })+ await link.online()+ const big = 'x'.repeat(300 * 1024)+ for (let n = 0; n < 10; n++) server.send({ type: 'commander_event', machineId: LINKED, agentId: 'a1', payload: { __e2e: { n, k: 'g', ct: big } } })+ await until('the excess said', () => lines.filter((line) => line.includes('held too much')).length === 4)+ expect(seal.hello).toHaveBeenCalledTimes(1)+ server.send({ type: 'e2e_welcome', machineId: LINKED, payload: { ephPub: 'E' } })+ await until('the six held', () => heard.length === 6)+ })++ // Security review 2 on #2356.+ it('a refusal within the limit is still reported, and the session renewed once the limit allows', async () => {+ const { server, seal, link } = await lane({ renewEveryMs: 300 })+ const undelivered: Array<Record<string, unknown>> = []+ link.onUndelivered((what) => { undelivered.push({ ...what }) })+ await link.online()+ await link.sendSealed({ type: 'message', machineId: LINKED, payload: { agentId: 'a1', content: 'one' } })+ await until('the first', () => server.forMachines().filter((frame) => frame.type === 'message').length === 1)+ server.send({ type: 'e2e_session_unknown', machineId: LINKED, payload: { refused: { type: 'message', n: await sealedCounter(seal, LINKED, 'message') } } })+ await until('the first report', () => undelivered.length === 1)+ await link.sendSealed({ type: 'message', machineId: LINKED, payload: { agentId: 'a2', content: 'two' } })+ await until('the second', () => server.forMachines().filter((frame) => frame.type === 'message').length === 2)+ // Restarted again moments later: what it refused is reported at once, the drop waits for the limit.+ server.send({ type: 'e2e_session_unknown', machineId: LINKED, payload: { refused: { type: 'message', n: await sealedCounter(seal, LINKED, 'message', 1) } } })+ await until('the second report', () => undelivered.length === 2)+ expect(undelivered[1]).toEqual({ machineId: LINKED, type: 'message', agentId: 'a2' })+ expect(seal.drop).toHaveBeenCalledTimes(1)+ await until('the deferred drop', () => seal.drop.mock.calls.length === 2)+ await link.sendSealed({ type: 'message', machineId: LINKED, payload: { agentId: 'a3', content: 'three' } })+ await until('the third hello', () => seal.hello.mock.calls.length === 3)+ })++ it('a new epoch within the limit is held, not dropped, and read after the deferred renewal', async () => {+ const { server, seal, link, heard } = await lane({ renewEveryMs: 300 })+ await link.online()+ await link.establish(LINKED)+ seal.open.mockResolvedValueOnce({ unknownEpoch: true })+ server.send({ type: 'commander_question', machineId: LINKED, agentId: 'a1', payload: { __e2e: { n: 0, k: 'g' } } })+ await until('the first replay', () => heard.length === 1)+ expect(seal.hello).toHaveBeenCalledTimes(2)+ // A second restart inside the limit: its replay waits for the next renewal instead of being lost.+ seal.open.mockResolvedValueOnce({ unknownEpoch: true })+ server.send({ type: 'commander_question', machineId: LINKED, agentId: 'a2', payload: { __e2e: { n: 0, k: 'g' } } })+ await new Promise((resolve) => setTimeout(resolve, 50))+ expect(seal.hello).toHaveBeenCalledTimes(2)+ await until('the second replay', () => heard.length === 2)+ expect(seal.hello).toHaveBeenCalledTimes(3)+ expect(heard[1]).toMatchObject({ type: 'commander_question', agentId: 'a2' })+ })++ it('evicts held frames past their time when holding more, and drops them when the hello times out or is denied', async () => {+ let now = 1_000_000+ const { server, seal, link, lines } = await lane({ welcome: false, handshakeMs: 300, now: () => now })+ await link.online()+ for (let n = 0; n < 64; n++) server.send({ type: 'commander_event', machineId: LINKED, agentId: 'a1', payload: { __e2e: { n, k: 'g' } } })+ await until('the hello', () => seal.hello.mock.calls.length === 1)+ now += 31_000+ server.send({ type: 'commander_event', machineId: LINKED, agentId: 'a1', payload: { __e2e: { n: 64, k: 'g' } } })+ await until('the eviction said', () => lines.some((line) => line.includes('64 held frame(s) from linked-machine waited too long')))+ expect(lines.some((line) => line.includes('held too many'))).toBe(false)+ // The hello is never answered: what was held goes with it.+ await until('the timeout drop', () => lines.some((line) => line.includes('dropped 1 held frame(s) from linked-machine')))+ // Denied: held frames go too.+ now += 31_000+ server.send({ type: 'commander_event', machineId: LINKED_2, agentId: 'b1', payload: { __e2e: { n: 0, k: 'g' } } })+ await until('the second hello', () => seal.hello.mock.calls.length === 2)+ server.send({ type: 'e2e_denied', machineId: LINKED_2, payload: {} })+ await until('the denied drop', () => lines.some((line) => line.includes('dropped 1 held frame(s) from second-linked-machine')))+ })++ it('an offline notice during a renewal leaves the hello and what was held alone', async () => {+ const { server, seal, link, heard } = await lane({ welcome: false })+ await link.online()+ server.send({ type: 'commander_question', machineId: LINKED, agentId: 'a1', payload: { __e2e: { n: 0, k: 'g' } } })+ await until('the hello', () => seal.hello.mock.calls.length === 1)+ server.send({ type: 'node_status', machineId: LINKED, payload: { online: false } })+ await until('the notice passed on', () => heard.some((frame) => frame.type === 'node_status'))+ // The machine answers the hello when it is back: the replay is read.+ server.send({ type: 'e2e_welcome', machineId: LINKED, payload: { ephPub: 'E' } })+ await until('the held question', () => heard.some((frame) => frame.type === 'commander_question'))+ expect(heard.find((frame) => frame.type === 'commander_question')).toMatchObject({ agentId: 'a1' })+ expect(seal.drop).not.toHaveBeenCalled()+ expect(seal.hello).toHaveBeenCalledTimes(1)+ })++ it('reads the pinned keys once in a while for sealed frames from a machine it has no session with, not per frame', async () => {+ const { server, link, heard, peerReads } = await lane()+ await link.online()+ for (let n = 0; n < 20; n++) server.send({ type: 'commander_event', machineId: CLOUD, agentId: 'c1', payload: { __e2e: { n, k: 'g' } } })+ await until('the twenty', () => heard.length === 20)+ expect(peerReads.filter((machineId) => machineId === CLOUD).length).toBe(1)+ })++ it('holds a bounded number of frames, and none survive the lane stopping', async () => {+ const { server, seal, link, heard, lines } = await lane({ welcome: false })+ await link.online()+ for (let n = 0; n < 70; n++) server.send({ type: 'commander_event', machineId: LINKED, agentId: 'a1', payload: { __e2e: { n, k: 'g' } } })+ await until('the overflow said', () => lines.filter((line) => line.includes('held too many')).length === 6)+ expect(seal.hello).toHaveBeenCalledTimes(1)+ server.send({ type: 'e2e_welcome', machineId: LINKED, payload: { ephPub: 'E' } })+ await until('the 64 held', () => heard.length === 64)+ expect((heard[0].payload as { opened: { n: number } }).opened.n).toBe(0)+ // Held again, then the lane stops: nothing is read afterwards.+ seal.open.mockResolvedValueOnce({ unknownEpoch: true })+ server.send({ type: 'commander_event', machineId: LINKED, agentId: 'a1', payload: { __e2e: { n: 100, k: 'g' } } })+ await until('the renewal', () => seal.hello.mock.calls.length === 2)+ link.stop()+ await new Promise((resolve) => setTimeout(resolve, 50))+ expect(heard).toHaveLength(64)+ })+})diff --git a/cli/src/device/deviceLink.ts b/cli/src/device/deviceLink.tsindex 4d8d387eb..b1fd37721 100644--- a/cli/src/device/deviceLink.ts+++ b/cli/src/device/deviceLink.ts@@ -49,6 +49,35 @@ const PING_EVERY_MS = 15_000const BASE_DELAY_MS = 1_000const MAX_DELAY_MS = 30_000+/**+ * A machine's session is thrown away on the far side's word ("session unknown", a new epoch) at most this+ * often, and a session is started for frames nobody asked for at most this often. Both words come through+ * the relay, which end-to-end encryption does not trust: without a limit, repeating them would make every+ * frame cost a handshake. A far daemon restarting twice inside it is still caught by the next one.+ */+const RENEW_EVERY_MS = 30_000+/** After the far end refused this daemon's key, frames from it start no session for this long. */+const DENIED_QUIET_MS = 10 * 60_000+/** Frames held per machine while its session renews, and for how long. The restart replay is a few dozen. */+const HELD_MAX = 64+const HELD_TTL_MS = 30_000+/** And by size, in bytes as they came: the socket takes frames of any size, so a count alone would let a+ * relay park megabytes. */+const HELD_MAX_BYTES = 2 * 1024 * 1024+/** How long a machine's linked-or-not answer is kept for frames arriving with no session (see `linked`). */+const PEER_CACHE_MS = 5_000+/** What the person sent each machine, kept under its session so a refusal can name what was not delivered. */+const SENT_KEPT = 32+/** A refusal with no counter names what was sealed this recently. */+const SENT_RECENT_MS = 60_000+/** The frames that carry what the person said or chose: a turn, a stop, an answer. */+const DELIVERABLE = new Set(['message', 'cancel', 'question_response'])+/** The error a request gets when its machine's session goes before the answer came: never asked again. */+export const SESSION_GONE = 'E2EE_SESSION_GONE'++/** A turn, stop or answer that did not reach its machine, for the dial to say so (deviceFleet.ts). */+export interface Undelivered { machineId: string; type: string; agentId?: string; requestId?: string }+export type DeviceLinkStatus = 'idle' | 'connecting' | 'ready' | 'error'export interface DeviceLinkOpts {@@ -75,11 +104,20 @@ export interface DeviceLinkOpts {localMachineId: () => stringlog: (line: string) => void+ /** The clock, for the renewal limit. Tests only. */+ now?: () => number+ /** How long a hello waits for its welcome. Tests only; 15 s otherwise. */+ handshakeTimeoutMs?: number+ /** The per-machine limit on renewals and drops on another's word. Tests only; 30 s otherwise. */+ renewEveryMs?: number}/** The lane's side of a machine's E2EE session: whether it is up. Its keys are the gateway's. */interface LaneSession { ready: boolean }+/** What the person sent one session of a machine: each frame with the counter it was sealed under. */+interface SentUnder { session: LaneSession; frames: Array<{ n: number | null; frame: DeviceFrame; at: number }> }+export class DeviceLink {private ws: WebSocket | null = nullprivate attached = ''@@ -89,9 +127,11 @@ export class DeviceLink {private pingTimer: NodeJS.Timeout | null = nullprivate state: DeviceLinkStatus = 'idle'/** The dial is plugged in, so this socket should exist even with no machine selected. */- private held = false- private readonly pending = new Map<string, { resolve: (v: Record<string, unknown>) => void; reject: (e: Error) => void; timer: NodeJS.Timeout }>()+ private heldOpen = false+ /** Each request in flight, with the machine it asked: a session that goes fails only that machine's. */+ private readonly pending = new Map<string, { resolve: (v: Record<string, unknown>) => void; reject: (e: Error) => void; timer: NodeJS.Timeout; machineId: string }>()private readonly listeners = new Set<(frame: DeviceFrame) => void>()+ private readonly undeliveredListeners = new Set<(what: Undelivered) => void>()/** Resolves when `machine_selected` lands, so callers can await the attach rather than poll for it. */private selectWaiter: { resolve: () => void; reject: (e: Error) => void; timer: NodeJS.Timeout } | null = null/**@@ -118,10 +158,33 @@ export class DeviceLink {*/private outbound: Promise<void> = Promise.resolve()private inbound: Promise<void> = Promise.resolve()---- constructor(private readonly opts: DeviceLinkOpts) {}+ /**+ * Sealed frames from a machine that arrived while it had no session up, read once the next one is.+ *+ * THE RESTART REPLAY. A far daemon that comes back replays its agents and open questions at once, under+ * its new process's keys, before anything here knows it restarted. Dropped, those questions vanished+ * from the dial for good: the far side replays only when a commander joins, not when a session renews.+ */+ private readonly held = new Map<string, Array<{ frame: DeviceFrame; at: number; bytes: number }>>()+ /** When each machine's session was last thrown away on the far side's word, last started for a frame, and+ * last dropped on an offline notice: each limited per machine (RENEW_EVERY_MS). */+ private readonly renewedAt = new Map<string, number>()+ private readonly startedAt = new Map<string, number>()+ private readonly offlineAt = new Map<string, number>()+ /** A renewal the limit deferred, per machine: run once the limit allows, if the same session is still in use. */+ private readonly renewLater = new Map<string, NodeJS.Timeout>()+ /** Whether each machine is linked, read for frames that arrive with no session; kept a few seconds. */+ private readonly linkedCache = new Map<string, { linked: boolean; at: number }>()+ /** What the person sent under each machine's current session, and under the one before it. */+ private readonly sent = new Map<string, SentUnder>()+ private readonly sentBefore = new Map<string, SentUnder>()+ private readonly now: () => number+ private readonly renewEvery: number++ constructor(private readonly opts: DeviceLinkOpts) {+ this.now = opts.now ?? Date.now+ this.renewEvery = opts.renewEveryMs ?? RENEW_EVERY_MS+ }status(): DeviceLinkStatus { return this.state }get selectedMachine(): string { return this.attached }@@ -131,6 +194,12 @@ export class DeviceLink {return () => this.listeners.delete(cb)}+ /** Hear each turn, stop or answer that did not reach its machine. Returns how to stop hearing. */+ onUndelivered(cb: (what: Undelivered) => void): () => void {+ this.undeliveredListeners.add(cb)+ return () => this.undeliveredListeners.delete(cb)+ }+/*** Open the socket WITHOUT attaching to any machine, and start watching the machine list.*@@ -142,7 +211,7 @@ export class DeviceLink {* nobody is looking at.*/async online(): Promise<void> {- this.held = true+ this.heldOpen = trueawait this.connect()this.send({ type: 'machines_watch' })}@@ -181,10 +250,13 @@ export class DeviceLink {const session: LaneSession = { ready: false }this.sessions.set(machineId, session)const handshake = new Promise<void>((resolve, reject) => {+ // Unanswered (or answered only with welcomes that do not verify — see onWelcome): the session that+ // never came up is let go here and at the gateway, with whatever was held for it.const timer = setTimeout(() => {+ if (this.sessions.get(machineId) === session) { this.failCrypto(machineId, new Error('the machine did not answer the E2EE hello')); return }this.cryptoWaiters.delete(machineId)reject(new Error('the machine did not answer the E2EE hello'))- }, RPC_TIMEOUT_MS)+ }, this.opts.handshakeTimeoutMs ?? RPC_TIMEOUT_MS)this.cryptoWaiters.set(machineId, { resolve, reject, timer })// The gateway starts the session and words the hello. It goes in clear AND tagged: the backend routes// a device frame by its outer machineId, so without the tag the handshake for a background machine@@ -227,14 +299,86 @@ export class DeviceLink {resetSession(machineId: string): boolean {if (!machineId || this.handshakes.has(machineId)) return falseif (!this.sessions.has(machineId)) return false+ this.retire(machineId)this.sessions.delete(machineId)this.opts.seal.drop(machineId)return true}+ /**+ * A machine's session is gone, on the far side's word or the backend's: drop it here and at the gateway,+ * and fail at once every request still waiting on that machine (and only that machine). Their answers+ * would come under a session nobody holds any more, so each would otherwise wait out its 15 seconds, and+ * the agents list would read as empty meanwhile. A handshake in flight is the repair already under way+ * and is left alone, with what is held for it — an offline notice too: the hello is answered when the+ * machine is back, or times out (security review 2 on #2356: the notice can be the relay's).+ */+ private sessionGone(machineId: string): void {+ if (this.handshakes.has(machineId)) {+ // The repair already under way.+ } else if (this.sessions.has(machineId)) {+ this.retire(machineId)+ this.sessions.delete(machineId)+ this.opts.seal.drop(machineId)+ }+ for (const [requestId, waiter] of [...this.pending]) {+ if (waiter.machineId !== machineId) continue+ this.pending.delete(requestId)+ clearTimeout(waiter.timer)+ waiter.reject(new Error(SESSION_GONE))+ }+ }++ /** The backend says a machine went offline: its session goes, at most once per machine per RENEW_EVERY_MS. */+ private wentOffline(machineId: string): void {+ if (!this.sessions.has(machineId) && !this.hasPending(machineId)) return+ if (!this.allow(this.offlineAt, machineId)) {+ this.opts.log(`device: ${machineId} reported offline again moments after the last — its session is kept`)+ return+ }+ this.sessionGone(machineId)+ }++ private hasPending(machineId: string): boolean {+ for (const waiter of this.pending.values()) if (waiter.machineId === machineId) return true+ return false+ }++ /** What was sent under a machine's session, kept as "the one before" once that session goes. */+ private retire(machineId: string): void {+ const current = this.sent.get(machineId)+ if (current) this.sentBefore.set(machineId, current)+ this.sent.delete(machineId)+ }++ /** Whether the far side's word may throw away a machine's session now — see RENEW_EVERY_MS. */+ private mayRenew(machineId: string): boolean {+ return this.allow(this.renewedAt, machineId)+ }++ private allow(at: Map<string, number>, machineId: string): boolean {+ const now = this.now()+ const last = at.get(machineId)+ if (last !== undefined && now - last < this.renewEvery) return false+ at.set(machineId, now)+ return true+ }++ private undelivered(machineId: string, frame: DeviceFrame): void {+ const payload = (frame.payload ?? {}) as Record<string, unknown>+ const what: Undelivered = {+ machineId,+ type: String(frame.type ?? ''),+ ...(typeof payload.agentId === 'string' ? { agentId: payload.agentId } : {}),+ ...(typeof payload.requestId === 'string' ? { requestId: payload.requestId } : {}),+ }+ this.opts.log(`device: ${what.type} for ${machineId} was not delivered`)+ for (const cb of this.undeliveredListeners) cb(what)+ }+release(): void {this.wanted = ''- this.held = false+ this.heldOpen = falsethis.attached = ''if (this.ws?.readyState === WebSocket.OPEN) {this.send({ type: 'machine_deselect' })@@ -244,15 +388,21 @@ export class DeviceLink {stop(): void {this.wanted = ''- this.held = false+ this.heldOpen = falsethis.teardown('daemon stopping')}/** Fire-and-forget. Dropped with a line rather than thrown: a turn is not worth an unhandled rejection. */send(frame: DeviceFrame): void {+ this.enqueue(frame, false)+ }++ /** `deliverable`: the frame carries what the person said or chose, so a loss is reported, never silent. */+ private enqueue(frame: DeviceFrame, deliverable: boolean): void {const ws = this.wsif (ws?.readyState !== WebSocket.OPEN) {this.opts.log(`device: dropped ${frame.type ?? '?'} — no link`)+ if (deliverable) this.undelivered(frame.machineId || this.attached, frame)return}// Wrapped only once THAT MACHINE's session is up. `e2e_*` frames are the handshake itself and must go@@ -275,13 +425,16 @@ export class DeviceLink {if ('lost' in sealed) {this.forget(machineId, session)this.opts.log(`device: dropped ${frame.type ?? '?'} for ${machineId} — its E2EE session is gone`)+ if (deliverable) this.undelivered(machineId, frame)return}out = sealed.frame as DeviceFrame+ if (deliverable && session) this.noteSent(machineId, session, frame, out)}// The socket it was handed for: one closed meanwhile takes it with it, never the next connection.if (ws.readyState !== WebSocket.OPEN) {this.opts.log(`device: dropped ${frame.type ?? '?'} — no link`)+ if (deliverable) this.undelivered(machineId, frame)return}try { ws.send(JSON.stringify(out)) } catch (err) {@@ -292,7 +445,38 @@ export class DeviceLink {/** A session the gateway no longer holds (it restarted): forgotten here too, so the next call starts one. */private forget(machineId: string, session: LaneSession | undefined): void {- if (session && this.sessions.get(machineId) === session && !this.handshakes.has(machineId)) this.sessions.delete(machineId)+ if (session && this.sessions.get(machineId) === session && !this.handshakes.has(machineId)) {+ this.retire(machineId)+ this.sessions.delete(machineId)+ }+ }++ /** Keep a turn, stop or answer with the counter it went under, so a refusal of that counter can name it. */+ private noteSent(machineId: string, session: LaneSession, frame: DeviceFrame, sealed: DeviceFrame): void {+ let under = this.sent.get(machineId)+ if (under?.session !== session) {+ // Sealed under a session already replaced here: what it says belongs to that one, which is gone.+ if (this.sessions.get(machineId) !== session) return+ under = { session, frames: [] }+ this.sent.set(machineId, under)+ }+ const n = (sealed.payload as { __e2e?: { n?: unknown } } | undefined)?.__e2e?.n+ under.frames.push({ n: typeof n === 'number' ? n : null, frame, at: this.now() })+ if (under.frames.length > SENT_KEPT) under.frames.shift()+ }++ /**+ * The far end could not open what was sealed under `under`'s session from counter `n` on: it has no session+ * for this connection, so it opened NONE of them, and each turn, stop or answer among them is reported.+ * Reported, never sent again: the refusal is a clear frame that comes through the relay, and re-sending on+ * its word would let the relay replay a person's turn into a fresh session — a turn run twice.+ */+ private refused(machineId: string, under: SentUnder | undefined, n: number | null): void {+ if (!under) return+ const now = this.now()+ const lost = under.frames.filter((sent) => (n === null ? now - sent.at <= SENT_RECENT_MS : sent.n !== null && sent.n >= n))+ under.frames = under.frames.filter((sent) => !lost.includes(sent))+ for (const sent of lost) this.undelivered(machineId, sent.frame)}/**@@ -304,15 +488,18 @@ export class DeviceLink {* runs itself, where there is no daemon to seal for and plaintext is the only form it reads.*/async sendSealed(frame: DeviceFrame & { machineId: string }): Promise<void> {+ const deliverable = DELIVERABLE.has(String(frame.type ?? ''))try { await this.establish(frame.machineId) } catch (err) {this.opts.log(`device: dropped ${frame.type ?? '?'} for ${frame.machineId} — ${(err as Error).message}`)+ if (deliverable) this.undelivered(frame.machineId, frame)return}if (this.opts.peer(frame.machineId) && !this.sessions.get(frame.machineId)?.ready) {this.opts.log(`device: dropped ${frame.type ?? '?'} for ${frame.machineId} — no E2EE session`)+ if (deliverable) this.undelivered(frame.machineId, frame)return}- this.send(frame)+ this.enqueue(frame, deliverable)}/**@@ -325,6 +512,10 @@ export class DeviceLink {async rpc(type: string, payload: Record<string, unknown> = {}, machineId = ''): Promise<Record<string, unknown>> {if (this.ws?.readyState !== WebSocket.OPEN) throw new Error('not connected')if (machineId) await this.establish(machineId)+ // Never in the clear to a linked machine: `send()` seals only for a session that is up, and one can go+ // between the handshake and here (a refusal, an offline notice, a pin made meanwhile). Decided in the+ // same step as the send below, so nothing can change in between.+ if (machineId && this.opts.peer(machineId) && !this.sessions.get(machineId)?.ready) throw new Error(SESSION_GONE)const requestId = randomUUID()return new Promise<Record<string, unknown>>((resolve, reject) => {@@ -333,7 +524,7 @@ export class DeviceLink {this.opts.log(`device: ${type} timed out after ${RPC_TIMEOUT_MS} ms`)reject(new Error(`${type} timed out`))}, RPC_TIMEOUT_MS)- this.pending.set(requestId, { resolve, reject, timer })+ this.pending.set(requestId, { resolve, reject, timer, machineId: machineId || this.attached })this.send(machineId ? { type, machineId, payload: { ...payload, requestId } } : { type, payload: { ...payload, requestId } })})@@ -428,24 +619,101 @@ export class DeviceLink {})}+ /**+ * A welcome is read only while this daemon's hello for that machine waits for one.+ *+ * The relay can send any frame, including a replayed old welcome or garbage. Read against a session that+ * is up, one that did not verify used to throw the session away — and with it, after this lane began+ * holding frames, the restart replay — with no limit and no line (security review 1 on #2356: three+ * forged welcomes in 30 s cost three drops and four hellos). So one with no hello waiting is ignored, and+ * one that does not verify is ignored too: the hello waits on for the real one, or times out.+ */private async onWelcome(machineId: string, payload: Record<string, unknown>): Promise<void> {const session = this.sessions.get(machineId)- if (!session) return+ if (!session || session.ready || !this.cryptoWaiters.has(machineId)) {+ this.opts.log(`device: ignored an e2e_welcome from ${machineId || '?'} — no hello of this daemon is waiting for one`)+ return+ }const welcomed = await this.opts.seal.welcome(machineId, payload).catch(() => false)// Given up while the gateway read it (the socket closed, a reset): a newer session is not this one's.if (this.sessions.get(machineId) !== session) return- if (!welcomed) { this.failCrypto(machineId, new Error('E2EE_HANDSHAKE_FAILED')); return }+ if (!welcomed) {+ this.opts.log(`device: ignored an e2e_welcome from ${machineId} that does not verify — still waiting for the hello's own`)+ return+ }session.ready = trueconst waiter = this.cryptoWaiters.get(machineId)if (waiter) { clearTimeout(waiter.timer); this.cryptoWaiters.delete(machineId); waiter.resolve() }+ // Inside the inbound queue, so what was held is read before anything that came after the welcome.+ await this.drain(machineId, session)}private failCrypto(machineId: string, err: Error): void {+ if (this.sessions.get(machineId)) this.retire(machineId)if (this.sessions.delete(machineId)) this.opts.seal.drop(machineId)+ this.drop(machineId, 'its session could not be made')const waiter = this.cryptoWaiters.get(machineId)if (waiter) { clearTimeout(waiter.timer); this.cryptoWaiters.delete(machineId); waiter.reject(err) }}+ /**+ * Keep a sealed frame from a machine with no session up, and start one for it unless one is on its way.+ * `renewing`: the caller just threw the old session away for it, which was already limited.+ */+ private hold(machineId: string, frame: DeviceFrame, bytes: number, start: 'now' | 'limited' | 'never'): void {+ // Past their time first: a machine that starts no hello (denied, or limited) would otherwise keep them,+ // and the count and size caps would stay full of frames nobody will read.+ const now = this.now()+ const held = this.held.get(machineId) ?? []+ const list = held.filter((h) => now - h.at <= HELD_TTL_MS)+ if (list.length < held.length) this.opts.log(`device: ${held.length - list.length} held frame(s) from ${machineId} waited too long — dropped`)+ const total = list.reduce((sum, h) => sum + h.bytes, 0)+ if (list.length >= HELD_MAX) {+ this.opts.log(`device: held too many frames for ${machineId} while its session renews — dropped ${frame.type ?? '?'}`)+ } else if (total + bytes > HELD_MAX_BYTES) {+ this.opts.log(`device: held too much for ${machineId} while its session renews — dropped ${frame.type ?? '?'} (${bytes} bytes)`)+ } else {+ list.push({ frame, at: now, bytes })+ }+ if (list.length) this.held.set(machineId, list)+ else this.held.delete(machineId)+ if (start === 'never' || this.handshakes.has(machineId)) return+ if (start === 'limited' && !this.allow(this.startedAt, machineId)) return+ // Not awaited: its welcome comes through the very inbound queue this is running in.+ void this.establish(machineId).catch((err: unknown) => {+ this.opts.log(`device: could not renew the E2EE session with ${machineId} (${err instanceof Error ? err.message : String(err)})`)+ })+ }++ /** Read what was held for a machine under the session that just came up, in the order it arrived. */+ private async drain(machineId: string, session: LaneSession): Promise<void> {+ const list = this.held.get(machineId)+ if (!list) return+ this.held.delete(machineId)+ const now = this.now()+ for (const { frame, at } of list) {+ if (now - at > HELD_TTL_MS) { this.opts.log(`device: a held ${frame.type ?? '?'} from ${machineId} waited too long — dropped`); continue }+ // Given up while the gateway read the last one (the socket closed, a reset): a newer session is not this one's.+ if (this.sessions.get(machineId) !== session) return+ const opened = await this.opts.seal.open(machineId, frame as Record<string, unknown>).catch((): { lost: true } => ({ lost: true }))+ if (!('frame' in opened)) {+ // Still not readable under the session it renewed: stale, or forged by the relay. Never held again.+ this.opts.log(`device: a held ${frame.type ?? '?'} from ${machineId} is not from the session it renewed — dropped`)+ continue+ }+ this.route(opened.frame as DeviceFrame)+ }+ }++ /** Let go of what was held for a machine (or for all of them), saying so. */+ private drop(machineId: string | null, why: string): void {+ for (const [id, list] of [...this.held]) {+ if (machineId !== null && id !== machineId) continue+ this.held.delete(id)+ if (list.length) this.opts.log(`device: dropped ${list.length} held frame(s) from ${id} — ${why}`)+ }+ }+private armPing(): void {if (this.pingTimer) clearInterval(this.pingTimer)@@ -456,6 +724,8 @@ export class DeviceLink {private teardown(why: string): void {if (this.pingTimer) { clearInterval(this.pingTimer); this.pingTimer = null }+ for (const timer of this.renewLater.values()) clearTimeout(timer)+ this.renewLater.clear()if (this.reconnectTimer) { clearTimeout(this.reconnectTimer); this.reconnectTimer = null }for (const [, p] of this.pending) { clearTimeout(p.timer); p.reject(new Error(why)) }this.pending.clear()@@ -466,6 +736,10 @@ export class DeviceLink {for (const machineId of [...this.cryptoWaiters.keys(), ...this.sessions.keys()]) {this.failCrypto(machineId, new Error(why))}+ this.drop(null, why)+ // What was sent on this socket is unknowable now: none of it is named by a later refusal.+ this.sent.clear()+ this.sentBefore.clear()const ws = this.wsthis.ws = null@@ -477,9 +751,9 @@ export class DeviceLink {private onClose(code: number): void {this.opts.log(`device: closed (${code})`)const wanted = this.wanted- const held = this.held+ const heldOpen = this.heldOpenthis.teardown(`socket closed (${code})`)- if (!wanted && !held) return+ if (!wanted && !heldOpen) return// 401/403 after the one refresh above is a decision, not a hiccup: stop, and let the cabled machine// carry on. Clearing the session here is NOT this class's call — see rule 2 in the header.if (code === 4401 || code === 4403) {@@ -498,7 +772,9 @@ export class DeviceLink {private async onMessage(raw: WebSocket.RawData): Promise<void> {let frame: DeviceFrame- try { frame = JSON.parse(raw.toString()) as DeviceFrame } catch { return }+ const text = raw.toString()+ try { frame = JSON.parse(text) as DeviceFrame } catch { return }+ const bytes = Buffer.byteLength(text)// WHICH MACHINE THIS CAME FROM. The backend tags every commander frame with it (hub.ts// deliverUpLocal), and with N machines attached at once it is the only thing that says which key@@ -521,17 +797,33 @@ export class DeviceLink {// 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} — 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'))+ // Its frames start no session for a while: each would only be denied again.+ this.startedAt.set(from, this.now() + DENIED_QUIET_MS - this.renewEvery)return}+ if (frame.type === 'e2e_session_unknown') { if (from) this.onSessionUnknown(from, (frame.payload ?? {}) as Record<string, unknown>); return }const session = this.sessions.get(from)+ const wrapped = isWrapped(frame.payload)+ // Sealed by a linked machine while no session with it is up — after a drop, or before the first call:+ // held, and read once one is (see `held`).+ if (wrapped && from && !session?.ready && this.linked(from)) { this.hold(from, frame, bytes, 'limited'); return }// A frame that was never sealed (a control frame) is read as it is, as the session itself would read it// (lib/e2ee/relayClient.ts `unwrapIncoming`): only a sealed one goes to the gateway to be opened.- if (session?.ready && isWrapped(frame.payload)) {+ if (session?.ready && wrapped) {const opened = await this.opts.seal.open(from, frame as Record<string, unknown>).catch((): { lost: true } => ({ lost: true }))if ('lost' in opened) {+ // The gateway restarted under the lane and holds no session: kept, and read under the next one.this.forget(from, session)- this.opts.log(`device: could not decrypt ${frame.type ?? '?'} — the E2EE session with ${from} is gone, dropped`)+ this.opts.log(`device: could not decrypt ${frame.type ?? '?'} — the E2EE session with ${from} is gone, holding it for a new one`)+ this.hold(from, frame, bytes, 'limited')+ return+ }+ if ('unknownEpoch' in opened) {+ // The far daemon restarted: this is its replay, under keys of a process the session here never met.+ // Held either way: within the limit the renewal waits for it rather than losing the replay.+ this.hold(from, frame, bytes, 'never')+ this.renew(from, session, `${frame.type ?? '?'} names a new epoch`)return}if ('unreadable' in opened) {@@ -542,6 +834,78 @@ export class DeviceLink {}frame = opened.frame as DeviceFrame}+ this.route(frame)+ }++ /**+ * The far daemon says it holds no session for what this one sealed: it restarted, and opened none of it.+ *+ * Believed only for a session that is up and was not renewed moments ago. One that lands while a new hello+ * is out refused what the OLD session sealed — the far side answers in order, so its refusals of frames sent+ * before the hello come back before the welcome — and must not throw away the session being made; it still+ * names what the old session sent from the refused counter on.+ */+ private onSessionUnknown(from: string, payload: Record<string, unknown>): void {+ const refused = (payload.refused ?? {}) as { n?: unknown }+ const n = typeof refused.n === 'number' ? refused.n : null+ const session = this.sessions.get(from)+ if (!session?.ready || this.handshakes.has(from)) {+ this.refused(from, this.sentBefore.get(from), n)+ return+ }+ // What it names is reported whatever the limit says: the limit gates only the drop (review 2 on #2356).+ this.refused(from, this.sent.get(from), n)+ this.renew(from, session, 'it no longer knows this session')+ }++ /**+ * Throw a machine's session away on the far side's word and start a new one if anything is held for it:+ * now if the limit allows, else once it does — and then only if the same session is still the one in use,+ * so a renewal that happened meanwhile is not repeated.+ */+ private renew(machineId: string, session: LaneSession, why: string): void {+ if (this.mayRenew(machineId)) { this.renewNow(machineId, why); return }+ this.opts.log(`device: ${machineId}: ${why}, but it renewed its session moments ago — held until it may renew again`)+ if (this.renewLater.has(machineId)) return+ const wait = Math.max(0, this.renewEvery - (this.now() - (this.renewedAt.get(machineId) ?? 0)))+ const timer = setTimeout(() => {+ this.renewLater.delete(machineId)+ // In the inbound queue, so it lands between frames, never in the middle of one.+ this.inbound = this.inbound.then(() => {+ if (this.sessions.get(machineId) !== session || !session.ready) return+ if (this.mayRenew(machineId)) this.renewNow(machineId, why)+ })+ }, wait)+ timer.unref?.()+ this.renewLater.set(machineId, timer)+ }++ private renewNow(machineId: string, why: string): void {+ const later = this.renewLater.get(machineId)+ if (later) { clearTimeout(later); this.renewLater.delete(machineId) }+ this.opts.log(`device: ${machineId} restarted (${why}) — dropped its E2EE session, the next call says hello again`)+ this.sessionGone(machineId)+ if (this.held.get(machineId)?.length) {+ void this.establish(machineId).catch((err: unknown) => {+ this.opts.log(`device: could not renew the E2EE session with ${machineId} (${err instanceof Error ? err.message : String(err)})`)+ })+ }+ }++ /** Whether a machine is linked, for a sealed frame from one with no session: read fresh at most every few+ * seconds, not per frame (`peer()` reads the pinned keys from disk; review 2 on #2356). */+ private linked(machineId: string): boolean {+ const now = this.now()+ const cached = this.linkedCache.get(machineId)+ if (cached && now - cached.at >= 0 && now - cached.at < PEER_CACHE_MS) return cached.linked+ const linked = !!this.opts.peer(machineId)+ this.linkedCache.set(machineId, { linked, at: now })+ return linked+ }++ /** A frame read (opened, or never sealed): to its waiter, or to the listeners. */+ private route(frame: DeviceFrame): void {+ const from = typeof frame.machineId === 'string' ? frame.machineId : ''const type = frame.type ?? ''const payload = (frame.payload ?? {}) as Record<string, unknown>@@ -563,6 +927,16 @@ export class DeviceLink {this.teardown('revoked')return}+ // A machine the backend says went offline took its session with it: its daemon is gone or going, and the+ // one that comes back holds none. Dropped now, so the next call says hello instead of sealing for nobody.+ // Still passed on below: these are the wheel's dots. Limited per machine like every other drop on+ // another's word: the notice comes through the relay too, and repeated it would cost a hello each call.+ if (type === 'node_status' && from && payload.online === false) this.wentOffline(from)+ if (type === 'machines_status' && Array.isArray(payload.statuses)) {+ for (const row of payload.statuses as Array<{ machineId?: unknown; online?: unknown }>) {+ if (typeof row?.machineId === 'string' && row.machineId && row.online === false) this.wentOffline(row.machineId)+ }+ }if (type.endsWith('_result')) {const requestId = typeof payload.requestId === 'string' ? payload.requestId : ''diff --git a/cli/src/gateway/gatewayProcess.spec.ts b/cli/src/gateway/gatewayProcess.spec.tsindex a93313d9b..6495bfd3e 100644--- a/cli/src/gateway/gatewayProcess.spec.ts+++ b/cli/src/gateway/gatewayProcess.spec.ts@@ -320,6 +320,9 @@ describe('the gateway\'s process, spoken to by the core', () => {await lane.rekey('m2', { epoch: 'x' })expect(await lane.seal('m2', { type: 'message' })).toEqual({ frame: { type: 'message', sealed: true } })expect(await lane.open('m2', { type: 'message' })).toEqual({ unreadable: true })+ // The far daemon's new epoch crosses the process line as itself.+ w.gateways[0]!.ops.lane.open.mockResolvedValueOnce({ unknownEpoch: true } as never)+ expect(await lane.open('m2', { type: 'commander_question' })).toEqual({ unknownEpoch: true })lane.drop('m2')await Promise.resolve()const { ops } = w.gateways[0]diff --git a/cli/src/gateway/lane.spec.ts b/cli/src/gateway/lane.spec.tsindex b8bbd2aaf..c84f781b6 100644--- a/cli/src/gateway/lane.spec.ts+++ b/cli/src/gateway/lane.spec.ts@@ -107,6 +107,56 @@ describe('the fleet\'s lane, sealed by the gateway', () => {expect(await lane.open(MACHINE, { type: 'machine_selected', payload: { machineId: MACHINE } })).toEqual({ frame: { type: 'machine_selected', payload: { machineId: MACHINE } } })})+ it('tells a far daemon that restarted apart from a frame that does not open: a new epoch is unknown, an old one stale', async () => {+ // Diego, 10-30: every CLI release restarts the far daemon, which comes back with a new group key and+ // epoch and at once replays its agents and open questions under them. Read as "unreadable", 1,130 of+ // those were dropped in a day and the session kept, so the questions never reached this Mac.+ const { lane, far, welcome } = await welcomed()+ expect(await lane.welcome(MACHINE, welcome.payload as Frame)).toBe(true)+ const before = far.manager.wrapCommander({ type: 'commander_event', machineId: MACHINE, payload: { kind: 'done', text: 'before the restart' } })+ expect(await lane.open(MACHINE, before)).toEqual({ frame: expect.objectContaining({ payload: { kind: 'done', text: 'before the restart' } }) })+ // The far daemon restarts: the same identity on disk, a new process with its own epoch.+ const restarted = new E2eeManager({ machineId: MACHINE, sendTo: (_connId, frame) => { far.sent.push(frame) }, isConnected: () => true })+ const replay = restarted.wrapCommander({ type: 'commander_question', machineId: MACHINE, payload: { requestId: 'q1', questions: ['Ship it?'] } })+ expect(JSON.stringify(replay)).not.toContain('Ship it?')+ expect(await lane.open(MACHINE, replay)).toEqual({ unknownEpoch: true })+ // A garbled frame under the epoch the session holds is still only unreadable.+ const env = (before.payload as { __e2e: Record<string, unknown> }).__e2e+ expect(await lane.open(MACHINE, { ...before, payload: { __e2e: { ...env, n: 50, ct: 'AAAA' } } })).toEqual({ unreadable: true })+ // A new session with the restarted daemon opens its replay.+ const hello = await lane.hello(MACHINE, far.pub)+ restarted.handleFrame('device:lane-2', hello)+ const welcome2 = far.sent.filter((frame) => frame.type === 'e2e_welcome').at(-1)!+ expect(await lane.welcome(MACHINE, welcome2.payload as Frame)).toBe(true)+ expect(await lane.open(MACHINE, replay)).toEqual({ frame: expect.objectContaining({ type: 'commander_question', payload: { requestId: 'q1', questions: ['Ship it?'] } }) })+ // A late frame from the old process is stale, never unknown: it must not throw the new session away.+ const late = far.manager.wrapCommander({ type: 'commander_event', machineId: MACHINE, payload: { kind: 'done', text: 'late' } })+ expect(await lane.open(MACHINE, late)).toEqual({ unreadable: true })+ // Nor is one from an epoch the old session was rekeyed away from, or after the lane dropped the session.+ lane.drop(MACHINE)+ expect(await lane.open(MACHINE, late)).toEqual({ lost: true })+ })++ it('never opens a card twice across a renewal: what one session read, the next refuses as a replay', async () => {+ // Security review 2 on #2356: a relay can force a renewal (a made-up epoch, an offline notice) and then+ // replay an old question or turn card from the same far process; a new session that starts its group+ // counters from nothing would open it as new.+ const { lane, far, welcome } = await welcomed()+ expect(await lane.welcome(MACHINE, welcome.payload as Frame)).toBe(true)+ const card = far.manager.wrapCommander({ type: 'commander_question', machineId: MACHINE, payload: { requestId: 'q1', questions: ['Ship it?'] } })+ expect('frame' in await lane.open(MACHINE, card)).toBe(true)+ // Renewed with the same far process: the same group key and epoch come back in its welcome.+ lane.drop(MACHINE)+ const hello = await lane.hello(MACHINE, far.pub)+ far.manager.handleFrame('device:lane-2', hello)+ const welcome2 = far.sent.filter((frame) => frame.type === 'e2e_welcome').at(-1)!+ expect(await lane.welcome(MACHINE, welcome2.payload as Frame)).toBe(true)+ expect(await lane.open(MACHINE, card)).toEqual({ unreadable: true })+ // What the far process sends after the renewal is read as usual.+ const next = far.manager.wrapCommander({ type: 'commander_event', machineId: MACHINE, payload: { kind: 'done', text: 'after' } })+ expect('frame' in await lane.open(MACHINE, next)).toBe(true)+ })+it('takes the far machine\'s new keys, and a new hello replaces the session it had', async () => {const { lane, far, welcome, identity } = await welcomed()expect(await lane.welcome(MACHINE, welcome.payload as Frame)).toBe(true)diff --git a/cli/src/gateway/lane.ts b/cli/src/gateway/lane.tsindex 04856b9f9..a5621b261 100644--- a/cli/src/gateway/lane.ts+++ b/cli/src/gateway/lane.ts@@ -12,28 +12,54 @@*/import type { LaneOpened, LaneSeal, LaneSealed } from '../core/api.js'import { b64d, type Identity } from '../lib/e2ee/core.js'-import { RelaySessionCrypto } from '../lib/e2ee/relayClient.js'+import { GROUP_EPOCHS_KEPT, RelaySessionCrypto } from '../lib/e2ee/relayClient.js'type Frame = Record<string, unknown>export class LaneSessions implements LaneSeal {private readonly sessions = new Map<string, RelaySessionCrypto>()+ /**+ * Every group epoch a session with each machine has held, oldest first, kept past the session itself.+ *+ * WHY AN UNKNOWN EPOCH IS NOT "UNREADABLE". A far daemon that restarts (every CLI release updates it)+ * comes back with a new group key and epoch, and replays its agents and open questions under them at+ * once. The session here is with the process that is gone, so none of it opens — and read as merely+ * unreadable it was dropped and the session kept: 1,130 frames in a day on Diego's Mac, 9 bursts, each+ * a few minutes after a release, and the questions in them never shown. An epoch NO session here ever+ * held means the far process is new. One a session here did hold is a late frame from an old process+ * and stays unreadable: it must not throw away the session that replaced it.+ */+ private readonly epochs = new Map<string, string[]>()+ /**+ * Each machine's group counters (epoch → highest counter read), shared by every session with it, as the+ * windows' relay shares them (lib/remoteRelay.ts). A session that started from nothing would open again+ * a card an earlier session already read: a relay could force a renewal (a made-up epoch, an offline+ * notice) and then replay an old question or turn card from the same far process (security review 2+ * on #2356). Bounded per machine by the session (GROUP_EPOCHS_KEPT epochs).+ */+ private readonly groupSeen = new Map<string, Map<string, number>>()/** `identity` is read when a session starts: the one on disk, as the gateway's own store holds it. */constructor(private readonly identity: () => Identity) {}async hello(machineId: string, peerPub: string): Promise<Frame> {- const session = new RelaySessionCrypto({ machineId, selfIdentity: this.identity(), peerPub: b64d(peerPub) })+ let groupSeen = this.groupSeen.get(machineId)+ if (!groupSeen) { groupSeen = new Map(); this.groupSeen.set(machineId, groupSeen) }+ const session = new RelaySessionCrypto({ machineId, selfIdentity: this.identity(), peerPub: b64d(peerPub), groupSeen })this.sessions.set(machineId, session)return session.helloFrame()}async welcome(machineId: string, payload: Frame): Promise<boolean> {- return this.sessions.get(machineId)?.handleWelcome(payload) ?? false+ const session = this.sessions.get(machineId)+ if (!session?.handleWelcome(payload)) return false+ this.remember(machineId, session.groupEpoch)+ return true}async rekey(machineId: string, payload: Frame): Promise<void> {- this.sessions.get(machineId)?.handleRekey(payload)+ const session = this.sessions.get(machineId)+ if (session?.handleRekey(payload)) this.remember(machineId, session.groupEpoch)}async seal(machineId: string, frame: Frame): Promise<LaneSealed> {@@ -45,6 +71,9 @@ export class LaneSessions implements LaneSeal {async open(machineId: string, frame: Frame): Promise<LaneOpened> {const session = this.sessions.get(machineId)if (!session?.ready) return { lost: true }+ const env = (frame.payload as { __e2e?: { k?: unknown; epoch?: unknown } } | undefined)?.__e2e+ if (env?.k === 'g' && typeof env.epoch === 'string' && env.epoch !== session.groupEpoch+ && !this.epochs.get(machineId)?.includes(env.epoch)) return { unknownEpoch: true }const plain = session.unwrapIncoming(frame)return plain ? { frame: plain } : { unreadable: true }}@@ -56,5 +85,16 @@ export class LaneSessions implements LaneSeal {/** The gateway is stopping: every session goes with it. */clear(): void {this.sessions.clear()+ this.epochs.clear()+ this.groupSeen.clear()+ }++ private remember(machineId: string, epoch: string): void {+ const seen = this.epochs.get(machineId) ?? []+ if (!epoch || seen.includes(epoch)) return+ seen.push(epoch)+ // As many as a session keeps counters for (relayClient.ts): a few restarts' worth, the oldest let go.+ if (seen.length > GROUP_EPOCHS_KEPT) seen.shift()+ this.epochs.set(machineId, seen)}}diff --git a/cli/src/lib/e2ee/relayClient.ts b/cli/src/lib/e2ee/relayClient.tsindex 8596ed605..e6093f49f 100644--- a/cli/src/lib/e2ee/relayClient.ts+++ b/cli/src/lib/e2ee/relayClient.ts@@ -61,6 +61,8 @@ export class RelaySessionCrypto {}get ready(): boolean { return this.c2s !== null && this.s2c !== null }+ /** The far process's group-key epoch, as its welcome or its last rekey named it ('' before either). */+ get groupEpoch(): string { return this.epoch }get terminalP2pVersion(): number { return this.p2pVersion }get viewerForwardingVersion(): number { return this.viewerVersion }/** The daemon opens every sealed type and refuses STRICT_DOWN_TYPES unsealed (its welcome said so). */diff --git a/cli/src/services/fleet.spec.ts b/cli/src/services/fleet.spec.tsindex f0031336a..144a18bc1 100644--- a/cli/src/services/fleet.spec.ts+++ b/cli/src/services/fleet.spec.ts@@ -24,10 +24,12 @@ const lane = vi.hoisted(() => ({peers: new Map<string, { pub: string }>(),}))vi.mock('../device/deviceLink.js', () => ({+ SESSION_GONE: 'E2EE_SESSION_GONE',DeviceLink: class {selectedMachine = ''constructor(opts: DeviceLinkOpts) { lane.opts = opts }onFrame(cb: (frame: Record<string, unknown>) => void) { lane.frames = cb; return () => {} }+ onUndelivered() { return () => {} }stop() { lane.stop() }rpc(type: string) { return lane.rpc(type) }sendSealed(...args: unknown[]) { return lane.sendSealed(...(args as [])) }