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 relay host and client with a peer-attach seam, hooks and deny()

review66df372db7a6
diff --git a/src/core/relay/relay-client.ts b/src/core/relay/relay-client.ts
new file mode 100644
index 000000000..46619799e
--- /dev/null
+++ b/src/core/relay/relay-client.ts
@@ -0,0 +1,236 @@
+// The interactive-client CONNECTOR (docs/remote-sessions.md 4c): the CLIENT half of the mutual-
+// approval handshake, and the tunnel↔renderer frame pipe. It is the MIRROR IMAGE of
+// `connectRelayHost` (relay-host.ts) — connect OUT to a host's pairing offer, run the same
+// `createTrustGate` from the client side (compute + surface the SAS, confirm over the ENCRYPTED
+// tunnel, receive the host's confirm the same way), and once BOTH humans have approved, expose the
+// raw rpc.ts frame pipe so a later RpcClient (Task 4/5's FrameTransport + buildRelayApi) can drive
+// the host's core over `relay:client:send` / `relay:client:frame`.
+//
+// SECURITY — the client's obligations are the symmetric image of the host's (see relay-host.ts and
+// mutual-approval-core.ts). A mistake here forges the LOCAL human's consent or lets the relay open
+// the session without the REMOTE human, either of which grants shell access on a machine:
+// - obligation (a): the ONLY thing that can advance approval is a trust frame that came out of the
+// E2EE box (`connectRelay`'s `onTunnel`). Our own confirm rides the SAME sealed channel via
+// `socket.sendTunnelText` inside the gate's `sendConfirm` — never a plaintext path. A plaintext
+// frame the relay injects dies in relay-socket's `handleControl` and never reaches the gate.
+// - obligation (b): EXACTLY ONE `MutualApproval`, bound to THIS session's host key. For a client
+// the pinned host key from the offer (`opts.hostKeyB64`) IS the socket's peer key
+// (`socket.peerPublicKeyB64()`) — it seeded the ECDH shared secret the SAS is derived from, and
+// the client role never re-derives it. `peerKeyIntact()` re-asserts it against the live socket on
+// every tunnel frame, so a mid-session re-key (which relay-socket already refuses) can never
+// advance approval, forward a frame, or open the pipe under a swapped key.
+//
+// This file BUILDS NO api: it produces the SAS/approval events and the raw frame pipe only. It never
+// modifies the reviewed transport/trust/host machinery — it USES it.
+//
+// It lives in core so any shell can dial out through it; the desktop wrapper
+// (src/main/remote/relay-client.ts) adds only WHERE the host key is pinned (approved-devices).
+import { connectRelay, type RelayTransport, type RelaySocket } from './relay-socket'
+import {
+ createTrustGate,
+ parseDenied,
+ type PinStore,
+ type TrustDeniedReason,
+ type TrustGate
+} from './relay-trust'
+import type { KeyPair } from './e2ee'
+import { decodePtyData } from '../../shared/rpc'
+
+export interface RelayClientSession {
+ /** The 6-digit SAS both humans compare, or null before the key is derived. */
+ sas(): string | null
+ /** The host's stable box public key (base64) this session is bound to, or null before ready. */
+ peerKeyB64(): string | null
+ /** This human compared the SAS and pressed Confirm — sends our confirm over the ENCRYPTED tunnel. */
+ confirm(): void
+ /** Cast an outbound rpc.ts frame (JSON) at the host. Refused (returns false) before mutual approval:
+ * the host answers pre-approval reqs with E_UNAUTHORIZED anyway, so nothing is gained by sending. */
+ send(json: string): boolean
+ /** Both humans confirmed → the frame pipe is live. */
+ isOpen(): boolean
+ /** Tear down: close the relay socket. Idempotent. */
+ close(): void
+}
+
+export interface ConnectRelayClientOptions {
+ /** The relay wss URL from the decoded pairing offer. */
+ url: string
+ /** The single-use pairing token from the offer. */
+ token: string
+ /** The host's pinned box public key (base64) from the offer — the ECDH peer key for this session. */
+ hostKeyB64: string
+ /** Our long-lived peer identity (4d: pinned on both ends). Load via `loadOrCreatePeerKeyPair`. */
+ ourKeys: KeyPair
+ /** TEST ONLY: an in-process RelayTransport. Production opens a real ws (relay-socket.ts). */
+ transport?: RelayTransport
+ /** The SAS is known (the handshake completed) — ask this human to compare it. NOTHING is open yet. */
+ onSas(session: RelayClientSession): void
+ /** Mutually approved: the frame pipe is live (Task 4 builds the RpcClient on top). */
+ onApproved(session: RelayClientSession): void
+ /** An inbound rpc.ts TEXT frame from the host (a `res`/`ev`) → forward to the renderer. Trust frames
+ * are consumed by the gate BEFORE this and never delivered here. */
+ onFrame(json: string): void
+ /** An inbound pty:data BINARY frame → forward as pty output (mirrors the ws-bridge binary path). */
+ onPtyData(sessionId: string, data: string): void
+ /** The relay socket dropped (host/relay gone). */
+ onClose(): void
+ /** Where to record the host key after mutual approval (desktop: approved-devices). Absent = nowhere. */
+ pins?: PinStore
+ /** The host key is bookmarked AND this device was approved before: latch our confirm at once. */
+ autoApprove?: boolean
+ /** The host refused us over the encrypted tunnel ('denied' | 'removed' | 'expired'). */
+ onDenied?(reason: TrustDeniedReason): void
+}
+
+export function connectRelayClient(opts: ConnectRelayClientOptions): RelayClientSession {
+ // `socket` is assigned AFTER `connectRelay` returns, but over an in-process transport the client's
+ // handshake (and thus `onReady`) completes SYNCHRONOUSLY during that call — so `onReady` must not
+ // reach for `socket` (it uses `opts.hostKeyB64`, which IS the socket's peer key for a client), and
+ // the deferred gate/session closures below guard with `socket?.`.
+ let socket: RelaySocket | null = null
+ // Everything that can happen in that window and needs the socket is settled right after
+ // `connectRelay` returns (see the end of this function):
+ // - our auto-approve confirm: sent inside onReady it would ride `socket?.` into nothing, the host
+ // would never hear it, and a pinned reconnect would never open;
+ // - tunnel frames and the close: the host may answer inside its own onReady (a denial, its own
+ // confirm) and even close. Such a frame cannot pass peerKeyIntact() without a socket to read the
+ // live key from, so it is HELD here, in arrival order, and replayed through the same path.
+ // A real WebSocket never delivers inside connectRelay, so production never fills either.
+ let confirmOwed = false
+ const early: Array<() => void> = []
+ let gate: TrustGate | null = null
+ let opened = false
+ let closed = false
+ // OBLIGATION (b) — defence in depth. The host key this session is bound to (== socket peer key for a
+ // client). If the socket's live peer key ever diverges from it, the session key was swapped under us;
+ // we then refuse to advance approval, forward a frame, or open. relay-socket's layer-1 guard already
+ // refuses the swap — this is the second, independent check.
+ let sessionPeerKey: string | null = null
+ let keySwapped = false
+
+ const session: RelayClientSession = {
+ sas: () => gate?.sas() ?? null,
+ peerKeyB64: () => gate?.peerKeyB64() ?? null,
+ confirm: () => gate?.confirmHere(),
+ send: (json) => {
+ if (!opened || closed || !socket) return false
+ return socket.sendTunnelText(json)
+ },
+ isOpen: () => opened,
+ close() {
+ if (closed) return
+ closed = true
+ socket?.close()
+ }
+ }
+
+ /** The socket's live peer key still matches the one bound into the gate. 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 frame pipe is live. */
+ const open = (): void => {
+ if (closed || opened) return
+ if (!peerKeyIntact()) return
+ opened = true
+ opts.onApproved(session)
+ }
+
+ /** Our auto-approve confirm (never a human's): sent only once `socket` exists, see `confirmOwed`. */
+ const autoConfirm = (): void => {
+ if (!closed) gate?.confirmHere()
+ }
+
+ /** A decrypted tunnel frame from the host (only ever called once `socket` exists). */
+ const onTunnel = (kind: 'text' | 'binary', payload: Uint8Array): void => {
+ // OBLIGATION (b) — before advancing approval or forwarding a frame: the session key must still
+ // belong to the ORIGINAL host. A frame that decrypted under a swapped key must not reach the gate
+ // or the renderer.
+ if (!peerKeyIntact()) return
+ if (kind === 'binary') {
+ // Binary is pty output only (mirrors the ws-bridge binary path). Anything undecodable is dropped.
+ const decoded = decodePtyData(payload)
+ if (decoded) opts.onPtyData(decoded.sessionId, decoded.data)
+ return
+ }
+ const json = new TextDecoder().decode(payload)
+ // The host refused us. Not a trust frame (the gate never consumes it) and never an RPC frame:
+ // it only says WHY the host is about to close.
+ const denied = parseDenied(json)
+ if (denied) {
+ opts.onDenied?.(denied)
+ return
+ }
+ // Trust frames are consumed here and NEVER forwarded to the renderer's RPC client.
+ if (gate?.onTunnelText(json)) return
+ opts.onFrame(json)
+ }
+
+ socket = connectRelay({
+ url: opts.url,
+ token: opts.token,
+ role: 'client',
+ ourKeys: opts.ourKeys,
+ theirPubB64: opts.hostKeyB64,
+ transport: opts.transport,
+ onReady: () => {
+ // E2EE is up. This proves only that the host holds the pairing token — NOT that the human at the
+ // other end is who we think. Build the trust gate and ask this human to compare the SAS; nothing
+ // opens until BOTH confirm. Bind to the pinned host key (this session's ECDH peer key).
+ if (gate) return
+ sessionPeerKey = opts.hostKeyB64
+ gate = createTrustGate({
+ peerKeyB64: opts.hostKeyB64,
+ sessionId: `${opts.hostKeyB64}:${Date.now()}`, // obligation (b): ONE state per pairing attempt
+ sas: () => socket?.sas() ?? null,
+ // The ONLY confirm we ever send — over the ENCRYPTED, session-keyed tunnel (obligation (a)).
+ sendConfirm: (json) => {
+ socket?.sendTunnelText(json)
+ },
+ onOpen: open,
+ pins: opts.pins,
+ // Never let the gate send its confirm while it is being built: `socket` may not exist yet.
+ autoApprove: false
+ })
+ if (opts.autoApprove === true) {
+ // A pinned host raises no SAS dialog; our confirm goes out the moment it can be delivered.
+ if (socket) autoConfirm()
+ else confirmOwed = true
+ } else {
+ opts.onSas(session)
+ }
+ },
+ // The legacy phone dialect is not spoken here.
+ onRpc: () => {},
+ onFrame: () => {},
+ onTunnel: (kind, payload) => {
+ if (!socket) {
+ early.push(() => onTunnel(kind, payload))
+ return
+ }
+ onTunnel(kind, payload)
+ },
+ onClose: () => {
+ if (!socket) {
+ early.push(() => opts.onClose())
+ return
+ }
+ opts.onClose()
+ }
+ })
+
+ // The socket exists now: settle what the in-process handshake could not (see `confirmOwed`).
+ if (confirmOwed) {
+ confirmOwed = false
+ autoConfirm()
+ }
+ for (const run of early.splice(0)) run()
+
+ return session
+}
diff --git a/src/core/relay/relay-host.core.test.ts b/src/core/relay/relay-host.core.test.ts
new file mode 100644
index 000000000..3373f64ee
--- /dev/null
+++ b/src/core/relay/relay-host.core.test.ts
@@ -0,0 +1,295 @@
+// src/core/relay/relay-host.core.test.ts
+import { describe, it, expect, vi } from 'vitest'
+import { connectRelayHost, killRelayHostsByPeerKey, type PeerAttach, type RelayHostSession } from './relay-host'
+import { connectRelayClient } from './relay-client'
+import { transportPair } from './transport-pair'
+import { genKeyPair, publicKeyToB64 } from './e2ee'
+import { connectRelay } from './relay-socket'
+import { createTrustGate, deniedFrame, type TrustGate } from './relay-trust'
+import type { RpcRequest } from '../../shared/rpc'
+
+function fakeAttach() {
+ const dispatched: RpcRequest[] = []
+ const casts: Array<{ method: string; args: unknown[] }> = []
+ const sinks = new Map<number, { sendText(j: string): void }>()
+ let next = 1
+ const attach: PeerAttach = {
+ attach: (sink) => { const id = next++; sinks.set(id, sink); return id },
+ detach: (id) => { sinks.delete(id) },
+ dispatch: async (_id, req) => { dispatched.push(req); return { t: 'res', id: req.id, ok: true, result: 'ok' } },
+ cast: (_id, method, args) => { casts.push({ method, args }) }
+ }
+ return { attach, dispatched, casts, sinks }
+}
+
+function open(opts: Partial<Parameters<typeof connectRelayHost>[0]> = {}, clientAuto = false) {
+ const hostKeys = genKeyPair()
+ const peerKeys = genKeyPair()
+ const { hostT, peerT } = transportPair()
+ const fa = fakeAttach()
+ const frames: string[] = []
+ let hostSession!: RelayHostSession
+ const opened: string[] = []
+ hostSession = connectRelayHost({
+ url: 'ws://127.0.0.1/x', token: 't', ourKeys: hostKeys, attach: fa.attach, transport: hostT,
+ onPeerPending: () => {}, onOpen: () => opened.push('host'), onClose: () => {}, ...opts
+ })
+ const client = connectRelayClient({
+ url: 'ws://127.0.0.1/x', token: 't', hostKeyB64: publicKeyToB64(hostKeys.publicKey), ourKeys: peerKeys,
+ transport: peerT, autoApprove: clientAuto, onSas: () => {}, onApproved: () => opened.push('peer'),
+ onFrame: (j) => frames.push(j), onPtyData: () => {}, onClose: () => {}
+ })
+ return { hostSession, client, fa, frames, opened, peerKeyB64: publicKeyToB64(peerKeys.publicKey) }
+}
+
+describe('core relay host', () => {
+ it('pinned peer + auto-approving client open with no human', async () => {
+ const t = open({ autoApprove: () => true }, true)
+ await vi.waitFor(() => expect(t.opened.sort()).toEqual(['host', 'peer']))
+ expect(t.fa.sinks.size).toBe(1)
+ })
+
+ it('autoApprove is asked with the handshake peer key', async () => {
+ const seen: string[] = []
+ const t = open({ autoApprove: (k) => { seen.push(k); return false } })
+ await vi.waitFor(() => expect(seen).toEqual([t.peerKeyB64]))
+ expect(t.opened).toEqual([])
+ })
+
+ it('interceptReq answers before dispatch and never reaches the platform', async () => {
+ const t = open({
+ autoApprove: () => true,
+ hooks: { interceptReq: (_s, m) => (m === 'relay:hosted:self' ? Promise.resolve({ role: 'viewer' }) : null) }
+ }, true)
+ await vi.waitFor(() => expect(t.opened.length).toBe(2))
+ t.client.send(JSON.stringify({ t: 'req', id: 7, method: 'relay:hosted:self', args: [] }))
+ await vi.waitFor(() => expect(t.frames.some((f) => f.includes('"id":7') && f.includes('viewer'))).toBe(true))
+ expect(t.fa.dispatched).toEqual([])
+ })
+
+ it('access refusal answers E_ROLE and does not dispatch; allow may rewrite args', async () => {
+ const t = open({
+ autoApprove: () => true,
+ hooks: {
+ access: (_s, _k, method, args) =>
+ method === 'fs:write' ? { allow: false, message: 'Viewers cannot edit files.' }
+ : method === 'pty:resize' ? { allow: true, args: [args[0], null, null] } : { allow: true }
+ }
+ }, true)
+ await vi.waitFor(() => expect(t.opened.length).toBe(2))
+ t.client.send(JSON.stringify({ t: 'req', id: 1, method: 'fs:write', args: ['/x', 'y'] }))
+ t.client.send(JSON.stringify({ t: 'cast', method: 'pty:resize', args: ['s1', 200, 50] }))
+ await vi.waitFor(() => expect(t.frames.some((f) => f.includes('E_ROLE'))).toBe(true))
+ expect(t.fa.dispatched).toEqual([])
+ expect(t.fa.casts).toEqual([{ method: 'pty:resize', args: ['s1', null, null] }])
+ })
+
+ it('deny() tells the client why before closing', async () => {
+ const denied: string[] = []
+ const hostKeys = genKeyPair()
+ const { hostT, peerT } = transportPair()
+ const s = connectRelayHost({
+ url: 'ws://127.0.0.1/x', token: 't', ourKeys: hostKeys, attach: fakeAttach().attach, transport: hostT,
+ onPeerPending: (sess) => sess.deny('denied'), onOpen: () => {}, onClose: () => {}
+ })
+ connectRelayClient({
+ url: 'ws://127.0.0.1/x', token: 't', hostKeyB64: publicKeyToB64(hostKeys.publicKey), ourKeys: genKeyPair(),
+ transport: peerT, onSas: () => {}, onApproved: () => {}, onFrame: () => {}, onPtyData: () => {},
+ onClose: () => {}, onDenied: (r) => denied.push(r)
+ })
+ await vi.waitFor(() => expect(denied).toEqual(['denied']))
+ expect(s.clientId()).toBeNull()
+ })
+})
+
+// Ruling R9: an auto-approving gate must never send its confirm before the socket (and the gate) can
+// carry it. Over an in-process transport the whole handshake runs synchronously inside the CLIENT's
+// connectRelay call, so both of these fail when the confirm is sent at gate construction.
+describe('core relay — auto-approve confirms are deferred until they can be delivered', () => {
+ it('an auto-approving CLIENT still delivers its confirm to a host whose human confirms', async () => {
+ const hostKeys = genKeyPair()
+ const { hostT, peerT } = transportPair()
+ const opened: string[] = []
+ let sasShown = 0
+ const host = connectRelayHost({
+ url: 'ws://127.0.0.1/x', token: 't', ourKeys: hostKeys, attach: fakeAttach().attach, transport: hostT,
+ onPeerPending: () => {}, onOpen: () => opened.push('host'), onClose: () => {}
+ })
+ connectRelayClient({
+ url: 'ws://127.0.0.1/x', token: 't', hostKeyB64: publicKeyToB64(hostKeys.publicKey), ourKeys: genKeyPair(),
+ transport: peerT, autoApprove: true, onSas: () => sasShown++, onApproved: () => opened.push('peer'),
+ onFrame: () => {}, onPtyData: () => {}, onClose: () => {}
+ })
+ host.confirm() // the host's human
+ await vi.waitFor(() => expect(opened.sort()).toEqual(['host', 'peer']))
+ expect(sasShown).toBe(0) // a pinned host raises no SAS dialog
+ })
+
+ it('an auto-approving HOST confirms after the current turn, so a peer that builds its gate after its socket hears it', async () => {
+ const hostKeys = genKeyPair()
+ const { hostT, peerT } = transportPair()
+ const opened: string[] = []
+ let pending = 0
+ connectRelayHost({
+ url: 'ws://127.0.0.1/x', token: 't', ourKeys: hostKeys, attach: fakeAttach().attach, transport: hostT,
+ autoApprove: () => true, onPeerPending: () => pending++, onOpen: () => opened.push('host'), onClose: () => {}
+ })
+ // The shape the desktop tests use: the peer's gate exists only once connectRelay has returned.
+ let peerGate: TrustGate | null = null
+ const peerSocket = connectRelay({
+ url: 'ws://127.0.0.1/x', token: 't', role: 'client', ourKeys: genKeyPair(),
+ theirPubB64: publicKeyToB64(hostKeys.publicKey), transport: peerT,
+ onReady: () => {}, onRpc: () => {}, onFrame: () => {}, onClose: () => {},
+ onTunnel: (kind, payload) => {
+ if (kind === 'text') peerGate?.onTunnelText(new TextDecoder().decode(payload))
+ }
+ })
+ peerGate = createTrustGate({
+ peerKeyB64: peerSocket.peerPublicKeyB64()!, sessionId: 'peer', sas: () => peerSocket.sas(),
+ sendConfirm: (j) => peerSocket.sendTunnelText(j), onOpen: () => opened.push('peer')
+ })
+ peerGate.confirmHere() // the peer's human
+ await vi.waitFor(() => expect(opened.sort()).toEqual(['host', 'peer']))
+ expect(pending).toBe(0) // an auto-approved peer never raises the approve dialog
+ })
+})
+
+describe('core relay host — hooks and refusals', () => {
+ it('the attached sink reports the relay socket’s REAL buffered bytes (obligation 2)', async () => {
+ const hostKeys = genKeyPair()
+ const buffered = { n: 0 }
+ const { hostT, peerT } = transportPair({ hostBuffered: () => buffered.n })
+ const sinks: Array<{ bufferedAmount?(): number }> = []
+ const opened: string[] = []
+ connectRelayHost({
+ url: 'ws://127.0.0.1/x', token: 't', ourKeys: hostKeys, transport: hostT,
+ attach: { ...fakeAttach().attach, attach: (sink) => { sinks.push(sink); return 1 } },
+ autoApprove: () => true, onPeerPending: () => {}, onOpen: () => opened.push('host'), onClose: () => {}
+ })
+ connectRelayClient({
+ url: 'ws://127.0.0.1/x', token: 't', hostKeyB64: publicKeyToB64(hostKeys.publicKey), ourKeys: genKeyPair(),
+ transport: peerT, autoApprove: true, onSas: () => {}, onApproved: () => {}, onFrame: () => {},
+ onPtyData: () => {}, onClose: () => {}
+ })
+ await vi.waitFor(() => expect(opened).toEqual(['host']))
+ buffered.n = 9_000_000
+ expect(sinks[0].bufferedAmount?.()).toBe(9_000_000)
+ })
+
+ it('wrapSink decides what is attached, and still sees the honest base sink', async () => {
+ const hostKeys = genKeyPair()
+ const buffered = { n: 42 }
+ const { hostT, peerT } = transportPair({ hostBuffered: () => buffered.n })
+ const fa = fakeAttach()
+ const wrapped: string[] = []
+ const frames: string[] = []
+ const opened: string[] = []
+ let baseBuffered = -1
+ connectRelayHost({
+ url: 'ws://127.0.0.1/x', token: 't', ourKeys: hostKeys, attach: fa.attach, transport: hostT,
+ autoApprove: () => true,
+ hooks: {
+ wrapSink: (_s, base) => {
+ baseBuffered = base.bufferedAmount?.() ?? -1
+ return { ...base, sendText: (j) => { wrapped.push(j); base.sendText(j) } }
+ }
+ },
+ onPeerPending: () => {}, onOpen: () => opened.push('host'), onClose: () => {}
+ })
+ connectRelayClient({
+ url: 'ws://127.0.0.1/x', token: 't', hostKeyB64: publicKeyToB64(hostKeys.publicKey), ourKeys: genKeyPair(),
+ transport: peerT, autoApprove: true, onSas: () => {}, onApproved: () => {}, onFrame: (j) => frames.push(j),
+ onPtyData: () => {}, onClose: () => {}
+ })
+ await vi.waitFor(() => expect(opened).toEqual(['host']))
+ expect(baseBuffered).toBe(42)
+ const ev = JSON.stringify({ t: 'ev', channel: 'x', args: [] })
+ fa.sinks.get(1)!.sendText(ev)
+ expect(wrapped).toEqual([ev])
+ await vi.waitFor(() => expect(frames).toContain(ev))
+ })
+
+ it('narrowResponse rewrites a successful result and never touches an error', async () => {
+ const narrowed: string[] = []
+ const fa = fakeAttach()
+ const t = open({
+ autoApprove: () => true,
+ attach: {
+ ...fa.attach,
+ dispatch: async (_id, req) => req.method === 'bad'
+ ? { t: 'res', id: req.id, ok: false, error: { code: 'E_HANDLER', message: 'no' } }
+ : { t: 'res', id: req.id, ok: true, result: 'full' }
+ },
+ hooks: { narrowResponse: (_s, method, result) => { narrowed.push(method); return `${String(result)}-narrowed` } }
+ }, true)
+ await vi.waitFor(() => expect(t.opened.length).toBe(2))
+ t.client.send(JSON.stringify({ t: 'req', id: 1, method: 'good', args: [] }))
+ t.client.send(JSON.stringify({ t: 'req', id: 2, method: 'bad', args: [] }))
+ await vi.waitFor(() => expect(t.frames.length).toBe(2))
+ const res = t.frames.map((f) => JSON.parse(f))
+ expect(res.find((r) => r.id === 1)).toMatchObject({ ok: true, result: 'full-narrowed' })
+ expect(res.find((r) => r.id === 2)).toMatchObject({ ok: false, error: { code: 'E_HANDLER' } })
+ expect(narrowed).toEqual(['good'])
+ })
+
+ it('a denial frame a PEER sends is consumed, never forwarded to the core', async () => {
+ const t = open({ autoApprove: () => true }, true)
+ await vi.waitFor(() => expect(t.opened.length).toBe(2))
+ t.client.send(deniedFrame('removed'))
+ // Positive control, sent AFTER: once it has arrived, the denial had its turn.
+ t.client.send(JSON.stringify({ t: 'cast', method: 'pty:write', args: ['s1', 'x'] }))
+ await vi.waitFor(() => expect(t.fa.casts.length).toBe(1))
+ expect(t.fa.casts).toEqual([{ method: 'pty:write', args: ['s1', 'x'] }])
+ })
+
+ it('killRelayHostsByPeerKey with a reason tells the peer why; without one it only closes', async () => {
+ const hostKeys = genKeyPair()
+ const peerKeys = genKeyPair()
+ const fa = fakeAttach()
+ const events: string[] = []
+ const run = (): RelayHostSession => {
+ const { hostT, peerT } = transportPair()
+ const host = connectRelayHost({
+ url: 'ws://127.0.0.1/x', token: 't', ourKeys: hostKeys, attach: fa.attach, transport: hostT,
+ autoApprove: () => true, onPeerPending: () => {}, onOpen: () => events.push('open'), onClose: () => {}
+ })
+ connectRelayClient({
+ url: 'ws://127.0.0.1/x', token: 't', hostKeyB64: publicKeyToB64(hostKeys.publicKey), ourKeys: peerKeys,
+ transport: peerT, autoApprove: true, onSas: () => {}, onApproved: () => {}, onFrame: () => {},
+ onPtyData: () => {}, onClose: () => events.push('close'), onDenied: (r) => events.push(`denied:${r}`)
+ })
+ return host
+ }
+ const peerKeyB64 = publicKeyToB64(peerKeys.publicKey)
+
+ const first = run()
+ await vi.waitFor(() => expect(events).toEqual(['open']))
+ killRelayHostsByPeerKey(peerKeyB64, 'removed')
+ expect(events).toEqual(['open', 'denied:removed', 'close']) // the reason lands BEFORE the close
+ expect(first.clientId()).toBeNull()
+ expect(fa.sinks.size).toBe(0)
+
+ events.length = 0
+ const second = run()
+ await vi.waitFor(() => expect(events).toEqual(['open']))
+ killRelayHostsByPeerKey(peerKeyB64)
+ expect(events).toEqual(['open', 'close'])
+ expect(second.clientId()).toBeNull()
+ })
+
+ it('a denial sent during the in-process handshake still reaches the client before its close', async () => {
+ const hostKeys = genKeyPair()
+ const { hostT, peerT } = transportPair()
+ const events: string[] = []
+ connectRelayHost({
+ url: 'ws://127.0.0.1/x', token: 't', ourKeys: hostKeys, attach: fakeAttach().attach, transport: hostT,
+ onPeerPending: (sess) => sess.deny('expired'), onOpen: () => {}, onClose: () => {}
+ })
+ connectRelayClient({
+ url: 'ws://127.0.0.1/x', token: 't', hostKeyB64: publicKeyToB64(hostKeys.publicKey), ourKeys: genKeyPair(),
+ transport: peerT, onSas: () => {}, onApproved: () => {}, onFrame: () => {}, onPtyData: () => {},
+ onClose: () => events.push('close'), onDenied: (r) => events.push(`denied:${r}`)
+ })
+ expect(events).toEqual(['denied:expired', 'close'])
+ })
+})
diff --git a/src/core/relay/relay-host.ts b/src/core/relay/relay-host.ts
new file mode 100644
index 000000000..efeacc25a
--- /dev/null
+++ b/src/core/relay/relay-host.ts
@@ -0,0 +1,432 @@
+// The JOIN POINT on the host (docs/remote-sessions.md 4c): once two humans have mutually approved
+// each other, the bridged peer becomes a FIRST-CLASS CorePlatform client of this core.
+//
+// There is very little code here on purpose. The platform is multi-client (a client is a webContents
+// OR a UiSink in a peer registry), and Stages 1-3 wrote presence, the canvas reflector and terminal
+// co-attach against CorePlatform. So the whole of "a remote desktop opens as a project tab" reduces
+// to: mint one ClientId, register one sink, join presence, and route the encrypted tunnel into
+// `dispatch` / `cast`. Everything else just works (src/main/peer-integration.test.ts proved it
+// against a fake sink; this module supplies the socket).
+//
+// THE SEAM. Everything shell-specific — minting the ClientId, the peer registry, the presence join,
+// the platform's dispatch/cast and where a mutual approval is pinned — arrives through `PeerAttach`
+// and `PinStore`, so the desktop's Team Access (src/main/remote/relay-host.ts) and the Server
+// Edition's hosted team relay (docs/hosted-team-relay.md) run this ONE handshake + tunnel. The
+// optional `RelayHostHooks` let a host that serves several roles answer, refuse, narrow or filter
+// per session; a host that passes none (the desktop) takes exactly the unhooked path.
+//
+// It is the relay twin of `src/server/ws.ts`, and it deliberately mirrors that file's shape: attach
+// the sink, join the hub, req → dispatch → respond, cast → cast, and on close run the ONE teardown
+// (leave → dropClient → prune). Divergence between the two remote surfaces is a bug.
+//
+// SECURITY — nothing is served before MUTUAL approval. The peer is registered (and therefore able to
+// reach any channel the shell registered on the platform) only from the trust gate's `onOpen`, i.e.
+// after BOTH humans compared the same SAS and pressed Confirm. The E2EE handshake completing
+// (`onReady`) proves only that SOMEONE holds the pairing token — a pre-approval request is answered
+// with E_UNAUTHORIZED and never touches a handler. A pairing grants shell access; the SAS is the
+// only thing between a relay MITM and that shell.
+//
+// SCOPE: this is the DESKTOP-peer vocabulary (the invited peer is fully trusted, as the invite copy
+// states). The standing PHONE host keeps its existing legacy vocabulary in `host-service.ts` — with
+// its deny-by-default fs jail — and is deliberately NOT routed through this dispatch path.
+import { connectRelay, type RelayTransport } from './relay-socket'
+import {
+ createTrustGate,
+ deniedFrame,
+ parseDenied,
+ type PinStore,
+ type TrustDeniedReason,
+ type TrustGate
+} from './relay-trust'
+import type { KeyPair } from './e2ee'
+import type { UiSink } from '../ui-sink-registry'
+import {
+ E_UNAUTHORIZED,
+ parseRpcMessage,
+ type RpcErr,
+ type RpcOk,
+ type RpcRequest
+} from '../../shared/rpc'
+import { IPC } from '../../shared/ipc'
+import { scopeWorkspaceToProject } from '../../shared/relay-workspace-scope'
+import { outOfProjectScope } from './relay-project-scope'
+import type { Workspace } from '../../shared/types'
+
+/**
+ * How a mutually-approved peer joins the shell's core, and how it leaves. The shell owns every step
+ * (ClientId allocation, the peer registry, presence, the platform's dispatch table); this module
+ * only decides WHEN.
+ */
+export interface PeerAttach {
+ /** Register the sink AND join presence as a 'desktop' peer. Returns the peer's ClientId. */
+ attach(sink: UiSink): number
+ /** The ONE teardown (presence leave → dropClient → registry prune). */
+ detach(id: number): void
+ dispatch(id: number, req: RpcRequest): Promise<RpcOk | RpcErr>
+ cast(id: number, method: string, args: unknown[]): void
+}
+
+/** A per-request verdict. `args` (when present) replaces the peer's args for everything downstream. */
+export type AccessDecision = { allow: true; args?: unknown[] } | { allow: false; message: string }
+
+/** Optional per-session policy. Absent (the desktop) = the unhooked path, byte for byte. */
+export interface RelayHostHooks {
+ /** Answer a request here instead of dispatching it. `null` = not intercepted. */
+ interceptReq?(s: RelayHostSession, method: string, args: unknown[]): Promise<unknown> | null
+ /** Allow (optionally rewriting args) or refuse a request/cast before any scope check or dispatch. */
+ access?(s: RelayHostSession, kind: 'req' | 'cast', method: string, args: unknown[]): AccessDecision
+ /** Filter what reaches the peer. Keep `bufferedAmount` pointing at the base sink's (obligation 2). */
+ wrapSink?(s: RelayHostSession, sink: UiSink): UiSink
+ /** Narrow a SUCCESSFUL dispatch result before it goes back over the tunnel. */
+ narrowResponse?(s: RelayHostSession, method: string, result: unknown): unknown
+}
+
+export interface RelayHostSession {
+ /** The peer's presence/platform ClientId once it is open, else null. */
+ clientId(): number | null
+ /** The 6-digit SAS both humans compare, or null before the key is derived. */
+ sas(): string | null
+ /** The peer's stable box public key (base64), or null before the handshake learned it. */
+ peerKeyB64(): string | null
+ /** The single project this hosting session shares with the peer, or undefined if unscoped. */
+ sharedProjectId(): string | undefined
+ /** This human confirmed the SAS (from the approve dialog). */
+ confirm(): void
+ /** Refuse the peer: tell it WHY over the encrypted tunnel, then close. Idempotent. */
+ deny(reason: TrustDeniedReason): void
+ /** Tear down: detach the peer (leave + dropClient + prune), close the socket. Idempotent. */
+ close(): void
+}
+
+export interface ConnectRelayHostOptions {
+ url: string
+ token: string
+ ourKeys: KeyPair
+ /** How the approved peer joins (and leaves) the shell's core. */
+ attach: PeerAttach
+ /** TEST ONLY: an in-process RelayTransport. Production opens a real ws (relay-socket.ts). */
+ transport?: RelayTransport
+ /** The single project this hosting session shares with the peer. Undefined → unscoped (legacy
+ * behaviour: the peer sees the whole workspace). Held on the session for Task 2's scoped serve. */
+ sharedProjectId?: string
+ /** Where a mutual approval is pinned. Absent = pin nothing (the session still opens). */
+ pins?: PinStore
+ /**
+ * Latch THIS end's confirm without a human, for a peer key this host already trusts. Asked once,
+ * with the HANDSHAKE's peer key (the key whose shared secret produced the SAS), and it must answer
+ * from the host's OWN pin store — never from anything the peer sent. It never touches the peer's
+ * half: the peer must still confirm over the encrypted tunnel. An auto-approved peer raises no
+ * `onPeerPending`.
+ */
+ autoApprove?: (peerKeyB64: string) => boolean
+ /** Per-session policy (roles). Absent = the unhooked path. */
+ hooks?: RelayHostHooks
+ /** The SAS is known — ask the human to compare it. */
+ onPeerPending(session: RelayHostSession): void
+ /** Mutually approved: the peer is a CorePlatform client of this core now. */
+ onOpen(session: RelayHostSession): void
+ /** The relay socket dropped (the peer is already torn down when this fires). */
+ onClose(): void
+}
+
+/** Live bridged peers, for revocation: unpinning a key refuses the NEXT handshake, but the OPEN
+ * socket keeps full shell access until it is cut (see revocation.ts). */
+const live = new Set<RelayHostSession>()
+
+/** Cut every live session with this peer key. The revoker's `onRevoke` (src/main/index.ts). With a
+ * reason, the peer is told why over the encrypted tunnel first (`deny`); without one it is closed. */
+export function killRelayHostsByPeerKey(peerKeyB64: string, reason?: TrustDeniedReason): void {
+ for (const session of [...live]) {
+ if (session.peerKeyB64() !== peerKeyB64) continue
+ if (reason) session.deny(reason)
+ else session.close()
+ }
+}
+
+export function connectRelayHost(opts: ConnectRelayHostOptions): RelayHostSession {
+ let clientId: number | null = null
+ let gate: TrustGate | null = null
+ let 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
+
+ // Board-log onChanged over the relay rides the core's per-project watch refcount
+ // (registerBoardLogHandlers): the guest casts board-log:subscribe / :unsubscribe, which start/stop
+ // the host watch. But a guest whose tab closes or whose socket drops sends no balancing unsubscribe,
+ // so we track THIS connection's net per-project subscribe count and replay the unsubscribes on
+ // teardown (see detach) — the host watch is released, and the shared local refcount is never touched
+ // below this connection's own contribution (an unbalanced guest unsubscribe is ignored).
+ const boardLogSubs = new Map<string, number>()
+
+ /** The ONE teardown, mirroring src/server/ws.ts's close path exactly: `attach.detach` IS the three
+ * steps (presence leave → onPeerGone → PtyManager.dropClient → registry prune). Do NOT
+ * re-implement them here. */
+ const detach = (): void => {
+ if (clientId === null) return
+ // Release any board-log watches this connection still holds — a dropped guest tab never sends the
+ // balancing unsubscribe, so replay one per outstanding count before the client id is gone.
+ for (const [projectId, count] of boardLogSubs) {
+ for (let i = 0; i < count; i++) opts.attach.cast(clientId, IPC.boardLogUnsubscribe, [projectId])
+ }
+ boardLogSubs.clear()
+ opts.attach.detach(clientId)
+ clientId = null
+ }
+
+ const session: RelayHostSession = {
+ clientId: () => clientId,
+ sas: () => gate?.sas() ?? null,
+ peerKeyB64: () => gate?.peerKeyB64() ?? null,
+ sharedProjectId: () => opts.sharedProjectId,
+ confirm: () => gate?.confirmHere(),
+ deny(reason) {
+ if (closed) return
+ // Over the ENCRYPTED tunnel, so only the real peer can read it (and the relay cannot forge it).
+ socket.sendTunnelText(deniedFrame(reason))
+ session.close()
+ },
+ close() {
+ if (closed) return
+ closed = true
+ live.delete(session)
+ detach()
+ socket.close()
+ }
+ }
+
+ /** 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()) return
+ // A DEAD socket must THROW (the registry evicts a sink after 2 consecutive throws and runs the
+ // full teardown), and a healthy one must NOT (two throws in a row would kick a live peer out).
+ // sendTunnel* returns false only when the channel is gone — turn exactly that into a throw.
+ //
+ // OBLIGATION 2. The number Stage 2's per-client backpressure AND the 8 MB WS_DROP_WATER
+ // drop-and-redraw ceiling key on (src/core/ui-sink-registry.ts). `bufferedAmount` is OPTIONAL
+ // on UiSink and defaults to 0, so a sink that omits it — or stubs it — typechecks, passes every
+ // test, and silently disables the ceiling: a slow peer then queues pty output without bound,
+ // nothing pauses the pty or drops its backlog, and the HOST'S MEMORY GROWS UNTIL THE PROCESS
+ // DIES. RelaySocket.bufferedAmount() is honest (ws.bufferedAmount + the pre-open queue).
+ // Never make this a constant.
+ //
+ // A `wrapSink` hook must keep its `bufferedAmount` pointing at `base.bufferedAmount`.
+ const base: UiSink = {
+ sendText: (json) => { if (!socket.sendTunnelText(json)) throw new Error('relay socket is not connected') },
+ sendBinary: (buf) => { if (!socket.sendTunnelBinary(buf)) throw new Error('relay socket is not connected') },
+ bufferedAmount: () => socket.bufferedAmount()
+ }
+ const id = opts.attach.attach(opts.hooks?.wrapSink ? opts.hooks.wrapSink(session, base) : base)
+ clientId = id
+ opts.onOpen(session)
+ }
+
+ /** UX scope, NOT a trust boundary: for the ONE `workspace:load` method, when this hosting session
+ * is bound to a single project, narrow the successful response to that project (see
+ * scopeWorkspaceToProject). Every other method — and an error response, and an unscoped session —
+ * passes through byte-identical. This can only NARROW: it never exposes anything the core did not
+ * already return, and it never touches a non-`workspace:load` response. */
+ const scopeResponse = (method: string, res: RpcOk | RpcErr): RpcOk | RpcErr => {
+ if (!opts.sharedProjectId || method !== IPC.workspaceLoad || res.ok !== true) return res
+ return { ...res, result: scopeWorkspaceToProject(res.result as Workspace, opts.sharedProjectId) }
+ }
+
+ /** The hook's narrowing, for a SUCCESSFUL response only. No hook → the response untouched. */
+ const narrowResponse = (method: string, res: RpcOk | RpcErr): RpcOk | RpcErr => {
+ const narrow = opts.hooks?.narrowResponse
+ if (!narrow || res.ok !== true) return res
+ return { ...res, result: narrow(session, method, res.result) }
+ }
+
+ /** SCOPE jail for the board log (beyond the host registry's own projectId jail): a session bound to
+ * one project must never let the guest reach ANOTHER project's board log. A board-log method naming
+ * a different projectId is out of scope. Unscoped sessions pass through — the registry is the only
+ * gate then, exactly as for the host's own renderer. The guest can never supply a filesystem path;
+ * only a projectId the host resolves through its own router. */
+ const boardLogOutOfScope = (projectId: unknown): boolean =>
+ !!opts.sharedProjectId && projectId !== opts.sharedProjectId
+
+ /** The degraded response for an out-of-scope board-log request — the SAME shape the router gives an
+ * unknown project, produced WITHOUT dispatching (never resolving a path). Never throws. */
+ const boardLogRefusal = (method: string, id: number): RpcOk =>
+ method === IPC.boardLogRead
+ ? { t: 'res', id, ok: true, result: { entries: [], unsupported: true } }
+ : { t: 'res', id, ok: true, result: false }
+
+ /** SCOPE jail for every project-naming channel class (`relay-project-scope.ts`): a method in a
+ * scoped class that names another project — or that the table cannot read a projectId out of —
+ * is refused on a session bound to one project. Fail-closed by class, so a channel added to
+ * `githubIssues:*` / `board-log:*` / `projects.*` without a table row is refused, not waved on. */
+ const projectOutOfScope = (method: string, args: unknown[]): boolean =>
+ outOfProjectScope(opts.sharedProjectId, method, args)
+
+ const projectScopeRefusal = (method: string, id: number): RpcErr => ({
+ t: 'res',
+ id,
+ ok: false,
+ error: {
+ code: 'E_FORBIDDEN',
+ message: method.startsWith('githubIssues:')
+ ? 'GitHub Issues project is outside this relay session'
+ : 'That project is outside this relay session'
+ }
+ })
+
+ const socket = connectRelay({
+ url: opts.url,
+ token: opts.token,
+ role: 'host',
+ ourKeys: opts.ourKeys,
+ transport: opts.transport,
+ onReady: () => {
+ // E2EE is up. This proves only that SOMEONE holds the pairing token — NOT that the human at
+ // 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 = peerKey
+ // Asked with the HANDSHAKE key, before the gate exists: a pinned peer skips the dialog.
+ const auto = opts.autoApprove?.(peerKey) === true
+ gate = createTrustGate({
+ peerKeyB64: peerKey,
+ sessionId: `${peerKey}:${Date.now()}`, // obligation (b): ONE state per pairing attempt
+ sas: () => socket.sas(),
+ sendConfirm: (json) => socket.sendTunnelText(json),
+ onOpen: open,
+ pins: opts.pins,
+ // Never let the gate send its confirm while it is being built: see the deferral below.
+ autoApprove: false
+ })
+ live.add(session)
+ if (auto) {
+ // The auto-confirm goes out AFTER the current turn, never inside onReady. Over an in-process
+ // transport this onReady runs inside the PEER's connectRelay call — before the peer holds its
+ // socket or its gate — so a confirm sent now is dropped on the floor and a pinned reconnect
+ // never opens. Over a real WebSocket the microtask costs nothing.
+ queueMicrotask(() => {
+ if (!closed) gate?.confirmHere()
+ })
+ } else {
+ opts.onPeerPending(session)
+ }
+ },
+ // The legacy phone dialect is not served here: nothing is wired to onRpc / onFrame.
+ onRpc: () => {},
+ onFrame: () => {},
+ onTunnel: (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()) return
+ const json = new TextDecoder().decode(payload)
+ // A denial is the HOST's word to a peer, never the other way round: a peer that sends one is
+ // ignored, and the frame never reaches the core (the gate does not consume it).
+ if (parseDenied(json)) return
+ // Trust frames are consumed BEFORE dispatch and never reach the core.
+ if (gate?.onTunnelText(json)) return
+ const m = parseRpcMessage(json)
+ if (!m) return
+ if (clientId === null) {
+ // Not mutually approved: refuse — but ANSWER, or the peer's `await` would hang forever.
+ if (m.t === 'req') {
+ socket.sendTunnelText(
+ JSON.stringify({
+ t: 'res',
+ id: m.id,
+ ok: false,
+ error: { code: E_UNAUTHORIZED, message: 'Awaiting mutual approval.' }
+ })
+ )
+ }
+ return
+ }
+ if (m.t === 'req') {
+ // A hook may answer the request itself — it then never reaches a scope check or the core.
+ const intercepted = opts.hooks?.interceptReq?.(session, m.method, m.args) ?? null
+ if (intercepted) {
+ void intercepted.then(
+ (result) => socket.sendTunnelText(JSON.stringify({ t: 'res', id: m.id, ok: true, result: result ?? null })),
+ (err) => socket.sendTunnelText(JSON.stringify({ t: 'res', id: m.id, ok: false,
+ error: { code: 'E_HANDLER', message: err instanceof Error ? err.message : String(err) } }))
+ )
+ return
+ }
+ const decision = opts.hooks?.access?.(session, 'req', m.method, m.args) ?? { allow: true as const }
+ if (!decision.allow) {
+ socket.sendTunnelText(JSON.stringify({ t: 'res', id: m.id, ok: false, error: { code: 'E_ROLE', message: decision.message } }))
+ return
+ }
+ const args = decision.args ?? m.args
+ // Board-log read/append naming a project outside this session's scope: refuse WITHOUT
+ // dispatching (the host router never resolves it), degrading exactly as an unknown project.
+ // Checked before the generic jail so these two keep their established degraded shape.
+ if (
+ (m.method === IPC.boardLogAppend || m.method === IPC.boardLogRead) &&
+ boardLogOutOfScope(args[0])
+ ) {
+ socket.sendTunnelText(JSON.stringify(boardLogRefusal(m.method, m.id)))
+ return
+ }
+ if (projectOutOfScope(m.method, args)) {
+ socket.sendTunnelText(JSON.stringify(projectScopeRefusal(m.method, m.id)))
+ return
+ }
+ const id = clientId
+ void opts.attach
+ .dispatch(id, { ...m, args })
+ .then((res) =>
+ socket.sendTunnelText(JSON.stringify(narrowResponse(m.method, scopeResponse(m.method, res))))
+ )
+ } else if (m.t === 'cast') {
+ const d = opts.hooks?.access?.(session, 'cast', m.method, m.args) ?? { allow: true as const }
+ if (!d.allow) return
+ const args = d.args ?? m.args
+ if (projectOutOfScope(m.method, args)) return
+ // Board-log subscribe/unsubscribe: scope-jail out-of-scope projects, and track this
+ // connection's net per-project count so a dropped guest's watch is released in detach().
+ if (m.method === IPC.boardLogSubscribe || m.method === IPC.boardLogUnsubscribe) {
+ const projectId = args[0]
+ if (typeof projectId !== 'string' || boardLogOutOfScope(projectId)) return
+ if (m.method === IPC.boardLogSubscribe) {
+ boardLogSubs.set(projectId, (boardLogSubs.get(projectId) ?? 0) + 1)
+ } else {
+ const cur = boardLogSubs.get(projectId) ?? 0
+ if (cur <= 0) return // this connection holds no such watch — never decrement the shared count
+ if (cur === 1) boardLogSubs.delete(projectId)
+ else boardLogSubs.set(projectId, cur - 1)
+ }
+ }
+ opts.attach.cast(clientId, m.method, args)
+ }
+ // res/ev from a peer are ignored (mirrors src/server/ws.ts).
+ },
+ onClose: () => {
+ // The peer is GONE — the same state a closed browser tab leaves the core in.
+ live.delete(session)
+ detach()
+ opts.onClose()
+ }
+ })
+
+ return session
+}
diff --git a/src/core/relay/relay-trust.core.test.ts b/src/core/relay/relay-trust.core.test.ts
index 883d03837..3c862dd3f 100644
--- a/src/core/relay/relay-trust.core.test.ts
+++ b/src/core/relay/relay-trust.core.test.ts
@@ -40,6 +40,7 @@ describe('core trust gate', () => {
t.flush()
await new Promise((r) => setTimeout(r, 10))
expect(t.opened).toEqual([])
+ expect(t.recorded).toEqual([])
t.peer.confirmHere()
t.flush()
await vi.waitFor(() => expect(t.opened.sort()).toEqual(['host', 'peer']))
diff --git a/src/core/relay/relay-trust.ts b/src/core/relay/relay-trust.ts
index 26fad8a5e..0191d2e3f 100644
--- a/src/core/relay/relay-trust.ts
+++ b/src/core/relay/relay-trust.ts
@@ -105,6 +105,17 @@ export interface TrustGateOptions {
* 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()`).
+ *
+ * (a) The confirm is sent SYNCHRONOUSLY, inside `createTrustGate` itself — before the caller has
+ * even stored the returned gate. `sendConfirm` must therefore already be able to deliver: over an
+ * in-process transport the relay socket may not exist yet during `onReady`, and a confirm sent
+ * into nothing is lost silently (a pinned reconnect then never opens). A caller that cannot promise
+ * that passes `false` and calls `confirmHere()` itself once the socket and the gate exist, as the
+ * core relay host and client do.
+ *
+ * (b) Derive it from the caller's OWN pin store, for exactly `peerKeyB64` (this session's ECDH
+ * peer key) — never from anything the peer sent. A value the peer can influence turns this into a
+ * remote-controlled local confirm, i.e. one-way approval.
*/
autoApprove?: boolean
}
diff --git a/src/core/relay/transport-pair.ts b/src/core/relay/transport-pair.ts
new file mode 100644
index 000000000..e821355fd
--- /dev/null
+++ b/src/core/relay/transport-pair.ts
@@ -0,0 +1,29 @@
+// src/core/relay/transport-pair.ts
+// In-process RelayTransport pair for tests: what one side sends, the other receives, synchronously.
+// The same wiring relay-host.test.ts builds by hand; shared here for the core tests.
+import type { RelayTransport } from './relay-socket'
+
+export function transportPair(opts: { hostBuffered?: () => number } = {}): {
+ hostT: RelayTransport
+ peerT: RelayTransport
+} {
+ let hostOnMsg: ((d: unknown) => void) | null = null
+ let peerOnMsg: ((d: unknown) => void) | null = null
+ let hostOnClose: (() => void) | null = null
+ let peerOnClose: (() => void) | null = null
+ const hostT: RelayTransport = {
+ get bufferedAmount() { return opts.hostBuffered?.() ?? 0 },
+ send: (d) => peerOnMsg?.(d),
+ close: () => { peerOnClose?.(); hostOnClose?.() },
+ onMessage: (cb) => { hostOnMsg = cb },
+ onClose: (cb) => { hostOnClose = cb }
+ }
+ const peerT: RelayTransport = {
+ bufferedAmount: 0,
+ send: (d) => hostOnMsg?.(d),
+ close: () => { hostOnClose?.(); peerOnClose?.() },
+ onMessage: (cb) => { peerOnMsg = cb },
+ onClose: (cb) => { peerOnClose = cb }
+ }
+ return { hostT, peerT }
+}
diff --git a/src/main/remote/relay-client.ts b/src/main/remote/relay-client.ts
index eb5dfc8e2..9de8ff90c 100644
--- a/src/main/remote/relay-client.ts
+++ b/src/main/remote/relay-client.ts
@@ -1,170 +1,23 @@
-// The interactive-client CONNECTOR (docs/remote-sessions.md 4c): the CLIENT half of the mutual-
-// approval handshake, and the tunnel↔renderer frame pipe. It is the MIRROR IMAGE of
-// `connectRelayHost` (relay-host.ts) — connect OUT to a host's pairing offer, run the same
-// `createTrustGate` from the client side (compute + surface the SAS, confirm over the ENCRYPTED
-// tunnel, receive the host's confirm the same way), and once BOTH humans have approved, expose the
-// raw rpc.ts frame pipe so a later RpcClient (Task 4/5's FrameTransport + buildRelayApi) can drive
-// the host's core over `relay:client:send` / `relay:client:frame`.
-//
-// SECURITY — the client's obligations are the symmetric image of the host's (see relay-host.ts and
-// mutual-approval-core.ts). A mistake here forges the LOCAL human's consent or lets the relay open
-// the session without the REMOTE human, either of which grants shell access on a machine:
-// - obligation (a): the ONLY thing that can advance approval is a trust frame that came out of the
-// E2EE box (`connectRelay`'s `onTunnel`). Our own confirm rides the SAME sealed channel via
-// `socket.sendTunnelText` inside the gate's `sendConfirm` — never a plaintext path. A plaintext
-// frame the relay injects dies in relay-socket's `handleControl` and never reaches the gate.
-// - obligation (b): EXACTLY ONE `MutualApproval`, bound to THIS session's host key. For a client
-// the pinned host key from the offer (`opts.hostKeyB64`) IS the socket's peer key
-// (`socket.peerPublicKeyB64()`) — it seeded the ECDH shared secret the SAS is derived from, and
-// the client role never re-derives it. `peerKeyIntact()` re-asserts it against the live socket on
-// every tunnel frame, so a mid-session re-key (which relay-socket already refuses) can never
-// advance approval, forward a frame, or open the pipe under a swapped key.
-//
-// This file BUILDS NO api: it produces the SAS/approval events and the raw frame pipe only. It never
-// modifies the reviewed transport/trust/host machinery — it USES it.
-import { connectRelay, type RelayTransport, type RelaySocket } from './relay-socket'
-import { createTrustGate, type TrustGate } from './relay-trust'
-import type { KeyPair } from './e2ee'
-import { decodePtyData } from '../../shared/rpc'
-
-export interface RelayClientSession {
- /** The 6-digit SAS both humans compare, or null before the key is derived. */
- sas(): string | null
- /** The host's stable box public key (base64) this session is bound to, or null before ready. */
- peerKeyB64(): string | null
- /** This human compared the SAS and pressed Confirm — sends our confirm over the ENCRYPTED tunnel. */
- confirm(): void
- /** Cast an outbound rpc.ts frame (JSON) at the host. Refused (returns false) before mutual approval:
- * the host answers pre-approval reqs with E_UNAUTHORIZED anyway, so nothing is gained by sending. */
- send(json: string): boolean
- /** Both humans confirmed → the frame pipe is live. */
- isOpen(): boolean
- /** Tear down: close the relay socket. Idempotent. */
- close(): void
-}
-
-export interface ConnectRelayClientOptions {
- /** The relay wss URL from the decoded pairing offer. */
- url: string
- /** The single-use pairing token from the offer. */
- token: string
- /** The host's pinned box public key (base64) from the offer — the ECDH peer key for this session. */
- hostKeyB64: string
- /** Our long-lived peer identity (4d: pinned on both ends). Load via `loadOrCreatePeerKeyPair`. */
- ourKeys: KeyPair
- /** TEST ONLY: an in-process RelayTransport. Production opens a real ws (relay-socket.ts). */
- transport?: RelayTransport
- /** The SAS is known (the handshake completed) — ask this human to compare it. NOTHING is open yet. */
- onSas(session: RelayClientSession): void
- /** Mutually approved: the frame pipe is live (Task 4 builds the RpcClient on top). */
- onApproved(session: RelayClientSession): void
- /** An inbound rpc.ts TEXT frame from the host (a `res`/`ev`) → forward to the renderer. Trust frames
- * are consumed by the gate BEFORE this and never delivered here. */
- onFrame(json: string): void
- /** An inbound pty:data BINARY frame → forward as pty output (mirrors the ws-bridge binary path). */
- onPtyData(sessionId: string, data: string): void
- /** The relay socket dropped (host/relay gone). */
- onClose(): void
-}
+// The desktop relay client: a thin wrapper over the core client (src/core/relay/relay-client.ts),
+// which holds the whole mechanism and its SECURITY obligations — 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 client moved to core (docs/hosted-team-relay.md).
+import {
+ connectRelayClient as connectCoreRelayClient,
+ type RelayClientSession,
+ type ConnectRelayClientOptions as CoreOptions
+} from '../../core/relay/relay-client'
+import { recordApproval } from '../../core/relay/mutual-approval-core'
+import { updateApprovedDevices } from './approved-devices'
+
+export type { RelayClientSession }
+export type ConnectRelayClientOptions = Omit<CoreOptions, 'pins'>
export function connectRelayClient(opts: ConnectRelayClientOptions): RelayClientSession {
- // `socket` is assigned AFTER `connectRelay` returns, but over an in-process transport the client's
- // handshake (and thus `onReady`) completes SYNCHRONOUSLY during that call — so `onReady` must not
- // reach for `socket` (it uses `opts.hostKeyB64`, which IS the socket's peer key for a client), and
- // the deferred gate/session closures below guard with `socket?.`.
- let socket: RelaySocket | null = null
- let gate: TrustGate | null = null
- let opened = false
- let closed = false
- // OBLIGATION (b) — defence in depth. The host key this session is bound to (== socket peer key for a
- // client). If the socket's live peer key ever diverges from it, the session key was swapped under us;
- // we then refuse to advance approval, forward a frame, or open. relay-socket's layer-1 guard already
- // refuses the swap — this is the second, independent check.
- let sessionPeerKey: string | null = null
- let keySwapped = false
-
- const session: RelayClientSession = {
- sas: () => gate?.sas() ?? null,
- peerKeyB64: () => gate?.peerKeyB64() ?? null,
- confirm: () => gate?.confirmHere(),
- send: (json) => {
- if (!opened || closed || !socket) return false
- return socket.sendTunnelText(json)
- },
- isOpen: () => opened,
- close() {
- if (closed) return
- closed = true
- socket?.close()
- }
- }
-
- /** The socket's live peer key still matches the one bound into the gate. 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 frame pipe is live. */
- const open = (): void => {
- if (closed || opened) return
- if (!peerKeyIntact()) return
- opened = true
- opts.onApproved(session)
- }
-
- socket = connectRelay({
- url: opts.url,
- token: opts.token,
- role: 'client',
- ourKeys: opts.ourKeys,
- theirPubB64: opts.hostKeyB64,
- transport: opts.transport,
- onReady: () => {
- // E2EE is up. This proves only that the host holds the pairing token — NOT that the human at the
- // other end is who we think. Build the trust gate and ask this human to compare the SAS; nothing
- // opens until BOTH confirm. Bind to the pinned host key (this session's ECDH peer key).
- if (gate) return
- sessionPeerKey = opts.hostKeyB64
- gate = createTrustGate({
- peerKeyB64: opts.hostKeyB64,
- sessionId: `${opts.hostKeyB64}:${Date.now()}`, // obligation (b): ONE state per pairing attempt
- sas: () => socket?.sas() ?? null,
- // The ONLY confirm we ever send — over the ENCRYPTED, session-keyed tunnel (obligation (a)).
- sendConfirm: (json) => {
- socket?.sendTunnelText(json)
- },
- onOpen: open
- })
- opts.onSas(session)
- },
- // The legacy phone dialect is not spoken here.
- onRpc: () => {},
- onFrame: () => {},
- onTunnel: (kind, payload) => {
- // OBLIGATION (b) — before advancing approval or forwarding a frame: the session key must still
- // belong to the ORIGINAL host. A frame that decrypted under a swapped key must not reach the gate
- // or the renderer.
- if (!peerKeyIntact()) return
- if (kind === 'binary') {
- // Binary is pty output only (mirrors the ws-bridge binary path). Anything undecodable is dropped.
- const decoded = decodePtyData(payload)
- if (decoded) opts.onPtyData(decoded.sessionId, decoded.data)
- return
- }
- const json = new TextDecoder().decode(payload)
- // Trust frames are consumed here and NEVER forwarded to the renderer's RPC client.
- if (gate?.onTunnelText(json)) return
- opts.onFrame(json)
- },
- onClose: () => {
- opts.onClose()
- }
+ return connectCoreRelayClient({
+ ...opts,
+ // recordApproval refuses unless BOTH confirmed and pins only the key carried by the state; the
+ // serialized updateApprovedDevices queue keeps concurrent approvals and a racing revoke intact.
+ pins: { record: (pinned) => updateApprovedDevices((store) => recordApproval(store, pinned)) }
})
-
- return session
}
diff --git a/src/main/remote/relay-host.ts b/src/main/remote/relay-host.ts
index b6a3202b9..f07b69bb6 100644
--- a/src/main/remote/relay-host.ts
+++ b/src/main/remote/relay-host.ts
@@ -22,298 +22,63 @@
// SCOPE: this is the DESKTOP-peer vocabulary (the invited peer is fully trusted, as the invite copy
// states). The standing PHONE host keeps its existing legacy vocabulary in `host-service.ts` — with
// its deny-by-default fs jail — and is deliberately NOT routed through this dispatch path.
-import { connectRelay, type RelayTransport } from './relay-socket'
-import { createTrustGate, type TrustGate } from './relay-trust'
-import type { KeyPair } from './e2ee'
+//
+// THE MECHANISM LIVES IN CORE (src/core/relay/relay-host.ts, docs/hosted-team-relay.md): the
+// handshake, the trust gate, the tunnel dispatch and every SECURITY obligation above. This file is
+// the desktop's side of its seam — the `PeerAttach` that mints a ClientId, registers the peer sink
+// and joins presence, the electronPlatform dispatch/cast, and where a mutual approval is pinned
+// (approved-devices). It passes no hooks and no autoApprove, so the desktop takes the unhooked path.
+import {
+ connectRelayHost as connectCoreRelayHost,
+ killRelayHostsByPeerKey,
+ type RelayHostSession as CoreRelayHostSession,
+ type ConnectRelayHostOptions as CoreOptions,
+ type PeerAttach
+} from '../../core/relay/relay-host'
+import type { PinStore } from '../../core/relay/relay-trust'
+import { recordApproval } from '../../core/relay/mutual-approval-core'
import type { ElectronPlatform } from '../platform-electron'
import { registerPeerSink, unregisterPeerSink } from '../peer-registry'
import { allocateRelayClientId, presenceHub } from '../../core/presence/hub'
-import { E_UNAUTHORIZED, parseRpcMessage, type RpcErr, type RpcOk } from '../../shared/rpc'
-import { IPC } from '../../shared/ipc'
-import { scopeWorkspaceToProject } from '../../shared/relay-workspace-scope'
-import { outOfProjectScope } from './relay-project-scope'
-import type { Workspace } from '../../shared/types'
+import { updateApprovedDevices } from './approved-devices'
-export interface RelayHostSession {
- /** The peer's presence/platform ClientId once it is open, else null. */
- clientId(): number | null
- /** The 6-digit SAS both humans compare, or null before the key is derived. */
- sas(): string | null
- /** The peer's stable box public key (base64), or null before the handshake learned it. */
- peerKeyB64(): string | null
- /** The single project this hosting session shares with the peer, or undefined if unscoped. */
- sharedProjectId(): string | undefined
- /** This human confirmed the SAS (from the approve dialog). */
- confirm(): void
- /** Tear down: unregister the sink (leave + dropClient + prune), close the socket. Idempotent. */
- close(): void
-}
+export { killRelayHostsByPeerKey }
-export interface ConnectRelayHostOptions {
- url: string
- token: string
- ourKeys: KeyPair
+/** The desktop's view of a hosting session: the core session minus `deny`. Team Access never refuses
+ * a peer with a reason (a revoke closes it), so the desktop surface stays exactly what it was. */
+export type RelayHostSession = Omit<CoreRelayHostSession, 'deny'>
+
+export interface ConnectRelayHostOptions extends Omit<CoreOptions, 'attach' | 'pins'> {
platform: ElectronPlatform
- /** TEST ONLY: an in-process RelayTransport. Production opens a real ws (relay-socket.ts). */
- transport?: RelayTransport
- /** The single project this hosting session shares with the peer. Undefined → unscoped (legacy
- * behaviour: the peer sees the whole workspace). Held on the session for Task 2's scoped serve. */
- sharedProjectId?: string
- /** The SAS is known — ask the human to compare it. */
- onPeerPending(session: RelayHostSession): void
- /** Mutually approved: the peer is a CorePlatform client of this core now. */
- onOpen(session: RelayHostSession): void
- /** The relay socket dropped (the peer is already torn down when this fires). */
- onClose(): void
}
-/** Live bridged peers, for revocation: unpinning a key refuses the NEXT handshake, but the OPEN
- * socket keeps full shell access until it is cut (see revocation.ts). */
-const live = new Set<RelayHostSession>()
-
-/** Cut every live session with this peer key. The revoker's `onRevoke` (src/main/index.ts). */
-export function killRelayHostsByPeerKey(peerKeyB64: string): void {
- for (const session of [...live]) {
- if (session.peerKeyB64() === peerKeyB64) session.close()
+/** How a mutually-approved peer joins THIS desktop's core. `unregisterPeerSink` IS the ONE teardown
+ * (presenceHub.leave → onPeerGone → PtyManager.dropClient → registry prune); do NOT call
+ * `wirePeerRegistry` here — it is wired once at boot. */
+function desktopAttach(platform: ElectronPlatform): PeerAttach {
+ return {
+ attach(sink) {
+ const id = allocateRelayClientId()
+ registerPeerSink(id, sink)
+ // Join AFTER registering the sink, so the hub's `presence:sync` sendTo lands on a live sink (the
+ // order src/server/ws.ts uses). A peer desktop is a 'desktop' peer, not a 'phone'.
+ presenceHub.join(id, 'desktop')
+ return id
+ },
+ detach: (id) => unregisterPeerSink(id),
+ dispatch: (id, req) => platform.dispatch(id, req),
+ cast: (id, method, args) => platform.cast(id, method, args)
}
}
-export function connectRelayHost(opts: ConnectRelayHostOptions): RelayHostSession {
- let clientId: number | null = null
- let gate: TrustGate | null = null
- let 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
-
- // Board-log onChanged over the relay rides the core's per-project watch refcount
- // (registerBoardLogHandlers): the guest casts board-log:subscribe / :unsubscribe, which start/stop
- // the host watch. But a guest whose tab closes or whose socket drops sends no balancing unsubscribe,
- // so we track THIS connection's net per-project subscribe count and replay the unsubscribes on
- // teardown (see detach) — the host watch is released, and the shared local refcount is never touched
- // below this connection's own contribution (an unbalanced guest unsubscribe is ignored).
- const boardLogSubs = new Map<string, number>()
-
- /** 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
- * re-implement them here, and do NOT call `wirePeerRegistry` — it is wired once at boot. */
- const detach = (): void => {
- if (clientId === null) return
- // Release any board-log watches this connection still holds — a dropped guest tab never sends the
- // balancing unsubscribe, so replay one per outstanding count before the client id is gone.
- for (const [projectId, count] of boardLogSubs) {
- for (let i = 0; i < count; i++) opts.platform.cast(clientId, IPC.boardLogUnsubscribe, [projectId])
- }
- boardLogSubs.clear()
- unregisterPeerSink(clientId)
- clientId = null
- }
-
- const session: RelayHostSession = {
- clientId: () => clientId,
- sas: () => gate?.sas() ?? null,
- peerKeyB64: () => gate?.peerKeyB64() ?? null,
- sharedProjectId: () => opts.sharedProjectId,
- confirm: () => gate?.confirmHere(),
- close() {
- if (closed) return
- closed = true
- live.delete(session)
- detach()
- socket.close()
- }
- }
-
- /** 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()) return
- const id = allocateRelayClientId()
- registerPeerSink(id, {
- // A DEAD socket must THROW (the registry evicts a sink after 2 consecutive throws and runs the
- // full teardown), and a healthy one must NOT (two throws in a row would kick a live peer out).
- // sendTunnel* returns false only when the channel is gone — turn exactly that into a throw.
- sendText: (json) => {
- if (!socket.sendTunnelText(json)) throw new Error('relay socket is not connected')
- },
- sendBinary: (buf) => {
- if (!socket.sendTunnelBinary(buf)) throw new Error('relay socket is not connected')
- },
- // OBLIGATION 2. The number Stage 2's per-client backpressure AND the 8 MB WS_DROP_WATER
- // drop-and-redraw ceiling key on (src/core/ui-sink-registry.ts). `bufferedAmount` is OPTIONAL
- // on UiSink and defaults to 0, so a sink that omits it — or stubs it — typechecks, passes every
- // test, and silently disables the ceiling: a slow peer then queues pty output without bound,
- // nothing pauses the pty or drops its backlog, and the HOST'S MEMORY GROWS UNTIL THE PROCESS
- // DIES. RelaySocket.bufferedAmount() is honest (ws.bufferedAmount + the pre-open queue).
- // Never make this a constant.
- bufferedAmount: () => socket.bufferedAmount()
- })
- // Join AFTER registering the sink, so the hub's `presence:sync` sendTo lands on a live sink (the
- // order src/server/ws.ts uses). A peer desktop is a 'desktop' peer, not a 'phone'.
- presenceHub.join(id, 'desktop')
- clientId = id
- opts.onOpen(session)
- }
-
- /** UX scope, NOT a trust boundary: for the ONE `workspace:load` method, when this hosting session
- * is bound to a single project, narrow the successful response to that project (see
- * scopeWorkspaceToProject). Every other method — and an error response, and an unscoped session —
- * passes through byte-identical. This can only NARROW: it never exposes anything the core did not
- * already return, and it never touches a non-`workspace:load` response. */
- const scopeResponse = (method: string, res: RpcOk | RpcErr): RpcOk | RpcErr => {
- if (!opts.sharedProjectId || method !== IPC.workspaceLoad || res.ok !== true) return res
- return { ...res, result: scopeWorkspaceToProject(res.result as Workspace, opts.sharedProjectId) }
- }
-
- /** SCOPE jail for the board log (beyond the host registry's own projectId jail): a session bound to
- * one project must never let the guest reach ANOTHER project's board log. A board-log method naming
- * a different projectId is out of scope. Unscoped sessions pass through — the registry is the only
- * gate then, exactly as for the host's own renderer. The guest can never supply a filesystem path;
- * only a projectId the host resolves through its own router. */
- const boardLogOutOfScope = (projectId: unknown): boolean =>
- !!opts.sharedProjectId && projectId !== opts.sharedProjectId
-
- /** The degraded response for an out-of-scope board-log request — the SAME shape the router gives an
- * unknown project, produced WITHOUT dispatching (never resolving a path). Never throws. */
- const boardLogRefusal = (method: string, id: number): RpcOk =>
- method === IPC.boardLogRead
- ? { t: 'res', id, ok: true, result: { entries: [], unsupported: true } }
- : { t: 'res', id, ok: true, result: false }
-
- /** SCOPE jail for every project-naming channel class (`relay-project-scope.ts`): a method in a
- * scoped class that names another project — or that the table cannot read a projectId out of —
- * is refused on a session bound to one project. Fail-closed by class, so a channel added to
- * `githubIssues:*` / `board-log:*` / `projects.*` without a table row is refused, not waved on. */
- const projectOutOfScope = (method: string, args: unknown[]): boolean =>
- outOfProjectScope(opts.sharedProjectId, method, args)
-
- const projectScopeRefusal = (method: string, id: number): RpcErr => ({
- t: 'res',
- id,
- ok: false,
- error: {
- code: 'E_FORBIDDEN',
- message: method.startsWith('githubIssues:')
- ? 'GitHub Issues project is outside this relay session'
- : 'That project is outside this relay session'
- }
- })
-
- const socket = connectRelay({
- url: opts.url,
- token: opts.token,
- role: 'host',
- ourKeys: opts.ourKeys,
- transport: opts.transport,
- onReady: () => {
- // E2EE is up. This proves only that SOMEONE holds the pairing token — NOT that the human at
- // 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 = peerKey
- gate = createTrustGate({
- peerKeyB64: peerKey,
- sessionId: `${peerKey}:${Date.now()}`, // obligation (b): ONE state per pairing attempt
- sas: () => socket.sas(),
- sendConfirm: (json) => socket.sendTunnelText(json),
- onOpen: open
- })
- live.add(session)
- opts.onPeerPending(session)
- },
- // The legacy phone dialect is not served here: nothing is wired to onRpc / onFrame.
- onRpc: () => {},
- onFrame: () => {},
- onTunnel: (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()) return
- const json = new TextDecoder().decode(payload)
- // Trust frames are consumed BEFORE dispatch and never reach the core.
- if (gate?.onTunnelText(json)) return
- const m = parseRpcMessage(json)
- if (!m) return
- if (clientId === null) {
- // Not mutually approved: refuse — but ANSWER, or the peer's `await` would hang forever.
- if (m.t === 'req') {
- socket.sendTunnelText(
- JSON.stringify({
- t: 'res',
- id: m.id,
- ok: false,
- error: { code: E_UNAUTHORIZED, message: 'Awaiting mutual approval.' }
- })
- )
- }
- return
- }
- if (m.t === 'req') {
- // Board-log read/append naming a project outside this session's scope: refuse WITHOUT
- // dispatching (the host router never resolves it), degrading exactly as an unknown project.
- // Checked before the generic jail so these two keep their established degraded shape.
- if (
- (m.method === IPC.boardLogAppend || m.method === IPC.boardLogRead) &&
- boardLogOutOfScope(m.args[0])
- ) {
- socket.sendTunnelText(JSON.stringify(boardLogRefusal(m.method, m.id)))
- return
- }
- if (projectOutOfScope(m.method, m.args)) {
- socket.sendTunnelText(JSON.stringify(projectScopeRefusal(m.method, m.id)))
- return
- }
- const id = clientId
- void opts.platform
- .dispatch(id, m)
- .then((res) => socket.sendTunnelText(JSON.stringify(scopeResponse(m.method, res))))
- } else if (m.t === 'cast') {
- if (projectOutOfScope(m.method, m.args)) return
- // Board-log subscribe/unsubscribe: scope-jail out-of-scope projects, and track this
- // connection's net per-project count so a dropped guest's watch is released in detach().
- if (m.method === IPC.boardLogSubscribe || m.method === IPC.boardLogUnsubscribe) {
- const projectId = m.args[0]
- if (typeof projectId !== 'string' || boardLogOutOfScope(projectId)) return
- if (m.method === IPC.boardLogSubscribe) {
- boardLogSubs.set(projectId, (boardLogSubs.get(projectId) ?? 0) + 1)
- } else {
- const cur = boardLogSubs.get(projectId) ?? 0
- if (cur <= 0) return // this connection holds no such watch — never decrement the shared count
- if (cur === 1) boardLogSubs.delete(projectId)
- else boardLogSubs.set(projectId, cur - 1)
- }
- }
- opts.platform.cast(clientId, m.method, m.args)
- }
- // res/ev from a peer are ignored (mirrors src/server/ws.ts).
- },
- onClose: () => {
- // The peer is GONE — the same state a closed browser tab leaves the core in.
- live.delete(session)
- detach()
- opts.onClose()
- }
- })
+/** Desktop pins: the phone/desktop approved-devices store, exactly as before the gate moved to core.
+ * recordApproval refuses unless BOTH confirmed and pins only the key carried by the state; the
+ * serialized updateApprovedDevices queue keeps concurrent approvals and a racing revoke intact. */
+function desktopPins(): PinStore {
+ return { record: (pinned) => updateApprovedDevices((store) => recordApproval(store, pinned)) }
+}
- return session
+export function connectRelayHost(opts: ConnectRelayHostOptions): RelayHostSession {
+ const { platform, ...rest } = opts
+ return connectCoreRelayHost({ ...rest, attach: desktopAttach(platform), pins: desktopPins() })
}