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.

security(remote): harden pairing trust model (R1–R3)

enes02431adadc8b
diff --git a/src/main/remote/client-service.ts b/src/main/remote/client-service.ts
index cf26c54fb..2c188d1ce 100644
--- a/src/main/remote/client-service.ts
+++ b/src/main/remote/client-service.ts
@@ -296,8 +296,9 @@ export function initRemoteClient(win: BrowserWindow, deps?: { isPackaged?: boole
ourKeys,
theirPubB64: offer.hostPublicKeyB64,
onReady: () => {
- // Bridge established. Ask the host to (re-)push its current canvas, in case our mirror
- // subscribed after the host's connect-time push (there is no replay otherwise).
+ // Bridge established. Surface the channel SAS so the client human can compare it with the
+ // code the host shows before approving. Then ask the host to (re-)push its current canvas.
+ send(IPC.remoteClientSas(connectionId), socket.sas())
socket.notify(CANVAS_REQUEST_METHOD)
},
onRpc: (req) => {
diff --git a/src/main/remote/e2ee.ts b/src/main/remote/e2ee.ts
index 15cc9d237..ddcde80dc 100644
--- a/src/main/remote/e2ee.ts
+++ b/src/main/remote/e2ee.ts
@@ -44,6 +44,17 @@ export function encrypt(plain: Uint8Array, shared: Uint8Array): Uint8Array {
return box
}
+// Short Authentication String: a 6-digit code derived from the ECDH shared key. Both peers
+// compute the SAME value (same shared key), so the two humans can compare it out-of-band to
+// confirm they're on the same channel before the host approves a connection. Formatted "NNN NNN".
+export function sasFromSharedKey(shared: Uint8Array): string {
+ const h = nacl.hash(shared) // SHA-512
+ // Fold the first 4 bytes into a 32-bit int, then take 6 decimal digits.
+ const n = ((h[0] << 24) | (h[1] << 16) | (h[2] << 8) | h[3]) >>> 0
+ const code = (n % 1_000_000).toString().padStart(6, '0')
+ return `${code.slice(0, 3)} ${code.slice(3)}`
+}
+
// Decrypt a `nonce ‖ ciphertext ‖ mac` box. Returns null on malformed input or
// a failed MAC check — never throws.
export function decrypt(box: Uint8Array, shared: Uint8Array): Uint8Array | null {
diff --git a/src/main/remote/host-service.ts b/src/main/remote/host-service.ts
index e34ada24b..8cbece164 100644
--- a/src/main/remote/host-service.ts
+++ b/src/main/remote/host-service.ts
@@ -110,10 +110,30 @@ function str(value: unknown): string | undefined {
*
* `nextStreamId` lets tests assert deterministic ids; production uses a monotonic counter.
*/
+/**
+ * Lexically resolve `target` and confirm it sits inside one of `roots` (or equals a root). Uses
+ * path.resolve so `..` traversal is normalized away — a remote client cannot reach `/etc/passwd`
+ * or `~/.ssh` via `../../`. (Symlinks inside a shared root are not chased; the shared roots are
+ * the user's own project directories.)
+ */
+function isWithinRoots(target: string, roots: string[]): boolean {
+ if (!target) return false
+ const resolved = path.resolve(target)
+ for (const root of roots) {
+ if (!root) continue
+ const r = path.resolve(root)
+ if (resolved === r || resolved.startsWith(r + path.sep)) return true
+ }
+ return false
+}
+
export function createHostHandlers(
pty: HostPtyManager,
socket: HostRelaySocket,
- fs: HostFsOps = fsOps
+ fs: HostFsOps = fsOps,
+ // Directories the remote client may read/write within. Empty ⇒ no filesystem access is served
+ // (deny-by-default). Production passes the cwds of the host's shared canvas nodes.
+ getRoots: () => string[] = () => []
): HostHandlers {
// streamId -> Stream. PTY callbacks close over their own `streamId` directly, so no
// reverse (sessionId -> streamId) index is needed.
@@ -153,33 +173,6 @@ export function createHostHandlers(
}
}
- function handleCreate(req: RpcRequest): void {
- const p = asRecord(req.params)
- const options: PtyCreateOptions = {
- cols: Math.max(1, num(p.cols, 80)),
- rows: Math.max(1, num(p.rows, 24)),
- cwd: str(p.cwd),
- shell: str(p.shell),
- persistKey: str(p.persistKey),
- agentId: str(p.agentId) as AgentId | undefined
- }
-
- const streamId = ++streamCounter
- const stream: Stream = { sessionId: '', seq: 0, paused: false }
- const sinks = makeSinks(streamId, stream)
-
- let sessionId: string
- try {
- sessionId = pty.createDetached(options, sinks)
- } catch (err) {
- socket.respond(req.id, false, { message: (err as Error).message })
- return
- }
- stream.sessionId = sessionId
- streams.set(streamId, stream)
- socket.respond(req.id, true, { streamId })
- }
-
// Reassembled snapshot is sent as one or more OP.SnapshotChunk frames between Start and End.
// 256 KB keeps each chunk well under the relay's per-frame limits while a full-screen capture
// (with colors) stays small in practice.
@@ -254,6 +247,25 @@ export function createHostHandlers(
const p = asRecord(req.params)
const filePath = str(p.path) ?? ''
const respond = (body: unknown): void => socket.respond(req.id, true, body)
+ // Confine remote filesystem access to the shared project roots. A path outside them (or any
+ // `../` traversal) is denied — degrade to the same empty/false shape fs-ops returns on error,
+ // so the remote Explorer/Editor just sees "nothing there" rather than a thrown RPC.
+ if (!isWithinRoots(filePath, getRoots())) {
+ switch (req.method) {
+ case 'fs.list':
+ respond({ entries: [] })
+ break
+ case 'fs.readBinary':
+ respond({ base64: '' })
+ break
+ case 'fs.write':
+ respond({ ok: false })
+ break
+ default:
+ respond({ content: '' })
+ }
+ return
+ }
switch (req.method) {
case 'fs.list':
void fs.listDir(filePath).then((entries) => respond({ entries }))
@@ -284,7 +296,10 @@ export function createHostHandlers(
onRpc(req) {
switch (req.method) {
case 'pty.create':
- handleCreate(req)
+ // Reject: remote clients only ever attach to the host's existing tmux sessions
+ // (`pty.attach`). `pty.create` would let a client spawn an arbitrary shell with a
+ // client-chosen cwd — full remote command execution — so it is not served.
+ socket.respond(req.id, false, { message: 'pty.create is not permitted for remote clients.' })
break
case 'pty.attach':
handleAttach(req)
@@ -389,6 +404,16 @@ export function createHostCanvasSync(
}
}
+// The directories a remote client may touch over fs.* = the cwds of the host's shared canvas
+// nodes (each terminal node carries its project cwd). Empty when nothing is shared yet ⇒
+// deny-by-default. Subdirectories are allowed via the prefix check in isWithinRoots.
+function rootsFromCanvas(canvas: CanvasState | null): string[] {
+ if (!canvas) return []
+ const roots = new Set<string>()
+ for (const node of canvas.nodes) if (node.cwd) roots.add(node.cwd)
+ return [...roots]
+}
+
// --- pairing-token mint ------------------------------------------------------
interface PairTokenResponse {
@@ -478,6 +503,10 @@ export function initRemoteHost(win: BrowserWindow, ptyManager: PtyManager): void
let socket: RelaySocket | null = null
let handlers: HostHandlers | null = null
let canvasSync: HostCanvasSync | null = null
+ // Connection-approval gate: a freshly-bridged client serves NO pty/fs RPCs or input frames
+ // until the host human approves it (so a leaked offer cannot grant silent access). Reset on
+ // every (re)connect and teardown.
+ let approved = false
// Latest snapshot pushed from the renderer, kept across (re)connects so a freshly joined
// client always gets the current state even if it connected after the last edit.
let latestCanvas: CanvasState | null = null
@@ -491,6 +520,7 @@ export function initRemoteHost(win: BrowserWindow, ptyManager: PtyManager): void
clearTimeout(broadcastTimer)
broadcastTimer = null
}
+ approved = false
handlers?.closeAll()
handlers = null
canvasSync = null
@@ -543,28 +573,43 @@ export function initRemoteHost(win: BrowserWindow, ptyManager: PtyManager): void
role: 'host',
ourKeys: keys,
onReady: () => {
- // Bridge established with a client — push the current canvas so it mirrors immediately.
+ // Bridge established with a client. Require explicit host approval before serving any
+ // pty/fs RPC — surface the SAS so the human can verify + allow. Canvas state still pushes
+ // (read-only mirror) so the client isn't staring at a blank screen while pending.
+ approved = false
+ send(IPC.remoteHostPeerPending, { sas: socket?.sas() ?? null })
if (latestCanvas) canvasSync?.setState(latestCanvas)
},
onRpc: (req) => {
- // A client asking for a fresh canvas snapshot → re-push the current one.
+ // A client asking for a fresh canvas snapshot → re-push the current one (read-only).
if (req.method === CANVAS_REQUEST_METHOD) {
canvasSync?.broadcastCurrent()
return
}
+ // Until the host approves this device, refuse every state-changing request: pty/fs RPCs
+ // and client canvas mutations. (canvas:request above is the only allowed pre-approval op.)
+ if (!approved) {
+ if (req.id) socket?.respond(req.id, false, { message: 'Awaiting host approval.' })
+ return
+ }
// Canvas mutations route to the canvas sync (which forwards them to the host renderer,
// the single writer); everything else is a pty RPC.
if (canvasSync?.handleRpc(req)) return
handlers?.onRpc(req)
},
- onFrame: (frame) => handlers?.onFrame(frame),
+ // Input/resize frames are dropped until approved (no keystrokes reach a host PTY).
+ onFrame: (frame) => {
+ if (approved) handlers?.onFrame(frame)
+ },
onClose: () => {
// The client (or relay) dropped — kill served PTYs. relay-socket may reconnect; the
- // handlers stay bound to the same socket object across reconnects.
+ // handlers stay bound to the same socket object across reconnects. Re-require approval.
+ approved = false
handlers?.closeAll()
}
})
- handlers = createHostHandlers(ptyManager, socket)
+ // Confine the client's fs.* access to the cwds of the host's currently-shared canvas nodes.
+ handlers = createHostHandlers(ptyManager, socket, fsOps, () => rootsFromCanvas(latestCanvas))
// The host renderer applies inbound client mutations to its React Flow (single writer).
canvasSync = createHostCanvasSync(socket, (mutation) =>
send(IPC.remoteHostApplyMutation, mutation)
@@ -579,6 +624,15 @@ export function initRemoteHost(win: BrowserWindow, ptyManager: PtyManager): void
}
})
+ // Host human approved the pending device → start serving its pty/fs RPCs.
+ ipcMain.on(IPC.remoteHostApprove, () => {
+ if (socket) approved = true
+ })
+ // Host human rejected the device → drop the connection entirely.
+ ipcMain.on(IPC.remoteHostReject, () => {
+ teardown()
+ })
+
ipcMain.handle(IPC.remoteHostStop, () => {
teardown()
})
diff --git a/src/main/remote/relay-socket.ts b/src/main/remote/relay-socket.ts
index d0acc5c5f..a97953927 100644
--- a/src/main/remote/relay-socket.ts
+++ b/src/main/remote/relay-socket.ts
@@ -30,7 +30,7 @@
// so tests drive two RelaySockets via in-process fakes with no real network;
// production passes a `ws` WebSocket wrapped via `wrapWebSocket`.
-import { decrypt, deriveSharedKey, encrypt, publicKeyToB64, type KeyPair } from './e2ee'
+import { decrypt, deriveSharedKey, encrypt, publicKeyToB64, sasFromSharedKey, type KeyPair } from './e2ee'
import { decodeFrame, encodeFrame, type Frame, MAX_BINARY_BUFFERED_AMOUNT } from './framing'
// A minimal duplex transport. `send` accepts a string (handshake control) or a
@@ -64,6 +64,9 @@ export type RelaySocket = {
// Send a terminal frame to the peer. Returns false when the transport is over
// its buffered-amount threshold (backpressure) or not connected.
sendFrame(op: number, streamId: number, seq: number, payload: Uint8Array): boolean
+ // The Short Authentication String for this channel (derived from the shared key), or null
+ // before the handshake has derived a key. Both peers compute the same value.
+ sas(): string | null
// Tear down: stops reconnects and closes the transport.
close(): void
}
@@ -126,6 +129,13 @@ export function connectRelay(opts: ConnectRelayOptions): RelaySocket {
let keepaliveTimer: ReturnType<typeof setInterval> | null = null
let requestCounter = 0
let readyFired = false
+ // Replay/reorder protection: every encrypted message carries a strictly-increasing per-
+ // direction counter inside the authenticated plaintext. The receiver rejects any message whose
+ // counter is not greater than the last accepted one, so a relay (or on-path attacker) cannot
+ // replay a captured box (e.g. re-injecting an OP.Input keystroke frame or a pty.kill RPC) nor
+ // reorder traffic. Counters reset per (re)connection — a fresh handshake is a fresh stream.
+ let sendSeq = 0
+ let recvSeq = -1
const pending = new Map<
string,
@@ -146,6 +156,8 @@ export function connectRelay(opts: ConnectRelayOptions): RelaySocket {
state = 'connecting'
sharedKey = null
readyFired = false
+ sendSeq = 0
+ recvSeq = -1
if (opts.transport) {
// Injected transport (tests). It is already "open"; treat that as the
@@ -172,11 +184,24 @@ export function connectRelay(opts: ConnectRelayOptions): RelaySocket {
transport?.send(JSON.stringify(control))
}
+ // Prepend the outbound monotonic counter (8 bytes LE) to the plaintext before sealing, so the
+ // peer can reject replays/reorders. Mirrors framing.ts's 64-bit split to stay within safe ints.
+ const SEQ_BYTES = 8
+ function withSeq(plaintext: Uint8Array): Uint8Array {
+ const seq = sendSeq++
+ const out = new Uint8Array(SEQ_BYTES + plaintext.length)
+ const view = new DataView(out.buffer)
+ view.setUint32(0, Math.floor(seq / 0x100000000), true)
+ view.setUint32(4, seq >>> 0, true)
+ out.set(plaintext, SEQ_BYTES)
+ return out
+ }
+
function sendEncrypted(plaintext: Uint8Array): boolean {
if (!transport || !sharedKey || state !== 'ready') {
return false
}
- transport.send(encrypt(plaintext, sharedKey))
+ transport.send(encrypt(withSeq(plaintext), sharedKey))
return true
}
@@ -186,7 +211,7 @@ export function connectRelay(opts: ConnectRelayOptions): RelaySocket {
if (!transport || !sharedKey) {
return
}
- transport.send(encrypt(plaintext, sharedKey))
+ transport.send(encrypt(withSeq(plaintext), sharedKey))
}
function tagged(tag: number, body: Uint8Array): Uint8Array {
@@ -227,10 +252,19 @@ export function connectRelay(opts: ConnectRelayOptions): RelaySocket {
if (!sharedKey) {
return
}
- const plain = decrypt(bytes, sharedKey)
- if (!plain) {
+ const sealed = decrypt(bytes, sharedKey)
+ if (!sealed || sealed.length < SEQ_BYTES) {
return
}
+ // Enforce the strictly-increasing per-direction counter inside the authenticated plaintext.
+ // A non-increasing counter means a replayed or reordered box — drop it.
+ const seqView = new DataView(sealed.buffer, sealed.byteOffset, sealed.byteLength)
+ const seq = seqView.getUint32(0, true) * 0x100000000 + seqView.getUint32(4, true)
+ if (seq <= recvSeq) {
+ return
+ }
+ recvSeq = seq
+ const plain = sealed.subarray(SEQ_BYTES)
if (state === 'handshaking') {
handleHandshakeEncrypted(plain)
@@ -450,6 +484,9 @@ export function connectRelay(opts: ConnectRelayOptions): RelaySocket {
}
return sendEncrypted(tagged(TAG_FRAME, encodeFrame(op, streamId, seq, payload)))
},
+ sas() {
+ return sharedKey ? sasFromSharedKey(sharedKey) : null
+ },
close() {
intentionallyClosed = true
if (reconnectTimer) {
diff --git a/src/main/remote/remote-security.test.ts b/src/main/remote/remote-security.test.ts
new file mode 100644
index 000000000..1e10b11d2
--- /dev/null
+++ b/src/main/remote/remote-security.test.ts
@@ -0,0 +1,191 @@
+// Security regression tests for the remote subsystem hardening:
+// R1 — host serves no `pty.create`; `fs.*` is confined to the shared roots.
+// R2 — the channel SAS is deterministic + identical on both peers.
+// R3 — replayed/reordered encrypted boxes are dropped (per-direction monotonic counter).
+import { describe, expect, it, vi } from 'vitest'
+import { createHostHandlers, type HostFsOps, type HostPtyManager, type HostRelaySocket } from './host-service'
+import { genKeyPair, deriveSharedKey, sasFromSharedKey, publicKeyToB64 } from './e2ee'
+import { connectRelay, type RelaySocket, type RelayTransport } from './relay-socket'
+import { OP, type Frame } from './framing'
+
+// --- R1: pty.create rejected + fs jail --------------------------------------
+
+function makeHostFakes() {
+ const responses: Array<{ id: string; ok: boolean; body: unknown }> = []
+ const socket: HostRelaySocket = {
+ respond: (id, ok, body) => responses.push({ id, ok, body }),
+ sendFrame: () => true
+ }
+ const reads: string[] = []
+ const fs: HostFsOps = {
+ listDir: async (p) => {
+ reads.push(p)
+ return [{ name: 'x', isDirectory: false } as never]
+ },
+ readText: async (p) => {
+ reads.push(p)
+ return 'secret'
+ },
+ readBinary: async () => '',
+ writeText: async () => true
+ }
+ const pty = {
+ createDetached: vi.fn(() => 'sess'),
+ attachDetached: vi.fn(() => 'sess'),
+ captureSnapshot: vi.fn(async () => ''),
+ write: vi.fn(),
+ resize: vi.fn(),
+ setFlow: vi.fn(),
+ kill: vi.fn()
+ } as unknown as HostPtyManager
+ return { socket, responses, fs, reads, pty }
+}
+
+describe('R1: remote pty.create is not served', () => {
+ it('responds with an error and never spawns a PTY', () => {
+ const { socket, responses, fs, pty } = makeHostFakes()
+ const handlers = createHostHandlers(pty, socket, fs, () => ['/work'])
+ handlers.onRpc({ id: '1', method: 'pty.create', params: { shell: '/bin/sh', cwd: '/' } })
+ expect(responses).toEqual([
+ { id: '1', ok: false, body: { message: expect.stringContaining('not permitted') } }
+ ])
+ expect((pty.createDetached as ReturnType<typeof vi.fn>)).not.toHaveBeenCalled()
+ })
+})
+
+describe('R1: fs.* is confined to the shared roots', () => {
+ it('denies a path outside the roots (no fs-ops call, empty result)', async () => {
+ const { socket, responses, fs, reads } = makeHostFakes()
+ const handlers = createHostHandlers({} as HostPtyManager, socket, fs, () => ['/work'])
+ handlers.onRpc({ id: '1', method: 'fs.read', params: { path: '/Users/me/.ssh/id_ed25519' } })
+ await Promise.resolve()
+ expect(reads).toEqual([]) // fs-ops never touched
+ expect(responses).toEqual([{ id: '1', ok: true, body: { content: '' } }])
+ })
+
+ it('denies a ../ traversal escape from a root', async () => {
+ const { socket, responses, fs, reads } = makeHostFakes()
+ const handlers = createHostHandlers({} as HostPtyManager, socket, fs, () => ['/work'])
+ handlers.onRpc({ id: '1', method: 'fs.read', params: { path: '/work/../etc/passwd' } })
+ await Promise.resolve()
+ expect(reads).toEqual([])
+ expect(responses[0]).toEqual({ id: '1', ok: true, body: { content: '' } })
+ })
+
+ it('allows a path inside a root', async () => {
+ const { socket, responses, fs, reads } = makeHostFakes()
+ const handlers = createHostHandlers({} as HostPtyManager, socket, fs, () => ['/work'])
+ handlers.onRpc({ id: '1', method: 'fs.read', params: { path: '/work/src/app.ts' } })
+ await Promise.resolve()
+ await Promise.resolve()
+ expect(reads).toEqual(['/work/src/app.ts'])
+ expect(responses[0]).toEqual({ id: '1', ok: true, body: { content: 'secret' } })
+ })
+
+ it('denies everything when no roots are shared (deny-by-default)', async () => {
+ const { socket, responses, fs, reads } = makeHostFakes()
+ const handlers = createHostHandlers({} as HostPtyManager, socket, fs, () => [])
+ handlers.onRpc({ id: '1', method: 'fs.list', params: { path: '/work' } })
+ await Promise.resolve()
+ expect(reads).toEqual([])
+ expect(responses[0]).toEqual({ id: '1', ok: true, body: { entries: [] } })
+ })
+})
+
+// --- R2: SAS determinism -----------------------------------------------------
+
+describe('R2: channel SAS', () => {
+ it('is identical for both peers and stable, formatted NNN NNN', () => {
+ const host = genKeyPair()
+ const client = genKeyPair()
+ const hostShared = deriveSharedKey(publicKeyToB64(client.publicKey), host.secretKey)
+ const clientShared = deriveSharedKey(publicKeyToB64(host.publicKey), client.secretKey)
+ const a = sasFromSharedKey(hostShared)
+ const b = sasFromSharedKey(clientShared)
+ expect(a).toBe(b)
+ expect(a).toMatch(/^\d{3} \d{3}$/)
+ expect(sasFromSharedKey(hostShared)).toBe(a) // deterministic
+ })
+})
+
+// --- R3: replay protection (end-to-end over paired fake transports) ----------
+
+// A pair of in-process transports wired host<->client. Records every binary box delivered to the
+// client so a test can re-deliver (replay) it. Handshake control strings pass through too.
+function makeTransportPair() {
+ let hostOnMsg: ((d: unknown) => void) | null = null
+ let clientOnMsg: ((d: unknown) => void) | null = null
+ const toClient: Uint8Array[] = []
+ const host: RelayTransport = {
+ bufferedAmount: 0,
+ send: (d) => clientOnMsg?.(d),
+ close: () => {},
+ onMessage: (cb) => (hostOnMsg = cb),
+ onClose: () => {}
+ }
+ const client: RelayTransport = {
+ bufferedAmount: 0,
+ send: (d) => hostOnMsg?.(d),
+ close: () => {},
+ onMessage: (cb) => (clientOnMsg = cb),
+ onClose: () => {}
+ }
+ // Capture host→client binary boxes by wrapping host.send.
+ const realHostSend = host.send
+ host.send = (d) => {
+ if (d instanceof Uint8Array) toClient.push(d)
+ realHostSend(d)
+ }
+ return {
+ host,
+ client,
+ replayToClient: (box: Uint8Array) => clientOnMsg?.(box),
+ capturedToClient: toClient
+ }
+}
+
+describe('R3: replayed encrypted frames are dropped', () => {
+ it('delivers a frame once; a replay of the same box is ignored', () => {
+ const hostKeys = genKeyPair()
+ const clientKeys = genKeyPair()
+ const pair = makeTransportPair()
+
+ let hostSocket: RelaySocket | null = null
+ const clientFrames: Frame[] = []
+
+ // Host first (passive), then client (sends hello → drives the synchronous handshake).
+ hostSocket = connectRelay({
+ url: 'x',
+ token: 't',
+ role: 'host',
+ ourKeys: hostKeys,
+ transport: pair.host,
+ onReady: () => {},
+ onRpc: () => {},
+ onFrame: () => {},
+ onClose: () => {}
+ })
+ connectRelay({
+ url: 'x',
+ token: 't',
+ role: 'client',
+ ourKeys: clientKeys,
+ theirPubB64: publicKeyToB64(hostKeys.publicKey),
+ transport: pair.client,
+ onReady: () => {},
+ onRpc: () => {},
+ onFrame: (f) => clientFrames.push(f),
+ onClose: () => {}
+ })
+
+ // Host sends one output frame to the client.
+ const ok = hostSocket.sendFrame(OP.Output, 1, 0, new TextEncoder().encode('hi'))
+ expect(ok).toBe(true)
+ expect(clientFrames).toHaveLength(1)
+
+ // The last captured host→client box is that frame. Replay it verbatim.
+ const lastBox = pair.capturedToClient[pair.capturedToClient.length - 1]
+ pair.replayToClient(lastBox)
+ expect(clientFrames).toHaveLength(1) // dropped — not re-delivered
+ })
+})
diff --git a/src/preload/index.ts b/src/preload/index.ts
index ec7fa76b7..d96f032c6 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -35,6 +35,9 @@ function subscribe<A extends unknown[] = []>(channel: string) {
// Fan-out subscriber for the host's inbound apply-mutation events (a single ipcRenderer
// listener shared by all renderer subscribers, like the other event channels).
const subscribeMutation = subscribe<[CanvasMutation]>(IPC.remoteHostApplyMutation)
+// Fan-out subscriber for the connection-approval prompt (main → host renderer when a client
+// finishes the handshake; carries the SAS to show in the approval dialog).
+const subscribePeerPending = subscribe<[{ sas: string | null }]>(IPC.remoteHostPeerPending)
const api: NodeTerminalApi = {
pty: {
@@ -214,7 +217,10 @@ const api: NodeTerminalApi = {
start: () => ipcRenderer.invoke(IPC.remoteHostStart),
stop: () => ipcRenderer.invoke(IPC.remoteHostStop),
sendCanvasState: (state) => ipcRenderer.send(IPC.remoteHostCanvasState, state),
- onApplyMutation: subscribeMutation
+ onApplyMutation: subscribeMutation,
+ onPeerPending: subscribePeerPending,
+ approve: () => ipcRenderer.send(IPC.remoteHostApprove),
+ reject: () => ipcRenderer.send(IPC.remoteHostReject)
},
remoteClient: {
connect: (offer) => ipcRenderer.invoke(IPC.remoteClientConnect, offer),
@@ -251,6 +257,12 @@ const api: NodeTerminalApi = {
ipcRenderer.on(channel, handler)
return () => ipcRenderer.removeListener(channel, handler)
},
+ onSas: (connectionId, listener) => {
+ const channel = IPC.remoteClientSas(connectionId)
+ const handler = (_e: unknown, sas: string | null) => listener(sas)
+ ipcRenderer.on(channel, handler)
+ return () => ipcRenderer.removeListener(channel, handler)
+ },
sendMutation: (connectionId, mutation) =>
ipcRenderer.send(IPC.remoteClientMutate, connectionId, mutation),
fsList: (connectionId, path) => ipcRenderer.invoke(IPC.remoteClientFsList, connectionId, path),
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 58698506e..f6531629d 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -169,6 +169,8 @@ export function Canvas() {
// When set, a full-surface remote mirror of a connected host is shown over the local canvas.
const [remoteConnId, setRemoteConnId] = useState<string | null>(null)
const [remoteDialogOpen, setRemoteDialogOpen] = useState(false)
+ // A client has finished the handshake and is awaiting this host's approval (carries the SAS).
+ const [pendingPeer, setPendingPeer] = useState<{ sas: string | null } | null>(null)
const [confirm, setConfirm] = useState<{
message: string
onConfirm: () => void
@@ -584,6 +586,12 @@ export function Canvas() {
})
}, [setNodes, markDirty])
+ // Host connection-approval gate: when a client finishes the handshake, prompt the host to
+ // verify the SAS and allow/deny before any remote pty/fs RPC is served.
+ useEffect(() => {
+ return window.nodeTerminal.remoteHost.onPeerPending((info) => setPendingPeer(info))
+ }, [])
+
// Record an undo snapshot when the canvas settles (debounced; skips drag frames/loads).
useEffect(() => {
if (loadingRef.current) {
@@ -2484,6 +2492,28 @@ export function Canvas() {
/>
)}
+ {pendingPeer && (
+ <ConfirmDialog
+ message={
+ `A device wants to access this machine.\n\n` +
+ `Approve ONLY if you started this connection. The other device shows the same code:\n\n` +
+ ` ${pendingPeer.sas ?? '— — —'}\n\n` +
+ `If the codes don't match, deny it.`
+ }
+ confirmLabel="Allow"
+ cancelLabel="Deny"
+ danger={false}
+ onConfirm={() => {
+ window.nodeTerminal.remoteHost.approve()
+ setPendingPeer(null)
+ }}
+ onCancel={() => {
+ window.nodeTerminal.remoteHost.reject()
+ setPendingPeer(null)
+ }}
+ />
+ )}
+
<UpgradeDialog />
{remotePicker && (
diff --git a/src/renderer/components/RemoteAccessDialog.tsx b/src/renderer/components/RemoteAccessDialog.tsx
index fab44cac5..599c66494 100644
--- a/src/renderer/components/RemoteAccessDialog.tsx
+++ b/src/renderer/components/RemoteAccessDialog.tsx
@@ -22,6 +22,8 @@ export function RemoteAccessDialog({ onClose }: { onClose: () => void }): React.
const [error, setError] = useState('')
const [clientCode, setClientCode] = useState('')
const [connecting, setConnecting] = useState(false)
+ const [clientSas, setClientSas] = useState<string | null>(null)
+ const [connectedId, setConnectedId] = useState<string | null>(null)
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
@@ -50,6 +52,13 @@ export function RemoteAccessDialog({ onClose }: { onClose: () => void }): React.
setHostOffer('')
setHostBusy(false)
}
+ // Surface the channel SAS once the handshake completes, so the user can verify it matches the
+ // code the host shows before approving there. Keep the dialog open to display it.
+ useEffect(() => {
+ if (!connectedId) return
+ return window.nodeTerminal.remoteClient.onSas(connectedId, (sas) => setClientSas(sas))
+ }, [connectedId])
+
const connect = async () => {
const code = clientCode.trim()
if (!code) return
@@ -60,7 +69,9 @@ export function RemoteAccessDialog({ onClose }: { onClose: () => void }): React.
window.dispatchEvent(
new CustomEvent('nodeterm:open-remote-terminal', { detail: { connectionId } })
)
- onClose()
+ // Don't close yet: show the verification code + "waiting for host approval" status. The
+ // mirror node already opened; the user can close this dialog once approved.
+ setConnectedId(connectionId)
} catch (err) {
setError((err as Error).message)
} finally {
@@ -114,17 +125,28 @@ export function RemoteAccessDialog({ onClose }: { onClose: () => void }): React.
)}
<h4 className="remote-dialog__head4">Connect to a host</h4>
- <div className="remote-dialog__block">
- <Input
- className="w-full"
- placeholder="paste the host's code"
- value={clientCode}
- onChange={(e) => setClientCode(e.target.value)}
- />
- <Button disabled={connecting || !clientCode.trim()} onClick={() => void connect()}>
- {connecting ? 'Connecting…' : 'Connect'}
- </Button>
- </div>
+ {connectedId ? (
+ <div className="remote-dialog__block">
+ <p className="remote-dialog__hint">
+ Connected — waiting for the host to approve. Verify this code matches the one shown on
+ the host:
+ </p>
+ <Input className="w-full" readOnly value={clientSas ?? 'establishing…'} />
+ <Button onClick={onClose}>Done</Button>
+ </div>
+ ) : (
+ <div className="remote-dialog__block">
+ <Input
+ className="w-full"
+ placeholder="paste the host's code"
+ value={clientCode}
+ onChange={(e) => setClientCode(e.target.value)}
+ />
+ <Button disabled={connecting || !clientCode.trim()} onClick={() => void connect()}>
+ {connecting ? 'Connecting…' : 'Connect'}
+ </Button>
+ </div>
+ )}
{error ? <p className="remote-dialog__err">{error}</p> : null}
</div>
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index 0fc805c7d..0c33a62f9 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -102,6 +102,12 @@ export const IPC = {
commitGenerate: 'commit:generate',
remoteHostStart: 'remote:host:start',
remoteHostStop: 'remote:host:stop',
+ // Connection approval gate: main → renderer when a client finishes the handshake (carries the
+ // SAS to display); renderer → main to approve/reject. Until approved, the host serves no
+ // pty/fs RPCs or input frames, so a leaked offer cannot grant silent access.
+ remoteHostPeerPending: 'remote:host:peer-pending',
+ remoteHostApprove: 'remote:host:approve',
+ remoteHostReject: 'remote:host:reject',
// Host canvas mirror: renderer pushes its serialized active-project canvas to main;
// main pushes a client's mutation back to the host renderer to apply.
remoteHostCanvasState: 'remote:host:canvas-state',
@@ -121,6 +127,9 @@ export const IPC = {
remoteClientFsRead: 'remote:client:fs-read',
remoteClientFsReadBinary: 'remote:client:fs-read-binary',
remoteClientFsWrite: 'remote:client:fs-write',
+ // The channel SAS pushed main->renderer once the client handshake completes, so the client
+ // human can compare it with the code shown on the host before the host approves.
+ remoteClientSas: (connectionId: string) => `remote:client:sas:${connectionId}`,
// Host canvas snapshot pushed main->renderer for a connection (connectionId appended).
remoteClientCanvasState: (connectionId: string) => `remote:client:canvas-state:${connectionId}`,
// Per-session events broadcast main->renderer (connectionId + streamId appended).
diff --git a/src/shared/types.ts b/src/shared/types.ts
index cf78630dd..aa217d1cd 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -249,7 +249,8 @@ export interface Settings {
disabledAgents: AgentId[]
/** Which agent the ⌘⇧C shortcut / quick-add launches. Always a launchable builtin. */
defaultAgent: AgentId
- /** Send anonymous usage data (version/OS) to the telemetry backend. Opt-out (default on). */
+ /** Send anonymous usage data (version/OS) to the telemetry backend. Opt-in (default off)
+ * so we never collect without explicit consent (GDPR). Toggle in Settings → Privacy. */
telemetryEnabled: boolean
}
@@ -274,7 +275,7 @@ export const DEFAULT_SETTINGS: Settings = {
customAgents: [],
disabledAgents: [],
defaultAgent: 'claude',
- telemetryEnabled: true
+ telemetryEnabled: false
}
export interface SettingsApi {
@@ -635,6 +636,16 @@ export interface RemoteHostApi {
* Flow (the single writer). Returns an unsubscribe function.
*/
onApplyMutation(listener: (mutation: CanvasMutation) => void): () => void
+ /**
+ * Fires when a client finishes the E2EE handshake and is awaiting approval. The host must call
+ * `approve()` before any of the client's pty/fs RPCs are served; `sas` is the channel
+ * verification code to display. Returns an unsubscribe function.
+ */
+ onPeerPending(listener: (info: { sas: string | null }) => void): () => void
+ /** Approve the pending client → the host begins serving its pty/fs RPCs. */
+ approve(): void
+ /** Reject the pending client → the connection is dropped. */
+ reject(): void
}
export interface RemoteClientApi {
@@ -669,6 +680,11 @@ export interface RemoteClientApi {
* Returns an unsubscribe function.
*/
onCanvasState(connectionId: string, listener: (state: CanvasState) => void): () => void
+ /**
+ * Listen for the channel SAS once the handshake completes, so the client human can compare it
+ * with the code shown on the host before the host approves. Returns an unsubscribe function.
+ */
+ onSas(connectionId: string, listener: (sas: string | null) => void): () => void
/**
* Send a canvas mutation to the host (the client's optimistic edit). Main forwards it as a
* `canvas:mutate` RPC; the host applies it and the next `canvas:state` reconciles.
diff --git a/test/remote/b5-e2e.test.ts b/test/remote/b5-e2e.test.ts
index 15b07d204..5423804ca 100644
--- a/test/remote/b5-e2e.test.ts
+++ b/test/remote/b5-e2e.test.ts
@@ -279,7 +279,8 @@ describe('B5 remote project mirror end-to-end (real relay + real handlers + fake
onFrame: (frame) => hostHandlers?.onFrame(frame),
onClose: () => hostHandlers?.closeAll()
})
- hostHandlers = createHostHandlers(makeEchoPty(), hostSocket, hostFs)
+ // Share the temp dir as the allowed fs root (fs jail) so the client's fs.* RPCs are served.
+ hostHandlers = createHostHandlers(makeEchoPty(), hostSocket, hostFs, () => [tmpDir])
// Mirror the real host: a client mutation is applied to the host's authoritative state (the
// single writer), then re-broadcast as the new `canvas:state`.
hostCanvasSync = createHostCanvasSync(hostSocket, (mutation: CanvasMutation) => {
diff --git a/test/remote/host-handlers.test.ts b/test/remote/host-handlers.test.ts
index 64cca6a2d..0cece70ff 100644
--- a/test/remote/host-handlers.test.ts
+++ b/test/remote/host-handlers.test.ts
@@ -71,16 +71,26 @@ const resizePayload = (cols: number, rows: number) => {
return buf
}
+// Open a stream the only way a remote client can: pty.attach to an existing session. Resolves
+// once the async snapshot+attach has bound the sinks (sessionId 'pty-1'). Returns streamId 1.
+async function openViaAttach(
+ h: ReturnType<typeof createHostHandlers>,
+ nodeId = 'node-1'
+): Promise<void> {
+ h.onRpc({ id: `open-${nodeId}`, method: 'pty.attach', params: { nodeId, cols: 80, rows: 24 } })
+ await new Promise((r) => setTimeout(r, 0))
+}
+
describe('createHostHandlers', () => {
- it('maps pty.create to createDetached and returns a streamId', () => {
+ it('rejects pty.create — remote clients may only attach to existing sessions', () => {
const pty = fakePty()
const sock = fakeSocket()
const h = createHostHandlers(pty.mgr, sock.socket)
- h.onRpc({ id: 'r1', method: 'pty.create', params: { cols: 100, rows: 30, cwd: '/tmp' } })
+ h.onRpc({ id: 'r1', method: 'pty.create', params: { cols: 100, rows: 30, cwd: '/', shell: '/bin/sh' } })
- expect(pty.options()).toMatchObject({ cols: 100, rows: 30, cwd: '/tmp' })
- expect(sock.responses).toEqual([{ id: 'r1', ok: true, body: { streamId: 1 } }])
+ expect(sock.responses[0]).toMatchObject({ id: 'r1', ok: false })
+ expect(pty.calls.some((c) => c.method === 'createDetached')).toBe(false)
})
it('maps pty.attach to a snapshot sequence then attachDetached on the existing session', async () => {
@@ -140,26 +150,27 @@ describe('createHostHandlers', () => {
expect(sock.responses[0]).toMatchObject({ id: 'r1', ok: false })
})
- it('pipes PTY output into OP.Output frames with an incrementing seq', () => {
+ it('pipes PTY output into OP.Output frames with an incrementing seq', async () => {
const pty = fakePty()
const sock = fakeSocket()
const h = createHostHandlers(pty.mgr, sock.socket)
- h.onRpc({ id: 'r1', method: 'pty.create', params: { cols: 80, rows: 24 } })
+ await openViaAttach(h)
pty.sinks().onData('hello')
pty.sinks().onData('world')
- expect(sock.frames).toHaveLength(2)
- expect(sock.frames[0]).toMatchObject({ op: OP.Output, streamId: 1, seq: 0 })
- expect(Buffer.from(sock.frames[0].payload).toString('utf8')).toBe('hello')
- expect(sock.frames[1]).toMatchObject({ op: OP.Output, streamId: 1, seq: 1 })
+ const outs = sock.frames.filter((f) => f.op === OP.Output)
+ expect(outs).toHaveLength(2)
+ expect(outs[0]).toMatchObject({ op: OP.Output, streamId: 1 })
+ expect(Buffer.from(outs[0].payload).toString('utf8')).toBe('hello')
+ expect(outs[1].seq).toBe(outs[0].seq + 1) // monotonic
})
- it('routes OP.Input frames to write and OP.Resize frames to resize', () => {
+ it('routes OP.Input frames to write and OP.Resize frames to resize', async () => {
const pty = fakePty()
const sock = fakeSocket()
const h = createHostHandlers(pty.mgr, sock.socket)
- h.onRpc({ id: 'r1', method: 'pty.create', params: { cols: 80, rows: 24 } })
+ await openViaAttach(h)
h.onFrame({ op: OP.Input, streamId: 1, seq: 0, payload: new TextEncoder().encode('ls\n') })
h.onFrame({ op: OP.Resize, streamId: 1, seq: 0, payload: resizePayload(120, 40) })
@@ -176,11 +187,11 @@ describe('createHostHandlers', () => {
expect(pty.calls).toHaveLength(0)
})
- it('pauses the PTY on backpressure and resumes on the next successful send', () => {
+ it('pauses the PTY on backpressure and resumes on the next successful send', async () => {
const pty = fakePty()
const sock = fakeSocket(false) // sendFrame returns false → backpressure
const h = createHostHandlers(pty.mgr, sock.socket)
- h.onRpc({ id: 'r1', method: 'pty.create', params: { cols: 80, rows: 24 } })
+ await openViaAttach(h)
pty.sinks().onData('a') // send fails → pause
expect(pty.calls).toContainEqual({ method: 'setFlow', args: ['pty-1', false] })
@@ -199,11 +210,11 @@ describe('createHostHandlers', () => {
expect(sock.responses[0]).toMatchObject({ id: 'r9', ok: false })
})
- it('pty.kill kills the session and forgets the stream', () => {
+ it('pty.kill kills the session and forgets the stream', async () => {
const pty = fakePty()
const sock = fakeSocket()
const h = createHostHandlers(pty.mgr, sock.socket)
- h.onRpc({ id: 'r1', method: 'pty.create', params: { cols: 80, rows: 24 } })
+ await openViaAttach(h)
h.onRpc({ id: 'r2', method: 'pty.kill', params: { streamId: 1 } })
expect(pty.calls).toContainEqual({ method: 'kill', args: ['pty-1'] })
@@ -213,11 +224,11 @@ describe('createHostHandlers', () => {
expect(pty.calls).toHaveLength(0)
})
- it('emits an OP.Error frame on PTY exit and drops the stream', () => {
+ it('emits an OP.Error frame on PTY exit and drops the stream', async () => {
const pty = fakePty()
const sock = fakeSocket()
const h = createHostHandlers(pty.mgr, sock.socket)
- h.onRpc({ id: 'r1', method: 'pty.create', params: { cols: 80, rows: 24 } })
+ await openViaAttach(h)
pty.sinks().onExit(0)
const errFrame = sock.frames.find((f) => f.op === OP.Error)
@@ -225,12 +236,12 @@ describe('createHostHandlers', () => {
expect(JSON.parse(Buffer.from(errFrame!.payload).toString('utf8'))).toEqual({ exitCode: 0 })
})
- it('closeAll kills every live session', () => {
+ it('closeAll kills every live session', async () => {
const pty = fakePty()
const sock = fakeSocket()
const h = createHostHandlers(pty.mgr, sock.socket)
- h.onRpc({ id: 'r1', method: 'pty.create', params: { cols: 80, rows: 24 } })
- h.onRpc({ id: 'r2', method: 'pty.create', params: { cols: 80, rows: 24 } })
+ await openViaAttach(h, 'node-1')
+ await openViaAttach(h, 'node-2')
h.closeAll()
expect(pty.calls.filter((c) => c.method === 'kill')).toHaveLength(2)
})
diff --git a/test/remote/remote-fs.test.ts b/test/remote/remote-fs.test.ts
index e778f80d0..df39ec429 100644
--- a/test/remote/remote-fs.test.ts
+++ b/test/remote/remote-fs.test.ts
@@ -81,7 +81,8 @@ describe('remote filesystem round-trip (client fs RPC → host fs-ops → real t
// wire the host's `respond` back through the same pair.
let host!: ReturnType<typeof createHostHandlers>
const pair = fakePair(() => host)
- host = createHostHandlers(noopPty(), pair.hostSocket)
+ // The temp dir is the shared root so the client's fs.* RPCs are permitted (fs jail).
+ host = createHostHandlers(noopPty(), pair.hostSocket, undefined, () => [dir])
const client = createClientHandlers(pair.clientSocket, noopSinks)
const file = path.join(dir, 'note.txt')
@@ -106,7 +107,7 @@ describe('remote filesystem round-trip (client fs RPC → host fs-ops → real t
it('degrades to empty/false on host fs errors (read/list/write of a bad path)', async () => {
let host!: ReturnType<typeof createHostHandlers>
const pair = fakePair(() => host)
- host = createHostHandlers(noopPty(), pair.hostSocket)
+ host = createHostHandlers(noopPty(), pair.hostSocket, undefined, () => [dir])
const client = createClientHandlers(pair.clientSocket, noopSinks)
expect(await client.fsRead(path.join(dir, 'does-not-exist.txt'))).toBe('')