Skip to content

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.

feat(relay): core trust gate with injected pins and auto-approve

review039b65e60f3c
diff --git a/src/core/relay/relay-trust.core.test.ts b/src/core/relay/relay-trust.core.test.ts
new file mode 100644
index 000000000..883d03837
--- /dev/null
+++ b/src/core/relay/relay-trust.core.test.ts
@@ -0,0 +1,111 @@
+// src/core/relay/relay-trust.core.test.ts
+import { describe, it, expect, vi } from 'vitest'
+import { createTrustGate, TRUST_CONFIRM, deniedFrame, parseDenied } from './relay-trust'
+
+function pair(opts: { hostAuto?: boolean; peerAuto?: boolean } = {}) {
+ const opened: string[] = []
+ const recorded: string[] = []
+ let host!: ReturnType<typeof createTrustGate>
+ let peer!: ReturnType<typeof createTrustGate>
+ const toPeer: string[] = []
+ const toHost: string[] = []
+ host = createTrustGate({
+ peerKeyB64: 'PEER', sessionId: 's1', sas: () => '123 456',
+ sendConfirm: (j) => toPeer.push(j), onOpen: () => opened.push('host'),
+ pins: { record: async (s) => { recorded.push(s.peerKeyB64) } },
+ autoApprove: opts.hostAuto
+ })
+ peer = createTrustGate({
+ peerKeyB64: 'HOST', sessionId: 's1', sas: () => '123 456',
+ sendConfirm: (j) => toHost.push(j), onOpen: () => opened.push('peer'),
+ autoApprove: opts.peerAuto
+ })
+ const flush = () => {
+ for (const j of toPeer.splice(0)) peer.onTunnelText(j)
+ for (const j of toHost.splice(0)) host.onTunnelText(j)
+ }
+ return { host, peer, opened, recorded, flush }
+}
+
+describe('core trust gate', () => {
+ it('autoApprove on BOTH ends opens with no human', async () => {
+ const t = pair({ hostAuto: true, peerAuto: true })
+ t.flush()
+ await vi.waitFor(() => expect(t.opened.sort()).toEqual(['host', 'peer']))
+ expect(t.recorded).toEqual(['PEER'])
+ })
+
+ it('autoApprove on one end only still waits for the other human', async () => {
+ const t = pair({ hostAuto: true })
+ t.flush()
+ await new Promise((r) => setTimeout(r, 10))
+ expect(t.opened).toEqual([])
+ t.peer.confirmHere()
+ t.flush()
+ await vi.waitFor(() => expect(t.opened.sort()).toEqual(['host', 'peer']))
+ })
+
+ it('without autoApprove nothing is sent at construction (byte-identical legacy)', () => {
+ const sent: string[] = []
+ createTrustGate({ peerKeyB64: 'P', sessionId: 's', sas: () => null, sendConfirm: (j) => sent.push(j), onOpen: () => {} })
+ expect(sent).toEqual([])
+ })
+
+ it('a failing pin store never strands a mutually-approved session', async () => {
+ const opened: string[] = []
+ const g = createTrustGate({
+ peerKeyB64: 'P', sessionId: 's', sas: () => null, sendConfirm: () => {},
+ onOpen: () => opened.push('x'), pins: { record: async () => { throw new Error('disk') } }
+ })
+ g.confirmHere()
+ g.onTunnelText(JSON.stringify({ t: 'cast', method: TRUST_CONFIRM, args: [] }))
+ await vi.waitFor(() => expect(opened).toEqual(['x']))
+ })
+
+ it('isOpen() stays false while the pin write is in flight, and agrees with onOpen after', async () => {
+ let finishPin!: () => void
+ const opened: string[] = []
+ const g = createTrustGate({
+ peerKeyB64: 'P', sessionId: 's', sas: () => null, sendConfirm: () => {},
+ onOpen: () => opened.push('x'),
+ pins: { record: () => new Promise<void>((r) => { finishPin = r }) }
+ })
+ g.confirmHere()
+ g.onTunnelText(JSON.stringify({ t: 'cast', method: TRUST_CONFIRM, args: [] }))
+ await new Promise((r) => setTimeout(r, 10))
+ expect(g.isOpen()).toBe(false)
+ expect(opened).toEqual([])
+ finishPin()
+ await vi.waitFor(() => expect(g.isOpen()).toBe(true))
+ expect(opened).toEqual(['x'])
+ })
+
+ it('opens exactly once, however many confirms arrive', async () => {
+ let records = 0
+ const opened: string[] = []
+ const g = createTrustGate({
+ peerKeyB64: 'P', sessionId: 's', sas: () => null, sendConfirm: () => {},
+ onOpen: () => opened.push('x'), pins: { record: async () => { records++ } }
+ })
+ const confirm = JSON.stringify({ t: 'cast', method: TRUST_CONFIRM, args: [] })
+ g.confirmHere()
+ g.onTunnelText(confirm)
+ g.onTunnelText(confirm)
+ g.confirmHere()
+ await vi.waitFor(() => expect(opened).toEqual(['x']))
+ await new Promise((r) => setTimeout(r, 10))
+ expect(opened).toEqual(['x'])
+ expect(records).toBe(1)
+ })
+
+ it('a denial frame is not a trust frame: the gate does not consume it', () => {
+ const g = createTrustGate({ peerKeyB64: 'P', sessionId: 's', sas: () => null, sendConfirm: () => {}, onOpen: () => {} })
+ expect(g.onTunnelText(deniedFrame('denied'))).toBe(false)
+ })
+
+ it('denied frames round-trip and anything else is not a denial', () => {
+ expect(parseDenied(deniedFrame('removed'))).toBe('removed')
+ expect(parseDenied(JSON.stringify({ t: 'cast', method: 'trust:denied', args: ['bogus'] }))).toBeNull()
+ expect(parseDenied(JSON.stringify({ t: 'cast', method: TRUST_CONFIRM, args: [] }))).toBeNull()
+ })
+})
diff --git a/src/core/relay/relay-trust.ts b/src/core/relay/relay-trust.ts
new file mode 100644
index 000000000..26fad8a5e
--- /dev/null
+++ b/src/core/relay/relay-trust.ts
@@ -0,0 +1,179 @@
+// 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.
+//
+// LOCAL confirms have exactly three call sites: `confirmHere()` from the desktop dialog
+// (`relay:host:confirm`), `autoApprove` for a pinned key, and the hosted owner's
+// `relay:hosted:approve`. A fourth is a design change.
+import {
+ confirmLocal,
+ confirmRemote,
+ emptyMutualApproval,
+ isMutuallyApproved,
+ type MutualApproval
+} from './mutual-approval-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'
+
+/**
+ * A host's refusal, sent over the ENCRYPTED tunnel right before it closes a peer it will not serve.
+ * It is NOT a trust frame: the gate never consumes it (`onTunnelText` returns false for it) and it
+ * can never advance approval — it only tells the peer WHY the connection is about to end.
+ */
+export const TRUST_DENIED = 'trust:denied'
+
+export type TrustDeniedReason = 'denied' | 'removed' | 'expired'
+const DENIED_REASONS: readonly TrustDeniedReason[] = ['denied', 'removed', 'expired']
+
+export interface PinStore {
+ /** Persist the approval. Called once, only after BOTH ends confirmed; failures are swallowed. */
+ record(state: MutualApproval): Promise<void>
+}
+
+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 pin attempt has settled and `onOpen` has fired. True exactly when
+ * `onOpen` has run: never while the pin write is still in flight.
+ */
+ 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
+ /** Where a mutual approval is pinned. Absent = pin nothing (the session still opens). */
+ pins?: PinStore
+ /**
+ * Latch the LOCAL confirm at construction (and send it to the peer) — for a key this end already
+ * trusts. It never touches the REMOTE half: the peer's human (or the peer's own pin) must still
+ * confirm over the encrypted tunnel before anything opens. Absent/false = byte-identical legacy
+ * behavior (nothing is sent until `confirmHere()`).
+ */
+ autoApprove?: boolean
+}
+
+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)
+ // Two flags, deliberately: `approved` latches synchronously the moment BOTH confirms are in (so the
+ // pin-then-open sequence runs exactly once), while `opened` flips only when that sequence ends and
+ // `onOpen` fires. `isOpen()` reads `opened`, so it can never report an open session whose pin
+ // write is still in flight or whose `onOpen` has not run — it and `onOpen` agree by construction,
+ // whatever the pin store's microtask depth.
+ let approved = false
+ let opened = false
+
+ const settle = (): void => {
+ if (approved || !isMutuallyApproved(state)) {
+ return
+ }
+ approved = true
+ const pinned = state
+ void (async () => {
+ // Pin FIRST (the store is handed only a state in which BOTH confirmed, carrying only the key
+ // bound into it), 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.
+ try {
+ await opts.pins?.record(pinned)
+ } catch {
+ // Persisting the pin is best-effort; consent for THIS session is already mutual.
+ }
+ opened = true
+ opts.onOpen()
+ })()
+ }
+
+ const gate: TrustGate = {
+ 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
+ }
+ // A fresh state has no remote confirm, so this can never open the gate by itself.
+ if (opts.autoApprove) gate.confirmHere()
+ return gate
+}
+
+/** The cast a host sends over the ENCRYPTED tunnel right before closing a refused peer. */
+export function deniedFrame(reason: TrustDeniedReason): string {
+ return JSON.stringify({ t: 'cast', method: TRUST_DENIED, args: [reason] })
+}
+
+/** A denial reason, or null for anything that is not a well-formed denial. */
+export function parseDenied(json: string): TrustDeniedReason | null {
+ const m = parseRpcMessage(json)
+ if (!m || m.t !== 'cast' || m.method !== TRUST_DENIED) return null
+ const r = m.args[0]
+ return (DENIED_REASONS as readonly unknown[]).includes(r) ? (r as TrustDeniedReason) : null
+}
diff --git a/src/main/remote/relay-trust.ts b/src/main/remote/relay-trust.ts
index 7ba1f371c..d768da9b0 100644
--- a/src/main/remote/relay-trust.ts
+++ b/src/main/remote/relay-trust.ts
@@ -1,133 +1,45 @@
-// 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.
+// The desktop trust gate: a thin wrapper over the core gate (src/core/relay/relay-trust.ts), which
+// holds the whole mechanism and its SECURITY obligations (a) and (b) — read them there before
+// touching any call site. The only thing this layer adds is WHERE a mutual approval is pinned: the
+// desktop's approved-devices store, exactly as before the gate moved to core (docs/hosted-team-relay.md).
import {
- confirmLocal,
- confirmRemote,
- emptyMutualApproval,
- isMutuallyApproved,
- recordApproval,
- type MutualApproval
-} from './mutual-approval-core'
+ createTrustGate as createCoreTrustGate,
+ TRUST_CONFIRM,
+ TRUST_DENIED,
+ deniedFrame,
+ parseDenied,
+ type TrustGate,
+ type TrustGateOptions as CoreTrustGateOptions,
+ type TrustDeniedReason
+} from '../../core/relay/relay-trust'
+import { recordApproval } from '../../core/relay/mutual-approval-core'
import { loadApprovedDevices, saveApprovedDevices, updateApprovedDevices } 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 { TRUST_CONFIRM, TRUST_DENIED, deniedFrame, parseDenied, type TrustGate, type TrustDeniedReason }
-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
+export interface TrustGateOptions extends Omit<CoreTrustGateOptions, 'pins'> {
load?: () => Promise<ApprovedDevices>
save?: (s: ApprovedDevices) => Promise<void>
}
+/** Desktop trust gate: pins go to the phone/desktop approved-devices store, exactly as before. */
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 {
- if (opts.load || opts.save) await save(recordApproval(await load(), pinned))
- else await updateApprovedDevices((store) => recordApproval(store, pinned))
- } catch {
- // Persisting the pin is best-effort; consent for THIS session is already mutual.
+ const { load, save, ...rest } = opts
+ return createCoreTrustGate({
+ ...rest,
+ pins: {
+ // recordApproval refuses unless BOTH confirmed, and pins only the key carried by the state.
+ // Injected load/save keep their read-then-write path; the default goes through the serialized
+ // updateApprovedDevices queue, so concurrent approvals never lose pins and a racing revoke is
+ // never undone from a stale snapshot.
+ async record(pinned) {
+ if (load || save) {
+ await (save ?? saveApprovedDevices)(recordApproval(await (load ?? loadApprovedDevices)(), pinned))
+ } else {
+ await updateApprovedDevices((store) => recordApproval(store, pinned))
+ }
}
- 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
- }
+ }
+ })
}