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
fix(main): validate the webContents id the renderer registers as a browser guest
Claude Code5b4ab3a8a29d
diff --git a/src/main/browser-guest-registry.test.ts b/src/main/browser-guest-registry.test.tsnew file mode 100644index 000000000..b555dee11--- /dev/null+++ b/src/main/browser-guest-registry.test.ts@@ -0,0 +1,130 @@+// The guard main did not have: `browserGuests` stored whatever integer arrived over IPC. Every+// case below is a renderer-supplied value, because the renderer is the attackable half of this+// boundary — a compromised or merely buggy one must not be able to nominate the app's own window.+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'+import { resolve } from 'node:path'+import {+ browserDiscardedMessage,+ registerBrowserGuest,+ type BrowserGuest,+ type BrowserSurfaceKind+} from './browser-guest-registry'++const lookup =+ (types: Record<number, string>) =>+ (id: number): { getType: () => string } | null =>+ types[id] ? { getType: () => types[id] } : null++describe('registerBrowserGuest', () => {+ it('stores a real webview guest', () => {+ const m = new Map<number, BrowserGuest>()+ expect(registerBrowserGuest(m, 7, 'browser-1', 'canvas', lookup({ 7: 'webview' }))).toBe(true)+ expect(m.get(7)).toEqual({ nodeId: 'browser-1', surface: 'canvas' })+ })++ it('REFUSES an id naming the app window — this is the escalation the guard exists for', () => {+ const m = new Map<number, BrowserGuest>()+ expect(registerBrowserGuest(m, 1, 'browser-1', 'canvas', lookup({ 1: 'window' }))).toBe(false)+ expect(m.size).toBe(0)+ })++ it('refuses every non-webview type Electron can hand back, not just `window`', () => {+ const m = new Map<number, BrowserGuest>()+ for (const type of ['window', 'browserView', 'remote', 'backgroundPage', 'offscreen']) {+ expect(registerBrowserGuest(m, 5, 'browser-1', 'canvas', lookup({ 5: type })), type).toBe(+ false+ )+ }+ expect(m.size).toBe(0)+ })++ it('refuses an id that names nothing at all', () => {+ const m = new Map<number, BrowserGuest>()+ expect(registerBrowserGuest(m, 99, 'browser-1', 'canvas', lookup({}))).toBe(false)+ expect(m.size).toBe(0)+ })++ it('refuses a lookup that throws — a destroyed id is not a guest', () => {+ const m = new Map<number, BrowserGuest>()+ const throwing = (): never => {+ throw new Error('Object has been destroyed')+ }+ expect(registerBrowserGuest(m, 7, 'browser-1', 'canvas', throwing)).toBe(false)+ expect(m.size).toBe(0)+ })++ it('refuses an id that is not a positive integer, before it ever reaches the lookup', () => {+ const m = new Map<number, BrowserGuest>()+ // A lookup that would happily call ANYTHING a webview: the id guard is the only thing under+ // test here, so nothing else may be doing the refusing.+ let lookups = 0+ const anything = (): { getType: () => string } => {+ lookups += 1+ return { getType: () => 'webview' }+ }+ for (const id of [0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY]) {+ expect(registerBrowserGuest(m, id, 'browser-1', 'canvas', anything), `${id}`).toBe(false)+ }+ expect(m.size).toBe(0)+ expect(lookups).toBe(0)+ })++ it('refuses a node id `isSafeNodeId` refuses — it is a map key and, later, a storage key', () => {+ const m = new Map<number, BrowserGuest>()+ for (const bad of ['../etc', '', '.', '..', 'a/b', 'a b', 'x'.repeat(200)]) {+ expect(registerBrowserGuest(m, 7, bad, 'canvas', lookup({ 7: 'webview' })), bad).toBe(false)+ }+ expect(m.size).toBe(0)+ })++ it('refuses an unknown surface value', () => {+ const m = new Map<number, BrowserGuest>()+ // The renderer is the more attackable half; `surface` is what selects a debugger target later.+ for (const bad of ['modal ', 'CANVAS', '', undefined, null, 1]) {+ expect(+ registerBrowserGuest(m, 7, 'browser-1', bad as unknown as BrowserSurfaceKind, lookup({ 7: 'webview' })),+ String(bad)+ ).toBe(false)+ }+ expect(m.size).toBe(0)+ })++ it('accepts the modal surface, and keeps both of a node`s guests apart', () => {+ const m = new Map<number, BrowserGuest>()+ expect(registerBrowserGuest(m, 11, 'browser-3', 'modal', lookup({ 11: 'webview' }))).toBe(true)+ expect(registerBrowserGuest(m, 12, 'browser-3', 'canvas', lookup({ 12: 'webview' }))).toBe(true)+ expect(m.get(11)).toEqual({ nodeId: 'browser-3', surface: 'modal' })+ expect(m.get(12)).toEqual({ nodeId: 'browser-3', surface: 'canvas' })+ })+})++describe('browserDiscardedMessage', () => {+ it('names the memory saver rather than reading as a permissions failure', () => {+ const msg = browserDiscardedMessage('browser-3')+ expect(msg).toContain('browser-3')+ expect(msg).toContain('memory')+ // The rule it exists for: never blame permissions for a lifecycle event. "not drivable" would+ // send the next debugger to the identity code for a bug in browser-discard-policy.ts.+ expect(msg).not.toContain('drivable')+ expect(msg).not.toMatch(/refus|permission|identity|token/i)+ // It also has to say what to DO — a message with no way out is a dead end for the agent.+ expect(msg).toContain('bring it on screen')+ // Single line: every control reply is rendered as one.+ expect(msg).not.toContain('\n')+ })+})++/**+ * The guard is only worth anything if it is on the path. `ipcMain.on` cannot be exercised without+ * Electron, so this one claim — every write to `browserGuests` goes through the guard — is checked+ * against the source. It is the failure a pure unit test cannot see: a guard nobody calls.+ */+describe('the IPC handler is wired through it', () => {+ it('main never writes to browserGuests directly', () => {+ const src = readFileSync(resolve(__dirname, 'index.ts'), 'utf8')+ expect(src).toContain('registerBrowserGuest(browserGuests')+ // `.set(` anywhere on this map would be a second, unguarded door.+ expect(src).not.toContain('browserGuests.set(')+ })+})diff --git a/src/main/browser-guest-registry.ts b/src/main/browser-guest-registry.tsnew file mode 100644index 000000000..9cdf3be01--- /dev/null+++ b/src/main/browser-guest-registry.ts@@ -0,0 +1,78 @@+/**+ * Who is allowed into `browserGuests`, and what the answer is when the page an agent asked for is+ * gone. The pure half of both, so it is testable without Electron.+ */+// `src/main` may import `src/core`; the renderer may not, which is why this predicate will move to+// `@shared/safe-id` when the capability work needs it renderer-side. One predicate, never a copy.+import { isSafeNodeId } from '../core/remote-safety'++/**+ * Which of a node's two possible webviews a registration is.+ *+ * One node id can have TWO live guests — the canvas one (`BrowserNode`) and the kanban card modal+ * one (`CardModal`) — both mounting `BrowserSurface` with the SAME nodeId, so a reverse lookup by+ * node id picks arbitrarily. The field is recorded here first; threading it from both mount sites+ * is its own change.+ */+export type BrowserSurfaceKind = 'canvas' | 'modal'++export interface BrowserGuest {+ nodeId: string+ surface: BrowserSurfaceKind+}++/** The minimum of Electron's `webContents` this module needs, injected so the guard is testable+ * without Electron (`src/main` is not unit-testable against the real module). */+export type WebContentsLookup = (id: number) => { getType(): string } | null++/**+ * Record a browser guest, having first proven the renderer told the truth about it.+ *+ * WHY THE GUARD: main stored whatever integer the renderer sent. That was harmless while the map+ * only routed new-window events — and it becomes a privilege escalation the moment the integer+ * selects a `webContents` whose `.debugger` we attach to, because an unvalidated id can name the+ * app's own window. Stolen from the external S8 backend (`browser-use-backend.ts`, which checked+ * `contents.getType() !== 'webview'` before treating a renderer-supplied id as a guest) with credit+ * to **proteus-dev**; the strongest single idea in that file, and the only part of it kept.+ *+ * The node id is validated too: it is a map key here and a lease/partition key later, and it comes+ * from a canvas built out of git-shared `project.json`.+ *+ * Returns whether the registration was accepted, so the caller can say so in the log rather than+ * failing silently — a refused guest shows up later as a popup that does not open, and there is+ * nothing else on the wire to explain it.+ */+export function registerBrowserGuest(+ guests: Map<number, BrowserGuest>,+ webContentsId: number,+ nodeId: string,+ surface: BrowserSurfaceKind,+ lookup: WebContentsLookup+): boolean {+ if (!Number.isInteger(webContentsId) || webContentsId <= 0) return false+ if (!isSafeNodeId(nodeId)) return false+ if (surface !== 'canvas' && surface !== 'modal') return false+ // The lookup can throw for a destroyed id (Electron's own accessors do); a guest that cannot be+ // looked at is not a guest.+ let contents: { getType(): string } | null = null+ try {+ contents = lookup(webContentsId)+ } catch {+ return false+ }+ if (!contents || contents.getType() !== 'webview') return false+ guests.set(webContentsId, { nodeId, surface })+ return true+}++/**+ * What to say when a node exists but its page does not, because the memory saver released it.+ *+ * NEVER blame permissions for a lifecycle event. A target killed by the hidden-webview discard+ * reads as a permissions failure if we answer "not drivable", and that sends the next debugger to+ * the identity code for a bug that lives in `browser-discard-policy.ts`. It names the cause, names+ * the two ways out, and stays one line (every control reply is single-line by construction).+ */+export const browserDiscardedMessage = (id: string): string =>+ `browser: ${id} was released to save memory while hidden and its page is gone; ` ++ `bring it on screen or open a new one`diff --git a/src/main/index.ts b/src/main/index.tsindex e6f66a5eb..2dae3c816 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -5,10 +5,15 @@ import { readFile } from 'fs/promises'import { statSync } from 'fs'import { homedir, hostname } from 'os'import { randomUUID } from 'crypto'-import { app, BrowserWindow, clipboard, dialog, ipcMain, Notification, powerMonitor, safeStorage, shell, systemPreferences } from 'electron'+import { app, BrowserWindow, clipboard, dialog, ipcMain, Notification, powerMonitor, safeStorage, shell, systemPreferences, webContents } from 'electron'import { IPC } from '../shared/ipc'import { writeFilesToClipboard } from './clipboard-files'import { registerFsHandlers } from '../core/fs-handlers'+import {+ registerBrowserGuest,+ type BrowserGuest,+ type BrowserSurfaceKind+} from './browser-guest-registry'import { registerBoardLogHandlers, type BoardLogRoute } from '../core/board-log-handlers'import type { RemoteLogExec } from '../core/board-log'import { boardLogRemotePath } from '../core/board-log'@@ -323,8 +328,10 @@ let activeRemote: { cwd: string; ref: GitRemoteRef } | null = null// True from the first before-quit on: lets window close-events through (see hide-on-close).let quitting = false-// Browser <webview> guest webContents id → its browser node id (for new-window capture).-const browserGuests = new Map<number, string>()+// Browser <webview> guest webContents id → the browser node (and which of its two surfaces) it+// belongs to. Used today for new-window capture; every entry is proven to BE a <webview> before it+// lands here — see `registerBrowserGuest`.+const browserGuests = new Map<number, BrowserGuest>()// Node → live tail bookkeeping, so closing a node (× → pty:destroy) releases its file tailers.// Without this, a node closed mid-run never emits SessionEnd/PostToolUse, so context-tail (1s@@ -519,7 +526,7 @@ app.whenReady().then(async () => {// (never a real popup). Only http(s); other schemes are dropped. The map is consulted// live at call time, so a guest registered later (on dom-ready) is seen when a popup fires.contents.setWindowOpenHandler(({ url }) => {- const sourceNodeId = browserGuests.get(contents.id)+ const sourceNodeId = browserGuests.get(contents.id)?.nodeIdif (sourceNodeId && /^https?:\/\//i.test(url)) {sendToMain(IPC.browserNewWindow, { url, sourceNodeId })}@@ -570,9 +577,24 @@ app.whenReady().then(async () => {ipcMain.handle(IPC.mediaAllow, (_e, absPath: string) => allowMediaPath(absPath))ipcMain.handle(IPC.mediaWriteHtml, (_e, html: string) => writeAgentHtml(html))- ipcMain.on(IPC.browserRegister, (_e, webContentsId: number, nodeId: string) => {- browserGuests.set(webContentsId, nodeId)- })+ ipcMain.on(+ IPC.browserRegister,+ (_e, webContentsId: number, nodeId: string, surface?: BrowserSurfaceKind) => {+ // `surface` is optional ON THE WIRE only: both mount sites still send two arguments, so an+ // absent value means "the canvas one", which is what every registration was taken to be+ // before the field existed. A value that is present and wrong is refused, not defaulted.+ const kind = surface === undefined ? 'canvas' : surface+ if (+ !registerBrowserGuest(browserGuests, webContentsId, nodeId, kind, (id) =>+ webContents.fromId(id) ?? null+ )+ ) {+ // Loud, because the symptom otherwise is "popups from this node stopped opening" with+ // nothing anywhere to explain it.+ console.warn('[browser] refused guest registration', { webContentsId, nodeId, surface })+ }+ }+ )ipcMain.on(IPC.browserUnregister, (_e, webContentsId: number) => {browserGuests.delete(webContentsId)})