Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(relay): freeze the E2EE handshake once ready + bind approval to the session's peer key
enes66ea49cd0914
diff --git a/src/main/remote/relay-host.test.ts b/src/main/remote/relay-host.test.tsindex 9fc8fa755..84e65f50c 100644--- a/src/main/remote/relay-host.test.ts+++ b/src/main/remote/relay-host.test.ts@@ -378,6 +378,24 @@ describe('relay host — nothing is served before mutual approval', () => {expect(s.opens).toEqual([])})+ it('a peer CAST before mutual approval is DROPPED (no dispatch, no sink, no presence)', async () => {+ // The req case is covered above; a cast has no id to answer, so the code silently drops it. Prove+ // it never reaches a handler: a pre-approval pty:write must not run a command on this machine.+ const casts: Array<[number, string]> = []+ platform.onWithSender('pty:write', (clientId: number, data: string) => casts.push([clientId, data]))+ const s = openHostAgainstFakeRelay() // E2EE is up, approval is NOT given+ expect(s.pending).toHaveLength(1)++ s.peerSendsTunnelText(JSON.stringify({ t: 'cast', method: 'pty:write', args: ['rm -rf ~\r'] }))+ await new Promise((r) => setTimeout(r, 20))++ expect(casts).toEqual([]) // never dispatched+ expect(s.session.clientId()).toBeNull()+ expect(peerRegistry().ids()).toEqual([])+ expect(presenceHub.peers()).toEqual([])+ expect(s.opens).toEqual([])+ })+it('ONE human confirming is not enough — the peer is still not a client', async () => {const s = openHostAgainstFakeRelay()s.session.confirm() // only this sidediff --git a/src/main/remote/relay-host.ts b/src/main/remote/relay-host.tsindex a169e1600..2ae4a59e5 100644--- a/src/main/remote/relay-host.ts+++ b/src/main/remote/relay-host.ts@@ -73,6 +73,15 @@ export function connectRelayHost(opts: ConnectRelayHostOptions): RelayHostSessiolet clientId: number | null = nulllet gate: TrustGate | null = nulllet closed = false+ // OBLIGATION (a) — defence in depth. The peer's ECDH public key at the moment the gate is created+ // (the same key `emptyMutualApproval` is seeded with, and whose shared secret produced the SAS the+ // humans compared). If the socket's live peer key ever diverges from this, the session key was+ // swapped under us (a mid-session re-key by a relay MITM) — we then refuse to advance approval,+ // dispatch peer traffic, or open the sink. relay-socket's layer-1 guard already prevents the swap;+ // this is the second, independent check so the property does not rest on that one guard.+ let sessionPeerKey: string | null = null+ // True once we have detected a key swap and cut the session, so we don't do it twice.+ let keySwapped = false/** The ONE teardown, mirroring src/server/ws.ts's close path exactly: `unregisterPeerSink` IS the* three steps (presenceHub.leave → onPeerGone → PtyManager.dropClient → registry prune). Do NOT@@ -97,9 +106,21 @@ export function connectRelayHost(opts: ConnectRelayHostOptions): RelayHostSessio}}+ /** The socket's live peer key still matches the one bound into the gate/approval state. A false+ * return means the session key was swapped under us — refuse everything and cut the session. */+ const peerKeyIntact = (): boolean => {+ if (keySwapped) return false+ if (sessionPeerKey !== null && socket.peerPublicKeyB64() === sessionPeerKey) return true+ keySwapped = true+ session.close()+ return false+ }+/** Both humans confirmed: the peer joins this core as a client. */const open = (): void => {if (closed || clientId !== null) return+ // The key that keyed this session must still be the original peer's (belt to layer-1's brace).+ if (!peerKeyIntact()) returnconst id = allocateRelayClientId()registerPeerSink(id, {// A DEAD socket must THROW (the registry evicts a sink after 2 consecutive throws and runs the@@ -138,6 +159,8 @@ export function connectRelayHost(opts: ConnectRelayHostOptions): RelayHostSessio// the other end is who we think. Serve nothing yet: build the gate and ask for the SAS.const peerKey = socket.peerPublicKeyB64()if (!peerKey || gate) return+ // Bind the session to THIS peer key. Every later approval/dispatch step re-asserts it.+ sessionPeerKey = peerKeygate = createTrustGate({peerKeyB64: peerKey,sessionId: `${peerKey}:${Date.now()}`, // obligation (b): ONE state per pairing attempt@@ -154,6 +177,10 @@ export function connectRelayHost(opts: ConnectRelayHostOptions): RelayHostSessioonTunnel: (kind, payload) => {// Binary peer→host frames are ignored: pty input rides JSON casts, exactly as on the WS.if (kind !== 'text') return+ // OBLIGATION (a) — before ANYTHING (advancing approval via the gate, or dispatching a peer+ // RPC/cast): the session key must still belong to the ORIGINAL peer. A tunnel frame that+ // decrypted under a swapped key must not advance confirmRemote or reach the core.+ if (!peerKeyIntact()) returnconst json = new TextDecoder().decode(payload)// Trust frames are consumed BEFORE dispatch and never reach the core.if (gate?.onTunnelText(json)) returndiff --git a/src/main/remote/relay-socket.test.ts b/src/main/remote/relay-socket.test.tsnew file mode 100644index 000000000..d1327b3fe--- /dev/null+++ b/src/main/remote/relay-socket.test.ts@@ -0,0 +1,131 @@+// Handshake state-machine safety for the relay socket (main process).+//+// The load-bearing property here is that the E2EE session's derived identity — the SAS the two+// humans compare and the peer public key the trust gate binds to — is FROZEN once the session is+// ready. A relay man-in-the-middle can put anything on the wire, including a second, plaintext+// `e2ee_hello` after the genuine handshake. Re-processing it would let the MITM re-key a LIVE+// session under its own keypair and then forge the second human's `trust:confirm` under the swapped+// key (see docs/remote-sessions.md, obligation (a)). This suite drives REAL relay sockets over an+// in-process transport that also models the relay's own injection capability.+import { describe, expect, it } from 'vitest'+import { connectRelay, type RelaySocket, type RelayTransport } from './relay-socket'+import { genKeyPair, publicKeyToB64, randomSessionNonce } from './e2ee'++// A pair of in-process transports wired host<->client, PLUS the relay's injection ports: the relay+// is untrusted and forwards opaque bytes, so it can also ORIGINATE traffic in either direction.+function makeTransportPair(): {+ host: RelayTransport+ client: RelayTransport+ injectToHost: (data: string | Uint8Array) => void+ injectToClient: (data: string | Uint8Array) => void+} {+ let hostOnMsg: ((d: unknown) => void) | null = null+ let clientOnMsg: ((d: unknown) => void) | null = null+ const host: RelayTransport = {+ bufferedAmount: 0,+ send: (d) => clientOnMsg?.(d),+ close: () => {},+ onMessage: (cb) => (hostOnMsg = cb),+ onClose: () => {}+ }+ const client: RelayTransport = {+ bufferedAmount: 0,+ send: (d) => hostOnMsg?.(d),+ close: () => {},+ onMessage: (cb) => (clientOnMsg = cb),+ onClose: () => {}+ }+ return {+ host,+ client,+ injectToHost: (d) => hostOnMsg?.(d),+ injectToClient: (d) => clientOnMsg?.(d)+ }+}++function readyPair(): {+ host: RelaySocket+ client: RelaySocket+ pair: ReturnType<typeof makeTransportPair>+ hostKeys: ReturnType<typeof genKeyPair>+ clientKeys: ReturnType<typeof genKeyPair>+} {+ const hostKeys = genKeyPair()+ const clientKeys = genKeyPair()+ const pair = makeTransportPair()+ let hostReady = false+ let clientReady = false+ const noop = (): void => {}+ const host = connectRelay({+ url: 'x',+ token: 't',+ role: 'host',+ ourKeys: hostKeys,+ transport: pair.host,+ onReady: () => (hostReady = true),+ onRpc: noop,+ onFrame: noop,+ onClose: noop+ })+ const client = connectRelay({+ url: 'x',+ token: 't',+ role: 'client',+ ourKeys: clientKeys,+ theirPubB64: publicKeyToB64(hostKeys.publicKey),+ transport: pair.client,+ onReady: () => (clientReady = true),+ onRpc: noop,+ onFrame: noop,+ onClose: noop+ })+ // The in-process handshake completes synchronously inside the second connectRelay.+ expect(hostReady && clientReady).toBe(true)+ return { host, client, pair, hostKeys, clientKeys }+}++describe('relay-socket: a handshake control frame after the session is READY is refused', () => {+ it('a post-ready plaintext e2ee_hello does NOT re-key the host (sas + peer key are frozen)', () => {+ const { host, pair, clientKeys } = readyPair()+ const attackerKeys = genKeyPair()++ const sasBefore = host.sas()+ const peerBefore = host.peerPublicKeyB64()+ expect(peerBefore).toBe(publicKeyToB64(clientKeys.publicKey)) // the REAL peer+ expect(sasBefore).toMatch(/^\d{3} \d{3}$/)++ // The MITM injects a fresh, well-formed e2ee_hello carrying the ATTACKER's keypair. On the+ // vulnerable code this re-derives baseKey/sessionKey and overwrites peerPubB64.+ const attackerHello = JSON.stringify({+ type: 'e2ee_hello',+ publicKeyB64: publicKeyToB64(attackerKeys.publicKey),+ nonceB64: Buffer.from(randomSessionNonce()).toString('base64')+ })+ pair.injectToHost(attackerHello)++ // Frozen: the live session's identity is unchanged, and in particular is NOT the attacker's.+ expect(host.peerPublicKeyB64()).toBe(peerBefore)+ expect(host.sas()).toBe(sasBefore)+ expect(host.peerPublicKeyB64()).not.toBe(publicKeyToB64(attackerKeys.publicKey))+ })++ it('a post-ready plaintext e2ee_ready does NOT re-key the client', () => {+ const { client, pair, hostKeys } = readyPair()+ const sasBefore = client.sas()+ const peerBefore = client.peerPublicKeyB64()+ expect(peerBefore).toBe(publicKeyToB64(hostKeys.publicKey))++ pair.injectToClient(+ JSON.stringify({ type: 'e2ee_ready', nonceB64: Buffer.from(randomSessionNonce()).toString('base64') })+ )++ expect(client.sas()).toBe(sasBefore)+ expect(client.peerPublicKeyB64()).toBe(peerBefore)+ })++ it('the genuine single handshake is unaffected (both ends reach ready and agree on the SAS)', () => {+ const { host, client } = readyPair()+ expect(host.sas()).toMatch(/^\d{3} \d{3}$/)+ expect(host.sas()).toBe(client.sas())+ })+})diff --git a/src/main/remote/relay-socket.ts b/src/main/remote/relay-socket.tsindex 5502ce6d0..3d4e3b05e 100644--- a/src/main/remote/relay-socket.ts+++ b/src/main/remote/relay-socket.ts@@ -348,6 +348,21 @@ export function connectRelay(opts: ConnectRelayOptions): RelaySocket {}function handleControl(raw: string): void {+ // SECURITY: a handshake control frame (`e2ee_hello` / `e2ee_ready`) is legitimate ONLY during the+ // one handshake, i.e. before the session goes ready. Once ready, re-processing one would let a+ // relay MITM RE-KEY a live session under its own keypair (re-deriving baseKey/sessionKey and+ // overwriting peerPubB64) and then forge the peer's encrypted `trust:confirm` under the swapped+ // key — degrading mutual approval to one-way (see docs/remote-sessions.md, obligation (a)). The+ // real peer never re-sends a hello on an established session, so such a frame is an attack or a+ // bug, never legitimate. Drop it WITHOUT re-keying: the derived session identity (SAS + peer key)+ // stays frozen. We do NOT close the socket — the relay already fully controls the transport+ // (it can drop us at will), so closing would add no real protection while handing a MITM a+ // trivial way to tear down an established, mutually-approved session with one plaintext frame.+ // Ignoring keeps the good session robust; layer 2 (relay-host key binding) independently+ // guarantees no traffic or approval can advance under a swapped key even if this check regressed.+ if (readyFired) {+ return+ }let control: HandshakeControltry {control = JSON.parse(raw) as HandshakeControldiff --git a/src/main/remote/relay-trust.test.ts b/src/main/remote/relay-trust.test.tsindex e56578c2e..cea1613fd 100644--- a/src/main/remote/relay-trust.test.ts+++ b/src/main/remote/relay-trust.test.ts@@ -4,7 +4,14 @@// it can inject anything it likes onto the wire, but it holds no session key.import { beforeEach, describe, expect, it, vi } from 'vitest'import { connectRelay, type RelaySocket, type RelayTransport } from './relay-socket'-import { genKeyPair, publicKeyToB64 } from './e2ee'+import {+ deriveSessionKey,+ deriveSharedKey,+ encrypt,+ genKeyPair,+ publicKeyToB64,+ randomSessionNonce+} from './e2ee'import { emptyApprovedDevices, type ApprovedDevices } from './approved-devices-core'import { TRUST_CONFIRM, createTrustGate, type TrustGate } from './relay-trust'@@ -187,6 +194,123 @@ describe('obligation (a): only the encrypted tunnel can confirm the peer', () =>expect(hostGate.sas()).toMatch(/^\d{3} \d{3}$/)expect(hostGate.sas()).toBe(peerGate.sas())})++ // The full attack obligation (a) exists to defeat: after the genuine handshake AND the host human's+ // confirm, a relay MITM injects a plaintext e2ee_hello to re-key the LIVE session under its own+ // keypair, then seals a trust:confirm under the swapped key. If the re-key were honoured, the box+ // would decrypt, reach confirmRemote, mutually approve, and pin — forging the second human's+ // consent. The MITM knows the host's session nonce (it saw e2ee_ready on the wire) and chooses its+ // own, so it can compute the exact key the host WOULD adopt.+ it('an attacker re-key + sealed trust:confirm does NOT confirm the peer or pin any key', async () => {+ const hostKeys = genKeyPair()+ const clientKeys = genKeyPair()+ const attackerKeys = genKeyPair()++ // Wire host<->client, capturing every frame the host emits (a real relay sees every byte).+ let hostOnMsg: ((d: unknown) => void) | null = null+ let clientOnMsg: ((d: unknown) => void) | null = null+ const hostEmitted: unknown[] = []+ const hostT: RelayTransport = {+ bufferedAmount: 0,+ send: (d) => {+ hostEmitted.push(d)+ clientOnMsg?.(d)+ },+ close: () => {},+ onMessage: (cb) => (hostOnMsg = cb),+ onClose: () => {}+ }+ const clientT: RelayTransport = {+ bufferedAmount: 0,+ send: (d) => hostOnMsg?.(d),+ close: () => {},+ onMessage: (cb) => (clientOnMsg = cb),+ onClose: () => {}+ }++ const opened: string[] = []+ let hostGate: TrustGate | null = null+ const hostSocket = connectRelay({+ url: 'x',+ token: 't',+ role: 'host',+ ourKeys: hostKeys,+ transport: hostT,+ onReady: () => {},+ onRpc: () => {},+ onFrame: () => {},+ onClose: () => {},+ onTunnel: (kind, payload) => {+ if (kind === 'text') hostGate?.onTunnelText(textDecoder.decode(payload))+ }+ })+ connectRelay({+ url: 'x',+ token: 't',+ role: 'client',+ ourKeys: clientKeys,+ theirPubB64: publicKeyToB64(hostKeys.publicKey),+ transport: clientT,+ onReady: () => {},+ onRpc: () => {},+ onFrame: () => {},+ onClose: () => {},+ onTunnel: () => {}+ })++ hostGate = createTrustGate({+ peerKeyB64: hostSocket.peerPublicKeyB64()!,+ sessionId: 'session-host',+ sas: () => hostSocket.sas(),+ sendConfirm: (json) => hostSocket.sendTunnelText(json),+ onOpen: () => opened.push('host')+ })++ hostGate.confirmHere() // the HOST human confirmed — only the second human's consent is missing++ // The MITM reads the host's own session nonce off the wire (from e2ee_ready).+ const readyFrame = hostEmitted+ .filter((f): f is string => typeof f === 'string')+ .map((s) => JSON.parse(s) as { type?: string; nonceB64?: string })+ .find((m) => m.type === 'e2ee_ready')+ expect(readyFrame?.nonceB64).toBeTruthy()+ const hostNonce = Uint8Array.from(Buffer.from(readyFrame!.nonceB64!, 'base64'))++ // 1. Re-key attempt: a plaintext e2ee_hello with the attacker's keypair.+ const attackerNonce = randomSessionNonce()+ hostOnMsg!(+ JSON.stringify({+ type: 'e2ee_hello',+ publicKeyB64: publicKeyToB64(attackerKeys.publicKey),+ nonceB64: Buffer.from(attackerNonce).toString('base64')+ })+ )++ // 2. Seal trust:confirm under the key the host WOULD derive from the attacker's hello. Plaintext+ // layout mirrors relay-socket withHeader+tagged: [role=2 (client)][seq:8 LE][TAG_TUNNEL_TEXT=3][json].+ const attackerBase = deriveSharedKey(publicKeyToB64(hostKeys.publicKey), attackerKeys.secretKey)+ const attackerSession = deriveSessionKey(attackerBase, hostNonce, attackerNonce)+ const jsonBytes = new TextEncoder().encode(confirmJson)+ const plain = new Uint8Array(1 + 8 + 1 + jsonBytes.length)+ plain[0] = 2 // PEER_ROLE from the host's perspective (client)+ const seq = 1000 // any value beyond the host's small handshake recvSeq+ const view = new DataView(plain.buffer)+ view.setUint32(1, Math.floor(seq / 0x100000000), true)+ view.setUint32(5, seq >>> 0, true)+ plain[9] = 0x03 // TAG_TUNNEL_TEXT+ plain.set(jsonBytes, 10)+ hostOnMsg!(encrypt(plain, attackerSession))++ await new Promise((r) => setTimeout(r, 20))++ // The forged confirm never landed: no mutual approval, no pin, and the session identity the two+ // humans compared is unchanged (still the real peer, never the attacker).+ expect(hostGate.isOpen()).toBe(false)+ expect(opened).toEqual([])+ expect((await loadApprovedDevices()).pubkeys).toEqual([])+ expect(hostSocket.peerPublicKeyB64()).toBe(publicKeyToB64(clientKeys.publicKey))+ expect(hostSocket.peerPublicKeyB64()).not.toBe(publicKeyToB64(attackerKeys.publicKey))+ })})describe('obligation (b): exactly one MutualApproval per pairing attempt', () => {