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(browser): a CDP allowlist of (method, params-validator) pairs, enforced in main

enes21a1911047eb
diff --git a/src/main/browser-cdp-allowlist.test.ts b/src/main/browser-cdp-allowlist.test.ts
new file mode 100644
index 000000000..92418f1ed
--- /dev/null
+++ b/src/main/browser-cdp-allowlist.test.ts
@@ -0,0 +1,99 @@
+import { describe, it, expect } from 'vitest'
+import fs from 'node:fs'
+import path from 'node:path'
+import { checkCdpCommand, type CdpContext } from './browser-cdp-allowlist'
+import { NT_SCRIPTS } from './browser-nt-scripts'
+
+const ctx: CdpContext = { viewport: { width: 1280, height: 800 } }
+
+describe('checkCdpCommand', () => {
+ it('an allowlist keyed on METHOD NAME is not what this is', () => {
+ // The danger in Runtime.evaluate is not its name, it is one parameter. So the list is
+ // (method, params-validator) pairs — which is also what buys the URL check on Page.navigate
+ // that a name-only list cannot express.
+ expect(checkCdpCommand('Page.navigate', { url: 'https://x.test/' }, ctx)).toBe(true)
+ expect(checkCdpCommand('Page.navigate', { url: 'javascript:alert(1)' }, ctx)).toBe(false)
+ expect(checkCdpCommand('Page.navigate', { url: 'file:///etc/passwd' }, ctx)).toBe(false)
+ expect(checkCdpCommand('Page.navigate', { url: 'data:text/html,<x>' }, ctx)).toBe(false)
+ })
+
+ it.each([
+ 'Runtime.evaluate', 'Runtime.compileScript', 'Runtime.runScript', 'Runtime.addBinding',
+ 'Debugger.enable', 'Debugger.setBreakpoint', 'Profiler.enable', 'Tracing.start',
+ 'Fetch.enable', 'Emulation.setUserAgentOverride', 'Storage.clearDataForOrigin',
+ 'Browser.close', 'Security.setIgnoreCertificateErrors',
+ 'IndexedDB.requestData', 'DOMStorage.getDOMStorageItems',
+ 'Network.getAllCookies', 'Page.bringToFront',
+ 'DOM.getOuterHTML', 'DOM.getAttributes', 'Input.synthesizeScrollGesture'
+ ])('%s is refused', (m) => {
+ expect(checkCdpCommand(m, {}, ctx)).toBe(false)
+ })
+
+ it('callFunctionOn requires IDENTITY with an NT_SCRIPTS entry and value-only arguments', () => {
+ const ok = { objectId: 'o1', functionDeclaration: NT_SCRIPTS.readMap, arguments: [{ value: '#x' }], returnByValue: true }
+ expect(checkCdpCommand('Runtime.callFunctionOn', ok, ctx)).toBe(true)
+ expect(checkCdpCommand('Runtime.callFunctionOn', { ...ok, functionDeclaration: 'function(){return 1}' }, ctx)).toBe(false)
+ expect(checkCdpCommand('Runtime.callFunctionOn', { ...ok, arguments: [{ objectId: 'o2' }] }, ctx)).toBe(false)
+ expect(checkCdpCommand('Runtime.callFunctionOn', { ...ok, arguments: [{ value: { a: 1 } }] }, ctx)).toBe(false)
+ expect(checkCdpCommand('Runtime.callFunctionOn', { ...ok, returnByValue: false }, ctx)).toBe(false)
+ })
+
+ it('mouse coordinates must be inside the reported viewport', () => {
+ expect(checkCdpCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10 }, ctx)).toBe(true)
+ expect(checkCdpCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: -1, y: 10 }, ctx)).toBe(false)
+ expect(checkCdpCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 99999, y: 10 }, ctx)).toBe(false)
+ })
+
+ it('selector length and DOM depth are bounded', () => {
+ expect(checkCdpCommand('DOM.querySelector', { nodeId: 1, selector: 'a'.repeat(1024) }, ctx)).toBe(true)
+ expect(checkCdpCommand('DOM.querySelector', { nodeId: 1, selector: 'a'.repeat(1025) }, ctx)).toBe(false)
+ expect(checkCdpCommand('DOM.getDocument', { depth: 2 }, ctx)).toBe(false)
+ })
+
+ it('Input.insertText is capped', () => {
+ expect(checkCdpCommand('Input.insertText', { text: 'x'.repeat(8192) }, ctx)).toBe(true)
+ expect(checkCdpCommand('Input.insertText', { text: 'x'.repeat(8193) }, ctx)).toBe(false)
+ })
+
+ it('cookie READS take one explicit domain; the jar-emptying call does not exist here', () => {
+ expect(checkCdpCommand('Network.getCookies', { urls: ['https://github.com/'] }, ctx)).toBe(true)
+ expect(checkCdpCommand('Network.getCookies', {}, ctx)).toBe(false) // no domain ⇒ the whole jar
+ expect(checkCdpCommand('Network.getAllCookies', {}, ctx)).toBe(false)
+ })
+
+ it('cookie WRITES are listed (owner decision 5) and unreachable in v1', () => {
+ // The methods stay listed so the allowlist RECORDS the decision; PR 9 Task 9.4 pins that no
+ // verb reaches them, because a write verb needs a design nobody has done: where does the agent
+ // get the value, and what stops it planting accounts.google.com so a later human visit is a
+ // login the attacker controls?
+ expect(checkCdpCommand('Network.setCookie', { name: 'a', value: 'b', domain: 'x.test' }, ctx)).toBe(true)
+ })
+
+ it('an unknown method is refused with NO per-method detail', () => {
+ // An allowlist that explains itself is a probing aid.
+ expect(checkCdpCommand('Made.Up', {}, ctx)).toBe(false)
+ })
+})
+
+/**
+ * Structural pin (the analogue of Task 4.4's second half). `checkCdpCommand` is only THE gate if it
+ * is unbypassable: every `sendCommand(` in the main-side browser surface must live inside the one
+ * wrapper, `browser-cdp-send.ts`, which calls this function. A direct `debugger.sendCommand` anywhere
+ * else is arbitrary CDP that never met the allowlist.
+ */
+describe('debugger.sendCommand has exactly one call site', () => {
+ const mainDir = path.resolve(__dirname)
+
+ it('every sendCommand( in src/main/browser-*.ts is inside browser-cdp-send.ts', () => {
+ const offenders: string[] = []
+ for (const f of fs.readdirSync(mainDir)) {
+ if (!/^browser-.*\.ts$/.test(f) || f.endsWith('.test.ts')) continue
+ if (f === 'browser-cdp-send.ts') continue
+ const src = fs.readFileSync(path.join(mainDir, f), 'utf8')
+ // Strip comments so a mention in prose is not a false positive; a real call is not a comment.
+ const code = src.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/[^\n]*/g, '')
+ if (/\bsendCommand\s*\(/.test(code)) offenders.push(f)
+ }
+ expect(offenders).toEqual([])
+ })
+})
diff --git a/src/main/browser-cdp-allowlist.ts b/src/main/browser-cdp-allowlist.ts
new file mode 100644
index 000000000..d5a438bf8
--- /dev/null
+++ b/src/main/browser-cdp-allowlist.ts
@@ -0,0 +1,168 @@
+/**
+ * THE CDP allowlist. The single gate every command bound for `debugger.sendCommand` passes through
+ * (the one caller is `browser-cdp-send.ts`, pinned structurally by this file's test). Default-DENY:
+ * an unknown method, or a known method with a parameter the validator rejects, is REFUSED — nothing
+ * falls through.
+ *
+ * It is NOT a set of method names. The danger in a page-side-eval command is not its name, it is one
+ * parameter — and a name-keyed list also cannot express the URL check on Page.navigate. So the table
+ * is (method, params-validator) pairs, each validator inspecting exactly the parameters that make its
+ * method safe or not.
+ *
+ * Lives in `src/main`, enforced on the way into the debugger — NEVER in the renderer (the half an
+ * XSS-in-a-node-title style bug lands in) and never in the shim or a skill document. Browser control
+ * exists only on the Electron desktop; Server Edition / Mobile never reach here.
+ *
+ * Excluded outright and for stated reasons: arbitrary page-side evaluation
+ * (Runtime.evaluate/compileScript/runScript/addBinding) and the whole Debugger domain (a second route
+ * to it), Fetch (request interception is a proxy for the user's session), Security (can disable
+ * certificate errors), Storage / IndexedDB / DOMStorage (the token stores this whole design exists to
+ * keep out), DOM.getOuterHTML / getAttributes (the full-DOM read arriving by another door),
+ * Page.bringToFront (a page that can raise itself can steal a click the user aimed elsewhere) and
+ * Network.getAllCookies (one call empties the jar for every site the profile ever touched, and no
+ * useful audit line names a domain). None of these is in the table, so default-deny refuses them.
+ */
+import { isNtScript } from './browser-nt-scripts'
+import { normalizeAddress } from '@shared/browserUrl'
+
+/** What the gate needs to know about the page beyond the command itself: the viewport from the last
+ * `Page.getLayoutMetrics`, so a mouse coordinate can be bounded to what is actually on screen. */
+export interface CdpContext {
+ viewport: { width: number; height: number }
+}
+
+type Validator = (params: unknown, ctx: CdpContext) => boolean
+
+function isRecord(v: unknown): v is Record<string, unknown> {
+ return typeof v === 'object' && v !== null && !Array.isArray(v)
+}
+
+/** A CDP argument for the call-a-function-on-object method is safe ONLY if it carries a single scalar
+ * `value` — never an `objectId` (an agent-chosen live handle) and never a structured value (an
+ * object literal is a re-entry point for logic the NT_SCRIPTS scan never saw). */
+function isScalar(v: unknown): boolean {
+ return v === null || typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean'
+}
+function valueOnlyArgs(args: unknown): boolean {
+ if (args === undefined) return true
+ if (!Array.isArray(args)) return false
+ return args.every(
+ (a) =>
+ isRecord(a) &&
+ Object.keys(a).length === 1 &&
+ Object.prototype.hasOwnProperty.call(a, 'value') &&
+ isScalar(a.value)
+ )
+}
+
+const MAX_SELECTOR = 1024
+const MAX_INSERT_TEXT = 8192
+
+/**
+ * The table. Every entry is a (method, validator) pair. A Map — not a plain object — so a method
+ * named `__proto__` / `constructor` can never resolve a validator off Object.prototype.
+ */
+const ALLOW = new Map<string, Validator>([
+ // ---- Agent-facing verbs (PRs 7-8). Each validator inspects the parameters that make it safe. ----
+
+ // The only navigation the agent can drive is to an http(s) URL, decided by the SAME
+ // `normalizeAddress` the address bar uses — javascript:/file:/data: all normalize to null.
+ ['Page.navigate', (p) => isRecord(p) && typeof p.url === 'string' && normalizeAddress(p.url) !== null],
+
+ // Page-side logic runs ONLY as an NT_SCRIPTS entry, by identity, returning a value, with scalar
+ // arguments. This is where the exclusion of arbitrary evaluation is actually enforced.
+ [
+ 'Runtime.callFunctionOn',
+ (p) =>
+ isRecord(p) &&
+ typeof p.functionDeclaration === 'string' &&
+ isNtScript(p.functionDeclaration) &&
+ p.returnByValue === true &&
+ valueOnlyArgs(p.arguments)
+ ],
+
+ // A synthesized mouse event must land inside the reported viewport — a coordinate off-screen is
+ // either a bug or an attempt to reach chrome the user cannot see.
+ [
+ 'Input.dispatchMouseEvent',
+ (p, ctx) =>
+ isRecord(p) &&
+ typeof p.type === 'string' &&
+ typeof p.x === 'number' &&
+ typeof p.y === 'number' &&
+ p.x >= 0 &&
+ p.y >= 0 &&
+ p.x <= ctx.viewport.width &&
+ p.y <= ctx.viewport.height
+ ],
+
+ // Typed text is capped; the text goes to insertText, never to a shell and never spliced anywhere.
+ ['Input.insertText', (p) => isRecord(p) && typeof p.text === 'string' && p.text.length <= MAX_INSERT_TEXT],
+
+ // A bounded selector against a known node.
+ [
+ 'DOM.querySelector',
+ (p) =>
+ isRecord(p) &&
+ typeof p.nodeId === 'number' &&
+ typeof p.selector === 'string' &&
+ p.selector.length <= MAX_SELECTOR
+ ],
+
+ // A shallow document read only (depth <= 1, no pierce) — the deep read is the full-DOM door that
+ // getOuterHTML/getAttributes are excluded to keep shut.
+ [
+ 'DOM.getDocument',
+ (p) =>
+ isRecord(p) &&
+ (p.depth === undefined || (typeof p.depth === 'number' && p.depth <= 1)) &&
+ p.pierce !== true
+ ],
+
+ // A cookie READ must name at least one URL — never the whole jar (that is getAllCookies, excluded).
+ [
+ 'Network.getCookies',
+ (p) => isRecord(p) && Array.isArray(p.urls) && p.urls.length > 0 && p.urls.every((u) => typeof u === 'string')
+ ],
+
+ // Cookie WRITES stay LISTED so the allowlist records owner decision 5, but no verb reaches them in
+ // v1 (pinned by PR 9 Task 9.4). A write needs one explicit domain — never a jar-wide write.
+ [
+ 'Network.setCookie',
+ (p) =>
+ isRecord(p) &&
+ typeof p.name === 'string' &&
+ typeof p.value === 'string' &&
+ typeof p.domain === 'string' &&
+ p.domain.length > 0
+ ],
+
+ // ---- Session lifecycle (issued by the lease, browser-lease.ts, not by an agent verb). Still gated
+ // here so the "single gate" property is literal: every sendCommand, infra or not, is checked. ----
+
+ ['Page.enable', () => true],
+ ['DOM.enable', () => true],
+ ['Runtime.enable', () => true],
+ ['Page.getLayoutMetrics', () => true],
+ // Flat-mode child attach only (S8): a nested/auto-attach mode is a different, unaudited surface.
+ [
+ 'Target.attachToTarget',
+ (p) => isRecord(p) && p.flatten === true && typeof p.targetId === 'string' && p.targetId.length > 0
+ ],
+ ['Target.detachFromTarget', (p) => isRecord(p) && typeof p.sessionId === 'string']
+])
+
+/**
+ * Is this exact (method, params) pair allowed, for this page context? Default-deny: an unknown
+ * method returns false with NO per-method detail (an allowlist that explains itself is a probing
+ * aid), and a validator that throws on a malformed payload is treated as a refusal.
+ */
+export function checkCdpCommand(method: string, params: unknown, ctx: CdpContext): boolean {
+ const validate = ALLOW.get(method)
+ if (!validate) return false
+ try {
+ return validate(params, ctx) === true
+ } catch {
+ return false
+ }
+}
diff --git a/src/renderer/nodes/browserUrl.ts b/src/renderer/nodes/browserUrl.ts
index d5bfd1426..42ef0a97a 100644
--- a/src/renderer/nodes/browserUrl.ts
+++ b/src/renderer/nodes/browserUrl.ts
@@ -1,26 +1,7 @@
-// Normalize an address-bar entry into an http(s) URL, or null when it can't be one.
-// Blocks file:/javascript:/data:/custom schemes; adds https:// to a bare host. No search fallback.
-export function normalizeAddress(input: string): string | null {
- const raw = input.trim()
- if (!raw) return null
- // Already a URL with a scheme?
- if (/^[a-z][a-z0-9+.-]*:/i.test(raw)) {
- try {
- const u = new URL(raw)
- return u.protocol === 'http:' || u.protocol === 'https:' ? u.toString() : null
- } catch {
- return null
- }
- }
- // No scheme: only treat as a host if it has a dot and no spaces.
- if (/\s/.test(raw) || !raw.includes('.')) return null
- try {
- const u = new URL(`https://${raw}`)
- return u.toString()
- } catch {
- return null
- }
-}
+// `normalizeAddress` now lives in `src/shared` so main's CDP allowlist can reuse the exact scheme
+// check the address bar uses (they must never disagree about javascript:/file:/data:). Re-exported
+// here so every existing `../nodes/browserUrl` import path is unchanged.
+export { normalizeAddress } from '@shared/browserUrl'
function googleSearch(query: string): string {
return `https://www.google.com/search?q=${encodeURIComponent(query)}`
diff --git a/src/shared/browserUrl.ts b/src/shared/browserUrl.ts
new file mode 100644
index 000000000..62379880f
--- /dev/null
+++ b/src/shared/browserUrl.ts
@@ -0,0 +1,29 @@
+// Address-bar normalization, in `src/shared` because BOTH shells need it: the renderer's address bar
+// (re-exported from `renderer/nodes/browserUrl.ts`, so no existing import path changes) and main's
+// CDP allowlist, whose `Page.navigate` validator reuses THIS scheme check rather than re-deriving it
+// — one place decides "is this an http(s) URL", so the address bar and the allowlist can never drift
+// into disagreeing about `javascript:`/`file:`/`data:`.
+
+// Normalize an address-bar entry into an http(s) URL, or null when it can't be one.
+// Blocks file:/javascript:/data:/custom schemes; adds https:// to a bare host. No search fallback.
+export function normalizeAddress(input: string): string | null {
+ const raw = input.trim()
+ if (!raw) return null
+ // Already a URL with a scheme?
+ if (/^[a-z][a-z0-9+.-]*:/i.test(raw)) {
+ try {
+ const u = new URL(raw)
+ return u.protocol === 'http:' || u.protocol === 'https:' ? u.toString() : null
+ } catch {
+ return null
+ }
+ }
+ // No scheme: only treat as a host if it has a dot and no spaces.
+ if (/\s/.test(raw) || !raw.includes('.')) return null
+ try {
+ const u = new URL(`https://${raw}`)
+ return u.toString()
+ } catch {
+ return null
+ }
+}