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
feat(relay): mutual approval driven only by the encrypted tunnel (obligation a)
enes0b78f2603e8d
diff --git a/src/main/remote/relay-trust.test.ts b/src/main/remote/relay-trust.test.tsnew file mode 100644index 000000000..e56578c2e--- /dev/null+++ b/src/main/remote/relay-trust.test.ts@@ -0,0 +1,258 @@+// The merge gate for obligation (a) of mutual-approval-core.ts: a peer's confirmation may ONLY+// arrive over the ENCRYPTED, session-keyed tunnel. These tests drive REAL relay sockets over+// in-process transports, so the forged-confirm test attacks the same code path a relay MITM has:+// 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 { emptyApprovedDevices, type ApprovedDevices } from './approved-devices-core'+import { TRUST_CONFIRM, createTrustGate, type TrustGate } from './relay-trust'++// The on-disk pin store, in memory. relay-trust's DEFAULT load/save are the electron-backed ones in+// ./approved-devices — mocking the module (rather than injecting fakes) means these tests exercise+// the production default path, not a test-only branch.+let disk: ApprovedDevices = emptyApprovedDevices()+vi.mock('./approved-devices', () => ({+ loadApprovedDevices: async () => disk,+ saveApprovedDevices: async (s: ApprovedDevices) => {+ disk = s+ }+}))+import { loadApprovedDevices } from './approved-devices'++beforeEach(() => {+ disk = emptyApprovedDevices()+})++// A pair of in-process transports wired host<->client, PLUS the relay's own injection ports: the+// relay is untrusted and forwards opaque bytes, so it can also *originate* traffic in either+// direction. `injectToHost` / `injectToClient` are that attacker capability.+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)+ }+}++const textDecoder = new TextDecoder()++// Two real relay sockets, each with a trust gate hung off its `onTunnel` — exactly the wiring the+// handshake must use: `onTunnelText` is reachable from nowhere else.+// `isolate` models the two ends as what they really are — two MACHINES with two pin stores. Left+// off (the default), both gates fall through to relay-trust's DEFAULT load/save (the production+// `./approved-devices` path, mocked to `disk`), which is what the forged-confirm merge gate must+// exercise: it has to prove that the real code path pins NOTHING.+function bridgedPair(isolate = false): {+ hostGate: TrustGate+ peerGate: TrustGate+ opened: string[]+ pair: ReturnType<typeof makeTransportPair>+ store: (end: 'host' | 'peer') => ApprovedDevices+} {+ const hostKeys = genKeyPair()+ const clientKeys = genKeyPair()+ const pair = makeTransportPair()+ const opened: string[] = []++ let hostGate: TrustGate | null = null+ let peerGate: TrustGate | null = null+ let hostReady = false+ let clientReady = false++ const hostSocket: RelaySocket = connectRelay({+ url: 'x',+ token: 't',+ role: 'host',+ ourKeys: hostKeys,+ transport: pair.host,+ onReady: () => (hostReady = true),+ onRpc: () => {},+ onFrame: () => {},+ onClose: () => {},+ onTunnel: (kind, payload) => {+ if (kind === 'text') hostGate?.onTunnelText(textDecoder.decode(payload))+ }+ })+ const clientSocket: RelaySocket = connectRelay({+ url: 'x',+ token: 't',+ role: 'client',+ ourKeys: clientKeys,+ theirPubB64: publicKeyToB64(hostKeys.publicKey),+ transport: pair.client,+ onReady: () => (clientReady = true),+ onRpc: () => {},+ onFrame: () => {},+ onClose: () => {},+ onTunnel: (kind, payload) => {+ if (kind === 'text') peerGate?.onTunnelText(textDecoder.decode(payload))+ }+ })+ // The in-process handshake completes synchronously inside the second connectRelay.+ expect(hostReady && clientReady).toBe(true)++ const stores: Record<'host' | 'peer', ApprovedDevices> = {+ host: emptyApprovedDevices(),+ peer: emptyApprovedDevices()+ }+ const gateFor = (socket: RelaySocket, tag: 'host' | 'peer'): TrustGate =>+ createTrustGate({+ peerKeyB64: socket.peerPublicKeyB64()!,+ sessionId: `session-${tag}`,+ sas: () => socket.sas(),+ sendConfirm: (json) => socket.sendTunnelText(json),+ onOpen: () => opened.push(tag),+ ...(isolate+ ? {+ load: async () => stores[tag],+ save: async (s: ApprovedDevices) => {+ stores[tag] = s+ }+ }+ : {})+ })+ hostGate = gateFor(hostSocket, 'host')+ peerGate = gateFor(clientSocket, 'peer')++ return { hostGate, peerGate, opened, pair, store: (end) => stores[end] }+}++const confirmJson = JSON.stringify({ t: 'cast', method: TRUST_CONFIRM, args: [] })++describe('obligation (a): only the encrypted tunnel can confirm the peer', () => {+ it('a forged PLAINTEXT confirm does not advance approval, does not open, pins nothing', async () => {+ const { hostGate, opened, pair } = bridgedPair()++ hostGate.confirmHere() // the local human confirms — one-way approval must NOT be enough++ // The MITM injects plaintext control frames that *look* like the peer's confirm, in every+ // dialect the code knows: the tunnel envelope, the legacy handshake shape, the hand-rolled+ // RPC envelope. None of them is sealed under the session key.+ pair.injectToHost(confirmJson)+ pair.injectToHost(JSON.stringify({ type: TRUST_CONFIRM }))+ pair.injectToHost(JSON.stringify({ kind: 'notify', method: TRUST_CONFIRM, params: {} }))+ pair.injectToHost(JSON.stringify({ kind: 'req', id: '1', method: TRUST_CONFIRM, params: {} }))+ // ...and raw bytes, which cannot decrypt.+ pair.injectToHost(new TextEncoder().encode(confirmJson))+ await new Promise((r) => setTimeout(r, 20))++ expect(hostGate.isOpen()).toBe(false) // approval did NOT advance+ expect(opened).toEqual([]) // no session opened+ expect((await loadApprovedDevices()).pubkeys).toEqual([]) // nothing pinned+ })++ it('a confirm that arrives over the ENCRYPTED tunnel does advance it (and pins, once)', async () => {+ const { hostGate, peerGate, opened, store } = bridgedPair(true)++ hostGate.confirmHere()+ expect(hostGate.isOpen()).toBe(false) // still waiting on the other human+ peerGate.confirmHere()++ await vi.waitFor(() => expect(hostGate.isOpen()).toBe(true))+ await vi.waitFor(() => expect(peerGate.isOpen()).toBe(true))+ expect(opened.sort()).toEqual(['host', 'peer'])+ // Each end pinned the OTHER end's key, in its own store, exactly once.+ await vi.waitFor(() => {+ expect(store('host').pubkeys).toEqual([hostGate.peerKeyB64()!])+ expect(store('peer').pubkeys).toEqual([peerGate.peerKeyB64()!])+ })+ expect(hostGate.peerKeyB64()).not.toBe(peerGate.peerKeyB64())+ })++ it('both ends see the same SAS (the digits the humans compare)', () => {+ const { hostGate, peerGate } = bridgedPair()+ expect(hostGate.sas()).toMatch(/^\d{3} \d{3}$/)+ expect(hostGate.sas()).toBe(peerGate.sas())+ })+})++describe('obligation (b): exactly one MutualApproval per pairing attempt', () => {+ it('a repeated remote confirm is idempotent and never stands in for the local one', () => {+ const sent: string[] = []+ const opened: string[] = []+ const gate = createTrustGate({+ peerKeyB64: 'PEER',+ sessionId: 's1',+ sas: () => '111 222',+ sendConfirm: (j) => sent.push(j),+ onOpen: () => opened.push('open'),+ load: async () => disk,+ save: async (s) => {+ disk = s+ }+ })++ expect(gate.onTunnelText(confirmJson)).toBe(true)+ expect(gate.onTunnelText(confirmJson)).toBe(true)+ expect(gate.isOpen()).toBe(false)+ expect(opened).toEqual([])+ expect(sent).toEqual([]) // we never echoed a confirm we did not make+ })++ it('ignores tunnel frames that are not a trust confirm (they stay available to the RPC dispatcher)', () => {+ const gate = createTrustGate({+ peerKeyB64: 'PEER',+ sessionId: 's1',+ sas: () => null,+ sendConfirm: () => {},+ onOpen: () => {},+ load: async () => disk,+ save: async (s) => {+ disk = s+ }+ })+ expect(gate.onTunnelText(JSON.stringify({ t: 'cast', method: 'pty.write', args: [] }))).toBe(false)+ expect(gate.onTunnelText(JSON.stringify({ t: 'req', id: 1, method: TRUST_CONFIRM, args: [] }))).toBe(+ false+ )+ expect(gate.onTunnelText('not json')).toBe(false)+ expect(gate.isOpen()).toBe(false)+ })++ it("a confirm delivered on session A's tunnel cannot advance session B's state", async () => {+ const a = bridgedPair()+ const b = bridgedPair()++ // Both humans on BOTH pairings pressed Confirm locally — only the remote half is missing.+ a.hostGate.confirmHere()+ b.hostGate.confirmHere()++ // Session A completes: its peer confirms over A's encrypted tunnel.+ a.peerGate.confirmHere()+ await vi.waitFor(() => expect(a.hostGate.isOpen()).toBe(true))++ // B's state is a DIFFERENT MutualApproval, bound to a different peer key + session. A's confirm+ // reached A's gate only; nothing routed it to B.+ expect(b.hostGate.isOpen()).toBe(false)+ expect(b.opened).toEqual([])+ expect((await loadApprovedDevices()).pubkeys).not.toContain(b.hostGate.peerKeyB64())++ // Even replayed verbatim onto B's WIRE, A's ciphertext does not decrypt under B's session key.+ b.pair.injectToHost(confirmJson)+ await new Promise((r) => setTimeout(r, 20))+ expect(b.hostGate.isOpen()).toBe(false)+ })+})diff --git a/src/main/remote/relay-trust.ts b/src/main/remote/relay-trust.tsnew file mode 100644index 000000000..2c5ae6337--- /dev/null+++ b/src/main/remote/relay-trust.ts@@ -0,0 +1,132 @@+// The connection-level trust gate: the ONE place a peer's confirmation is accepted.+//+// Stage 4 makes two desktops equal peers, which means a pairing GRANTS THE PEER SHELL ACCESS on this+// machine. The only thing standing between a relay man-in-the-middle and that shell is mutual+// approval: BOTH humans compare the same 6-digit SAS out of band and BOTH press Confirm. The pure+// latch is `mutual-approval-core.ts`; this file is the wiring it says it cannot enforce, and the+// wiring is where the property can be silently destroyed.+//+// SECURITY — obligation (a) of mutual-approval-core.ts: `onTunnelText` is called ONLY from+// `connectRelay`'s `onTunnel` callback (relay-socket.ts), which fires only for a payload that+// (1) DECRYPTED under THIS session's key (deriveSessionKey — fresh nonces both ways),+// (2) carried the PEER's role byte (so a relay cannot reflect our own confirm back at us), and+// (3) beat the per-direction monotonic replay counter.+// A plaintext frame from the relay reaches `handleControl` (which understands only `e2ee_hello` /+// `e2ee_ready`) and dies there; it can never reach this module. That is what makes `confirmRemote`+// proof that the REAL peer's human confirmed — and it is exactly what relay-trust.test.ts forges+// against. NEVER add a second call site for `confirmRemote`: not `onRpc`, not `onFrame`, not an IPC+// message from the renderer, not a plaintext handshake control. If a confirm can arrive any other+// way, mutual approval degrades back to ONE-WAY and the local human alone unlocks shell access while+// believing the remote human agreed. The SAS-mismatch backstop does NOT catch that (it catches key+// substitution, not a same-key relay forging the confirm DIRECTION).+//+// SECURITY — obligation (b): EXACTLY ONE `MutualApproval` per pairing attempt, seeded from THIS+// session's ECDH peer key (the key whose shared secret produced the SAS the humans compared). The+// state lives in this closure, is created once per gate, and each connection hangs its own gate off+// its own `onTunnel` — so a confirm arriving on session A's tunnel is physically unable to reach+// session B's state, and `recordApproval` can only ever pin the key bound into the state it is given.+import {+ confirmLocal,+ confirmRemote,+ emptyMutualApproval,+ isMutuallyApproved,+ recordApproval,+ type MutualApproval+} from './mutual-approval-core'+import { loadApprovedDevices, saveApprovedDevices } from './approved-devices'+import type { ApprovedDevices } from './approved-devices-core'+import { parseRpcMessage } from '../../shared/rpc'++/**+ * The ONLY remote-confirm signal, carried as an rpc.ts `cast` over the E2EE tunnel+ * (`RelaySocket.sendTunnelText` → TAG_TUNNEL_TEXT inside the box). It is deliberately NOT a method+ * of the peer RPC surface: a trust frame is consumed here and never forwarded to a dispatcher, so no+ * handler table can ever route a confirm.+ */+export const TRUST_CONFIRM = 'trust:confirm'++export interface TrustGate {+ /** SAS both humans compare ("NNN NNN"), or null before the key is derived. */+ sas(): string | null+ /** This human pressed Confirm. Latches localConfirmed and tells the peer over the tunnel. */+ confirmHere(): void+ /**+ * A TEXT frame arrived on the ENCRYPTED tunnel. Returns true when it was a trust frame (and was+ * therefore consumed — never forward it on to the RPC dispatcher). Anything that is not+ * `{t:'cast', method:'trust:confirm'}` is ignored and returns false.+ *+ * Call this ONLY from `connectRelay`'s `onTunnel`. See the SECURITY block above.+ */+ onTunnelText(json: string): boolean+ /** Both humans confirmed → the peer's key is pinned and the session may open. */+ isOpen(): boolean+ /** The peer's stable box public key (base64) this gate is bound to. */+ peerKeyB64(): string | null+}++export interface TrustGateOptions {+ /** The peer's stable box public key from THIS session's ECDH (`RelaySocket.peerPublicKeyB64()`). */+ peerKeyB64: string+ /** Identity of this pairing attempt. */+ sessionId: string+ /**+ * THIS session's SAS. Pass `socket.sas()` (`sasFromSharedKey(baseKey)`, the function `mutualSas`+ * aliases), NOT a value derived anywhere else: the digits the two humans compare must come from+ * the same ECDH shared secret that keys this connection.+ */+ sas: () => string | null+ /** Send our own confirm to the peer — MUST be `socket.sendTunnelText` (encrypted). */+ sendConfirm: (json: string) => void+ /** Fires exactly once, when both sides have confirmed: the session may open. */+ onOpen: () => void+ load?: () => Promise<ApprovedDevices>+ save?: (s: ApprovedDevices) => Promise<void>+}++export function createTrustGate(opts: TrustGateOptions): TrustGate {+ // Obligation (b): ONE state per pairing attempt, bound to THIS session's ECDH peer key.+ let state: MutualApproval = emptyMutualApproval(opts.peerKeyB64, opts.sessionId)+ let opened = false++ const settle = (): void => {+ if (opened || !isMutuallyApproved(state)) {+ return+ }+ opened = true+ const pinned = state+ void (async () => {+ // Pin FIRST (recordApproval refuses unless BOTH confirmed, and pins only the key carried by+ // the state), then open. A failed write must not strand a session both humans confirmed —+ // it only means the next connect asks for the SAS again, which is the safe direction.+ const load = opts.load ?? loadApprovedDevices+ const save = opts.save ?? saveApprovedDevices+ try {+ await save(recordApproval(await load(), pinned))+ } catch {+ // Persisting the pin is best-effort; consent for THIS session is already mutual.+ }+ opts.onOpen()+ })()+ }++ return {+ sas: () => opts.sas(),+ confirmHere() {+ state = confirmLocal(state)+ // Tell the peer over the ENCRYPTED tunnel. This is the only confirm we ever send.+ opts.sendConfirm(JSON.stringify({ t: 'cast', method: TRUST_CONFIRM, args: [] }))+ settle()+ },+ onTunnelText(json) {+ const m = parseRpcMessage(json)+ if (!m || m.t !== 'cast' || m.method !== TRUST_CONFIRM) {+ return false+ }+ state = confirmRemote(state)+ settle()+ return true // consumed: a trust frame is NEVER forwarded to the RPC dispatcher+ },+ isOpen: () => opened,+ peerKeyB64: () => opts.peerKeyB64+ }+}