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): --screenshot jailed to the project dir + allowlist entries (S8 PR9 Tasks 9.1/9.4)

Claude Code5b5ed4cfaebd
diff --git a/src/main/browser-cdp-allowlist.test.ts b/src/main/browser-cdp-allowlist.test.ts
index c5a9b006f..f860d8d38 100644
--- a/src/main/browser-cdp-allowlist.test.ts
+++ b/src/main/browser-cdp-allowlist.test.ts
@@ -1,7 +1,7 @@
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 { checkCdpCommand, COOKIE_WRITE_METHODS, type CdpContext } from './browser-cdp-allowlist'
import { NT_SCRIPTS } from './browser-nt-scripts'
const ctx: CdpContext = { viewport: { width: 1280, height: 800 } }
@@ -84,10 +84,29 @@ describe('checkCdpCommand', () => {
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?
+ // verb reaches them (browser-cookie-write-guard.test.ts), 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)
+ // The jar-mutating set is enumerated in one place; setCookie is the only one the ALLOW table
+ // admits, and it is unreachable from every verb (the reachability guard proves that).
+ expect(COOKIE_WRITE_METHODS).toContain('Network.setCookie')
+ expect(COOKIE_WRITE_METHODS).toContain('Network.deleteCookies')
+ expect(COOKIE_WRITE_METHODS).toContain('Storage.setCookies')
+ })
+
+ it('a screenshot is PNG-only, and its clip must be a numeric rectangle we authored (Task 9.1)', () => {
+ expect(checkCdpCommand('Page.captureScreenshot', {}, ctx)).toBe(true)
+ expect(checkCdpCommand('Page.captureScreenshot', { format: 'png' }, ctx)).toBe(true)
+ // No jpeg/pdf surface — a caller cannot pick the format (and never supplies params anyway).
+ expect(checkCdpCommand('Page.captureScreenshot', { format: 'jpeg' }, ctx)).toBe(false)
+ expect(checkCdpCommand('Page.captureScreenshot', { format: 'pdf' }, ctx)).toBe(false)
+ // A well-formed numeric clip (our own box model) passes; a structured/garbage clip is refused.
+ expect(
+ checkCdpCommand('Page.captureScreenshot', { clip: { x: 0, y: 0, width: 100, height: 50, scale: 1 } }, ctx)
+ ).toBe(true)
+ expect(checkCdpCommand('Page.captureScreenshot', { clip: { x: 0, y: 0, width: 100 } }, ctx)).toBe(false)
+ expect(checkCdpCommand('Page.captureScreenshot', { clip: 'whole-page' }, ctx)).toBe(false)
})
it('an unknown method is refused with NO per-method detail', () => {
diff --git a/src/main/browser-cdp-allowlist.ts b/src/main/browser-cdp-allowlist.ts
index 79466fdef..060d7f62d 100644
--- a/src/main/browser-cdp-allowlist.ts
+++ b/src/main/browser-cdp-allowlist.ts
@@ -59,6 +59,28 @@ function valueOnlyArgs(args: unknown): boolean {
const MAX_SELECTOR = 1024
const MAX_INSERT_TEXT = 8192
+/**
+ * The cookie-JAR-MUTATING CDP methods, listed in ONE place so the decision is recorded, and pinned
+ * UNREACHABLE by the verb-reachability guard in browser-cdp-allowlist.test.ts (PR 9 Task 9.4).
+ *
+ * `Network.setCookie` stays ADMITTED by the ALLOW table below (owner decision 5) so a future write
+ * verb inherits a validated entry rather than a fresh, unreviewed one — but v1 ships NO verb that
+ * emits any of these. The reason it is not merely "not built yet": a write verb needs a design nobody
+ * has done — where does the agent get the cookie value, and what stops it planting an attacker's
+ * session cookie for `accounts.google.com` so a later human visit to that node is a login the attacker
+ * controls? A cookie write, when designed, needs a LOUDER trace than a read: a write is persistent and
+ * silent, where a read is at least a one-time disclosure. So the list records the decision; the guard
+ * proves no action reaches it.
+ */
+export const COOKIE_WRITE_METHODS = [
+ 'Network.setCookie',
+ 'Network.setCookies',
+ 'Network.deleteCookies',
+ 'Network.clearBrowserCookies',
+ 'Storage.setCookies',
+ 'Storage.clearCookies'
+] as const
+
/** The dispatch types a key event may carry — a key-down, a key-up, or a raw key-down. There is
* deliberately NO `char` type: a character that types into the page belongs to `Input.insertText`
* (its own capped, data-only path), never to a key event. */
@@ -180,6 +202,29 @@ const ALLOW = new Map<string, Validator>([
p.domain.length > 0
],
+ // A screenshot is PNG-only and its clip comes from OUR OWN box model (the layout metrics), never
+ // from agent input — the path the agent supplies is jailed to the project dir in browser-screenshot.ts
+ // and never reaches CDP. So the only agent influence here is "take a picture"; format is pinned to
+ // png (no pdf/jpeg surface), and a clip, if present, must be numeric — a well-formed rectangle we
+ // authored, not a structured re-entry point.
+ [
+ 'Page.captureScreenshot',
+ (p) => {
+ if (!isRecord(p)) return false
+ if (p.format !== undefined && p.format !== 'png') return false
+ if (p.captureBeyondViewport !== undefined && typeof p.captureBeyondViewport !== 'boolean') return false
+ if (p.clip !== undefined) {
+ const c = p.clip
+ if (!isRecord(c)) return false
+ for (const k of ['x', 'y', 'width', 'height']) {
+ if (typeof c[k] !== 'number') return false
+ }
+ if (c.scale !== undefined && typeof c.scale !== 'number') return false
+ }
+ return true
+ }
+ ],
+
// ---- 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. ----
diff --git a/src/main/browser-screenshot.test.ts b/src/main/browser-screenshot.test.ts
new file mode 100644
index 000000000..f4a3c90e4
--- /dev/null
+++ b/src/main/browser-screenshot.test.ts
@@ -0,0 +1,148 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import fs from 'node:fs'
+import fsp from 'node:fs/promises'
+import os from 'node:os'
+import path from 'node:path'
+import {
+ resolveScreenshotPath,
+ browserScreenshot,
+ SCREENSHOT_OUTSIDE_PROJECT,
+ SCREENSHOT_NO_PROJECT_DIR
+} from './browser-screenshot'
+import type { Driver, LayoutMetrics } from './browser-actions'
+
+// The jail is proven against a REAL filesystem tree (constraint 8): a real project dir, a real
+// escaping symlink, a real sibling `proj-evil` — not a hand-rolled path model.
+let root: string
+let project: string
+let realpath: (p: string) => Promise<string>
+let lstat: (p: string) => Promise<{ isSymbolicLink(): boolean }>
+
+beforeEach(async () => {
+ root = await fsp.mkdtemp(path.join(os.tmpdir(), 'shot-'))
+ project = path.join(root, 'proj')
+ await fsp.mkdir(project, { recursive: true })
+ realpath = (p) => fsp.realpath(p)
+ lstat = (p) => fsp.lstat(p)
+})
+afterEach(async () => {
+ await fsp.rm(root, { recursive: true, force: true })
+})
+
+describe('resolveScreenshotPath — the jail (Task 9.1)', () => {
+ it('a relative path resolves against the project cwd', async () => {
+ const r = await resolveScreenshotPath(project, 'shot.png', { realpath, lstat })
+ expect(r).toEqual({ ok: true, abs: path.join(await fsp.realpath(project), 'shot.png') })
+ })
+
+ it('a relative path into a subdir stays inside the project', async () => {
+ await fsp.mkdir(path.join(project, 'sub'))
+ const r = await resolveScreenshotPath(project, 'sub/shot.png', { realpath, lstat })
+ expect(r).toEqual({ ok: true, abs: path.join(await fsp.realpath(project), 'sub', 'shot.png') })
+ })
+
+ it('a `..` traversal out of the project is refused', async () => {
+ const r = await resolveScreenshotPath(project, '../../etc/x.png', { realpath, lstat })
+ expect(r).toEqual({ ok: false, message: SCREENSHOT_OUTSIDE_PROJECT })
+ })
+
+ it('an absolute path outside the project is refused', async () => {
+ const r = await resolveScreenshotPath(project, '/tmp/x.png', { realpath, lstat })
+ expect(r).toEqual({ ok: false, message: SCREENSHOT_OUTSIDE_PROJECT })
+ })
+
+ it('a symlink whose PARENT resolves outside the project is refused', async () => {
+ // proj/escape -> root (outside proj). A path "escape/x.png" has parent proj/escape, which
+ // realpath resolves to `root` — outside the jail.
+ await fsp.symlink(root, path.join(project, 'escape'), 'dir')
+ const r = await resolveScreenshotPath(project, 'escape/x.png', { realpath, lstat })
+ expect(r).toEqual({ ok: false, message: SCREENSHOT_OUTSIDE_PROJECT })
+ })
+
+ it('the separator-terminated prefix stops a sibling `proj-evil` passing the `proj` check', async () => {
+ // A real sibling dir whose name is a prefix of the project dir must not be treated as inside it.
+ const evil = path.join(root, 'proj-evil')
+ await fsp.mkdir(evil)
+ // Point into it via a symlink parent so the raw resolve lands under proj but realpath escapes.
+ await fsp.symlink(evil, path.join(project, 'peer'), 'dir')
+ const r = await resolveScreenshotPath(project, 'peer/x.png', { realpath, lstat })
+ expect(r).toEqual({ ok: false, message: SCREENSHOT_OUTSIDE_PROJECT })
+ })
+
+ it('a final-component symlink pointing outside is refused (the write would follow it)', async () => {
+ // proj/shot.png is itself a symlink to root/loot.png — a plain writeFile would follow it out.
+ await fsp.writeFile(path.join(root, 'loot.png'), 'x')
+ await fsp.symlink(path.join(root, 'loot.png'), path.join(project, 'shot.png'))
+ const r = await resolveScreenshotPath(project, 'shot.png', { realpath, lstat })
+ expect(r).toEqual({ ok: false, message: SCREENSHOT_OUTSIDE_PROJECT })
+ })
+
+ it('an inline project with no cwd is a named refusal, not a crash', async () => {
+ const r = await resolveScreenshotPath(undefined, 'shot.png', { realpath, lstat })
+ expect(r).toEqual({ ok: false, message: SCREENSHOT_NO_PROJECT_DIR })
+ })
+})
+
+/** A Driver that answers the capture + a fixed viewport, and records every method it is sent. */
+function fakeDriver(metrics: Partial<LayoutMetrics> = {}): { s: Driver; sent: string[] } {
+ const m: LayoutMetrics = {
+ width: 1280,
+ height: 800,
+ scrollX: 0,
+ scrollY: 0,
+ contentWidth: 1280,
+ contentHeight: 5000,
+ ...metrics
+ }
+ const sent: string[] = []
+ const s: Driver = {
+ async send(method) {
+ sent.push(method)
+ if (method === 'Page.captureScreenshot') return { data: Buffer.from('PNGDATA').toString('base64') }
+ return {}
+ },
+ async refreshViewport() {
+ return m
+ }
+ }
+ return { s, sent }
+}
+
+describe('browserScreenshot — capture + jail + reply (Task 9.1)', () => {
+ it('writes inside the project and replies with the show-image line', async () => {
+ const { s } = fakeDriver()
+ const writeFile = vi.fn(async () => {})
+ const r = await browserScreenshot(s, 'browser-3', project, 'shot.png', {}, { realpath, lstat, writeFile })
+ const abs = path.join(await fsp.realpath(project), 'shot.png')
+ expect(r.ok).toBe(true)
+ expect(r.message).toBe(`wrote ${abs} (1280×800, 1 KB) — show it with: show-image ${abs}`)
+ expect(writeFile).toHaveBeenCalledWith(abs, expect.any(Buffer))
+ })
+
+ it('a traversal path never captures and never writes', async () => {
+ const { s, sent } = fakeDriver()
+ const writeFile = vi.fn(async () => {})
+ const r = await browserScreenshot(s, 'browser-3', project, '../../etc/x.png', {}, { realpath, lstat, writeFile })
+ expect(r).toEqual({ ok: false, message: SCREENSHOT_OUTSIDE_PROJECT })
+ expect(writeFile).not.toHaveBeenCalled()
+ expect(sent).not.toContain('Page.captureScreenshot') // refused BEFORE any CDP work
+ })
+
+ it('--full captures the whole content box and reports its dimensions', async () => {
+ const { s, sent } = fakeDriver({ contentHeight: 5000 })
+ const writeFile = vi.fn(async () => {})
+ const r = await browserScreenshot(s, 'browser-3', project, 'full.png', { full: true }, { realpath, lstat, writeFile })
+ expect(r.ok).toBe(true)
+ expect(r.message).toContain('1280×5000')
+ expect(sent).toContain('Page.captureScreenshot')
+ })
+
+ it('writes real bytes to a real file end-to-end', async () => {
+ const { s } = fakeDriver()
+ const writeFile = (p: string, d: Buffer) => fsp.writeFile(p, d)
+ const r = await browserScreenshot(s, 'browser-3', project, 'real.png', {}, { realpath, lstat, writeFile })
+ expect(r.ok).toBe(true)
+ const written = fs.readFileSync(path.join(project, 'real.png'))
+ expect(written.toString()).toBe('PNGDATA')
+ })
+})
diff --git a/src/main/browser-screenshot.ts b/src/main/browser-screenshot.ts
new file mode 100644
index 000000000..82d50f51a
--- /dev/null
+++ b/src/main/browser-screenshot.ts
@@ -0,0 +1,134 @@
+/**
+ * `--screenshot <path>` (PR 9 Task 9.1). Capture the guest's page and write a PNG to a caller-named
+ * path — and that path is the whole risk: UNJAILED, this is an arbitrary-file-write primitive with
+ * attacker-chosen PNG content. So the path is DATA, resolved against the project cwd and refused if it
+ * escapes: `..`, an absolute path outside the project, or a symlink whose parent resolves outside.
+ *
+ * The jail is `fs.realpath` on the target's PARENT (the file does not exist yet — we are about to
+ * write it) compared to the canonicalized project root with a SEPARATOR-TERMINATED prefix, so
+ * `/proj-evil` never passes the `/proj` check. A final-component symlink (planted at the exact target
+ * name, pointing outside) is caught by an `lstat` belt. Only the format `png` is issued, and the
+ * `clip` comes from OUR OWN box model (the layout metrics), never from agent input.
+ *
+ * Main-side only (it holds a debugger and writes a real file); never Server Edition.
+ */
+import path from 'node:path'
+import type { Driver, ActionResult } from './browser-actions'
+
+/** Refused: the resolved path (or a symlink on the way to it) is not inside the project directory. */
+export const SCREENSHOT_OUTSIDE_PROJECT =
+ 'browser: --screenshot path must be inside the project directory'
+
+/** Refused: this canvas/project has no working directory to jail a path to (an inline/no-cwd project). */
+export const SCREENSHOT_NO_PROJECT_DIR =
+ 'browser: --screenshot needs a project folder (this canvas has none)'
+
+/** The filesystem the jail consults, injected so the traversal refusals are unit-testable without a
+ * real tree (a fake `realpath` models a symlink whose parent resolves outside). */
+export interface ScreenshotPathDeps {
+ /** Canonicalize a path, following every symlink. Rejects when the path does not exist. */
+ realpath(p: string): Promise<string>
+ /** lstat WITHOUT following the final link — used to refuse a final-component symlink. */
+ lstat(p: string): Promise<{ isSymbolicLink(): boolean }>
+}
+
+export type ResolvedScreenshotPath = { ok: true; abs: string } | { ok: false; message: string }
+
+/**
+ * Resolve a caller-supplied screenshot path into a concrete absolute path INSIDE the project, or a
+ * named refusal. Pure of capture/IO beyond the injected `realpath`/`lstat`.
+ */
+export async function resolveScreenshotPath(
+ projectCwd: string | undefined,
+ rawPath: string,
+ deps: ScreenshotPathDeps
+): Promise<ResolvedScreenshotPath> {
+ if (!projectCwd) return { ok: false, message: SCREENSHOT_NO_PROJECT_DIR }
+ // A relative path resolves against the project cwd; an absolute path stays absolute (and is refused
+ // below unless it already lands inside the project).
+ const abs = path.resolve(projectCwd, rawPath)
+ const parent = path.dirname(abs)
+ let realBase: string
+ let realParent: string
+ try {
+ realBase = await deps.realpath(projectCwd)
+ // realpath the PARENT — following every link — so a symlink whose parent resolves outside the
+ // project is caught. The file itself does not exist yet, so we cannot realpath it directly.
+ realParent = await deps.realpath(parent)
+ } catch {
+ return { ok: false, message: SCREENSHOT_OUTSIDE_PROJECT }
+ }
+ // Separator-terminated prefix: `/proj-evil` must NOT pass the `/proj` check. Equality is the root
+ // itself (a file written directly in the project dir).
+ const baseWithSep = realBase.endsWith(path.sep) ? realBase : realBase + path.sep
+ if (realParent !== realBase && !realParent.startsWith(baseWithSep)) {
+ return { ok: false, message: SCREENSHOT_OUTSIDE_PROJECT }
+ }
+ const target = path.join(realParent, path.basename(abs))
+ // Belt against a final-component symlink planted at the exact target name pointing outside: a
+ // plain writeFile would follow it. A missing file (ENOENT) is the normal case and passes.
+ try {
+ const st = await deps.lstat(target)
+ if (st.isSymbolicLink()) return { ok: false, message: SCREENSHOT_OUTSIDE_PROJECT }
+ } catch {
+ /* does not exist yet — the expected case for a new screenshot */
+ }
+ return { ok: true, abs: target }
+}
+
+/** The IO the action needs beyond the jail: capture goes through the gated `Driver.send`; the file
+ * write is injected so the action is testable without touching disk. */
+export interface ScreenshotDeps extends ScreenshotPathDeps {
+ writeFile(p: string, data: Buffer): Promise<void>
+}
+
+/**
+ * `--screenshot <path>` with the optional `--full true` modifier. Jail the path, measure the page
+ * from OUR layout metrics, capture a PNG (viewport by default, the whole content box with `--full`),
+ * write it, and reply with the path, dimensions, size, and the exact `show-image` line the agent can
+ * echo to put the shot on the canvas.
+ */
+export async function browserScreenshot(
+ s: Driver,
+ nodeId: string,
+ projectCwd: string | undefined,
+ rawPath: string,
+ opts: { full?: boolean },
+ deps: ScreenshotDeps
+): Promise<ActionResult> {
+ const resolved = await resolveScreenshotPath(projectCwd, rawPath, deps)
+ if (!resolved.ok) return { ok: false, message: resolved.message }
+ const m = await s.refreshViewport()
+ const full = opts.full === true
+ // The clip is OURS — from the measured page, never a caller field. Default is the visible viewport
+ // (no clip); --full captures the whole content box.
+ const params = full
+ ? {
+ format: 'png',
+ captureBeyondViewport: true,
+ clip: {
+ x: 0,
+ y: 0,
+ width: Math.round(m.contentWidth),
+ height: Math.round(m.contentHeight),
+ scale: 1
+ }
+ }
+ : { format: 'png' }
+ const res = (await s.send('Page.captureScreenshot', params)) as { data?: unknown }
+ const b64 = typeof res?.data === 'string' ? res.data : ''
+ if (!b64) return { ok: false, message: `browser: ${nodeId} returned no screenshot data` }
+ const buf = Buffer.from(b64, 'base64')
+ try {
+ await deps.writeFile(resolved.abs, buf)
+ } catch {
+ return { ok: false, message: `browser: could not write the screenshot to ${resolved.abs}` }
+ }
+ const w = full ? Math.round(m.contentWidth) : Math.round(m.width)
+ const h = full ? Math.round(m.contentHeight) : Math.round(m.height)
+ const kb = Math.max(1, Math.round(buf.length / 1024))
+ return {
+ ok: true,
+ message: `wrote ${resolved.abs} (${w}×${h}, ${kb} KB) — show it with: show-image ${resolved.abs}`
+ }
+}