Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
security: fix 4 relay/server vulns from the audit (Vuln 1-4)
enes6cf1258f3351
diff --git a/src/main/remote/e2ee.ts b/src/main/remote/e2ee.tsindex 78687d05a..5f075121c 100644--- a/src/main/remote/e2ee.ts+++ b/src/main/remote/e2ee.ts@@ -3,6 +3,7 @@// Pure functions over NaCl box (Curve25519 + XSalsa20-Poly1305): no sockets, no// Electron. The box format is `nonce ‖ ciphertext ‖ mac` so an interoperable peer// can be implemented against the same wire format.+import { hkdfSync } from 'node:crypto'import nacl from 'tweetnacl'export type KeyPair = {@@ -27,12 +28,39 @@ export function publicKeyFromB64(b64: string): Uint8Array {}// Derive the shared secret (ECDH precompute) from the peer's base64 public key-// and our secret key. Both sides arrive at the same value.+// and our secret key. Both sides arrive at the same value. This is the STABLE+// per-device-pair key (both endpoints use static keys for pin-once), so it must+// NOT be used directly to encrypt traffic — see deriveSessionKey.export function deriveSharedKey(theirPubB64: string, ourSecret: Uint8Array): Uint8Array {const theirPub = publicKeyFromB64(theirPubB64)return nacl.box.before(theirPub, ourSecret)}+// A fresh 16-byte session nonce, exchanged in the handshake.+export function randomSessionNonce(): Uint8Array {+ return nacl.randomBytes(16)+}++// Per-SESSION traffic key = HKDF-SHA256(baseShared, salt = hostNonce ‖ clientNonce).+// Because both endpoints hold STATIC keys (stable pin-once identity), the raw ECDH+// `baseShared` is identical on every reconnect — encrypting with it lets a malicious+// relay replay a whole recorded session's boxes against a fresh connection (the seq+// counter resets per connection, so it can't stop this). Mixing in fresh per-session+// nonces makes the traffic key unique to each session, so recorded boxes never decrypt+// under a later session's key. RFC 5869 HKDF; matches iOS CryptoKit HKDF<SHA256>.+export function deriveSessionKey(+ baseShared: Uint8Array,+ hostNonce: Uint8Array,+ clientNonce: Uint8Array+): Uint8Array {+ const salt = new Uint8Array(hostNonce.length + clientNonce.length)+ salt.set(hostNonce)+ salt.set(clientNonce, hostNonce.length)+ const info = new TextEncoder().encode('nodeterm-relay-session-v2')+ const out = hkdfSync('sha256', baseShared, salt, info, 32)+ return new Uint8Array(out)+}+// Encrypt with the precomputed shared key. Returns `nonce ‖ ciphertext ‖ mac`.export function encrypt(plain: Uint8Array, shared: Uint8Array): Uint8Array {const nonce = nacl.randomBytes(nacl.box.nonceLength)diff --git a/src/main/remote/host-service.ts b/src/main/remote/host-service.tsindex b5c7e10d6..0bc20c6cf 100644--- a/src/main/remote/host-service.ts+++ b/src/main/remote/host-service.ts@@ -20,6 +20,7 @@// testable with fakes; `initRemoteHost` wires it to IPC, the license gate, and the API call.import { promises as fs } from 'fs'+import { randomUUID } from 'crypto'import path from 'path'import { app, ipcMain, safeStorage, type BrowserWindow } from 'electron'import { IPC } from '../../shared/ipc'@@ -599,6 +600,10 @@ export function connectHostSession(opts: HostSessionOptions): HostSession {let broadcastTimer: ReturnType<typeof setTimeout> | null = nullfunction pushCurrentCanvas(): void {+ // NEVER expose canvas state (node titles, project cwds, sticky text, editor file paths,+ // browser URLs, ssh user@host) before the human approves the device — a leaked/unapproved+ // client completing only the E2EE handshake must see nothing.+ if (!approved) returnconst state = opts.getLatestCanvas()if (state) canvasSync?.setState(state)}@@ -614,6 +619,8 @@ export function connectHostSession(opts: HostSessionOptions): HostSession {const session: HostSession = {approve() {approved = true+ // Flush the current canvas now that the device is trusted.+ pushCurrentCanvas()},isApproved() {return approved@@ -645,23 +652,23 @@ export function connectHostSession(opts: HostSessionOptions): HostSession {role: 'host',ourKeys: opts.ourKeys,onReady: () => {- // Bridge established. Require approval before serving any pty/fs RPC. Canvas state still- // pushes (read-only mirror) so the client isn't staring at a blank screen while pending.+ // Bridge established. Require approval before serving ANYTHING — including canvas state+ // (which carries workspace metadata). Nothing is pushed until approve() flushes it.approved = falseopts.onPeerReady(session)- pushCurrentCanvas()},onRpc: (req) => {+ // Until approved, refuse every request — pty/fs RPCs, client mutations, AND canvas+ // snapshots (canvas:request). An unapproved device gets nothing but the approval prompt.+ if (!approved) {+ if (req.id) socket.respond(req.id, false, { message: 'Awaiting host approval.' })+ return+ }// 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 approved, refuse every state-changing request (pty/fs RPCs + client mutations).- if (!approved) {- if (req.id) socket.respond(req.id, false, { message: 'Awaiting host approval.' })- return- }if (canvasSync?.handleRpc(req)) returnhandlers?.onRpc(req)},@@ -702,6 +709,10 @@ export function initRemoteHost(): void {initHostCanvasHub()let session: HostSession | null = null+ // A fresh id per pending approval. The approve/reject IPC channels are SHARED with the standing+ // phone host, and a single "Approve" click broadcasts to both listeners — so each acts only on+ // an event carrying ITS OWN pending id, never on one meant for the other host.+ let pendingApprovalId: string | null = nullfunction send(channel: string, ...args: unknown[]): void {if (!win.isDestroyed()) win.webContents.send(channel, ...args)@@ -735,9 +746,14 @@ export function initRemoteHost(subscribeCanvas,applyMutation: (mutation) => send(IPC.remoteHostApplyMutation, mutation),listProjects,- // Interactive host: surface the SAS so the human can verify + approve.- onPeerReady: (s) => send(IPC.remoteHostPeerPending, { sas: s.sas() }),- onClose: () => {}+ // Interactive host: surface the SAS + a fresh pending id so the human can verify + approve.+ onPeerReady: (s) => {+ pendingApprovalId = randomUUID()+ send(IPC.remoteHostPeerPending, { sas: s.sas(), id: pendingApprovalId })+ },+ onClose: () => {+ pendingApprovalId = null+ }})return {@@ -752,11 +768,15 @@ export function initRemoteHost(// Host human approved the pending device → start serving its pty/fs RPCs. Only act on a// still-pending session: the approve/reject channels are shared with the standing phone host,// so an event meant for the phone must not disturb an already-approved interactive session.- ipcMain.on(IPC.remoteHostApprove, () => {+ ipcMain.on(IPC.remoteHostApprove, (_e, msg: { id?: string } = {}) => {+ if (!pendingApprovalId || msg?.id !== pendingApprovalId) return+ pendingApprovalId = nullif (session && !session.isApproved()) session.approve()})// Host human rejected the pending device → drop the connection entirely (pending sessions only).- ipcMain.on(IPC.remoteHostReject, () => {+ ipcMain.on(IPC.remoteHostReject, (_e, msg: { id?: string } = {}) => {+ if (!pendingApprovalId || msg?.id !== pendingApprovalId) return+ pendingApprovalId = nullif (session && !session.isApproved()) {session.close()session = nulldiff --git a/src/main/remote/relay-socket.ts b/src/main/remote/relay-socket.tsindex a8b35abeb..d5491ef16 100644--- a/src/main/remote/relay-socket.ts+++ b/src/main/remote/relay-socket.ts@@ -30,7 +30,16 @@// 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, sasFromSharedKey, type KeyPair } from './e2ee'+import {+ decrypt,+ deriveSessionKey,+ deriveSharedKey,+ encrypt,+ publicKeyToB64,+ randomSessionNonce,+ 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@@ -111,8 +120,17 @@ type RpcEnvelope =| { kind: 'keepalive' }type HandshakeControl =- | { type: 'e2ee_hello'; publicKeyB64: string }- | { type: 'e2ee_ready' }+ | { type: 'e2ee_hello'; publicKeyB64: string; nonceB64: string }+ | { type: 'e2ee_ready'; nonceB64: string }++function nonceToB64(n: Uint8Array): string {+ return Buffer.from(n).toString('base64')+}+function nonceFromB64(b64: unknown): Uint8Array | null {+ if (typeof b64 !== 'string') return null+ const n = Uint8Array.from(Buffer.from(b64, 'base64'))+ return n.length === 16 ? n : null+}type State = 'connecting' | 'handshaking' | 'ready' | 'closed'@@ -125,7 +143,16 @@ export function connectRelay(opts: ConnectRelayOptions): RelaySocket {}let transport: RelayTransport | null = null- let sharedKey: Uint8Array | null = null+ // baseKey = the stable ECDH precompute (for the SAS, which represents the pinned identity).+ // sessionKey = HKDF(baseKey, hostNonce‖clientNonce) = the fresh per-session traffic key.+ let baseKey: Uint8Array | null = null+ let sessionKey: Uint8Array | null = null+ let ourNonce: Uint8Array | null = null+ // Role byte prefixed to every sealed plaintext, so a relay can't REFLECT a box back to its+ // sender (same sessionKey both directions): each side only accepts boxes tagged with the peer's+ // role. host=1, client=2.+ const OUR_ROLE = opts.role === 'host' ? 1 : 2+ const PEER_ROLE = opts.role === 'host' ? 2 : 1// The peer's base64 public key. Known up front for a client (the pinned host key); learned from// `e2ee_hello` for a host. Exposed via peerPublicKeyB64() for the standing host's pin-once check.let peerPubB64: string | null = opts.role === 'client' ? opts.theirPubB64 ?? null : null@@ -161,7 +188,9 @@ export function connectRelay(opts: ConnectRelayOptions): RelaySocket {return}state = 'connecting'- sharedKey = null+ baseKey = null+ sessionKey = null+ ourNonce = randomSessionNonce()readyFired = falsesendSeq = 0recvSeq = -1@@ -180,9 +209,14 @@ export function connectRelay(opts: ConnectRelayOptions): RelaySocket {state = 'handshaking'if (opts.role === 'client') {- // Client knows the host pubkey: derive now and greet.- sharedKey = deriveSharedKey(opts.theirPubB64!, opts.ourKeys.secretKey)- sendControl({ type: 'e2ee_hello', publicKeyB64: publicKeyToB64(opts.ourKeys.publicKey) })+ // Client knows the host pubkey: derive the base (identity) key now and greet with our+ // session nonce. The traffic key is derived once the host's nonce arrives in e2ee_ready.+ baseKey = deriveSharedKey(opts.theirPubB64!, opts.ourKeys.secretKey)+ sendControl({+ type: 'e2ee_hello',+ publicKeyB64: publicKeyToB64(opts.ourKeys.publicKey),+ nonceB64: nonceToB64(ourNonce!)+ })}// Host waits passively for `e2ee_hello` to learn the client pubkey.}@@ -193,32 +227,36 @@ export function connectRelay(opts: ConnectRelayOptions): RelaySocket {// 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.+ // Authenticated plaintext layout: [role:1][seq:8][payload…]. The role defeats reflection; the+ // strictly-increasing seq defeats in-session replay/reorder.const SEQ_BYTES = 8- function withSeq(plaintext: Uint8Array): Uint8Array {+ const HEADER_BYTES = 1 + SEQ_BYTES+ function withHeader(plaintext: Uint8Array): Uint8Array {const seq = sendSeq++- const out = new Uint8Array(SEQ_BYTES + plaintext.length)+ const out = new Uint8Array(HEADER_BYTES + plaintext.length)+ out[0] = OUR_ROLEconst view = new DataView(out.buffer)- view.setUint32(0, Math.floor(seq / 0x100000000), true)- view.setUint32(4, seq >>> 0, true)- out.set(plaintext, SEQ_BYTES)+ view.setUint32(1, Math.floor(seq / 0x100000000), true)+ view.setUint32(5, seq >>> 0, true)+ out.set(plaintext, HEADER_BYTES)return out}function sendEncrypted(plaintext: Uint8Array): boolean {- if (!transport || !sharedKey || state !== 'ready') {+ if (!transport || !sessionKey || state !== 'ready') {return false}- transport.send(encrypt(withSeq(plaintext), sharedKey))+ transport.send(encrypt(withHeader(plaintext), sessionKey))return true}// During the handshake the auth control frames must be sent before `state`// flips to 'ready', so this variant does not gate on state.function sendEncryptedHandshake(plaintext: Uint8Array): void {- if (!transport || !sharedKey) {+ if (!transport || !sessionKey) {return}- transport.send(encrypt(withSeq(plaintext), sharedKey))+ transport.send(encrypt(withHeader(plaintext), sessionKey))}function tagged(tag: number, body: Uint8Array): Uint8Array {@@ -255,23 +293,27 @@ export function connectRelay(opts: ConnectRelayOptions): RelaySocket {return}- // Everything binary is an E2EE box.- if (!sharedKey) {+ // Everything binary is an E2EE box, sealed under the fresh session key.+ if (!sessionKey) {return}- const sealed = decrypt(bytes, sharedKey)- if (!sealed || sealed.length < SEQ_BYTES) {+ const sealed = decrypt(bytes, sessionKey)+ if (!sealed || sealed.length < HEADER_BYTES) {+ return+ }+ // Reject a box tagged with our OWN role (a reflected message) — only the peer's role is valid.+ if (sealed[0] !== PEER_ROLE) {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)+ const seq = seqView.getUint32(1, true) * 0x100000000 + seqView.getUint32(5, true)if (seq <= recvSeq) {return}recvSeq = seq- const plain = sealed.subarray(SEQ_BYTES)+ const plain = sealed.subarray(HEADER_BYTES)if (state === 'handshaking') {handleHandshakeEncrypted(plain)@@ -291,19 +333,29 @@ export function connectRelay(opts: ConnectRelayOptions): RelaySocket {return}if (control.type === 'e2ee_hello' && opts.role === 'host') {- // Host learns the client pubkey, derives the shared key, replies ready.- if (typeof control.publicKeyB64 !== 'string') {+ // Host learns the client pubkey + its session nonce, derives the base identity key and the+ // fresh session traffic key, replies ready with its own nonce.+ const clientNonce = nonceFromB64(control.nonceB64)+ if (typeof control.publicKeyB64 !== 'string' || !clientNonce || !ourNonce) {return}peerPubB64 = control.publicKeyB64- sharedKey = deriveSharedKey(control.publicKeyB64, opts.ourKeys.secretKey)- sendControl({ type: 'e2ee_ready' })+ baseKey = deriveSharedKey(control.publicKeyB64, opts.ourKeys.secretKey)+ // salt = hostNonce ‖ clientNonce (host's nonce first, both roles agree on the order).+ sessionKey = deriveSessionKey(baseKey, ourNonce, clientNonce)+ sendControl({ type: 'e2ee_ready', nonceB64: nonceToB64(ourNonce) })return}if (control.type === 'e2ee_ready' && opts.role === 'client') {- // Client proves the pairing with an encrypted auth marker. The relay- // already verified the token and the offer pins the host pubkey, so a- // simple marker is sufficient for MVP.+ // Client learns the host's nonce, derives the same session key, and proves the pairing with+ // an encrypted auth marker. The marker is sealed under the SESSION key (which mixes in this+ // session's fresh nonces), so a recorded auth box from an earlier session can't be replayed+ // to silently authenticate a new one.+ const hostNonce = nonceFromB64(control.nonceB64)+ if (!hostNonce || !baseKey || !ourNonce) {+ return+ }+ sessionKey = deriveSessionKey(baseKey, hostNonce, ourNonce)sendEncryptedHandshake(tagged(TAG_RPC, textEncoder.encode(JSON.stringify({ type: 'e2ee_auth' }))))}}@@ -404,7 +456,8 @@ export function connectRelay(opts: ConnectRelayOptions): RelaySocket {function handleClose(): void {stopKeepalive()transport = null- sharedKey = null+ baseKey = null+ sessionKey = nullconst wasReady = state === 'ready'rejectAllPending('Relay connection closed.')if (intentionallyClosed) {@@ -490,7 +543,7 @@ export function connectRelay(opts: ConnectRelayOptions): RelaySocket {return sendEncrypted(tagged(TAG_FRAME, encodeFrame(op, streamId, seq, payload)))},sas() {- return sharedKey ? sasFromSharedKey(sharedKey) : null+ return baseKey ? sasFromSharedKey(baseKey) : null},peerPublicKeyB64() {return peerPubB64@@ -506,7 +559,8 @@ export function connectRelay(opts: ConnectRelayOptions): RelaySocket {state = 'closed'transport?.close()transport = null- sharedKey = null+ baseKey = null+ sessionKey = null}}}diff --git a/src/main/remote/standing-host.ts b/src/main/remote/standing-host.tsindex 8c55c1073..d3983bd23 100644--- a/src/main/remote/standing-host.ts+++ b/src/main/remote/standing-host.ts@@ -17,6 +17,7 @@// shared with the interactive host via `connectHostSession`. Pin/lookup logic is the pure,// unit-tested `approved-devices-core`.+import { randomUUID } from 'crypto'import { ipcMain, type BrowserWindow } from 'electron'import { IPC } from '../../shared/ipc'import type { CanvasMutation, Settings } from '../../shared/types'@@ -108,6 +109,9 @@ export function initStandingHost(// and pin it when the human approves, even though that session is already gone. The phone's next// connect (same stable key) then auto-approves.let pendingApprovalPub: string | null = null+ // Fresh id per pending approval; the approve/reject IPC must carry it (see the interactive host).+ let pendingApprovalId: string | null = null+ let pendingApprovalTimer: ReturnType<typeof setTimeout> | null = nulllet refreshTimer: ReturnType<typeof setTimeout> | null = nulllet reconnectTimer: ReturnType<typeof setTimeout> | null = nulllet reconnectAttempt = 0@@ -183,10 +187,22 @@ export function initStandingHost(return}// Unknown device → require the host human's approval (shared SAS dialog). Pin on approve.- // Remember the pubkey so approval pins it even if the phone's browse socket closes first.+ // Remember the pubkey (+ a fresh pending id) so approval pins THIS device even if the phone's+ // browse socket closes first — but only when the approve carries our matching id, so an+ // approve meant for the interactive host can never pin our (possibly stale) pubkey.pendingPeer = spendingApprovalPub = pub- send(IPC.remoteHostPeerPending, { sas: s.sas() })+ pendingApprovalId = randomUUID()+ // Bound the stale-pubkey window: if the human doesn't decide within a couple of minutes, drop+ // the remembered approval so it can't be pinned much later by an accidental approve.+ if (pendingApprovalTimer) clearTimeout(pendingApprovalTimer)+ pendingApprovalTimer = setTimeout(() => {+ pendingApprovalPub = null+ pendingApprovalId = null+ pendingApprovalTimer = null+ }, 120_000)+ pendingApprovalTimer.unref?.()+ send(IPC.remoteHostPeerPending, { sas: s.sas(), id: pendingApprovalId })}async function connectOnce(): Promise<void> {@@ -250,23 +266,32 @@ export function initStandingHost(// Host human approved / rejected the pending phone. These channels are shared with the// interactive host; guarding on our own `pendingPeer` keeps the two independent.- ipcMain.on(IPC.remoteHostApprove, () => {+ ipcMain.on(IPC.remoteHostApprove, (_e, msg: { id?: string } = {}) => {+ // Only act on an approve carrying OUR pending id — a click meant for the interactive host must+ // never pin our (possibly stale) pubkey.+ if (!pendingApprovalId || msg?.id !== pendingApprovalId) return+ pendingApprovalId = null+ if (pendingApprovalTimer) { clearTimeout(pendingApprovalTimer); pendingApprovalTimer = null }// Pin the DEVICE (its stable box key), whether or not its session is still live — the phone's// browse socket may have already closed. Prefer the live peer's key, else the remembered one.const pub = pendingPeer?.peerPublicKeyB64() ?? pendingApprovalPub- if (!pub) returnpendingApprovalPub = null- void loadApprovedDevices()- .then((store) => saveApprovedDevices(pinDevice(store, pub)))- .catch(() => {- // A failed pin is non-fatal: the device re-prompts next connect. Never block on the write.- })+ if (pub) {+ void loadApprovedDevices()+ .then((store) => saveApprovedDevices(pinDevice(store, pub)))+ .catch(() => {+ // A failed pin is non-fatal: the device re-prompts next connect. Never block on the write.+ })+ }// Approve the live session too, if this device is still connected (fast approval, same socket).const s = pendingPeerpendingPeer = nulls?.approve()})- ipcMain.on(IPC.remoteHostReject, () => {+ ipcMain.on(IPC.remoteHostReject, (_e, msg: { id?: string } = {}) => {+ if (!pendingApprovalId || msg?.id !== pendingApprovalId) return+ pendingApprovalId = null+ if (pendingApprovalTimer) { clearTimeout(pendingApprovalTimer); pendingApprovalTimer = null }pendingApprovalPub = nullconst s = pendingPeerif (!s) returndiff --git a/src/preload/index.ts b/src/preload/index.tsindex d72c85230..d3a2a00de 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -37,7 +37,7 @@ function subscribe<A extends unknown[] = []>(channel: string) {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 subscribePeerPending = subscribe<[{ sas: string | null; id: string }]>(IPC.remoteHostPeerPending)const api: NodeTerminalApi = {pty: {@@ -291,8 +291,8 @@ const api: NodeTerminalApi = {sendCanvasState: (state) => ipcRenderer.send(IPC.remoteHostCanvasState, state),onApplyMutation: subscribeMutation,onPeerPending: subscribePeerPending,- approve: () => ipcRenderer.send(IPC.remoteHostApprove),- reject: () => ipcRenderer.send(IPC.remoteHostReject),+ approve: (id: string) => ipcRenderer.send(IPC.remoteHostApprove, { id }),+ reject: (id: string) => ipcRenderer.send(IPC.remoteHostReject, { id }),setPhoneAccess: (enabled) => ipcRenderer.send(IPC.remoteStandingHostSet, enabled)},remoteClient: {diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.tsindex 55df9e0f7..665278d2f 100644--- a/src/renderer/bridge/stubs.ts+++ b/src/renderer/bridge/stubs.ts@@ -203,8 +203,8 @@ export function buildStubApi(): Omit<NodeTerminalApi, 'pty' | 'workspace' | 'setsendCanvasState: noop,onApplyMutation: noopUnsub,onPeerPending: noopUnsub,- approve: noop,- reject: noop,+ approve: (_id: string) => {},+ reject: (_id: string) => {},setPhoneAccess: noop},remoteClient: {diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 1851c7dd8..09cccddc7 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -321,7 +321,7 @@ export function Canvas() {// Live SSH ControlMaster status per project id (drives the thin connection banner).const [sshStatus, setSshStatus] = useState<Record<string, SshProjectStatus>>({})// 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 [pendingPeer, setPendingPeer] = useState<{ sas: string | null; id: string } | null>(null)const [confirm, setConfirm] = useState<{message: stringonConfirm: () => void@@ -3959,11 +3959,11 @@ export function Canvas() {cancelLabel="Deny"danger={false}onConfirm={() => {- window.nodeTerminal.remoteHost.approve()+ window.nodeTerminal.remoteHost.approve(pendingPeer.id)setPendingPeer(null)}}onCancel={() => {- window.nodeTerminal.remoteHost.reject()+ window.nodeTerminal.remoteHost.reject(pendingPeer.id)setPendingPeer(null)}}/>diff --git a/src/server/auth.ts b/src/server/auth.tsindex 9a082a981..a2db8d08c 100644--- a/src/server/auth.ts+++ b/src/server/auth.ts@@ -96,12 +96,18 @@ export class Auth {return this.setupTokenValue}- consumeSetupToken(candidate: string): boolean {+ /** Constant-time check WITHOUT consuming — GET /setup uses this to decide whether the caller+ * (who must present the token printed to the console) may see the setup form. */+ verifySetupToken(candidate: string): boolean {const current = this.setupTokenValue- if (current === null) return false+ if (current === null || !candidate) return falseconst a = crypto.createHash('sha256').update(candidate).digest()const b = crypto.createHash('sha256').update(current).digest()- if (!crypto.timingSafeEqual(a, b)) return false+ return crypto.timingSafeEqual(a, b)+ }++ consumeSetupToken(candidate: string): boolean {+ if (!this.verifySetupToken(candidate)) return falsethis.setupTokenValue = nullreturn true}diff --git a/src/server/http.ts b/src/server/http.tsindex adadad584..54c78aaac 100644--- a/src/server/http.ts+++ b/src/server/http.ts@@ -136,6 +136,10 @@ function loginPage(hasError: boolean): string {return `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Sign in — nodeterm</title></head><body style="${PAGE_STYLE}"><form method="post" action="/auth/login" style="${CARD_STYLE}"><h1 style="${H1_STYLE}">nodeterm</h1><p style="${SUB_STYLE}">Sign in to continue</p>${errLine}<input style="${INPUT_STYLE}" type="password" name="password" placeholder="Password" autofocus autocomplete="current-password"><button style="${BUTTON_STYLE}" type="submit">Sign in</button></form></body></html>`}+function setupNeedsTokenPage(): string {+ return `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Set up — nodeterm</title></head><body style="${PAGE_STYLE}"><div style="${CARD_STYLE}"><h1 style="${H1_STYLE}">Set up nodeterm</h1><p style="${SUB_STYLE}">Open the setup link printed in the server console — it carries a one-time token. This page can't be used without it.</p></div></body></html>`+}+function setupPage(token: string): string {return `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Set up — nodeterm</title></head><body style="${PAGE_STYLE}"><form method="post" action="/auth/setup" style="${CARD_STYLE}"><h1 style="${H1_STYLE}">Welcome to nodeterm</h1><p style="${SUB_STYLE}">Choose a password to secure this server.</p><input type="hidden" name="token" value="${esc(token)}"><input style="${INPUT_STYLE}" type="password" name="password" placeholder="New password (min 8 chars)" autofocus autocomplete="new-password" minlength="8"><button style="${BUTTON_STYLE}" type="submit">Create password</button></form></body></html>`}@@ -232,7 +236,15 @@ export function createHttpHandler(sendPage(res, 403, '<!doctype html><title>403</title><p style="color:#fff">Already configured.</p>')return}- sendPage(res, 200, setupPage(auth.setupToken()))+ // The setup token is printed to the SERVER CONSOLE and must be presented as `?token=`.+ // Never serve the live token to a caller that hasn't already got it (otherwise anyone who+ // can reach /setup before a password is set could harvest it → POST /auth/setup → takeover).+ const provided = url.searchParams.get('token') || ''+ if (!auth.verifySetupToken(provided)) {+ sendPage(res, 403, setupNeedsTokenPage())+ return+ }+ sendPage(res, 200, setupPage(provided))return}diff --git a/src/shared/types.ts b/src/shared/types.tsindex a14109ac2..9de288b05 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -915,11 +915,11 @@ export interface RemoteHostApi {* `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+ onPeerPending(listener: (info: { sas: string | null; id: string }) => void): () => void+ /** Approve the pending client (by its pending id) → the host begins serving its pty/fs RPCs. */+ approve(id: string): void+ /** Reject the pending client (by its pending id) → the connection is dropped. */+ reject(id: string): void/*** Start/stop the standing (phone) relay host so a paired phone can reach this Mac from anywhere.* Mirrors `settings.phoneAccessEnabled`; the host also honors the Pro gate internally.