fix(browser): require a per-session token on the local CDP proxy (#37938)

* fix(browser): require a per-session token on the local CDP proxy

* fix(browser): reset the helper session when the CDP proxy refuses it

Explain a 403/404 handshake from Orca's CDP proxy and retire the session so
the next command gets a fresh proxy and helper. Drop an inherited
AGENT_BROWSER_CDP from the helper env so only Orca names the target, and pin
the env contract and minimum bundled agent-browser version in tests.
This commit is contained in:
Neil
2026-11-06 14:42:33 -08:00
committed by GitHub
parent 738396cc7f
commit 5ed96fbdd9
11 changed files with 327 additions and 36 deletions
@@ -0,0 +1,143 @@
import type * as BrowserErrorTypes from '../browser-error'
import { describe, it, expect, vi, beforeEach } from 'vitest'
const { execFileMock, webContentsFromIdMock, existsSyncMock, readFileSyncMock, stdinWrites } =
vi.hoisted(() => ({
execFileMock: vi.fn(),
webContentsFromIdMock: vi.fn(),
existsSyncMock: vi.fn(() => false),
readFileSyncMock: vi.fn(() => Buffer.from('')),
stdinWrites: new Array<string>()
}))
vi.mock('child_process', () => ({ execFile: execFileMock }))
vi.mock('fs', () => ({
existsSync: existsSyncMock,
readFileSync: readFileSyncMock,
accessSync: vi.fn(),
chmodSync: vi.fn(),
constants: { X_OK: 1 }
}))
vi.mock('os', () => ({ platform: () => 'darwin', arch: () => 'arm64' }))
vi.mock('electron', () => {
return {
app: { getPath: vi.fn(() => '/app'), getAppPath: vi.fn(() => '/project'), isPackaged: false },
webContents: { fromId: webContentsFromIdMock }
}
})
const { CdpWsProxyMock, proxyStops } = vi.hoisted(() => {
const instances: unknown[] = []
const proxyStops: ReturnType<typeof vi.fn>[] = []
const MockClass = vi.fn().mockImplementation(function (
this: Record<string, unknown>,
_wc: unknown
) {
this._wc = _wc
const endpoint = `ws://127.0.0.1:9222/token-${instances.length}`
this.start = vi.fn(async () => endpoint)
const stop = vi.fn(async () => {})
this.stop = stop
proxyStops.push(stop)
this.getPort = vi.fn(() => 9222)
instances.push(this)
})
return { CdpWsProxyMock: Object.assign(MockClass, { instances }), proxyStops }
})
vi.mock('../cdp/transport/cdp-ws-proxy', () => ({
CdpWsProxy: CdpWsProxyMock
}))
vi.mock('../browser-error', () => ({
BrowserError: class BrowserError extends Error {
code: string
constructor(code: string, message: string) {
super(message)
this.code = code
}
}
}))
vi.mock('../cdp/commands/cdp-bridge', async () => {
const { BrowserError } = await vi.importMock<typeof BrowserErrorTypes>('../browser-error')
return { BrowserError }
})
import { AgentBrowserBridge } from './agent-browser-bridge'
import {
answerAgentBrowserCommands,
mockBrowserManager,
overrideBridgeWebContentsLookup,
resetAgentBrowserBridgeMocks,
succeedRecordingAgentBrowserSpawns
} from './agent-browser-bridge-test-harness'
overrideBridgeWebContentsLookup(AgentBrowserBridge.prototype, webContentsFromIdMock)
// agent-browser only reaches Orca's proxy through AGENT_BROWSER_CDP; `--cdp <port>` drops the token path.
describe('AgentBrowserBridge CDP endpoint contract', () => {
let bridge: AgentBrowserBridge
beforeEach(() => {
resetAgentBrowserBridgeMocks({
webContentsFromIdMock,
existsSyncMock,
readFileSyncMock,
stdinWrites,
cdpWsProxyInstances: CdpWsProxyMock.instances
})
proxyStops.length = 0
bridge = new AgentBrowserBridge(mockBrowserManager())
bridge.setActiveTab(100)
})
it('passes the tokened endpoint only through env, for batch and raw CLI spawns', async () => {
const spawns = succeedRecordingAgentBrowserSpawns(execFileMock, stdinWrites, {
snapshot: ''
})
await bridge.snapshot()
await bridge.exec('--cdp 4444 get title')
// The stale-session reset only closes a daemon; it must not name any CDP target.
const [reset, ...commands] = spawns
expect(reset).toMatchObject({ command: ['close'], cdp: undefined })
expect(commands.map(({ command }) => command[0])).toEqual(['snapshot', 'get'])
for (const spawn of commands) {
expect(spawn.cdp).toBe('ws://127.0.0.1:9222/token-0')
expect(spawn.args).not.toContain('--cdp')
expect(spawn.args.join(' ')).not.toContain('token-0')
}
})
it('resets the session and explains a proxy refusal so the next command reconnects', async () => {
let refuse = true
answerAgentBrowserCommands(execFileMock, stdinWrites, (command, cb, _args, _child, opts) => {
if (command[0] === 'close') {
cb(null, JSON.stringify({ success: true, data: null }), '')
} else if (refuse) {
cb(
Object.assign(new Error('exit 1'), { code: 1 }),
JSON.stringify({
success: false,
error: 'CDP WebSocket connect failed: HTTP error: 404 Not Found'
}),
''
)
} else {
cb(null, JSON.stringify({ success: true, data: { cdp: opts.env?.AGENT_BROWSER_CDP } }), '')
}
})
await expect(bridge.snapshot()).rejects.toMatchObject({
code: 'browser_error',
message: expect.stringMatching(/refused by Orca's browser proxy.*404.*retry the command/)
})
await vi.waitFor(() => expect(proxyStops[0]).toHaveBeenCalled())
refuse = false
await expect(bridge.snapshot()).resolves.toMatchObject({})
expect(CdpWsProxyMock.instances).toHaveLength(2)
const lastSpawnEnv = execFileMock.mock.calls.at(-1)?.[2]?.env
expect(lastSpawnEnv?.AGENT_BROWSER_CDP).toBe('ws://127.0.0.1:9222/token-1')
})
})
@@ -2,6 +2,7 @@ import { execFile } from 'node:child_process'
import type { WebContents } from 'electron'
import { BrowserError } from '../browser-error'
import {
isCdpProxyRejectedError,
isTabClosedTransportError,
pageUnavailableMessageForSession
} from './agent-browser-bridge-process'
@@ -17,7 +18,9 @@ import { assertExpectedPageUrlForStep } from '../cdp/input/browser-expected-page
import { ORCA_TAB_SESSION_PREFIX } from './agent-browser-orphan-sweep'
import { canSkipAgentBrowserSessionReset } from './agent-browser-session-reset'
import {
AGENT_BROWSER_CLEANUP_TIMEOUT_MS,
STALE_SESSION_CLOSE_TIMEOUT_MS,
type AgentBrowserCleanupOptions,
type AgentBrowserExecOptions,
type SessionState,
type ResolvedBrowserCommandTarget
@@ -29,7 +32,7 @@ const ELEMENT_COMMANDS_WITHOUT_POINTER = new Set(['check', 'uncheck', 'select',
export abstract class AgentBrowserBridgeExecution extends AgentBrowserBridgeTabs {
protected abstract destroySession(
sessionName: string,
options?: { closeTimeoutMs?: number }
options?: AgentBrowserCleanupOptions
): Promise<void>
protected abstract runAgentBrowserRaw(
@@ -156,10 +159,15 @@ export abstract class AgentBrowserBridgeExecution extends AgentBrowserBridgeTabs
commandArgs: string[],
execOptions?: AgentBrowserExecOptions
): Promise<string> {
const args = ['--session', sessionName]
// Every invocation must pin CDP ownership or a restarted daemon may launch Chrome.
const args = ['--session', sessionName, '--cdp', String(session.proxy.getPort())]
// The endpoint carries the proxy token, so it goes through env: argv is visible to other users.
execOptions = {
...execOptions,
envOverrides: { ...execOptions?.envOverrides, AGENT_BROWSER_CDP: session.cdpEndpoint }
}
// A caller's own stdin (eval --stdin) cannot share the pipe with batch input.
if (!execOptions?.cliArgv && execOptions?.stdinText === undefined) {
if (!execOptions.cliArgv && execOptions.stdinText === undefined) {
return this.runAgentBrowserRaw(sessionName, [...args, ...AGENT_BROWSER_BATCH_ARGS], {
...execOptions,
stdinText: agentBrowserBatchInput(commandArgs)
@@ -260,6 +268,17 @@ export abstract class AgentBrowserBridgeExecution extends AgentBrowserBridgeTabs
) {
return this.createPageUnavailableError(sessionName)
}
if (isCdpProxyRejectedError(message)) {
// The helper named a proxy endpoint this session no longer serves; start the next command fresh.
void this.destroySession(sessionName, {
closeTimeoutMs: AGENT_BROWSER_CLEANUP_TIMEOUT_MS,
keepQueuedCommands: true
})
return new BrowserError(
'browser_error',
`The agent-browser helper was refused by Orca's browser proxy (${message}). The helper session was reset; retry the command.`
)
}
return new BrowserError(fallbackCode, message)
}
@@ -176,6 +176,11 @@ export function isTabClosedTransportError(message: string): boolean {
)
}
/** agent-browser's handshake error when Orca's CDP proxy refuses its endpoint (wrong or missing token). */
export function isCdpProxyRejectedError(message: string): boolean {
return /websocket connect failed\b.*\b40[34]\b/i.test(message)
}
export function pageUnavailableMessageForSession(sessionName: string): string {
const prefix = ORCA_TAB_SESSION_PREFIX
const browserPageId = sessionName.startsWith(prefix) ? sessionName.slice(prefix.length) : null
@@ -166,11 +166,12 @@ export function answerAgentBrowserCommands(
command: string[],
cb: ExecFileCallback,
args: string[],
child: FakeAgentBrowserChild
child: FakeAgentBrowserChild,
opts: { env?: NodeJS.ProcessEnv }
) => void
): void {
execFileMock.mockImplementation(
(_bin: string, args: string[], _opts: unknown, cb: ExecFileCallback) => {
(_bin: string, args: string[], opts: { env?: NodeJS.ProcessEnv }, cb: ExecFileCallback) => {
const child = createFakeAgentBrowserChild({
kill: vi.fn(),
stdin: {
@@ -182,29 +183,29 @@ export function answerAgentBrowserCommands(
// Commands outside a batch were answered from argv at spawn.
return
}
answer(agentBrowserCommandOf(args, text), cb, args, child)
answer(agentBrowserCommandOf(args, text), cb, args, child, opts)
}
}
})
if (!args.includes('batch')) {
answer(agentBrowserCommandOf(args), cb, args, child)
answer(agentBrowserCommandOf(args), cb, args, child, opts)
}
return child
}
)
}
export type AgentBrowserSpawn = { command: string[]; args: string[] }
export type AgentBrowserSpawn = { command: string[]; args: string[]; cdp: string | undefined }
/** Succeeds every spawn with `data` and records each command beside its argv. */
/** Succeeds every spawn with `data` and records each command beside its argv and CDP endpoint. */
export function succeedRecordingAgentBrowserSpawns(
execFileMock: Mock,
stdinWrites: string[],
data: unknown
): AgentBrowserSpawn[] {
const spawns: AgentBrowserSpawn[] = []
answerAgentBrowserCommands(execFileMock, stdinWrites, (command, cb, args) => {
spawns.push({ command, args })
answerAgentBrowserCommands(execFileMock, stdinWrites, (command, cb, args, _child, opts) => {
spawns.push({ command, args, cdp: opts.env?.AGENT_BROWSER_CDP })
cb(null, JSON.stringify({ success: true, data }), '')
})
return spawns
@@ -0,0 +1,28 @@
import { readFileSync } from 'node:fs'
import { createRequire } from 'node:module'
import { describe, expect, it } from 'vitest'
import { createAgentBrowserProcessEnvironment } from './agent-browser-process-environment'
describe('createAgentBrowserProcessEnvironment', () => {
it('drops an inherited AGENT_BROWSER_CDP so only Orca names the CDP target', () => {
const { env } = createAgentBrowserProcessEnvironment({
inheritedEnv: { AGENT_BROWSER_CDP: '9222', PATH: '/bin' },
platform: 'win32',
userDataPath: '/user-data'
})
expect(env.AGENT_BROWSER_CDP).toBeUndefined()
expect(env.PATH).toBe('/bin')
})
})
describe('bundled agent-browser', () => {
it('reads AGENT_BROWSER_CDP, which carries the tokened proxy URL', () => {
// agent-browser 0.30 and older ignore AGENT_BROWSER_CDP and would launch their own Chrome.
const require = createRequire(import.meta.url)
const { version }: { version: string } = JSON.parse(
readFileSync(require.resolve('agent-browser/package.json'), 'utf8')
)
const [major, minor] = version.split('.').map(Number)
expect(major > 0 || minor >= 35, `agent-browser ${version}`).toBe(true)
})
})
@@ -19,6 +19,8 @@ export function createAgentBrowserProcessEnvironment(options: {
userDataPath: string
}): AgentBrowserProcessEnvironment {
const env = { ...options.inheritedEnv }
// Commands get Orca's tokened proxy URL per spawn; an inherited target must not reach `close`.
delete env.AGENT_BROWSER_CDP
if (!env.AGENT_BROWSER_IDLE_TIMEOUT_MS?.trim()) {
env.AGENT_BROWSER_IDLE_TIMEOUT_MS = String(AGENT_BROWSER_IDLE_TIMEOUT_MS)
}
@@ -1,10 +1,53 @@
import type { IncomingMessage } from 'node:http'
import { timingSafeEqual } from 'node:crypto'
/** Reject browser origins and require a loopback Host to prevent web-page access and DNS rebinding. */
export function isTrustedCdpLoopbackRequest(req: IncomingMessage, port: number): boolean {
function isTrustedCdpLoopbackRequest(req: IncomingMessage, port: number): boolean {
if (req.headers.origin !== undefined) {
return false
}
const host = req.headers.host?.toLowerCase()
return host === `127.0.0.1:${port}` || host === `localhost:${port}`
}
/**
* Other local processes can reach the loopback port, so every request must start with
* `/<token>`. Returns the remaining path, or null when the token is missing or wrong.
*/
function stripCdpProxyTokenPath(url: string | undefined, token: string): string | null {
const path = url ?? ''
const end = path.indexOf('/', 1)
const segment = Buffer.from(end === -1 ? path.slice(1) : path.slice(1, end))
const expected = Buffer.from(token)
if (
!path.startsWith('/') ||
segment.length !== expected.length ||
!timingSafeEqual(segment, expected)
) {
return null
}
return end === -1 ? '/' : path.slice(end)
}
/** Returns the path after the token, or the status to reject with: 403 for web/rebound requests, 404 otherwise. */
export function admitCdpProxyRequest(
req: IncomingMessage,
port: number,
token: string
): { path: string } | { status: 403 | 404 } {
if (!isTrustedCdpLoopbackRequest(req, port)) {
return { status: 403 }
}
const path = stripCdpProxyTokenPath(req.url, token)
return path === null ? { status: 404 } : { path }
}
export function verifyCdpProxyUpgrade(
req: IncomingMessage,
port: number,
token: string,
done: (result: boolean, code?: number) => void
): void {
const admission = admitCdpProxyRequest(req, port, token)
done(!('status' in admission), 'status' in admission ? admission.status : undefined)
}
@@ -1,5 +1,5 @@
import type { WebSocket } from 'ws'
import type { IncomingMessage, ServerResponse } from 'node:http'
import type { ServerResponse } from 'node:http'
import type { WebContents } from 'electron'
import type { CdpClientResponseWriter } from './cdp-client-response-writer'
import type { CdpSyntheticSessionRegistry } from '../commands/cdp-synthetic-session-registry'
@@ -9,11 +9,11 @@ export class CdpTargetDiscovery {
private readonly webContents: WebContents,
private readonly responder: CdpClientResponseWriter,
private readonly sessions: CdpSyntheticSessionRegistry,
private readonly getPort: () => number
private readonly getEndpoint: () => string
) {}
handleHttpRequest(req: IncomingMessage, res: ServerResponse): void {
const url = req.url ?? ''
/** `url` has the proxy token prefix already removed. */
handleHttpRequest(url: string, res: ServerResponse): void {
if (url === '/json/version' || url === '/json/version/') {
res.writeHead(200, { 'Content-Type': 'application/json' })
// Report the bundled Chrome version without exposing Orca’s automation identity.
@@ -22,7 +22,7 @@ export class CdpTargetDiscovery {
JSON.stringify({
Browser: `Chrome/${chromeVersion}`,
'Protocol-Version': '1.3',
webSocketDebuggerUrl: `ws://127.0.0.1:${this.getPort()}`
webSocketDebuggerUrl: this.getEndpoint()
})
)
return
@@ -34,7 +34,7 @@ export class CdpTargetDiscovery {
{
...this.buildTargetInfo(),
id: 'orca-proxy-target',
webSocketDebuggerUrl: `ws://127.0.0.1:${this.getPort()}`
webSocketDebuggerUrl: this.getEndpoint()
}
])
)
@@ -30,17 +30,27 @@ function rejectedUpgradeStatus(endpoint: string, headers: Record<string, string>
})
}
function httpStatus(port: number, path: string, host: string): Promise<number> {
function httpGet(
port: number,
path: string,
host = `127.0.0.1:${port}`
): Promise<{ status: number; body: string }> {
return new Promise((resolve, reject) => {
const req = request({ host: '127.0.0.1', port, path, headers: { Host: host } }, (res) => {
res.resume()
resolve(res.statusCode ?? 0)
let body = ''
res.setEncoding('utf8')
res.on('data', (chunk: string) => (body += chunk))
res.on('end', () => resolve({ status: res.statusCode ?? 0, body }))
})
req.on('error', reject)
req.end()
})
}
async function httpStatus(port: number, path: string, host: string): Promise<number> {
return (await httpGet(port, path, host)).status
}
describe('CdpWsProxy loopback request guard', () => {
let mock: MockWebContents
let proxy: CdpWsProxy
@@ -81,14 +91,50 @@ describe('CdpWsProxy loopback request guard', () => {
})
it('refuses discovery requests whose Host is not loopback', async () => {
const port = proxy.getPort()
await expect(
httpStatus(proxy.getPort(), '/json/version', `evil.example:${proxy.getPort()}`)
httpStatus(port, `${tokenPath()}/json/version`, `evil.example:${port}`)
).resolves.toBe(403)
})
it('still answers discovery requests addressed to loopback', async () => {
const port = proxy.getPort()
await expect(httpStatus(port, '/json/version', `127.0.0.1:${port}`)).resolves.toBe(200)
await expect(httpStatus(port, '/json/version', `localhost:${port}`)).resolves.toBe(200)
const path = `${tokenPath()}/json/version`
await expect(httpStatus(port, path, `127.0.0.1:${port}`)).resolves.toBe(200)
await expect(httpStatus(port, path, `localhost:${port}`)).resolves.toBe(200)
})
it('hides discovery and the websocket from local clients without the token', async () => {
const port = proxy.getPort()
const wrongToken = `/${'0'.repeat(64)}`
for (const path of ['/json/version', '/json/list', `${wrongToken}/json/version`, '/']) {
await expect(httpGet(port, path)).resolves.toEqual({ status: 404, body: '' })
}
await expect(rejectedUpgradeStatus(`ws://127.0.0.1:${port}`, {})).resolves.toBe(404)
await expect(rejectedUpgradeStatus(`ws://127.0.0.1:${port}${wrongToken}`, {})).resolves.toBe(
404
)
await expect(
rejectedUpgradeStatus(`ws://127.0.0.1:${port}/devtools/browser`, {})
).resolves.toBe(404)
})
it('accepts the token and returns it in discovered websocket URLs', async () => {
const port = proxy.getPort()
const version = await httpGet(port, `${tokenPath()}/json/version`)
expect(JSON.parse(version.body).webSocketDebuggerUrl).toBe(endpoint)
const list = await httpGet(port, `${tokenPath()}/json/list`)
expect(JSON.parse(list.body)[0].webSocketDebuggerUrl).toBe(endpoint)
const client = await connect(endpoint)
mock.webContents.debugger.sendCommand.mockResolvedValueOnce({ ok: true })
await expect(sendAndReceive(client, { id: 1, method: 'DOM.getDocument' })).resolves.toEqual(
expect.objectContaining({ result: { ok: true } })
)
client.close()
})
function tokenPath(): string {
return new URL(endpoint).pathname
}
})
@@ -107,7 +107,7 @@ describe('CdpWsProxy startup ownership', () => {
debuggerHandle.sendCommand.mockRejectedValueOnce(new Error('Page domain is not ready'))
const proxy = makeProxy(mock)
await expect(proxy.start()).resolves.toBe('ws://127.0.0.1:9222')
await expect(proxy.start()).resolves.toMatch(/^ws:\/\/127\.0\.0\.1:9222\//)
await proxy.stop()
expectNoListeners(mock)
+15 -11
View File
@@ -1,5 +1,6 @@
import { WebSocketServer, type WebSocket } from 'ws'
import { createServer, type Server } from 'node:http'
import { randomBytes } from 'node:crypto'
import type { WebContents } from 'electron'
import { CdpClientResponseWriter } from './cdp-client-response-writer'
import { CdpSyntheticSessionRegistry } from '../commands/cdp-synthetic-session-registry'
@@ -12,7 +13,7 @@ import { CdpPageCaptureCommands } from '../commands/cdp-page-capture-commands'
import type { CapturePaintHold } from '../commands/cdp-screenshot'
import type { AgentInputFocusGuard } from '../input/agent-input-focus-guard'
import { CdpPageInputCommands, type ShowAgentPointer } from '../commands/cdp-page-input-commands'
import { isTrustedCdpLoopbackRequest } from './cdp-loopback-request-guard'
import { admitCdpProxyRequest, verifyCdpProxyUpgrade } from './cdp-loopback-request-guard'
import { parseCdpClientCommand } from '../commands/cdp-client-command'
import {
assertRemoteCliPageAccess,
@@ -25,6 +26,7 @@ export class CdpWsProxy {
private client: WebSocket | null = null
private detachClientListeners: (() => void) | null = null
private port = 0
private readonly token = randomBytes(32).toString('hex')
private stopped = false
private readonly responder = new CdpClientResponseWriter(() => this.client)
private readonly sessions = new CdpSyntheticSessionRegistry()
@@ -43,11 +45,8 @@ export class CdpWsProxy {
guardFocus: AgentInputFocusGuard = async () => () => {},
showAgentPointer: ShowAgentPointer = async () => {}
) {
this.discovery = new CdpTargetDiscovery(
webContents,
this.responder,
this.sessions,
() => this.port
this.discovery = new CdpTargetDiscovery(webContents, this.responder, this.sessions, () =>
this.getEndpoint()
)
this.debuggerChannel = new CdpDebuggerChannel(
webContents,
@@ -91,16 +90,17 @@ export class CdpWsProxy {
}
return new Promise<string>((resolve, reject) => {
this.httpServer = createServer((req, res) => {
if (!isTrustedCdpLoopbackRequest(req, this.port)) {
res.writeHead(403)
const admission = admitCdpProxyRequest(req, this.port, this.token)
if ('status' in admission) {
res.writeHead(admission.status)
res.end()
return
}
this.discovery.handleHttpRequest(req, res)
this.discovery.handleHttpRequest(admission.path, res)
})
this.wss = new WebSocketServer({
server: this.httpServer,
verifyClient: ({ req }, done) => done(isTrustedCdpLoopbackRequest(req, this.port), 403)
verifyClient: ({ req }, done) => verifyCdpProxyUpgrade(req, this.port, this.token, done)
})
const failStart = (error: Error): void => {
this.httpServer?.removeListener('error', onListenError)
@@ -148,7 +148,7 @@ export class CdpWsProxy {
const addr = this.httpServer!.address()
if (typeof addr === 'object' && addr) {
this.port = addr.port
resolve(`ws://127.0.0.1:${this.port}`)
resolve(this.getEndpoint())
} else {
failStart(new Error('Failed to bind proxy server'))
}
@@ -178,6 +178,10 @@ export class CdpWsProxy {
return this.port
}
getEndpoint(): string {
return `ws://127.0.0.1:${this.port}/${this.token}`
}
private closeClient(): void {
const client = this.client
this.detachClientListeners?.()