Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(browser): add per-start (unauthenticated) proxy server support

Yecheng Fu53363c7296b1
diff --git a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
index f701610c7f..1f357b6446 100644
--- a/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
+++ b/apps/desktop/src/main/__tests__/makerEventHotPathOrdering.test.ts
@@ -363,6 +363,30 @@ describe('maker:event hot path ordering', () => {
);
});
+ it('stores the redacted permission request for reconnect and Feishu takeover', () => {
+ const interactionListenerSource = extractInstallDesktopInteractionListenerSource();
+ const boundaryIndex = interactionListenerSource.indexOf(
+ 'const boundaryRequest: InteractionRequest =',
+ );
+ const entryIndex = interactionListenerSource.indexOf(
+ 'const entry: PendingInteractionEntry =',
+ );
+ const pendingIndex = interactionListenerSource.indexOf(
+ 'pendingInteractionResolvers.set(req.requestId, entry);',
+ );
+
+ expect(boundaryIndex).toBeGreaterThanOrEqual(0);
+ expect(entryIndex).toBeGreaterThan(boundaryIndex);
+ expect(pendingIndex).toBeGreaterThan(entryIndex);
+ expect(interactionListenerSource.slice(entryIndex, pendingIndex)).toContain(
+ 'request: boundaryRequest,',
+ );
+ expect(source).toContain('out.push({ request: entry.request, persistId: entry.persistId });');
+ expect(source).toContain(
+ 'taken.push({ requestId, request: entry.request, resolve: entry.resolve });',
+ );
+ });
+
it('clears git snapshot coordinator state when sessions close', () => {
const closedBlock = extractSessionCloseAdaptersSource();
diff --git a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts
index e6f05cc178..fb74cdcb24 100644
--- a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts
+++ b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts
@@ -108,6 +108,7 @@ import {
noteTurnStarted,
saveTurnStartedAtForDeferred,
preserveTurnPersistStateForBackground,
+ redactToolInputForUntrustedBoundary,
} from '../messagePersistBroadcaster.js';
const SESSION = 'sess-tr';
@@ -145,6 +146,281 @@ beforeEach(() => {
clearSessionPersistState(SESSION);
});
+describe('browser proxy credential persistence', () => {
+ const proxyServer = 'http://user%40example.test:p%3Ass%2Fword%40%[email protected]:12323';
+
+ it('redacts proxyServer before persisting a browser tool_use', async () => {
+ onToolUseEvent(
+ SESSION,
+ {
+ toolUseId: 'browser-proxy-start',
+ toolName: 'mcp__cindy_browser__call_tool',
+ input: { name: 'browser', args: { action: 'start', proxyServer } },
+ },
+ null,
+ );
+ await flushWrites();
+
+ const persisted = vi.mocked(createMessage).mock.calls.find(
+ ([, body]) => (body as { toolUseId?: string }).toolUseId === 'browser-proxy-start',
+ )?.[1];
+ expect(persisted).toMatchObject({
+ content: {
+ input: {
+ name: 'browser',
+ args: {
+ action: 'start',
+ proxyServer: '[REDACTED]',
+ },
+ },
+ },
+ });
+ const serialized = JSON.stringify(persisted);
+ expect(serialized).not.toContain('user%40example.test');
+ expect(serialized).not.toContain('p%3Ass%2Fword%40%23');
+ });
+
+ it('leaves unrelated tools alone even when their input mentions proxyServer', () => {
+ // A patch that edits code containing the identifier must survive intact:
+ // blanking it would erase the tool detail from the live UI, the persisted
+ // record, and the rehydrated history.
+ const patch = 'diff --git a/proxy.ts b/proxy.ts\n+ const proxyServer = route.server;';
+ expect(redactToolInputForUntrustedBoundary('apply_patch', patch)).toBe(patch);
+ expect(redactToolInputForUntrustedBoundary('Bash', { command: 'grep -r proxyServer src' }))
+ .toEqual({ command: 'grep -r proxyServer src' });
+ // Even a literal proxyServer field on a non-browser tool is left as-is:
+ // only the browser tool surface is in scope for this redaction.
+ const unrelated = { proxyServer: 'http://user:[email protected]:8080' };
+ expect(redactToolInputForUntrustedBoundary('some_other_tool', unrelated)).toBe(unrelated);
+ });
+
+ it('redacts the Codex MCP approval envelope', () => {
+ // Codex approvals name the SERVER only and nest the call under toolParams,
+ // with a rendered copy under toolParamsDisplay. Neither the execution-event
+ // tool id nor the top-level proxyServer check reaches them, so an Ask-mode
+ // permission card would carry the credential before parsing rejects it.
+ const redacted = redactToolInputForUntrustedBoundary('mcp:cindy_browser', {
+ serverName: 'cindy_browser',
+ message: 'Allow Codex to use browser?',
+ toolName: 'call_tool',
+ toolParams: {
+ name: 'browser',
+ args: { action: 'start', proxyServer: 'http://user:[email protected]:8080' },
+ },
+ toolParamsDisplay: '{"action":"start","proxyServer":"http://user:[email protected]:8080"}',
+ }) as {
+ toolParams: { args: { proxyServer: string } };
+ toolParamsDisplay: string;
+ };
+
+ expect(redacted.toolParams.args.proxyServer).toBe('[REDACTED]');
+ expect(JSON.stringify(redacted)).not.toContain('secret');
+ });
+
+ it('still redacts on the browser tool surfaces', () => {
+ for (const name of [
+ 'mcp__cindy_browser__call_tool',
+ // Codex's translator emits `mcp:${server}:${tool}`, not the `__` form.
+ // Omitting it let a local Codex browser call persist and broadcast the
+ // credential-bearing URL unredacted.
+ 'mcp:cindy_browser:call_tool',
+ 'cindy_mcp_call_tool',
+ 'browser',
+ ]) {
+ const redacted = redactToolInputForUntrustedBoundary(name, {
+ name: 'browser',
+ args: { action: 'start', proxyServer: 'http://user:[email protected]:8080' },
+ }) as { args: { proxyServer: string } };
+ expect(redacted.args.proxyServer, name).toBe('[REDACTED]');
+ }
+ });
+
+ it('does not treat a third-party server impersonating the browser as first-party', () => {
+ // A custom MCP id may contain `__`, so `cindy_browser__evil` yields
+ // `mcp__cindy_browser__evil__call_tool`. A substring match reads that as
+ // the built-in browser and rewrites an unrelated server's input — blanking
+ // that tool call in the live UI, the persisted record and the rehydrated
+ // history. mcp-tool-target.ts names this exact id as why attribution must
+ // not be naive.
+ const impersonators = [
+ 'mcp__cindy_browser__evil__call_tool',
+ 'mcp__evil_browser__call_tool',
+ 'browser_impersonator',
+ 'not_cindy_browser_either',
+ ];
+ for (const name of impersonators) {
+ const input = {
+ name: 'browser',
+ args: { action: 'start', proxyServer: 'http://user:[email protected]:8080' },
+ };
+ expect(redactToolInputForUntrustedBoundary(name, input), name).toBe(input);
+ }
+ });
+
+ it('redacts proxyServer nested inside a Pi MCP gateway call_tool envelope', async () => {
+ const gatewayInput = {
+ server: 'cindy_browser',
+ tool: 'call_tool',
+ args: { name: 'browser', args: { action: 'start', proxyServer } },
+ };
+ expect(redactToolInputForUntrustedBoundary('cindy_mcp_call_tool', gatewayInput)).toEqual({
+ server: 'cindy_browser',
+ tool: 'call_tool',
+ args: {
+ name: 'browser',
+ args: {
+ action: 'start',
+ proxyServer: '[REDACTED]',
+ },
+ },
+ });
+ const safeGatewayInput = {
+ server: 'cindy_workspace',
+ tool: 'status',
+ args: {},
+ };
+ expect(
+ redactToolInputForUntrustedBoundary('cindy_mcp_call_tool', safeGatewayInput),
+ ).toBe(safeGatewayInput);
+
+ // A non-browser MCP whose args happen to carry a `proxyServer` field must
+ // pass through untouched. Recursing on any {server, tool} shape re-enters
+ // with an empty name, which skips the mayCarryProxyServer gate and would
+ // blank an unrelated tool's input in the UI, the persisted record, and the
+ // rehydrated history. Only the exact browser envelope may recurse.
+ const unrelatedGatewayInput = {
+ server: 'cindy_workspace',
+ tool: 'configure',
+ args: { proxyServer: 'http://user:[email protected]:8080' },
+ };
+ expect(
+ redactToolInputForUntrustedBoundary('cindy_mcp_call_tool', unrelatedGatewayInput),
+ ).toBe(unrelatedGatewayInput);
+
+ onToolUseEvent(
+ SESSION,
+ {
+ toolUseId: 'browser-proxy-gateway-start',
+ toolName: 'cindy_mcp_call_tool',
+ input: gatewayInput,
+ },
+ null,
+ );
+ await flushWrites();
+
+ const persisted = vi.mocked(createMessage).mock.calls.find(
+ ([, body]) => (body as { toolUseId?: string }).toolUseId === 'browser-proxy-gateway-start',
+ )?.[1];
+ const serialized = JSON.stringify(persisted);
+ expect(serialized).not.toContain('user%40example.test');
+ expect(serialized).not.toContain('p%3Ass%2Fword%40%23');
+ expect(serialized).toContain('[REDACTED]');
+ });
+
+ it('redacts proxyServer nested inside stringified gateway args', () => {
+ expect(
+ redactToolInputForUntrustedBoundary('cindy_mcp_call_tool', {
+ server: 'cindy_browser',
+ tool: 'call_tool',
+ args: JSON.stringify({ name: 'browser', args: { action: 'start', proxyServer } }),
+ }),
+ ).toEqual({
+ server: 'cindy_browser',
+ tool: 'call_tool',
+ args: JSON.stringify({
+ name: 'browser',
+ args: {
+ action: 'start',
+ proxyServer: '[REDACTED]',
+ },
+ }),
+ });
+ });
+
+ it('redacts the stringified-args fallback without changing unrelated browser inputs', () => {
+ expect(
+ redactToolInputForUntrustedBoundary('mcp__cindy_browser__call_tool', {
+ name: 'browser',
+ args: JSON.stringify({ action: 'start', proxyServer }),
+ }),
+ ).toEqual({
+ name: 'browser',
+ args: JSON.stringify({
+ action: 'start',
+ proxyServer: '[REDACTED]',
+ }),
+ });
+ const safeInput = { name: 'browser', args: { action: 'status' } };
+ expect(
+ redactToolInputForUntrustedBoundary('mcp__cindy_browser__call_tool', safeInput),
+ ).toBe(safeInput);
+ const unauthenticatedProxy = {
+ name: 'browser',
+ args: { action: 'start', proxyServer: 'http://proxy.example.test:12323' },
+ };
+ expect(
+ redactToolInputForUntrustedBoundary(
+ 'mcp__cindy_browser__call_tool',
+ unauthenticatedProxy,
+ ),
+ ).toBe(unauthenticatedProxy);
+ });
+
+ it('fails closed for malformed or non-string proxyServer inputs', async () => {
+ const malformed = 'user:[email protected]:12323';
+ const redacted = redactToolInputForUntrustedBoundary('mcp__cindy_browser__call_tool', {
+ name: 'browser',
+ args: { action: 'start', proxyServer: malformed },
+ });
+ expect(redacted).toEqual({
+ name: 'browser',
+ args: { action: 'start', proxyServer: '[REDACTED]' },
+ });
+ expect(
+ redactToolInputForUntrustedBoundary('mcp__cindy_browser__call_tool', {
+ name: 'browser',
+ args: JSON.stringify({ action: 'start', proxyServer: malformed }),
+ }),
+ ).toEqual({
+ name: 'browser',
+ args: JSON.stringify({ action: 'start', proxyServer: '[REDACTED]' }),
+ });
+ expect(
+ redactToolInputForUntrustedBoundary('mcp__cindy_browser__call_tool', {
+ name: 'browser',
+ args: { action: 'start', proxyServer: { password: 'nested-secret' } },
+ }),
+ ).toEqual({
+ name: 'browser',
+ args: { action: 'start', proxyServer: '[REDACTED]' },
+ });
+
+ onToolUseEvent(
+ SESSION,
+ {
+ toolUseId: 'browser-invalid-proxy-start',
+ toolName: 'mcp__cindy_browser__call_tool',
+ input: { name: 'browser', args: { action: 'start', proxyServer: malformed } },
+ },
+ null,
+ );
+ await flushWrites();
+
+ const persisted = vi.mocked(createMessage).mock.calls.find(
+ ([, body]) => (body as { toolUseId?: string }).toolUseId === 'browser-invalid-proxy-start',
+ )?.[1];
+ expect(JSON.stringify(persisted)).not.toContain('secret');
+ expect(persisted).toMatchObject({
+ content: {
+ input: {
+ name: 'browser',
+ args: { action: 'start', proxyServer: '[REDACTED]' },
+ },
+ },
+ });
+ });
+});
+
describe('update_plan tool_use persistence', () => {
it('persists native Codex plan state without relying on the session agent cache', async () => {
noteSessionAgentKind(SESSION, 'codex');
diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.ts
index c530dee6d3..fb6872f4fe 100644
--- a/apps/desktop/src/main/im/shared/turnRunner.ts
+++ b/apps/desktop/src/main/im/shared/turnRunner.ts
@@ -110,7 +110,10 @@ import { agentHandoffPending } from '../../maker-ipc/agentHandoffPendingSingleto
import { prependHandoffToUserMessage, prependNoteToWireUserMessage } from '../../maker-ipc/agentHandoff';
import { buildPlanReconcileNote, summarizeOpenPlan } from '../../maker-ipc/planReconcile';
import { listMessagesForAgentHandoff } from '../../localDb/ipc/messages';
-import { enqueueDurableWrite } from '../../messagePersistBroadcaster';
+import {
+ enqueueDurableWrite,
+ redactToolInputForUntrustedBoundary,
+} from '../../messagePersistBroadcaster';
import {
cancelPending,
registerPending,
@@ -3110,7 +3113,23 @@ export function createTurnRunner(
scopeKey?: string,
confirmationTimeoutMs?: number,
) {
- return async (req: InteractionRequest): Promise<InteractionDecision> => {
+ return async (rawReq: InteractionRequest): Promise<InteractionDecision> => {
+ // Redact BEFORE anything channel-facing sees the request. This listener
+ // replaces the Desktop handler, which does its own redaction, so without
+ // this the card builders (interactionCardModel copies `input` verbatim)
+ // would put a credential-bearing `proxyServer` into a Telegram/Feishu
+ // card. The browser tool rejects authenticated proxies later, but the
+ // card has already left the machine by then.
+ const req: InteractionRequest =
+ rawReq.kind === 'permission'
+ ? {
+ ...rawReq,
+ input: redactToolInputForUntrustedBoundary(
+ rawReq.toolName,
+ rawReq.input,
+ ) as Record<string, unknown>,
+ }
+ : rawReq;
log.info(
`interaction request kind=${req.kind} requestId=...${req.requestId.slice(-8)} session=...${localSessionId.slice(-8)}`,
);
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index c9b5c94c17..0c46d84cc5 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -494,6 +494,7 @@ import {
markAutoResumeOutcome,
onTurnErrorEvent,
prepareSyntheticToolEventForBroadcast,
+ redactToolInputForUntrustedBoundary,
resetTurnPersistState,
saveTurnStartedAtForDeferred,
} from '../messagePersistBroadcaster.js';
@@ -3910,11 +3911,21 @@ export function installDesktopInteractionListener(session: {
},
);
return new Promise<InteractionDecision>((resolve) => {
+ const boundaryRequest: InteractionRequest =
+ req.kind === 'permission'
+ ? {
+ ...req,
+ input: redactToolInputForUntrustedBoundary(
+ req.toolName,
+ req.input,
+ ) as Record<string, unknown>,
+ }
+ : req;
const entry: PendingInteractionEntry = {
sessionId: session.id,
kind: req.kind,
resolve,
- request: req,
+ request: boundaryRequest,
persistId: interactionPersistId ?? undefined,
};
if (req.kind === 'permission') {
@@ -3931,12 +3942,12 @@ export function installDesktopInteractionListener(session: {
pendingInteractionResolvers.set(req.requestId, entry);
broadcastToAllWindows(MAKER_PUSH.INTERACTION_REQUEST, {
sessionId: session.id,
- request: req,
+ request: boundaryRequest,
persistId: interactionPersistId,
});
handleAgentIslandInteractionAfterBroadcast(
session as { id: string; agentKind?: unknown; workDir?: unknown; workspaceKind?: unknown },
- req,
+ boundaryRequest,
agentIslandInteractionEpoch,
);
});
@@ -17375,6 +17386,16 @@ function redactEventForRenderer(event: AgentEvent): AgentEvent {
const data = event.data as Record<string, unknown>;
const safeData = { ...data };
let changed = false;
+ if (
+ typeof safeData.toolName === 'string' &&
+ Object.prototype.hasOwnProperty.call(safeData, 'input')
+ ) {
+ const redactedInput = redactToolInputForUntrustedBoundary(safeData.toolName, safeData.input);
+ if (redactedInput !== safeData.input) {
+ safeData.input = redactedInput;
+ changed = true;
+ }
+ }
// Main consumes this Cindy-owned durable projection marker before the event
// crosses renderer/device-link boundaries. Live task-card payloads therefore
// keep their existing wire shape and older mobile clients need no upgrade.
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/browserManagedConfig.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/browserManagedConfig.test.ts
index 60e7302852..cb955ac957 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/browserManagedConfig.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/browserManagedConfig.test.ts
@@ -1,6 +1,28 @@
+import nodePath from 'node:path';
import { describe, expect, it } from 'vitest';
-import { buildManagedConfig } from '../browser-managed-config.js';
+import { buildManagedConfig, managedBrowserGuardIdentity } from '../browser-managed-config.js';
+
+/** Netscape PAC `isInNet` over already-resolved IPv4, for the Node PAC harness. */
+function isInNet(host: string, pattern: string, mask: string): boolean {
+ const toInt = (value: string): number | null => {
+ const parts = value.split('.');
+ if (parts.length !== 4) return null;
+ let n = 0;
+ for (const part of parts) {
+ if (!/^\d+$/.test(part)) return null;
+ const octet = Number(part);
+ if (octet > 255) return null;
+ n = (n << 8) + octet;
+ }
+ return n >>> 0;
+ };
+ const ip = toInt(host);
+ const net = toInt(pattern);
+ const bits = toInt(mask);
+ if (ip === null || net === null || bits === null) return false;
+ return (ip & bits) === (net & bits);
+}
describe('managed browser runtime config', () => {
it.each([false, true])('allows private-network browsing with useRealProfile=%s', (useRealProfile) => {
@@ -9,6 +31,24 @@ describe('managed browser runtime config', () => {
});
});
+ it('points the CDP guard at Cindy-real and a relocated port', () => {
+ expect(managedBrowserGuardIdentity({
+ runtimeDir: '/runtime',
+ useRealProfile: false,
+ })).toEqual({
+ cdpHttpUrl: 'http://127.0.0.1:18800',
+ managedUserDataDir: nodePath.join('/runtime', 'browser', 'Cindy', 'user-data'),
+ });
+ expect(managedBrowserGuardIdentity({
+ runtimeDir: '/runtime',
+ useRealProfile: true,
+ cdpPort: 18801,
+ })).toEqual({
+ cdpHttpUrl: 'http://127.0.0.1:18801',
+ managedUserDataDir: nodePath.join('/runtime', 'browser', 'Cindy-real', 'user-data'),
+ });
+ });
+
it('labels both isolated and snapshot profiles Cindy on the Chrome chip', () => {
const isolated = buildManagedConfig().browser;
expect(isolated?.defaultProfile).toBe('Cindy');
@@ -19,4 +59,244 @@ describe('managed browser runtime config', () => {
expect(snapshot?.profiles?.['Cindy-real']?.displayName).toBe('Cindy');
expect(Object.keys(snapshot?.profiles ?? {})).toEqual(['Cindy-real']);
});
+
+ it('maps an explicit proxy server to a PAC-only Chrome launch', () => {
+ // Chromium applies exactly one proxy mode from the command line, and
+ // `--proxy-pac-url` outranks `--proxy-server` (ApplyProxyMode). Emitting
+ // both would leave a dead `--proxy-server` that reads as if fixed-proxy
+ // semantics applied; the proxy address belongs inside the PAC directive.
+ for (const [proxyServer, directive] of [
+ ['http://127.0.0.1:7890', 'PROXY 127.0.0.1:7890'],
+ ['socks5://[::1]:1080', 'SOCKS5 [::1]:1080'],
+ ] as const) {
+ const extraArgs = buildManagedConfig({ proxyServer }).browser?.extraArgs ?? [];
+ expect(extraArgs.some((arg) => arg.startsWith('--proxy-server'))).toBe(false);
+ expect(extraArgs.some((arg) => arg.startsWith('--no-proxy-server'))).toBe(false);
+ const pacArg = extraArgs.find((arg) => arg.startsWith('--proxy-pac-url=')) ?? '';
+ const decodedPac = Buffer.from(
+ pacArg.slice(pacArg.indexOf('base64,') + 'base64,'.length),
+ 'base64',
+ ).toString('utf8');
+ expect(decodedPac).toContain(JSON.stringify(directive));
+ }
+ });
+
+ describe('launch-time PAC allowlist', () => {
+ /**
+ * Evaluate the generated PAC with Netscape builtins injected. Default
+ * `dnsResolve` answers a public IPv4 so hostname tests stay independent of
+ * the address gate; pass `dns` to pin a private/empty answer.
+ */
+ const evaluatePac = (
+ options: Parameters<typeof buildManagedConfig>[0],
+ host: string,
+ scheme = 'https',
+ dns: Record<string, string> = {},
+ ): string => {
+ const pacArg = buildManagedConfig(options).browser?.extraArgs
+ ?.find((arg) => arg.startsWith('--proxy-pac-url='));
+ if (!pacArg) throw new Error('no PAC arg emitted');
+ const encoded = pacArg.slice(pacArg.indexOf('base64,') + 'base64,'.length);
+ const source = Buffer.from(encoded, 'base64').toString('utf8');
+ const dnsResolve = (name: string): string => {
+ const key = String(name || '').toLowerCase().replace(/\.+$/, '');
+ if (Object.prototype.hasOwnProperty.call(dns, key)) return dns[key] ?? '';
+ return '93.184.216.34';
+ };
+ // eslint-disable-next-line no-new-func
+ const findProxyForURL = new Function(
+ 'dnsResolve',
+ 'isInNet',
+ `${source}; return FindProxyForURL;`,
+ )(dnsResolve, isInNet) as (url: string, host: string) => string;
+ return findProxyForURL(`${scheme}://${host}/`, host);
+ };
+
+ const proxied = {
+ proxyServer: 'http://proxy.example.test:8080',
+ proxyAllowedHostnames: ['auth.example.com', '*.wild.example'],
+ };
+
+ it.each([
+ ['auth.example.com', 'PROXY proxy.example.test:8080'],
+ ['AUTH.example.com', 'PROXY proxy.example.test:8080'],
+ ['auth.example.com.', 'PROXY proxy.example.test:8080'],
+ ['sub.wild.example', 'PROXY proxy.example.test:8080'],
+ ['deep.sub.wild.example', 'PROXY proxy.example.test:8080'],
+ // Apex of a wildcard pattern, unrelated hosts, and suffix-confusion
+ // attempts must all hit the unreachable directive, never DIRECT.
+ ['wild.example', 'PROXY 0.0.0.0:0'],
+ ['evil.example', 'PROXY 0.0.0.0:0'],
+ ['auth.example.com.evil.test', 'PROXY 0.0.0.0:0'],
+ ['notauth.example.com', 'PROXY 0.0.0.0:0'],
+ ])('routes %s to %s', (host, expected) => {
+ expect(evaluatePac(proxied, host)).toBe(expected);
+ });
+
+ it.each([
+ ['http', 'auth.example.com'],
+ ['ws', 'auth.example.com'],
+ ['ftp', 'auth.example.com'],
+ ['HTTP', 'auth.example.com'],
+ ])('refuses %s requests to an allowlisted host at the launch floor', (scheme, host) => {
+ expect(evaluatePac(proxied, host, scheme)).toBe('PROXY 0.0.0.0:0');
+ });
+
+ // Chrome hands PAC the wss:/ws: scheme unrewritten, and CDP Fetch does not
+ // intercept WebSocket handshakes, so the PAC is the only gate these get:
+ // encrypted ones must pass the same hostname rules, cleartext must not.
+ it.each([
+ ['wss', 'auth.example.com', 'PROXY proxy.example.test:8080'],
+ ['wss', 'sub.wild.example', 'PROXY proxy.example.test:8080'],
+ ['WSS', 'auth.example.com', 'PROXY proxy.example.test:8080'],
+ ['wss', 'evil.example', 'PROXY 0.0.0.0:0'],
+ ['wss', 'wild.example', 'PROXY 0.0.0.0:0'],
+ ['ws', 'auth.example.com', 'PROXY 0.0.0.0:0'],
+ ])('routes %s://%s to %s', (scheme, host, expected) => {
+ expect(evaluatePac(proxied, host, scheme)).toBe(expected);
+ });
+
+ it.each([
+ ['127.0.0.1', 'loopback'],
+ ['10.1.2.3', 'RFC1918'],
+ ['192.168.0.9', 'RFC1918'],
+ ['172.16.4.1', 'RFC1918'],
+ ['169.254.169.254', 'link-local/metadata'],
+ ['100.64.1.1', 'CGNAT'],
+ ])('refuses an allowlisted name whose DNS is %s (%s)', (ip) => {
+ expect(evaluatePac(proxied, 'auth.example.com', 'https', { 'auth.example.com': ip }))
+ .toBe('PROXY 0.0.0.0:0');
+ expect(evaluatePac(proxied, 'auth.example.com', 'wss', { 'auth.example.com': ip }))
+ .toBe('PROXY 0.0.0.0:0');
+ });
+
+ it('still allows Clash/Surge fake-IP answers in 198.18.0.0/15', () => {
+ expect(evaluatePac(proxied, 'auth.example.com', 'https', { 'auth.example.com': '198.18.0.2' }))
+ .toBe('PROXY proxy.example.test:8080');
+ expect(evaluatePac(proxied, 'auth.example.com', 'wss', { 'auth.example.com': '198.18.255.1' }))
+ .toBe('PROXY proxy.example.test:8080');
+ });
+
+ it('fails closed when PAC dnsResolve returns empty', () => {
+ expect(evaluatePac(proxied, 'auth.example.com', 'https', { 'auth.example.com': '' }))
+ .toBe('PROXY 0.0.0.0:0');
+ expect(evaluatePac(proxied, 'auth.example.com', 'wss', { 'auth.example.com': '' }))
+ .toBe('PROXY 0.0.0.0:0');
+ });
+
+ it('embeds IPv6 loopback and link-local literal checks in the PAC source', () => {
+ const extraArgs = buildManagedConfig({
+ proxyServer: 'http://proxy.example.test:8080',
+ proxyAllowedHostnames: ['auth.example.com'],
+ }).browser?.extraArgs ?? [];
+ const pacArg = extraArgs.find((arg) => arg.startsWith('--proxy-pac-url=')) ?? '';
+ const decodedPac = Buffer.from(
+ pacArg.slice(pacArg.indexOf('base64,') + 'base64,'.length),
+ 'base64',
+ ).toString('utf8');
+ expect(decodedPac).toContain('::1');
+ expect(decodedPac).toContain('fe80:');
+ });
+
+ it('blocks everything when a proxied launch has no allowlist', () => {
+ expect(evaluatePac({ proxyServer: 'http://proxy.example.test:8080' }, 'anything.example'))
+ .toBe('PROXY 0.0.0.0:0');
+ });
+
+ it('emits scheme-appropriate PAC directives', () => {
+ expect(evaluatePac(
+ { proxyServer: 'socks5://[::1]:1080', proxyAllowedHostnames: ['auth.example.com'] },
+ 'auth.example.com',
+ )).toBe('SOCKS5 [::1]:1080');
+ expect(evaluatePac(
+ { proxyServer: 'https://proxy.example.test:8443', proxyAllowedHostnames: ['auth.example.com'] },
+ 'auth.example.com',
+ )).toBe('HTTPS proxy.example.test:8443');
+ });
+
+ it('does not emit PAC args for a direct launch', () => {
+ expect(buildManagedConfig().browser?.extraArgs).toBeUndefined();
+ });
+
+ it('keeps hostile hostname patterns as data, not PAC source', () => {
+ const directive = evaluatePac({
+ proxyServer: 'http://proxy.example.test:8080',
+ proxyAllowedHostnames: ['auth.example.com'],
+ }, '";return "DIRECT');
+ expect(directive).toBe('PROXY 0.0.0.0:0');
+ });
+ });
+
+ it('maps proxy navigation hostnames to the strict SSRF hostname allowlist', () => {
+ expect(buildManagedConfig({
+ proxyServer: 'http://127.0.0.1:7890',
+ proxyAllowedHostnames: ['*.example.com', 'auth.example.com'],
+ }).browser?.ssrfPolicy).toEqual({
+ // IPv4 fake-IP only. IPv6 ULA stays blocked in proxied mode: fc00::/7 is
+ // where real internal services live, so exempting it would contradict the
+ // route's public-host-only contract.
+ allowRfc2544BenchmarkRange: true,
+ hostnameAllowlist: ['*.example.com', 'auth.example.com'],
+ });
+ });
+
+ it('keeps the intranet-reachable policy for direct starts', () => {
+ // Direct mode is the agent's own browser: reaching the intranet there is a
+ // deliberate product decision and must not be narrowed by proxy support.
+ expect(buildManagedConfig({}).browser?.ssrfPolicy).toEqual({
+ dangerouslyAllowPrivateNetwork: true,
+ });
+ });
+
+ it.each([
+ 'ftp://proxy.example.test:21',
+ 'http://proxy.example.test:8080/path',
+ 'not a proxy URL',
+ ])('rejects unsafe or unsupported proxy server %s', (proxyServer) => {
+ expect(() => buildManagedConfig({ proxyServer })).toThrow(/invalid proxyServer/);
+ });
+
+ it('blocks non-proxied WebRTC egress on a proxied launch', () => {
+ // WebRTC uses UDP outside the proxy, so neither the PAC nor the CDP request
+ // gate can see it; without this policy an allowlisted page can disclose the
+ // machine's real IP while status reports a proxied route.
+ const proxied = buildManagedConfig({
+ proxyServer: 'http://proxy.example.test:8080',
+ proxyAllowedHostnames: ['auth.example.com'],
+ }).browser?.extraArgs ?? [];
+ expect(proxied).toContain('--webrtc-ip-handling-policy=disable_non_proxied_udp');
+ // Chrome ignores a --force- prefixed variant; guard against reintroducing it.
+ expect(proxied.join(' ')).not.toContain('--force-webrtc-ip-handling-policy');
+
+ // A direct launch has no proxy to bypass, so it keeps default behavior.
+ expect(buildManagedConfig().browser?.extraArgs).toBeUndefined();
+ });
+
+ it('rejects a credentialed proxy URL before building any launch args', () => {
+ // Authenticated proxies are unsupported, so credentials never reach launch
+ // args by construction: the config builder refuses the URL outright rather
+ // than stripping userinfo and launching a browser that cannot authenticate.
+ expect(() => buildManagedConfig({
+ proxyServer: 'http://user:p%[email protected]:8080',
+ proxyAllowedHostnames: ['auth.example.com'],
+ })).toThrow(/authenticated proxies are not supported/);
+ });
+
+ it('keeps a credential-free proxy in the PAC directive', () => {
+ const extraArgs = buildManagedConfig({
+ proxyServer: 'http://proxy.example.test:8080',
+ proxyAllowedHostnames: ['auth.example.com'],
+ }).browser?.extraArgs ?? [];
+ expect(extraArgs.some((arg) => arg.startsWith('--proxy-server'))).toBe(false);
+ const pacArg = extraArgs.find((arg) => arg.startsWith('--proxy-pac-url=')) ?? '';
+ const decodedPac = Buffer.from(
+ pacArg.slice(pacArg.indexOf('base64,') + 'base64,'.length),
+ 'base64',
+ ).toString('utf8');
+ expect(decodedPac).toContain('proxy.example.test:8080');
+ expect(decodedPac).toContain('dnsResolve');
+ // No userinfo can appear in a launch arg — the process command line is
+ // world-readable on every platform we ship.
+ expect(extraArgs.join(' ')).not.toContain('@');
+ });
});
diff --git a/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/external-chrome-backend.test.ts b/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/external-chrome-backend.test.ts
index 672cfe3634..4e6459284c 100644
--- a/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/external-chrome-backend.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/external-chrome-backend.test.ts
@@ -1,10 +1,15 @@
-// Verifies requests reach the runtime verbatim, status identifies the backend,
-// other results pass through unchanged, and dispose
-// goes through the same `stopRuntimeForQuit` contract (logs-and-swallows).
+// Verifies the external backend's route lifecycle: requests reach the runtime
+// verbatim, status identifies the backend and its proxy route, the route is
+// launch state rather than a per-request option, and dispose stops the browser
+// through the same logs-and-swallows quit contract.
import { describe, expect, it, vi } from 'vitest';
-import type { BrowserControlRequest, BrowserControlResult } from '@cindy/browser-control-runtime';
+import type {
+ BrowserControlRequest,
+ BrowserControlResult,
+ BrowserProxyRoute,
+} from '@cindy/browser-control-runtime';
import { ExternalChromeBackend } from '../external-chrome-backend.js';
@@ -12,64 +17,1347 @@ function fakeLogger() {
return { warn: vi.fn() };
}
-describe('ExternalChromeBackend', () => {
- it('reports kind = "external"', () => {
- const call = vi.fn();
- const backend = new ExternalChromeBackend({ call }, fakeLogger());
- expect(backend.kind).toBe('external');
+function fakeRuntime(initialRunning = false) {
+ let running = initialRunning;
+ const call = vi.fn(async (req: BrowserControlRequest): Promise<BrowserControlResult> => {
+ if (req.action === 'status') {
+ return { ok: true, action: req.action, status: 200, data: { running } };
+ }
+ if (req.action === 'start') {
+ running = true;
+ return { ok: true, action: req.action, status: 200, data: { ok: true } };
+ }
+ if (req.action === 'stop') {
+ const stopped = running;
+ running = false;
+ return { ok: true, action: req.action, status: 200, data: { stopped } };
+ }
+ return { ok: true, action: req.action, status: 200, data: { request: req } };
+ });
+ return { call };
+}
+
+function createHarness(initialRunning = false) {
+ const initial = fakeRuntime(initialRunning);
+ const created: Array<{ route: BrowserProxyRoute; runtime: ReturnType<typeof fakeRuntime> }> = [];
+ const auth = { start: vi.fn(async () => {}), dispose: vi.fn(async () => {}) };
+ let failProxyAuth = () => {};
+ const closeAdoptedBrowser = vi.fn(async () => true);
+ // Default: the browser is gone when the runtime says it stopped. Tests that
+ // exercise the busy-but-alive case override this.
+ const isBrowserGone = vi.fn(async () => true);
+ const backend = new ExternalChromeBackend(initial, fakeLogger(), {
+ createRuntime: (route) => {
+ const runtime = fakeRuntime();
+ created.push({ route, runtime });
+ return runtime;
+ },
+ createProxyAuth: (_route, _logger, onFailure) => {
+ failProxyAuth = onFailure;
+ return auth;
+ },
+ closeAdoptedBrowser,
+ isBrowserGone,
+ managedUserDataDir: '/managed/browser/Cindy/user-data',
+ });
+ return {
+ backend,
+ initial,
+ created,
+ auth,
+ closeAdoptedBrowser,
+ isBrowserGone,
+ failProxyAuth: () => failProxyAuth(),
+ };
+}
+
+describe('ExternalChromeBackend proxy lifecycle', () => {
+ it('reports kind = external', () => {
+ expect(createHarness().backend.kind).toBe('external');
});
it('identifies the external backend while preserving runtime status fields', async () => {
const result: BrowserControlResult = { ok: true, action: 'status', status: 200, data: { ready: true } };
const call = vi.fn<(req: BrowserControlRequest) => Promise<BrowserControlResult>>(async () => result);
- const backend = new ExternalChromeBackend({ call }, fakeLogger());
+ // This backend verifies process liveness on `status`, so pin the probe:
+ // without the seam it would reach the real loopback CDP endpoint and the
+ // result would depend on whatever is listening on the dev machine.
+ const backend = new ExternalChromeBackend({ call }, fakeLogger(), {
+ isBrowserGone: vi.fn(async () => true),
+ });
const got = await backend.call({ action: 'status' });
- expect(call).toHaveBeenCalledTimes(1);
expect(call.mock.calls[0][0]).toEqual({ action: 'status' });
- expect(got).toEqual({ ...result, data: { ready: true, backend: 'external' } });
+ // Backend identity rides alongside the route report, and the runtime's own
+ // fields survive. The runtime result object itself must not be mutated.
+ expect(got.data).toMatchObject({ ready: true, backend: 'external' });
expect(result.data).toEqual({ ready: true });
});
- it('passes complex requests through unchanged', async () => {
- const call = vi.fn<(req: BrowserControlRequest) => Promise<BrowserControlResult>>(
- async () => ({ ok: true, action: 'act' }),
- );
- const backend = new ExternalChromeBackend({ call }, fakeLogger());
-
+ it('passes ordinary requests through and rejects misplaced proxyServer', async () => {
+ const { backend, initial } = createHarness();
const req: BrowserControlRequest = {
action: 'act',
targetId: 'tab-1',
request: { kind: 'click', ref: 'ref-7' },
};
await backend.call(req);
+ expect(initial.call).toHaveBeenCalledWith(req);
- expect(call.mock.calls[0][0]).toBe(req);
+ // Keep credentials in THIS fixture: the point is that a rejected request
+ // never echoes the caller's secret back, whatever the rejection reason.
+ const invalid = await backend.call({
+ action: 'status',
+ proxyServer: 'http://user:[email protected]:8080',
+ });
+ expect(invalid).toMatchObject({
+ ok: false,
+ errorCode: 'BROWSER_RUNTIME_INVALID_REQUEST',
+ });
+ expect(JSON.stringify(invalid)).not.toContain('secret');
});
- it('dispose() sends a stop and resolves on success', async () => {
- const call = vi.fn<(req: BrowserControlRequest) => Promise<BrowserControlResult>>(
- async () => ({ ok: true, action: 'stop' }),
+ it('starts direct explicitly and safely restarts an unknown inherited process', async () => {
+ const { backend, initial, created, closeAdoptedBrowser } = createHarness(true);
+ const status = await backend.call({ action: 'status' });
+ expect(status.data).toMatchObject({ proxy: { mode: 'unknown' } });
+
+ const started = await backend.call({ action: 'start' });
+ expect(initial.call.mock.calls.map(([req]) => req.action)).toEqual(['status', 'status']);
+ expect(closeAdoptedBrowser).toHaveBeenCalledWith(
+ 'http://127.0.0.1:18800',
+ '/managed/browser/Cindy/user-data',
);
- const logger = fakeLogger();
- const backend = new ExternalChromeBackend({ call }, logger);
+ expect(created).toHaveLength(1);
+ expect(created[0].route).toEqual({ mode: 'direct' });
+ expect(started.data).toMatchObject({ proxy: { mode: 'direct' } });
+ });
+
+ it('closes an inherited process when status cannot establish whether it is running', async () => {
+ const initial = {
+ call: vi.fn(async (req: BrowserControlRequest): Promise<BrowserControlResult> => ({
+ ok: false,
+ action: req.action,
+ errorCode: 'BROWSER_RUNTIME_UNAVAILABLE',
+ })),
+ };
+ const closeAdoptedBrowser = vi.fn(async () => true);
+ const backend = new ExternalChromeBackend(initial, fakeLogger(), {
+ createRuntime: () => fakeRuntime(),
+ closeAdoptedBrowser,
+ isBrowserGone: vi.fn(async () => true),
+ managedUserDataDir: '/managed/browser/Cindy/user-data',
+ });
+ const started = await backend.call({ action: 'start' });
+
+ expect(started.ok).toBe(true);
+ expect(closeAdoptedBrowser).toHaveBeenCalled();
+ });
+
+ it('keeps repeated same-proxy starts idempotent', async () => {
+ const { backend, created } = createHarness();
+ await backend.call({ action: 'start', proxyServer: 'http://proxy-a.test:8080' });
+ await backend.call({ action: 'start', proxyServer: 'http://proxy-a.test:8080' });
+ expect(created).toHaveLength(1);
+ expect(created[0].runtime.call.mock.calls.map(([req]) => req.action)).toEqual(['start', 'status']);
+ });
+
+ it('keeps an active proxy route while status and focus raise the existing browser', async () => {
+ const { backend, created } = createHarness();
+ await backend.call({ action: 'start', proxyServer: 'http://proxy-a.test:8080' });
+
+ await backend.call({ action: 'status' });
+ await backend.call({ action: 'tabs' });
+ await backend.call({ action: 'focus', targetId: 'page-1' });
+
+ expect(created).toHaveLength(1);
+ expect(backend.getEffectiveProxy()).toEqual({
+ mode: 'proxied',
+ server: 'http://proxy-a.test:8080',
+ });
+ expect(created[0].runtime.call.mock.calls.map(([req]) => req.action)).toEqual([
+ 'start',
+ 'status',
+ 'tabs',
+ 'focus',
+ ]);
+ });
+
+ it('restarts on direct → proxy A → proxy B → direct transitions', async () => {
+ const { backend, created } = createHarness();
+ await backend.call({ action: 'start' });
+ await backend.call({ action: 'start', proxyServer: 'http://proxy-a.test:8080' });
+ await backend.call({ action: 'start', proxyServer: 'https://proxy-b.test:8443' });
+ const direct = await backend.call({ action: 'start' });
+
+ expect(created.map(({ route }) => route)).toEqual([
+ { mode: 'direct' },
+ { mode: 'proxied', server: 'http://proxy-a.test:8080' },
+ { mode: 'proxied', server: 'https://proxy-b.test:8443' },
+ { mode: 'direct' },
+ ]);
+ expect(created.slice(0, -1).every(({ runtime }) =>
+ runtime.call.mock.calls.some(([req]) => req.action === 'stop'))).toBe(true);
+ expect(direct.data).toMatchObject({ proxy: { mode: 'direct' } });
+ });
+
+ it('replaces a stopped proxy runtime with direct config before an implicit launch', async () => {
+ const { backend, created } = createHarness();
+ await backend.call({ action: 'start', proxyServer: 'http://proxy-a.test:8080' });
+
+ await backend.call({ action: 'stop' });
+ await backend.call({ action: 'tabs' });
+
+ expect(created.map(({ route }) => route)).toEqual([
+ { mode: 'proxied', server: 'http://proxy-a.test:8080' },
+ { mode: 'direct' },
+ ]);
+ expect(created[0].runtime.call.mock.calls.map(([request]) => request.action)).toEqual(['start', 'stop', 'status']);
+ expect(created[1].runtime.call).toHaveBeenCalledWith({ action: 'tabs' });
+ });
+
+ it('rejects an authenticated proxy URL without launching anything', async () => {
+ // Authenticated proxies are unsupported: the only credential channel that
+ // works over connectOverCDP also leaks to untrusted origins. The rejection
+ // must happen before any browser is created.
+ const { backend, created, auth } = createHarness();
+ const result = await backend.call({
+ action: 'start',
+ proxyServer: 'http://u%2Fser:p%40ss%[email protected]:8080',
+ });
+
+ expect(result).toMatchObject({
+ ok: false,
+ errorCode: 'BROWSER_RUNTIME_INVALID_REQUEST',
+ });
+ expect(result.message).toMatch(/authenticated proxies are not supported/);
+ expect(created).toHaveLength(0);
+ expect(auth.start).not.toHaveBeenCalled();
+ // The rejection text must not echo the caller's credentials back.
+ const serialized = JSON.stringify(result);
+ expect(serialized).not.toContain('u%2Fser');
+ expect(serialized).not.toContain('p%40ss');
+ });
+
+ it('reports unknown status without forgetting a known proxy route or its auth channel', async () => {
+ const { backend, created, auth } = createHarness();
+ await backend.call({
+ action: 'start',
+ proxyServer: 'http://proxy.test:8080',
+ });
+ created[0].runtime.call.mockImplementationOnce(async () => ({
+ ok: false,
+ action: 'status',
+ errorCode: 'BROWSER_RUNTIME_UNAVAILABLE',
+ }));
+
+ const status = await backend.call({ action: 'status' });
+
+ // An unreadable status does not prove the process exited, so the known
+ // route is retained AND reported — reporting `unknown` here would invite a
+ // caller to treat a live proxied browser as route-less.
+ expect(status.data).toEqual({
+ backend: 'external',
+ proxy: { mode: 'proxied', server: 'http://proxy.test:8080' },
+ });
+ expect(backend.getEffectiveProxy()).toEqual({
+ mode: 'proxied',
+ server: 'http://proxy.test:8080',
+ });
+ expect(auth.dispose).not.toHaveBeenCalled();
+ });
+
+ it('blocks a route after a later proxy-auth target failure', async () => {
+ const { backend, failProxyAuth } = createHarness();
+ await backend.call({
+ action: 'start',
+ proxyServer: 'http://proxy.test:8080',
+ });
+
+ failProxyAuth();
+ const status = await backend.call({ action: 'status' });
+ const tabs = await backend.call({ action: 'tabs' });
+ const restart = await backend.call({ action: 'start' });
+
+ expect(status.data).toEqual({ running: true, backend: 'external', proxy: { mode: 'unknown' } });
+ expect(tabs).toMatchObject({
+ ok: false,
+ errorCode: 'BROWSER_RUNTIME_UNAVAILABLE',
+ });
+ expect(restart).toMatchObject({
+ ok: false,
+ errorCode: 'BROWSER_RUNTIME_UNAVAILABLE',
+ });
+ });
+
+ it('fails closed and stops the new browser when auth setup fails', async () => {
+ const initial = fakeRuntime();
+ const runtime = fakeRuntime();
+ const backend = new ExternalChromeBackend(initial, fakeLogger(), {
+ createRuntime: () => runtime,
+ createProxyAuth: () => ({
+ start: async () => { throw new Error('auth setup failed'); },
+ dispose: async () => {},
+ }),
+ isBrowserGone: vi.fn(async () => true),
+ });
+ const result = await backend.call({
+ action: 'start',
+ proxyServer: 'http://proxy.test:8080',
+ });
+ expect(result.ok).toBe(false);
+ expect(runtime.call.mock.calls.map(([req]) => req.action)).toEqual(['start', 'stop', 'status']);
+ expect(backend.getEffectiveProxy()).toEqual({ mode: 'unknown' });
+ });
+
+ it('fails start when proxy auth reports a target failure during setup', async () => {
+ const runtime = fakeRuntime();
+ const auth = { dispose: vi.fn(async () => {}) };
+ const backend = new ExternalChromeBackend(fakeRuntime(), fakeLogger(), {
+ createRuntime: () => runtime,
+ createProxyAuth: (_route, _logger, onFailure) => ({
+ start: async () => { onFailure(); },
+ dispose: auth.dispose,
+ }),
+ isBrowserGone: vi.fn(async () => true),
+ });
+
+ const result = await backend.call({
+ action: 'start',
+ proxyServer: 'http://proxy.test:8080',
+ });
+
+ expect(result).toMatchObject({
+ ok: false,
+ errorCode: 'BROWSER_RUNTIME_ACTION_FAILED',
+ });
+ expect(runtime.call.mock.calls.map(([request]) => request.action)).toEqual(['start', 'stop', 'status']);
+ expect(auth.dispose).toHaveBeenCalledTimes(1);
+ expect(JSON.stringify(result)).not.toContain('secret');
+ });
+
+ it('keeps a direct start idempotent after an implicit launch by open/tabs', async () => {
+ // `open` launches the browser implicitly, as the real runtime does.
+ let running = false;
+ const initial = {
+ call: vi.fn(async (req: BrowserControlRequest): Promise<BrowserControlResult> => {
+ if (req.action === 'status') {
+ return { ok: true, action: req.action, status: 200, data: { running } };
+ }
+ if (req.action === 'start') {
+ running = true;
+ return { ok: true, action: req.action, status: 200, data: { ok: true } };
+ }
+ if (req.action === 'stop') {
+ const stopped = running;
+ running = false;
+ return { ok: true, action: req.action, status: 200, data: { stopped } };
+ }
+ // Like the real /tabs/open route: launches implicitly and returns a
+ // tab object with NO `running` field, so the backend cannot infer
+ // liveness from this response and must query `status`.
+ running = true;
+ return {
+ ok: true,
+ action: req.action,
+ status: 200,
+ data: { targetId: 'tab-1', url: 'about:blank' },
+ };
+ }),
+ };
+ const created: BrowserProxyRoute[] = [];
+ const closeAdoptedBrowser = vi.fn(async () => true);
+ const backend = new ExternalChromeBackend(initial, fakeLogger(), {
+ createRuntime: (route) => {
+ created.push(route);
+ return fakeRuntime();
+ },
+ closeAdoptedBrowser,
+ isBrowserGone: vi.fn(async () => true),
+ managedUserDataDir: '/managed/browser/Cindy/user-data',
+ });
+
+ // Cold start: no explicit `start` and no prior verified stop — `open`
+ // launches implicitly and must still be attributed to this runtime.
+ const implicit = await backend.call({ action: 'open' });
+ expect(implicit.ok).toBe(true);
+
+ // A same-route direct start must be idempotent: it must NOT adopt-and-close
+ // our own browser, which would destroy the user's tabs.
+ const restart = await backend.call({ action: 'start' });
+
+ expect(restart.ok).toBe(true);
+ expect(closeAdoptedBrowser).not.toHaveBeenCalled();
+ expect(created).toHaveLength(0);
+ expect(initial.call.mock.calls.map(([req]) => req.action)).not.toContain('start');
+ });
+
+ it('keeps a direct start idempotent after a verified stop then implicit launch', async () => {
+ let running = false;
+ const initial = {
+ call: vi.fn(async (req: BrowserControlRequest): Promise<BrowserControlResult> => {
+ if (req.action === 'status') {
+ return { ok: true, action: req.action, status: 200, data: { running } };
+ }
+ if (req.action === 'stop') {
+ const stopped = running;
+ running = false;
+ return { ok: true, action: req.action, status: 200, data: { stopped } };
+ }
+ running = true;
+ return {
+ ok: true,
+ action: req.action,
+ status: 200,
+ data: { targetId: 'tab-1', url: 'about:blank' },
+ };
+ }),
+ };
+ const closeAdoptedBrowser = vi.fn(async () => true);
+ const backend = new ExternalChromeBackend(initial, fakeLogger(), {
+ createRuntime: () => fakeRuntime(),
+ closeAdoptedBrowser,
+ isBrowserGone: vi.fn(async () => true),
+ managedUserDataDir: '/managed/browser/Cindy/user-data',
+ });
+
+ await backend.call({ action: 'start' });
+ await backend.call({ action: 'stop' });
+ await backend.call({ action: 'open' });
+
+ await expect(backend.call({ action: 'start' })).resolves.toMatchObject({ ok: true });
+ expect(closeAdoptedBrowser).not.toHaveBeenCalled();
+ });
+
+ it('attributes an implicit launch even when the action itself fails', async () => {
+ // Like snapshot: resolves (and thereby launches) a tab, then rejects an
+ // invalid argument combination.
+ let running = false;
+ const initial = {
+ call: vi.fn(async (req: BrowserControlRequest): Promise<BrowserControlResult> => {
+ if (req.action === 'status') {
+ return { ok: true, action: req.action, status: 200, data: { running } };
+ }
+ if (req.action === 'stop') {
+ running = false;
+ return { ok: true, action: req.action, status: 200, data: { stopped: true } };
+ }
+ running = true;
+ return {
+ ok: false,
+ action: req.action,
+ status: 400,
+ errorCode: 'BROWSER_RUNTIME_INVALID_REQUEST',
+ message: 'labels/mode=efficient require format=ai',
+ };
+ }),
+ };
+ const created: BrowserProxyRoute[] = [];
+ const closeAdoptedBrowser = vi.fn(async () => true);
+ const backend = new ExternalChromeBackend(initial, fakeLogger(), {
+ createRuntime: (route) => {
+ created.push(route);
+ return fakeRuntime();
+ },
+ closeAdoptedBrowser,
+ isBrowserGone: vi.fn(async () => true),
+ managedUserDataDir: '/managed/browser/Cindy/user-data',
+ });
+
+ await expect(backend.call({ action: 'snapshot' })).resolves.toMatchObject({ ok: false });
+
+ // The failed action still launched our browser, so a same-route start must
+ // stay idempotent rather than closing and relaunching it.
+ await expect(backend.call({ action: 'start' })).resolves.toMatchObject({ ok: true });
+ expect(closeAdoptedBrowser).not.toHaveBeenCalled();
+ expect(created).toHaveLength(0);
+ });
+
+ it('does not drop a proxied route when status reports a merely-unreachable browser', async () => {
+ // The vendored status sets running:cdpReady, so a busy-but-alive Chrome
+ // reports running:false. Treating that as stopped would dispose the proxy
+ // coordinator and swap in a direct runtime under a live proxied browser.
+ let reachable = true;
+ const proxied = {
+ call: vi.fn(async (req: BrowserControlRequest): Promise<BrowserControlResult> => {
+ if (req.action === 'status') {
+ return { ok: true, action: req.action, status: 200, data: { running: reachable } };
+ }
+ return { ok: true, action: req.action, status: 200, data: { ok: true } };
+ }),
+ };
+ const auth = { start: vi.fn(async () => {}), dispose: vi.fn(async () => {}) };
+ const created: BrowserProxyRoute[] = [];
+ // Tracks the real process, unlike the runtime's readiness-based `running`.
+ // Before the launch there is nothing; afterwards the process stays alive
+ // even while it is too busy to answer the readiness probe.
+ let processAlive = false;
+ const isBrowserGone = vi.fn(async () => !processAlive);
+ // A passive poll must never reach the destructive ownership check.
+ const closeAdoptedBrowser = vi.fn(async () => false);
+ const backend = new ExternalChromeBackend(fakeRuntime(), fakeLogger(), {
+ createRuntime: (route) => {
+ created.push(route);
+ return proxied;
+ },
+ createProxyAuth: () => auth,
+ isBrowserGone,
+ closeAdoptedBrowser,
+ managedUserDataDir: '/managed/browser/Cindy/user-data',
+ });
+
+ await backend.call({
+ action: 'start',
+ proxyServer: 'http://proxy.test:8080',
+ proxyAllowedHostnames: ['allowed.example'],
+ });
+ expect(created.map((route) => route.mode)).toEqual(['proxied']);
+ processAlive = true;
+
+ // The proxied Chrome is alive but too busy to answer the readiness probe,
+ // so the vendored status reports running:false.
+ reachable = false;
+ const status = await backend.call({ action: 'status' });
+
+ // The proxied route is retained and the coordinator kept; traffic is
+ // refused rather than silently switched to direct egress.
+ expect(status.data).toMatchObject({ proxy: { mode: 'proxied' } });
+ expect(auth.dispose).not.toHaveBeenCalled();
+ expect(created.map((route) => route.mode)).toEqual(['proxied']);
+ // The decisive property: a status poll checks liveness without ever
+ // issuing the Browser.close that ownership verification uses, so polling
+ // can never terminate the user's browser and discard their tabs.
+ expect(isBrowserGone).toHaveBeenCalled();
+ expect(closeAdoptedBrowser).not.toHaveBeenCalled();
+ await expect(backend.call({ action: 'tabs' })).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'BROWSER_RUNTIME_UNAVAILABLE',
+ });
+ });
+
+ it('clears a transient readiness block once the browser answers again', async () => {
+ // A busy Chrome misses the readiness probe, then recovers. The block that
+ // guarded the route while liveness was unproven must lift — otherwise every
+ // action but status/stop stays unavailable forever.
+ let reachable = true;
+ let launched = false;
+ const runtime = {
+ call: vi.fn(async (req: BrowserControlRequest): Promise<BrowserControlResult> => {
+ if (req.action === 'status') {
+ return { ok: true, action: req.action, status: 200, data: { running: reachable } };
+ }
+ if (req.action === 'start') launched = true;
+ return { ok: true, action: req.action, status: 200, data: { ok: true } };
+ }),
+ };
+ const backend = new ExternalChromeBackend(fakeRuntime(), fakeLogger(), {
+ createRuntime: () => runtime,
+ createProxyAuth: () => ({ start: vi.fn(async () => {}), dispose: vi.fn(async () => {}) }),
+ // The initial (pre-start) browser is genuinely absent, so `start` can
+ // proceed; only AFTER the proxied launch does the probe report the
+ // process as alive-but-unreadable.
+ isBrowserGone: vi.fn(async () => !launched),
+ closeAdoptedBrowser: vi.fn(async () => false),
+ managedUserDataDir: '/managed/browser/Cindy/user-data',
+ });
+ await backend.call({
+ action: 'start',
+ proxyServer: 'http://proxy.test:8080',
+ proxyAllowedHostnames: ['allowed.example'],
+ });
+
+ reachable = false;
+ await backend.call({ action: 'status' });
+ await expect(backend.call({ action: 'tabs' })).resolves.toMatchObject({ ok: false });
+
+ reachable = true;
+ await backend.call({ action: 'status' });
+
+ await expect(backend.call({ action: 'tabs' })).resolves.toMatchObject({ ok: true });
+ expect(backend.getEffectiveProxy()).toEqual({
+ mode: 'proxied',
+ server: 'http://proxy.test:8080',
+ });
+ });
+
+ it('keeps an auth-failure block even after the browser answers again', async () => {
+ // Distinct from the transient case: an auth failure means the route itself
+ // is untrusted, so recovery of the readiness probe must NOT lift it.
+ const { backend, failProxyAuth } = createHarness();
+ await backend.call({ action: 'start', proxyServer: 'http://proxy.test:8080' });
+
+ failProxyAuth();
+ await backend.call({ action: 'status' }); // browser answers: running
+ await expect(backend.call({ action: 'tabs' })).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'BROWSER_RUNTIME_UNAVAILABLE',
+ });
+ });
+
+ it('admits a same-route start through a transient readiness block', async () => {
+ // Settings' "open the agent browser" calls `start` after seeing
+ // `running: false`. A block that only means "the readiness probe missed"
+ // must not turn that into an error telling the user to stop a browser that
+ // is actually healthy — `startInRoute` has its own same-route liveness
+ // check. Ordinary traffic stays refused until the block lifts.
+ let reachable = true;
+ let launched = false;
+ const runtime = {
+ call: vi.fn(async (req: BrowserControlRequest): Promise<BrowserControlResult> => {
+ if (req.action === 'status') {
+ return { ok: true, action: req.action, status: 200, data: { running: reachable } };
+ }
+ if (req.action === 'start') launched = true;
+ return { ok: true, action: req.action, status: 200, data: { ok: true } };
+ }),
+ };
+ const backend = new ExternalChromeBackend(fakeRuntime(), fakeLogger(), {
+ createRuntime: () => runtime,
+ createProxyAuth: () => ({ start: vi.fn(async () => {}), dispose: vi.fn(async () => {}) }),
+ isBrowserGone: vi.fn(async () => !launched),
+ closeAdoptedBrowser: vi.fn(async () => false),
+ managedUserDataDir: '/managed/browser/Cindy/user-data',
+ });
+ await backend.call({ action: 'start', proxyServer: 'http://proxy.test:8080' });
+
+ reachable = false;
+ await backend.call({ action: 'status' }); // transient block
+ await expect(backend.call({ action: 'tabs' })).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'BROWSER_RUNTIME_UNAVAILABLE',
+ });
+
+ await expect(backend.call({ action: 'start', proxyServer: 'http://proxy.test:8080' }))
+ .resolves.toMatchObject({ ok: true });
+ // The confirmed-alive start also lifts the transient block, so ordinary
+ // traffic recovers without waiting for another status poll.
+ await expect(backend.call({ action: 'tabs' })).resolves.toMatchObject({ ok: true });
+ });
+
+ it('refuses a hard-blocked same-route start', async () => {
+ // The counterpart: an auth failure means the route itself is untrusted, so
+ // `start` must NOT be admitted the way a transient block admits it.
+ const { backend, failProxyAuth } = createHarness();
+ await backend.call({ action: 'start', proxyServer: 'http://proxy.test:8080' });
+
+ failProxyAuth();
+
+ await expect(backend.call({ action: 'start', proxyServer: 'http://proxy.test:8080' }))
+ .resolves.toMatchObject({ ok: false, errorCode: 'BROWSER_RUNTIME_UNAVAILABLE' });
+ });
+
+ it('fails closed when the route is blocked while a call is in flight', async () => {
+ // The auth coordinator's teardown runs detached from this queue, so a call
+ // that already passed the admission guard can be awaiting the runtime when
+ // the route becomes untrusted — and the vendored availability path may have
+ // launched a replacement Chrome with no request gate. Returning that data
+ // would hand back a page from a browser we can no longer vouch for.
+ let failNow = () => {};
+ const runtime = {
+ call: vi.fn(async (req: BrowserControlRequest): Promise<BrowserControlResult> => {
+ if (req.action === 'status') {
+ return { ok: true, action: req.action, status: 200, data: { running: true } };
+ }
+ if (req.action === 'tabs') {
+ // The coordinator dies while this call is awaiting the runtime.
+ failNow();
+ return { ok: true, action: req.action, status: 200, data: { tabs: ['leaked'] } };
+ }
+ return { ok: true, action: req.action, status: 200, data: { ok: true } };
+ }),
+ };
+ const backend = new ExternalChromeBackend(fakeRuntime(), fakeLogger(), {
+ createRuntime: () => runtime,
+ createProxyAuth: (_route, _logger, onFailure) => {
+ failNow = onFailure;
+ return { start: vi.fn(async () => {}), dispose: vi.fn(async () => {}) };
+ },
+ isBrowserGone: vi.fn(async () => false),
+ closeAdoptedBrowser: vi.fn(async () => false),
+ managedUserDataDir: '/managed/browser/Cindy/user-data',
+ });
+ await backend.call({ action: 'start', proxyServer: 'http://proxy.test:8080' });
+
+ const tabs = await backend.call({ action: 'tabs' });
+
+ expect(tabs).toMatchObject({ ok: false, errorCode: 'BROWSER_RUNTIME_UNAVAILABLE' });
+ expect(JSON.stringify(tabs)).not.toContain('leaked');
+ });
+
+ it('keeps an auth-failure block across an unproven status poll', async () => {
+ // The dangerous ordering, which "answers again" alone does not cover: a
+ // hard block, then a poll that finds the process alive but unreadable,
+ // then a poll that finds it running. If the middle poll marked the block
+ // transient, the last one would clear it and re-admit ordinary traffic on
+ // a browser whose CDP request gate died with the auth coordinator. The
+ // availability card polls status on its own, so this needs no user action.
+ let reachable = true;
+ const { backend, created, failProxyAuth, isBrowserGone } = createHarness();
+ await backend.call({ action: 'start', proxyServer: 'http://proxy.test:8080' });
+ // After the launch the process is alive, so a missed readiness probe reads
+ // as `unproven` rather than `gone`.
+ isBrowserGone.mockImplementation(async () => false);
+ const runtimeCall = created[created.length - 1]?.runtime.call;
+ if (!runtimeCall) throw new Error('proxied runtime was not created');
+ runtimeCall.mockImplementation(async (req: BrowserControlRequest) => ({
+ ok: true,
+ action: req.action,
+ status: 200,
+ data: req.action === 'status' ? { running: reachable } : { ok: true },
+ }));
+
+ failProxyAuth();
+ reachable = false;
+ await backend.call({ action: 'status' }); // unproven
+ reachable = true;
+ await backend.call({ action: 'status' }); // running again
+
+ await expect(backend.call({ action: 'tabs' })).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'BROWSER_RUNTIME_UNAVAILABLE',
+ });
+ });
+
+ it('recovers an adopted managed browser on stop instead of blocking forever', async () => {
+ // An adopted process: vendored stop reports ok but never actually stops it,
+ // because its ownership state is in-memory and empty after a Cindy restart.
+ const runtime = {
+ call: vi.fn(async (req: BrowserControlRequest): Promise<BrowserControlResult> => {
+ if (req.action === 'stop') {
+ return { ok: true, action: req.action, status: 200, data: { stopped: false } };
+ }
+ return { ok: true, action: req.action, status: 200, data: { running: true } };
+ }),
+ };
+ const closeAdoptedBrowser = vi.fn(async () => true);
+ const backend = new ExternalChromeBackend(runtime, fakeLogger(), {
+ createRuntime: () => fakeRuntime(),
+ closeAdoptedBrowser,
+ isBrowserGone: vi.fn(async () => true),
+ managedUserDataDir: '/managed/browser/Cindy/user-data',
+ });
+
+ const stopped = await backend.call({ action: 'stop' });
+
+ expect(stopped.ok).toBe(true);
+ // The vendored result said stopped:false; the adopted cleanup is what
+ // proved the exit, so the caller must be told what was actually verified
+ // rather than being left to retry a completed stop.
+ expect(stopped.data).toMatchObject({ stopped: true });
+ expect(closeAdoptedBrowser).toHaveBeenCalledTimes(1);
+ // The backend must be usable again, not stuck blocked until the user
+ // closes Chrome by hand.
+ await expect(backend.call({ action: 'tabs' })).resolves.toMatchObject({ ok: true });
+ });
+
+ it('stays blocked when an adopted browser cannot be verified closed', async () => {
+ const runtime = {
+ call: vi.fn(async (req: BrowserControlRequest): Promise<BrowserControlResult> => {
+ if (req.action === 'stop') {
+ return { ok: true, action: req.action, status: 200, data: { stopped: false } };
+ }
+ return { ok: true, action: req.action, status: 200, data: { running: true } };
+ }),
+ };
+ const backend = new ExternalChromeBackend(runtime, fakeLogger(), {
+ createRuntime: () => fakeRuntime(),
+ closeAdoptedBrowser: vi.fn(async () => false),
+ managedUserDataDir: '/managed/browser/Cindy/user-data',
+ isBrowserGone: vi.fn(async () => true),
+ });
+
+ await expect(backend.call({ action: 'stop' })).resolves.toMatchObject({ ok: false });
+ await expect(backend.call({ action: 'tabs' })).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'BROWSER_RUNTIME_UNAVAILABLE',
+ });
+ });
+
+ it('installs the lifetime guard for credential-free proxied launches too', async () => {
+ const auth = { start: vi.fn(async () => {}), dispose: vi.fn(async () => {}) };
+ const routes: BrowserProxyRoute[] = [];
+ const backend = new ExternalChromeBackend(fakeRuntime(), fakeLogger(), {
+ createRuntime: () => fakeRuntime(),
+ createProxyAuth: (route) => {
+ routes.push(route);
+ return auth;
+ },
+ isBrowserGone: vi.fn(async () => true),
+ });
+
+ await backend.call({
+ action: 'start',
+ proxyServer: 'http://proxy.test:8080',
+ proxyAllowedHostnames: ['allowed.example'],
+ });
+
+ expect(auth.start).toHaveBeenCalledTimes(1);
+ expect(routes[0]).toMatchObject({
+ mode: 'proxied',
+ allowedHostnames: ['allowed.example'],
+ });
+ expect(routes[0]?.username).toBeUndefined();
+
+ // Direct launches must not install the guard.
+ await backend.call({ action: 'start' });
+ expect(auth.start).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not report a stop as done when readiness lies about an inherited process', async () => {
+ // The reviewer's exact scenario: vendored stop returns stopped:false for an
+ // inherited process, and the readiness probe then says running:false only
+ // because the browser is busy. Treating that as a clean stop would release
+ // the proxy guard and reset to direct while the old process keeps serving
+ // the old route.
+ const runtime = {
+ call: vi.fn(async (req: BrowserControlRequest): Promise<BrowserControlResult> => {
+ if (req.action === 'stop') {
+ return { ok: true, action: req.action, status: 200, data: { stopped: false } };
+ }
+ // Busy browser: readiness reports NOT running though it is alive.
+ return { ok: true, action: req.action, status: 200, data: { running: false } };
+ }),
+ };
+ const auth = { start: vi.fn(async () => {}), dispose: vi.fn(async () => {}) };
+ const created: BrowserProxyRoute[] = [];
+ let launched = false;
+ const backend = new ExternalChromeBackend(fakeRuntime(), fakeLogger(), {
+ createRuntime: (route) => { created.push(route); launched = true; return runtime; },
+ createProxyAuth: () => auth,
+ isBrowserGone: vi.fn(async () => !launched), // alive after launch
+ closeAdoptedBrowser: vi.fn(async () => false),
+ managedUserDataDir: '/managed/browser/Cindy/user-data',
+ });
+ await backend.call({
+ action: 'start',
+ proxyServer: 'http://proxy.test:8080',
+ proxyAllowedHostnames: ['allowed.example'],
+ });
+
+ const stopped = await backend.call({ action: 'stop' });
+
+ expect(stopped).toMatchObject({ ok: false, errorCode: 'BROWSER_RUNTIME_ACTION_FAILED' });
+ expect(stopped.data).not.toMatchObject({ stopped: true });
+ // The proxy guard must NOT be released and no direct runtime substituted
+ // while the proxied process may still be alive.
+ expect(auth.dispose).not.toHaveBeenCalled();
+ expect(created.map((r) => r.mode)).toEqual(['proxied']);
+ });
+
+ it('does not restart a same-route browser that is merely busy', async () => {
+ // `running` is READINESS. A busy-but-alive browser reports false, and
+ // treating that as "not running" takes an unchanged route through
+ // stopCurrentRuntime() and a relaunch — destroying the user's open tabs to
+ // apply a route that is already in effect.
+ let busy = false;
+ const runtime = {
+ call: vi.fn(async (req: BrowserControlRequest): Promise<BrowserControlResult> => {
+ if (req.action === 'status') {
+ return { ok: true, action: req.action, status: 200, data: { running: !busy } };
+ }
+ return { ok: true, action: req.action, status: 200, data: { ok: true } };
+ }),
+ };
+ const created: BrowserProxyRoute[] = [];
+ const backend = new ExternalChromeBackend(fakeRuntime(), fakeLogger(), {
+ createRuntime: (route) => { created.push(route); return runtime; },
+ createProxyAuth: () => ({ start: vi.fn(async () => {}), dispose: vi.fn(async () => {}) }),
+ // Gone before the first start (so it launches), alive after.
+ isBrowserGone: vi.fn(async () => created.length === 0),
+ closeAdoptedBrowser: vi.fn(async () => true),
+ managedUserDataDir: '/managed/browser/Cindy/user-data',
+ });
+ const start = {
+ action: 'start' as const,
+ proxyServer: 'http://proxy.test:8080',
+ proxyAllowedHostnames: ['allowed.example'],
+ };
+ await backend.call(start);
+ expect(created).toHaveLength(1);
+
+ // Now the browser is alive but too busy to answer the readiness probe.
+ busy = true;
+ const again = await backend.call(start);
+
+ expect(again.ok).toBe(true);
+ // No relaunch: the user's tabs survive.
+ expect(created).toHaveLength(1);
+ expect(runtime.call.mock.calls.some(([req]) => req.action === 'stop')).toBe(false);
+ });
+
+ it('signals an inherited browser as proxy.mode unknown so callers can recover it', async () => {
+ // Contract openBrowserForLogin depends on: after a Cindy restart that
+ // inherited a running Chrome, `status` reports mode 'unknown' AND ordinary
+ // actions are refused. A caller that skips `start` on `running: true` would
+ // therefore return success while the window never comes forward, so the
+ // 'unknown' mode is what tells it an explicit start is still required.
+ const runtime = {
+ call: vi.fn(async (req: BrowserControlRequest): Promise<BrowserControlResult> => ({
+ ok: true,
+ action: req.action,
+ status: 200,
+ data: req.action === 'status' ? { running: true } : { ok: true },
+ })),
+ };
+ const backend = new ExternalChromeBackend(runtime, fakeLogger(), {
+ createRuntime: () => runtime,
+ isBrowserGone: vi.fn(async () => false), // alive, route unknown
+ closeAdoptedBrowser: vi.fn(async () => true),
+ managedUserDataDir: '/managed/browser/Cindy/user-data',
+ });
+
+ const status = await backend.call({ action: 'status' });
+
+ expect((status.data as { proxy?: { mode?: string } }).proxy?.mode).toBe('unknown');
+ expect(await backend.call({ action: 'tabs' })).toMatchObject({ ok: false });
+ });
+
+ it('refuses ordinary actions while a live browser has an unknown route', async () => {
+ // Cindy restarted and inherited a Chrome from a previous proxied start:
+ // route is unknown, the process is alive. Running the action anyway would
+ // attach to it, egress through the OLD proxy while this backend reports
+ // direct, and the previous instance's request gate is gone. Only
+ // status/start/stop may proceed.
+ const initial = {
+ call: vi.fn(async (req: BrowserControlRequest): Promise<BrowserControlResult> => ({
+ ok: true,
+ action: req.action,
+ status: 200,
+ data: req.action === 'status' ? { running: true } : { ok: true },
+ })),
+ };
+ const backend = new ExternalChromeBackend(initial, fakeLogger(), {
+ createRuntime: () => fakeRuntime(),
+ isBrowserGone: vi.fn(async () => false), // alive
+ closeAdoptedBrowser: vi.fn(async () => true),
+ managedUserDataDir: '/managed/browser/Cindy/user-data',
+ });
+
+ const navigated = await backend.call({ action: 'open', url: 'https://example.test/' } as BrowserControlRequest);
+
+ expect(navigated).toMatchObject({ ok: false, errorCode: 'BROWSER_RUNTIME_UNAVAILABLE' });
+ // The action must never have been forwarded to the inherited process.
+ expect(initial.call.mock.calls.map(([req]) => req.action)).not.toContain('open');
+ // status stays available so the caller can see the state and recover.
+ expect((await backend.call({ action: 'status' })).ok).toBe(true);
+ });
+
+ it('disposes a browser launched by an action that then failed', async () => {
+ // An action can start Chrome and then fail without a numeric status, which
+ // is what `used` is normally set from. If the follow-up probe establishes a
+ // running browser, that IS proof we own one — otherwise dispose() takes its
+ // `if (!this.used) return` path and leaves a headed Chrome after quit.
+ let running = false;
+ const runtime = {
+ call: vi.fn(async (req: BrowserControlRequest): Promise<BrowserControlResult> => {
+ if (req.action === 'status') {
+ return { ok: true, action: req.action, status: 200, data: { running } };
+ }
+ if (req.action === 'stop') {
+ running = false;
+ return { ok: true, action: req.action, status: 200, data: { stopped: true } };
+ }
+ // Launches Chrome, then fails — and returns NO numeric status.
+ running = true;
+ return { ok: false, action: req.action, errorCode: 'BROWSER_RUNTIME_ACTION_FAILED' };
+ }),
+ };
+ const backend = new ExternalChromeBackend(runtime, fakeLogger(), {
+ createRuntime: () => runtime,
+ isBrowserGone: vi.fn(async () => !running),
+ closeAdoptedBrowser: vi.fn(async () => true),
+ managedUserDataDir: '/managed/browser/Cindy/user-data',
+ });
+
+ await backend.call({ action: 'open', url: 'https://example.test/' } as BrowserControlRequest);
await backend.dispose();
- expect(call).toHaveBeenCalledTimes(1);
- expect(call.mock.calls[0][0]).toEqual({ action: 'stop' });
- expect(logger.warn).not.toHaveBeenCalled();
+ expect(runtime.call.mock.calls.some(([req]) => req.action === 'stop')).toBe(true);
+ });
+
+ it('refuses a same-route start while the route is blocked, and recovers via stop', async () => {
+ // A block from a failed auth channel is not cleared by the browser
+ // answering again: the request gate is gone. `start` is refused outright
+ // (its message tells the user to stop first), so the shortcut below never
+ // hands back success for a route whose gate no longer exists.
+ const { backend, failProxyAuth, created } = createHarness();
+ await backend.call({
+ action: 'start',
+ proxyServer: 'http://proxy.test:8080',
+ proxyAllowedHostnames: ['allowed.example'],
+ });
+ failProxyAuth();
+
+ const blocked = await backend.call({
+ action: 'start',
+ proxyServer: 'http://proxy.test:8080',
+ proxyAllowedHostnames: ['allowed.example'],
+ });
+ expect(blocked).toMatchObject({ ok: false, errorCode: 'BROWSER_RUNTIME_UNAVAILABLE' });
+ expect(created).toHaveLength(1); // no silent reuse of the blocked route
+
+ // The documented recovery works and restores ordinary traffic.
+ expect((await backend.call({ action: 'stop' })).ok).toBe(true);
+ const restarted = await backend.call({
+ action: 'start',
+ proxyServer: 'http://proxy.test:8080',
+ proxyAllowedHostnames: ['allowed.example'],
+ });
+ expect(restarted.ok).toBe(true);
+ expect((await backend.call({ action: 'tabs' })).ok).toBe(true);
+ });
+
+ it('tears the browser down when the runtime reports containment failed', async () => {
+ // The runtime validates and quarantines pages but cannot end a process.
+ // When it reports that containment failed and unvalidated pages may still
+ // be live, blocking future calls is not enough — those pages are already
+ // loaded and keep reaching the network. The host owns teardown, so it must
+ // actually stop the browser.
+ const { backend, created, auth } = createHarness();
+ await backend.call({
+ action: 'start',
+ proxyServer: 'http://proxy.test:8080',
+ proxyAllowedHostnames: ['allowed.example'],
+ });
+ const runtime = created[0].runtime;
+ runtime.call.mockResolvedValueOnce({
+ ok: false,
+ action: 'act',
+ errorCode: 'BROWSER_RUNTIME_ACTION_FAILED',
+ message: 'Navigation blocked: popup chain exceeded the validation budget and the browser '
+ + 'could not be torn down; unvalidated pages may still be live',
+ });
+
+ await backend.call({
+ action: 'act',
+ targetId: 't',
+ request: { kind: 'click', ref: 'e1' },
+ } as BrowserControlRequest);
+
+ // The surviving pages are gone because the process is.
+ expect(runtime.call.mock.calls.some(([req]) => req.action === 'stop')).toBe(true);
+ // The proxy guard is released only because the browser it guarded is gone.
+ expect(auth.dispose).toHaveBeenCalled();
+ expect(backend.getEffectiveProxy()).toEqual({ mode: 'unknown' });
+ });
+
+ it('keeps the route blocked when that teardown cannot be verified', async () => {
+ // If the stop cannot be verified, the pages may still be live — so the
+ // route must stay unusable rather than quietly recovering.
+ const { backend, created, isBrowserGone } = createHarness();
+ await backend.call({
+ action: 'start',
+ proxyServer: 'http://proxy.test:8080',
+ proxyAllowedHostnames: ['allowed.example'],
+ });
+ const runtime = created[0].runtime;
+ isBrowserGone.mockResolvedValue(false); // never verifiably gone
+ runtime.call.mockResolvedValueOnce({
+ ok: false,
+ action: 'act',
+ errorCode: 'BROWSER_RUNTIME_ACTION_FAILED',
+ message: 'Navigation blocked: popup chain exceeded the validation budget and the browser '
+ + 'could not be torn down; unvalidated pages may still be live',
+ });
+ runtime.call.mockResolvedValueOnce({
+ ok: true, action: 'stop', status: 200, data: { stopped: false },
+ });
+
+ await backend.call({
+ action: 'act',
+ targetId: 't',
+ request: { kind: 'click', ref: 'e1' },
+ } as BrowserControlRequest);
+
+ expect(await backend.call({ action: 'tabs' })).toMatchObject({
+ ok: false,
+ errorCode: 'BROWSER_RUNTIME_UNAVAILABLE',
+ });
+ // A status poll finding it alive must not clear this: containment failed
+ // regardless of whether the process is healthy.
+ await backend.call({ action: 'status' });
+ expect(await backend.call({ action: 'tabs' })).toMatchObject({
+ ok: false,
+ errorCode: 'BROWSER_RUNTIME_UNAVAILABLE',
+ });
+ });
+
+ it('does not trust a successful vendored stop as proof the process exited', async () => {
+ // stopOpenClawChrome breaks its wait as soon as proc.killed is set (SIGTERM
+ // does that synchronously), SIGKILLs, and returns without awaiting exit;
+ // stopRunningBrowser then reports stopped:true regardless. So stopped:true
+ // means "signals sent", not "process gone" — releasing the proxy guard on
+ // it would let a survivor keep serving the old route under a new launch.
+ const runtime = {
+ call: vi.fn(async (req: BrowserControlRequest): Promise<BrowserControlResult> => {
+ if (req.action === 'stop') {
+ return { ok: true, action: req.action, status: 200, data: { stopped: true } };
+ }
+ return { ok: true, action: req.action, status: 200, data: { running: false } };
+ }),
+ };
+ const auth = { start: vi.fn(async () => {}), dispose: vi.fn(async () => {}) };
+ const created: BrowserProxyRoute[] = [];
+ let launched = false;
+ const backend = new ExternalChromeBackend(fakeRuntime(), fakeLogger(), {
+ createRuntime: (route) => { created.push(route); launched = true; return runtime; },
+ createProxyAuth: () => auth,
+ isBrowserGone: vi.fn(async () => !launched), // still alive after launch
+ closeAdoptedBrowser: vi.fn(async () => false),
+ managedUserDataDir: '/managed/browser/Cindy/user-data',
+ });
+ await backend.call({
+ action: 'start',
+ proxyServer: 'http://proxy.test:8080',
+ proxyAllowedHostnames: ['allowed.example'],
+ });
+
+ const stopped = await backend.call({ action: 'stop' });
+
+ expect(stopped).toMatchObject({ ok: false, errorCode: 'BROWSER_RUNTIME_ACTION_FAILED' });
+ expect(stopped.data).not.toMatchObject({ stopped: true });
+ expect(auth.dispose).not.toHaveBeenCalled();
+ expect(created.map((r) => r.mode)).toEqual(['proxied']);
+ });
+
+ it('blocks traffic when a stop cannot be verified', async () => {
+ const runtime = {
+ call: vi.fn(async (req: BrowserControlRequest): Promise<BrowserControlResult> => {
+ if (req.action === 'start') return { ok: true, action: req.action, status: 200 };
+ if (req.action === 'stop') {
+ return { ok: true, action: req.action, status: 200, data: { stopped: false } };
+ }
+ if (req.action === 'status') {
+ return { ok: false, action: req.action, errorCode: 'BROWSER_RUNTIME_UNAVAILABLE' };
+ }
+ return { ok: true, action: req.action, status: 200 };
+ }),
+ };
+ const backend = new ExternalChromeBackend(fakeRuntime(), fakeLogger(), {
+ createRuntime: () => runtime,
+ createProxyAuth: () => ({ start: vi.fn(async () => {}), dispose: vi.fn(async () => {}) }),
+ // The point of this test: the stop cannot be VERIFIED. The process is
+ // still reachable, so absence is never established and the route must
+ // stay blocked rather than being reported as cleanly stopped.
+ isBrowserGone: vi.fn(async () => false),
+ });
+ await backend.call({ action: 'start', proxyServer: 'http://proxy.test:8080' });
+
+ const stopped = await backend.call({ action: 'stop' });
+ const tabs = await backend.call({ action: 'tabs' });
+
+ expect(stopped).toMatchObject({
+ ok: false,
+ errorCode: 'BROWSER_RUNTIME_ACTION_FAILED',
+ // This runtime fails `status`, so the start never committed a route and
+ // the reported mode is `unknown`. What matters here is that the stop is
+ // refused and traffic stays blocked — asserted below.
+ data: { proxy: { mode: 'unknown' } },
+ });
+ expect(tabs).toMatchObject({
+ ok: false,
+ errorCode: 'BROWSER_RUNTIME_UNAVAILABLE',
+ });
+ });
+
+ it('replaces the proxied runtime with direct config after a failed start whose cleanup stop was unverified', async () => {
+ let stopVerifiable = false;
+ const proxiedRuntime = {
+ call: vi.fn(async (req: BrowserControlRequest): Promise<BrowserControlResult> => {
+ if (req.action === 'start') return { ok: true, action: req.action, status: 200 };
+ if (req.action === 'stop') {
+ return { ok: true, action: req.action, status: 200, data: { stopped: stopVerifiable } };
+ }
+ if (req.action === 'status') {
+ return { ok: true, action: req.action, status: 200, data: { running: !stopVerifiable } };
+ }
+ return { ok: true, action: req.action, status: 200 };
+ }),
+ };
+ const created: Array<{ route: BrowserProxyRoute; runtime: ReturnType<typeof fakeRuntime> | typeof proxiedRuntime }> = [];
+ const backend = new ExternalChromeBackend(fakeRuntime(), fakeLogger(), {
+ createRuntime: (route) => {
+ const runtime = route.mode === 'proxied' ? proxiedRuntime : fakeRuntime();
+ created.push({ route, runtime });
+ return runtime;
+ },
+ createProxyAuth: () => ({
+ start: async () => { throw new Error('auth setup failed'); },
+ dispose: async () => {},
+ }),
+ isBrowserGone: vi.fn(async () => true),
+ });
+
+ const failedStart = await backend.call({
+ action: 'start',
+ proxyServer: 'http://proxy.test:8080',
+ });
+ expect(failedStart.ok).toBe(false);
+ await expect(backend.call({ action: 'tabs' })).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'BROWSER_RUNTIME_UNAVAILABLE',
+ });
+
+ stopVerifiable = true;
+ const stopped = await backend.call({ action: 'stop' });
+ expect(stopped.ok).toBe(true);
+
+ // The verified stop must retire the still-proxied runtime; implicit
+ // launches afterwards must run through a fresh direct runtime.
+ expect(created.map(({ route }) => route.mode)).toEqual(['proxied', 'direct']);
+ const directRuntime = created[1].runtime;
+ const tabs = await backend.call({ action: 'tabs' });
+ expect(tabs.ok).toBe(true);
+ expect(directRuntime.call.mock.calls.map(([req]) => req.action)).toContain('tabs');
+ expect(proxiedRuntime.call.mock.calls.map(([req]) => req.action)).not.toContain('tabs');
+ });
+
+ it('serializes concurrent lifecycle calls', async () => {
+ const events: string[] = [];
+ let releaseStart: (() => void) | undefined;
+ const initial = fakeRuntime();
+ const runtime = {
+ call: vi.fn(async (req: BrowserControlRequest): Promise<BrowserControlResult> => {
+ events.push(`${req.action}:begin`);
+ if (req.action === 'start') {
+ await new Promise<void>((resolve) => { releaseStart = resolve; });
+ }
+ events.push(`${req.action}:end`);
+ return {
+ ok: true,
+ action: req.action,
+ status: 200,
+ data: req.action === 'status' ? { running: true } : { stopped: true },
+ };
+ }),
+ };
+ const backend = new ExternalChromeBackend(initial, fakeLogger(), {
+ createRuntime: () => runtime,
+ createProxyAuth: () => ({ start: vi.fn(async () => {}), dispose: vi.fn(async () => {}) }),
+ isBrowserGone: vi.fn(async () => true),
+ });
+ const start = backend.call({ action: 'start', proxyServer: 'http://proxy.test:8080' });
+ const stop = backend.call({ action: 'stop' });
+ await vi.waitFor(() => expect(releaseStart).toBeTypeOf('function'));
+ expect(events).toEqual(['start:begin']);
+ releaseStart?.();
+ await Promise.all([start, stop]);
+ // The trailing status is the stop's independent exit verification: the
+ // vendored stopped:true only reports that signals were sent. What this test
+ // pins is the ordering — stop never interleaves with the in-flight start.
+ expect(events).toEqual([
+ 'start:begin', 'start:end', 'stop:begin', 'stop:end', 'status:begin', 'status:end',
+ ]);
+ });
+
+ it('rejects a late start after quit quiescence instead of relaunching', async () => {
+ const { backend, created } = createHarness();
+ await backend.call({ action: 'start' });
+
+ backend.beginQuiescence();
+ const dispose = backend.dispose();
+ const lateStart = backend.call({
+ action: 'start',
+ proxyServer: 'http://proxy-after-quit.test:8080',
+ });
+
+ await expect(lateStart).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'BROWSER_RUNTIME_UNAVAILABLE',
+ });
+ await dispose;
+ expect(created).toHaveLength(1);
+ expect(created[0].runtime.call.mock.calls.map(([req]) => req.action)).toEqual(['start', 'stop', 'status']);
});
- it('dispose() swallows runtime errors (quit path must not stall)', async () => {
- const call = vi.fn<(req: BrowserControlRequest) => Promise<BrowserControlResult>>(async () => {
+ it('swallows dispose errors and skips a runtime that was never used', async () => {
+ const unused = fakeRuntime();
+ const unusedBackend = new ExternalChromeBackend(unused, fakeLogger());
+ await expect(unusedBackend.dispose()).resolves.toBeUndefined();
+ expect(unused.call).not.toHaveBeenCalled();
+
+ const call = vi.fn(async (req: BrowserControlRequest): Promise<BrowserControlResult> => {
+ if (req.action === 'status') return { ok: true, action: req.action, status: 200, data: { running: true } };
throw new Error('boom');
});
const logger = fakeLogger();
- const backend = new ExternalChromeBackend({ call }, logger);
+ const usedBackend = new ExternalChromeBackend({ call }, logger);
+ await usedBackend.call({ action: 'status' });
+ await expect(usedBackend.dispose()).resolves.toBeUndefined();
+ expect(logger.warn).toHaveBeenCalled();
+ });
+
+ it('retains and blocks a known route when dispose cannot stop the browser', async () => {
+ const { backend, created, auth } = createHarness();
+ await backend.call({
+ action: 'start',
+ proxyServer: 'http://proxy.test:8080',
+ });
+ const runtime = created[0].runtime;
+ runtime.call.mockImplementationOnce(async () => {
+ throw new Error('stop failed');
+ });
await expect(backend.dispose()).resolves.toBeUndefined();
- expect(logger.warn).toHaveBeenCalledTimes(1);
+
+ expect(backend.getEffectiveProxy()).toEqual({
+ mode: 'proxied',
+ server: 'http://proxy.test:8080',
+ });
+ await expect(backend.call({ action: 'tabs' })).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'BROWSER_RUNTIME_UNAVAILABLE',
+ });
+ expect(auth.dispose).not.toHaveBeenCalled();
+ });
+
+ it('attaches the proxy guard to the live Cindy-real identity, not the isolated default', async () => {
+ let cdpHttpUrl = 'http://127.0.0.1:18800';
+ let managedUserDataDir = '/managed/browser/Cindy/user-data';
+ const auth = { start: vi.fn(async () => {}), dispose: vi.fn(async () => {}) };
+ const closeAdoptedBrowser = vi.fn(async () => true);
+ const backend = new ExternalChromeBackend(fakeRuntime(), fakeLogger(), {
+ createRuntime: () => fakeRuntime(),
+ createProxyAuth: () => auth,
+ closeAdoptedBrowser,
+ isBrowserGone: vi.fn(async () => true),
+ cdpHttpUrl: () => cdpHttpUrl,
+ managedUserDataDir: () => managedUserDataDir,
+ });
+
+ // wrapRuntimeWithRealProfile relocates off 18800 after construction.
+ cdpHttpUrl = 'http://127.0.0.1:18801';
+ managedUserDataDir = '/managed/browser/Cindy-real/user-data';
+ await backend.call({
+ action: 'start',
+ proxyServer: 'http://proxy-a.test:8080',
+ });
+
+ expect(auth.start).toHaveBeenCalledWith('http://127.0.0.1:18801');
+ expect(closeAdoptedBrowser).not.toHaveBeenCalled();
+ });
+
+ it('closes an inherited process using the live Cindy-real identity', async () => {
+ const closeAdoptedBrowser = vi.fn(async () => true);
+ const backend = new ExternalChromeBackend(fakeRuntime(true), fakeLogger(), {
+ createRuntime: () => fakeRuntime(),
+ createProxyAuth: () => ({ start: vi.fn(async () => {}), dispose: vi.fn(async () => {}) }),
+ closeAdoptedBrowser,
+ isBrowserGone: vi.fn(async () => false),
+ cdpHttpUrl: () => 'http://127.0.0.1:18801',
+ managedUserDataDir: () => '/managed/browser/Cindy-real/user-data',
+ });
+
+ await backend.call({
+ action: 'start',
+ proxyServer: 'http://proxy-a.test:8080',
+ });
+
+ expect(closeAdoptedBrowser).toHaveBeenCalledWith(
+ 'http://127.0.0.1:18801',
+ '/managed/browser/Cindy-real/user-data',
+ );
});
});
diff --git a/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/proxy-auth.test.ts b/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/proxy-auth.test.ts
new file mode 100644
index 0000000000..fd7e4fc5e0
--- /dev/null
+++ b/apps/desktop/src/main/mcp-integrations/browser-backend/__tests__/proxy-auth.test.ts
@@ -0,0 +1,674 @@
+import { createServer, type Server } from 'node:http';
+import type { AddressInfo } from 'node:net';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { WebSocketServer, type WebSocket } from 'ws';
+
+import { resetBrowserProxyDnsVerdictCache } from '@cindy/browser-control-runtime';
+
+import {
+ BrowserProxyAuthCoordinator,
+ closeAdoptedManagedBrowser,
+ commandLineHasExactArgument,
+} from '../proxy-auth.js';
+
+interface CdpCommand {
+ id: number;
+ method: string;
+ params?: Record<string, unknown>;
+ sessionId?: string;
+}
+
+const servers: Server[] = [];
+const sockets: WebSocket[] = [];
+
+afterEach(async () => {
+ for (const socket of sockets.splice(0)) socket.terminate();
+ await Promise.all(servers.splice(0).map((server) => new Promise<void>((resolve) => server.close(() => resolve()))));
+});
+
+async function listen(server: Server): Promise<number> {
+ await new Promise<void>((resolve, reject) => {
+ server.once('error', reject);
+ server.listen(0, '127.0.0.1', () => resolve());
+ });
+ servers.push(server);
+ return (server.address() as AddressInfo).port;
+}
+
+async function createFakeCdp(options: {
+ failAttachToTarget?: boolean;
+ failFetchEnable?: boolean;
+ failFetchEnableForSession?: string;
+ failBrowserClose?: boolean;
+ closeOnBrowserClose?: boolean;
+ emitAutoAttach?: boolean;
+ emitAutoAttachBeforeReadyBarrier?: boolean;
+ reportedUserDataDir?: string;
+ startupTargets?: Array<{ targetId: string; type: string }>;
+} = {}) {
+ const commands: CdpCommand[] = [];
+ let browserSocket: WebSocket | undefined;
+ let getTargetsCalls = 0;
+ const wsServer = new WebSocketServer({ noServer: true });
+ wsServer.on('connection', (socket) => {
+ sockets.push(socket);
+ browserSocket = socket;
+ socket.on('message', (raw) => {
+ const command = JSON.parse(raw.toString()) as CdpCommand;
+ commands.push(command);
+ if (command.method === 'Target.setAutoAttach' && options.emitAutoAttach) {
+ socket.send(JSON.stringify({
+ method: 'Target.attachedToTarget',
+ params: {
+ sessionId: 'session-1',
+ targetInfo: { targetId: 'page-1', type: 'page' },
+ },
+ }));
+ socket.send(JSON.stringify({ id: command.id, result: {} }));
+ } else if (command.method === 'Target.getTargets') {
+ getTargetsCalls += 1;
+ if (options.emitAutoAttachBeforeReadyBarrier && getTargetsCalls === 2) {
+ socket.send(JSON.stringify({
+ method: 'Target.attachedToTarget',
+ params: {
+ sessionId: 'session-2',
+ targetInfo: { targetId: 'page-2', type: 'page' },
+ },
+ }));
+ }
+ socket.send(JSON.stringify({
+ id: command.id,
+ result: {
+ targetInfos: options.startupTargets ?? [{ targetId: 'page-1', type: 'page' }],
+ },
+ }));
+ } else if (command.method === 'Target.attachToTarget') {
+ const requestedTargetId = (command.params as { targetId?: string } | undefined)?.targetId;
+ socket.send(JSON.stringify(options.failAttachToTarget
+ ? { id: command.id, error: { message: 'attach failed' } }
+ : {
+ id: command.id,
+ result: {
+ sessionId: options.startupTargets && requestedTargetId
+ ? `session-for-${requestedTargetId}`
+ : 'session-1',
+ },
+ }));
+ } else if (command.method === 'Fetch.enable' && (
+ options.failFetchEnable
+ || command.sessionId === options.failFetchEnableForSession
+ )) {
+ socket.send(JSON.stringify({ id: command.id, error: { message: 'dummy secret must not escape' } }));
+ } else if (command.method === 'Browser.close') {
+ if (options.failBrowserClose) {
+ socket.send(JSON.stringify({ id: command.id, error: { message: 'close failed' } }));
+ } else {
+ socket.send(JSON.stringify({ id: command.id, result: {} }));
+ if (options.closeOnBrowserClose) {
+ setTimeout(() => {
+ socket.close();
+ server.close();
+ }, 0);
+ }
+ }
+ } else if (command.method === 'SystemInfo.getInfo') {
+ const address = server.address() as AddressInfo;
+ socket.send(JSON.stringify({
+ id: command.id,
+ result: {
+ commandLine: options.reportedUserDataDir
+ ? `chrome --remote-debugging-port=${address.port} "--user-data-dir=${options.reportedUserDataDir}"`
+ : 'chrome',
+ },
+ }));
+ } else {
+ socket.send(JSON.stringify({ id: command.id, result: {} }));
+ }
+ });
+ });
+
+ const server = createServer((req, res) => {
+ if (req.url !== '/json/version') {
+ res.writeHead(404).end();
+ return;
+ }
+ const address = server.address() as AddressInfo;
+ res.setHeader('content-type', 'application/json');
+ res.end(JSON.stringify({ webSocketDebuggerUrl: `ws://127.0.0.1:${address.port}/devtools/browser/test` }));
+ });
+ server.on('upgrade', (request, socket, head) => {
+ wsServer.handleUpgrade(request, socket, head, (ws) => wsServer.emit('connection', ws, request));
+ });
+ const port = await listen(server);
+ return {
+ cdpUrl: `http://127.0.0.1:${port}`,
+ commands,
+ sendEvent(event: Record<string, unknown>) {
+ if (!browserSocket) throw new Error('fake CDP browser socket is not connected');
+ browserSocket.send(JSON.stringify(event));
+ },
+ disconnect() {
+ if (!browserSocket) throw new Error('fake CDP browser socket is not connected');
+ browserSocket.close();
+ },
+ };
+}
+
+// The request gate verifies DNS answers, so tests must supply a resolver:
+// the `.example` hosts they use do not resolve. Public answer by default.
+const publicLookup = (async () => [{ address: '93.184.216.34', family: 4 }]) as never;
+
+describe('commandLineHasExactArgument', () => {
+ const dir = '/Users/me/Library/Application Support/Cindy/browser/Cindy';
+
+ it('rejects a value the expected one is merely a prefix of', () => {
+ // The reason this cannot be `includes`: the result feeds a process kill, so
+ // matching `<dir>-backup` would terminate an unrelated browser and its tree.
+ expect(commandLineHasExactArgument(
+ `chrome --user-data-dir=${dir}-backup --remote-debugging-port=18800`,
+ `--user-data-dir=${dir}`,
+ )).toBe(false);
+ expect(commandLineHasExactArgument(
+ 'chrome --remote-debugging-port=188000',
+ '--remote-debugging-port=18800',
+ )).toBe(false);
+ });
+
+ it('accepts the argument when it stands as its own token', () => {
+ for (const line of [
+ `chrome --user-data-dir=${dir} --remote-debugging-port=18800`,
+ `chrome "--user-data-dir=${dir}" --headless`,
+ `--user-data-dir=${dir}`,
+ ]) {
+ expect(commandLineHasExactArgument(line, `--user-data-dir=${dir}`), line).toBe(true);
+ }
+ });
+});
+
+describe('BrowserProxyAuthCoordinator', () => {
+ beforeEach(() => {
+ // DNS verdicts are cached per hostname across coordinators, so one test's
+ // resolver would otherwise decide the next test's verdict for the same host.
+ resetBrowserProxyDnsVerdictCache();
+ });
+
+ it('answers only proxy challenges with decoded credentials and continues paused requests', async () => {
+ const cdp = await createFakeCdp();
+ const logger = { warn: vi.fn() };
+ const coordinator = new BrowserProxyAuthCoordinator({
+ mode: 'proxied',
+ server: 'http://proxy.test:8080',
+ username: 'u/ser',
+ password: 'p@ss:word',
+ allowedHostnames: ['allowed.example'],
+ }, logger, () => {}, publicLookup);
+ await coordinator.start(cdp.cdpUrl);
+
+ cdp.sendEvent({
+ method: 'Fetch.authRequired',
+ sessionId: 'session-1',
+ params: { requestId: 'proxy-request', authChallenge: { source: 'Proxy' } },
+ });
+ cdp.sendEvent({
+ method: 'Fetch.authRequired',
+ sessionId: 'session-1',
+ params: { requestId: 'origin-request', authChallenge: { source: 'Server' } },
+ });
+ cdp.sendEvent({
+ method: 'Fetch.requestPaused',
+ sessionId: 'session-1',
+ params: {
+ requestId: 'paused-request',
+ request: { url: 'https://allowed.example/page' },
+ },
+ });
+
+ await vi.waitFor(() => {
+ expect(cdp.commands.filter(({ method }) => method === 'Fetch.continueWithAuth')).toHaveLength(2);
+ expect(cdp.commands.some(({ method }) => method === 'Fetch.continueRequest')).toBe(true);
+ });
+ const authCommands = cdp.commands.filter(({ method }) => method === 'Fetch.continueWithAuth');
+ expect(authCommands[0]?.params).toMatchObject({
+ requestId: 'proxy-request',
+ authChallengeResponse: {
+ response: 'ProvideCredentials',
+ username: 'u/ser',
+ password: 'p@ss:word',
+ },
+ });
+ expect(authCommands[1]?.params).toMatchObject({
+ requestId: 'origin-request',
+ authChallengeResponse: { response: 'Default' },
+ });
+ expect(logger.warn).not.toHaveBeenCalled();
+ await coordinator.dispose();
+ });
+
+ it('enforces the HTTPS + hostname allowlist on every paused request, including credential-free proxies', async () => {
+ const cdp = await createFakeCdp();
+ const coordinator = new BrowserProxyAuthCoordinator({
+ mode: 'proxied',
+ server: 'http://proxy.test:8080',
+ allowedHostnames: ['allowed.example', '*.wild.example'],
+ }, { warn: vi.fn() }, () => {}, publicLookup);
+ // No credentials: the guard must still attach for the browser lifetime.
+ await coordinator.start(cdp.cdpUrl);
+
+ const cases: Array<{ requestId: string; url: string; allowed: boolean }> = [
+ { requestId: 'exact-https', url: 'https://allowed.example/page', allowed: true },
+ { requestId: 'wildcard-https', url: 'https://sub.wild.example/a', allowed: true },
+ { requestId: 'wildcard-apex', url: 'https://wild.example/a', allowed: false },
+ { requestId: 'plain-http', url: 'http://allowed.example/page', allowed: false },
+ { requestId: 'other-host', url: 'https://evil.example/page', allowed: false },
+ { requestId: 'no-url', url: '', allowed: false },
+ ];
+ for (const { requestId, url } of cases) {
+ cdp.sendEvent({
+ method: 'Fetch.requestPaused',
+ sessionId: 'session-1',
+ params: { requestId, ...(url ? { request: { url } } : {}) },
+ });
+ }
+
+ await vi.waitFor(() => {
+ const handled = cdp.commands.filter(
+ ({ method }) => method === 'Fetch.continueRequest' || method === 'Fetch.failRequest',
+ );
+ expect(handled).toHaveLength(cases.length);
+ });
+ for (const { requestId, allowed } of cases) {
+ const command = cdp.commands.find(
+ ({ method, params }) =>
+ (method === 'Fetch.continueRequest' || method === 'Fetch.failRequest')
+ && (params as { requestId?: string } | undefined)?.requestId === requestId,
+ );
+ expect(command?.method, requestId).toBe(
+ allowed ? 'Fetch.continueRequest' : 'Fetch.failRequest',
+ );
+ if (!allowed) {
+ expect(command?.params).toMatchObject({ errorReason: 'BlockedByClient' });
+ }
+ }
+ await coordinator.dispose();
+ });
+
+ it('blocks an allowlisted host whose DNS answer points into the private network', async () => {
+ // The allowlist is textual, so `allowed.example` matches — only resolution
+ // reveals the inward target (the `127.0.0.1.nip.io` / rebinding class).
+ const cdp = await createFakeCdp();
+ const coordinator = new BrowserProxyAuthCoordinator({
+ mode: 'proxied',
+ server: 'http://proxy.test:8080',
+ allowedHostnames: ['allowed.example'],
+ }, { warn: vi.fn() }, () => {}, (async () => [{ address: '127.0.0.1', family: 4 }]) as never);
+ await coordinator.start(cdp.cdpUrl);
+
+ cdp.sendEvent({
+ method: 'Fetch.requestPaused',
+ sessionId: 'session-1',
+ params: { requestId: 'rebound', request: { url: 'https://allowed.example/page' } },
+ });
+
+ await vi.waitFor(() => {
+ const command = cdp.commands.find(
+ ({ params }) => (params as { requestId?: string } | undefined)?.requestId === 'rebound',
+ );
+ expect(command?.method).toBe('Fetch.failRequest');
+ expect(command?.params).toMatchObject({ errorReason: 'BlockedByClient' });
+ });
+ await coordinator.dispose();
+ });
+
+ it('enables auto-attach recursively on each attached target session', async () => {
+ // Auto-attach only covers targets related to the session it was set on, so
+ // the browser-level call does not reach a page's own dedicated/shared
+ // workers. Without recursing per session such a worker never raises
+ // attachedToTarget, never gets Fetch, and its requests skip the gate —
+ // leaving only the hostname-only PAC. (Playwright recurses the same way.)
+ const cdp = await createFakeCdp({
+ startupTargets: [
+ { targetId: 'page-1', type: 'page' },
+ { targetId: 'sw-1', type: 'service_worker' },
+ ],
+ });
+ const coordinator = new BrowserProxyAuthCoordinator({
+ mode: 'proxied',
+ server: 'http://proxy.test:8080',
+ allowedHostnames: ['allowed.example'],
+ }, { warn: vi.fn() }, () => {}, publicLookup);
+ await coordinator.start(cdp.cdpUrl);
+
+ const autoAttachSessions = cdp.commands
+ .filter(({ method }) => method === 'Target.setAutoAttach')
+ .map(({ sessionId }) => sessionId);
+ // Browser level (no sessionId) plus one per attached network-capable target.
+ expect(autoAttachSessions).toContain(undefined);
+ for (const targetId of ['page-1', 'sw-1']) {
+ expect(autoAttachSessions, targetId).toContain(`session-for-${targetId}`);
+ }
+
+ // A target paused at start must not be resumed before its own children
+ // will be caught, so the recursion has to precede the resume.
+ const order = cdp.commands.filter(({ method, sessionId }) =>
+ sessionId === 'session-for-page-1'
+ && (method === 'Target.setAutoAttach' || method === 'Runtime.runIfWaitingForDebugger'));
+ expect(order.map(({ method }) => method)).toEqual([
+ 'Target.setAutoAttach',
+ 'Runtime.runIfWaitingForDebugger',
+ ]);
+ await coordinator.dispose();
+ });
+
+ it('gates workers and subframes, not just pages', async () => {
+ const cdp = await createFakeCdp({
+ startupTargets: [
+ { targetId: 'page-1', type: 'page' },
+ { targetId: 'sw-1', type: 'service_worker' },
+ { targetId: 'worker-1', type: 'worker' },
+ { targetId: 'shared-1', type: 'shared_worker' },
+ { targetId: 'frame-1', type: 'iframe' },
+ { targetId: 'other-1', type: 'browser' },
+ ],
+ });
+ const coordinator = new BrowserProxyAuthCoordinator({
+ mode: 'proxied',
+ server: 'http://proxy.test:8080',
+ allowedHostnames: ['allowed.example'],
+ }, { warn: vi.fn() });
+ await coordinator.start(cdp.cdpUrl);
+
+ const gatedSessions = cdp.commands
+ .filter(({ method }) => method === 'Fetch.enable')
+ .map(({ sessionId }) => sessionId);
+ for (const targetId of ['page-1', 'sw-1', 'worker-1', 'shared-1', 'frame-1']) {
+ expect(gatedSessions, targetId).toContain(`session-for-${targetId}`);
+ }
+ // A non-network target is resumed but never gets its own Fetch gate.
+ expect(gatedSessions).not.toContain('session-for-other-1');
+
+ // A worker request is enforced on its own session, like a page request.
+ cdp.sendEvent({
+ method: 'Fetch.requestPaused',
+ sessionId: 'session-for-sw-1',
+ params: { requestId: 'sw-egress', request: { url: 'https://evil.example/beacon' } },
+ });
+ await vi.waitFor(() => {
+ expect(
+ cdp.commands.some(
+ ({ method, params }) =>
+ method === 'Fetch.failRequest'
+ && (params as { requestId?: string } | undefined)?.requestId === 'sw-egress',
+ ),
+ ).toBe(true);
+ });
+ await coordinator.dispose();
+ });
+
+ it('blocks every request when a proxied launch carries no allowlist', async () => {
+ const cdp = await createFakeCdp();
+ const coordinator = new BrowserProxyAuthCoordinator({
+ mode: 'proxied',
+ server: 'http://proxy.test:8080',
+ }, { warn: vi.fn() });
+ await coordinator.start(cdp.cdpUrl);
+
+ cdp.sendEvent({
+ method: 'Fetch.requestPaused',
+ sessionId: 'session-1',
+ params: { requestId: 'no-allowlist', request: { url: 'https://anything.example/' } },
+ });
+
+ await vi.waitFor(() => {
+ expect(
+ cdp.commands.some(
+ ({ method, params }) =>
+ method === 'Fetch.failRequest'
+ && (params as { requestId?: string } | undefined)?.requestId === 'no-allowlist',
+ ),
+ ).toBe(true);
+ });
+ expect(cdp.commands.some(({ method }) => method === 'Fetch.continueRequest')).toBe(false);
+ await coordinator.dispose();
+ });
+
+ it('fails setup when Fetch authentication handling cannot be enabled', async () => {
+ const cdp = await createFakeCdp({ failFetchEnable: true });
+ const coordinator = new BrowserProxyAuthCoordinator({
+ mode: 'proxied',
+ server: 'http://proxy.test:8080',
+ username: 'dummy-user',
+ password: 'dummy-password',
+ }, { warn: vi.fn() });
+ await expect(coordinator.start(cdp.cdpUrl)).rejects.toThrow(
+ 'CDP proxy authentication command failed',
+ );
+ await coordinator.dispose();
+ });
+
+ it('fails setup when an existing live page cannot be attached', async () => {
+ const cdp = await createFakeCdp({ failAttachToTarget: true });
+ const coordinator = new BrowserProxyAuthCoordinator({
+ mode: 'proxied',
+ server: 'http://proxy.test:8080',
+ username: 'dummy-user',
+ password: 'dummy-password',
+ }, { warn: vi.fn() });
+
+ await expect(coordinator.start(cdp.cdpUrl)).rejects.toThrow(
+ 'CDP proxy authentication command failed',
+ );
+ expect(cdp.commands.filter(({ method }) => method === 'Target.getTargets')).toHaveLength(2);
+ expect(cdp.commands.filter(({ method }) => method === 'Fetch.enable')).toHaveLength(0);
+ await coordinator.dispose();
+ });
+
+ it('awaits auto-attached target setup without attaching the same target twice', async () => {
+ const cdp = await createFakeCdp({ emitAutoAttach: true });
+ const coordinator = new BrowserProxyAuthCoordinator({
+ mode: 'proxied',
+ server: 'http://proxy.test:8080',
+ username: 'user',
+ password: 'password',
+ }, { warn: vi.fn() });
+ await coordinator.start(cdp.cdpUrl);
+ expect(cdp.commands.filter(({ method }) => method === 'Target.attachToTarget')).toHaveLength(0);
+ expect(cdp.commands.filter(({ method }) => method === 'Fetch.enable')).toHaveLength(1);
+ expect(cdp.commands.filter(({ method }) => method === 'Runtime.runIfWaitingForDebugger')).toHaveLength(1);
+ await coordinator.dispose();
+ });
+
+ it('fails startup when target auth fails before the CDP readiness barrier', async () => {
+ const cdp = await createFakeCdp({
+ emitAutoAttachBeforeReadyBarrier: true,
+ failFetchEnableForSession: 'session-2',
+ });
+ const onFailure = vi.fn();
+ const coordinator = new BrowserProxyAuthCoordinator({
+ mode: 'proxied',
+ server: 'http://proxy.test:8080',
+ username: 'user',
+ password: 'password',
+ }, { warn: vi.fn() }, onFailure);
+
+ await expect(coordinator.start(cdp.cdpUrl)).rejects.toThrow('proxy authentication setup failed');
+ expect(onFailure).toHaveBeenCalledTimes(1);
+ await coordinator.dispose();
+ });
+
+ it('blocks the route when later target auth setup fails even if browser close also fails', async () => {
+ const cdp = await createFakeCdp({
+ failFetchEnableForSession: 'session-2',
+ failBrowserClose: true,
+ });
+ const logger = { warn: vi.fn() };
+ const onFailure = vi.fn();
+ const coordinator = new BrowserProxyAuthCoordinator({
+ mode: 'proxied',
+ server: 'http://proxy.test:8080',
+ username: 'user',
+ password: 'password',
+ }, logger, onFailure);
+ await coordinator.start(cdp.cdpUrl);
+
+ cdp.sendEvent({
+ method: 'Target.attachedToTarget',
+ params: {
+ sessionId: 'session-2',
+ targetInfo: { targetId: 'page-2', type: 'page' },
+ },
+ });
+
+ await vi.waitFor(() => {
+ expect(cdp.commands).toContainEqual(expect.objectContaining({ method: 'Browser.close' }));
+ });
+ expect(onFailure).toHaveBeenCalledTimes(1);
+ expect(cdp.commands).not.toContainEqual(expect.objectContaining({
+ method: 'Runtime.runIfWaitingForDebugger',
+ sessionId: 'session-2',
+ }));
+ expect(logger.warn).toHaveBeenCalledWith(
+ 'browser proxy authentication could not prepare a new browser target',
+ );
+ await coordinator.dispose();
+ });
+
+ it('blocks the route when the proxy-auth CDP channel disconnects unexpectedly', async () => {
+ const cdp = await createFakeCdp();
+ const onFailure = vi.fn();
+ const coordinator = new BrowserProxyAuthCoordinator({
+ mode: 'proxied',
+ server: 'http://proxy.test:8080',
+ username: 'user',
+ password: 'password',
+ }, { warn: vi.fn() }, onFailure);
+ await coordinator.start(cdp.cdpUrl);
+
+ cdp.disconnect();
+
+ await vi.waitFor(() => expect(onFailure).toHaveBeenCalledTimes(1));
+ await coordinator.dispose();
+ });
+
+ it('terminates the browser over a fresh connection when its own channel is dead', async () => {
+ // Blocking the host only stops future host calls. Pages and workers already
+ // running keep their network access, and the request gate died with the
+ // socket — leaving the hostname-only PAC. Browser.close over the dead
+ // channel is a no-op (command() rejects when the socket is not OPEN), so
+ // teardown must dial the endpoint again.
+ const userDataDir = '/managed/browser/Cindy/user-data';
+ const cdp = await createFakeCdp({ reportedUserDataDir: userDataDir });
+ const coordinator = new BrowserProxyAuthCoordinator({
+ mode: 'proxied',
+ server: 'http://proxy.test:8080',
+ allowedHostnames: ['allowed.example'],
+ }, { warn: vi.fn() }, () => {}, publicLookup, userDataDir);
+ await coordinator.start(cdp.cdpUrl);
+ const before = cdp.commands.filter(({ method }) => method === 'Browser.close').length;
+
+ cdp.disconnect();
+
+ // The close arrives on a NEW socket, after the coordinator's own is gone.
+ await vi.waitFor(() => {
+ const after = cdp.commands.filter(({ method }) => method === 'Browser.close').length;
+ expect(after).toBeGreaterThan(before);
+ }, { timeout: 10_000 });
+ await coordinator.dispose();
+ }, 20_000);
+
+ it('closes and verifies an adopted managed browser through loopback CDP', async () => {
+ const userDataDir = '/managed/browser/Cindy Profile/user-data';
+ const cdp = await createFakeCdp({ closeOnBrowserClose: true, reportedUserDataDir: userDataDir });
+ await expect(closeAdoptedManagedBrowser(cdp.cdpUrl, userDataDir)).resolves.toBe(true);
+ expect(cdp.commands).toContainEqual(expect.objectContaining({ method: 'Browser.close' }));
+ });
+
+ it('bounds auth attempt state without depending on CDP event ordering', async () => {
+ const cdp = await createFakeCdp();
+ const coordinator = new BrowserProxyAuthCoordinator({
+ mode: 'proxied',
+ server: 'http://proxy.test:8080',
+ username: 'u',
+ password: 'p',
+ allowedHostnames: ['allowed.example'],
+ }, { warn: vi.fn() });
+ await coordinator.start(cdp.cdpUrl);
+
+ const attempts = (coordinator as unknown as { authAttempts: Map<string, number> }).authAttempts;
+ // Far more unique challenges than a page could have in flight at once.
+ for (let i = 0; i < 700; i += 1) {
+ cdp.sendEvent({
+ method: 'Fetch.authRequired',
+ sessionId: 'session-1',
+ params: { requestId: `req-${i}`, authChallenge: { source: 'Proxy' } },
+ });
+ }
+ await vi.waitFor(() => {
+ expect(
+ cdp.commands.filter(({ method }) => method === 'Fetch.continueWithAuth'),
+ ).toHaveLength(700);
+ });
+
+ expect(attempts.size).toBeLessThanOrEqual(512);
+ // A challenge still in flight keeps its counter, so a repeat challenge is
+ // still recognized as a retry and cancelled rather than re-credentialed.
+ cdp.sendEvent({
+ method: 'Fetch.authRequired',
+ sessionId: 'session-1',
+ params: { requestId: 'req-699', authChallenge: { source: 'Proxy' } },
+ });
+ await vi.waitFor(() => {
+ const cancels = cdp.commands.filter(
+ ({ method, params }) =>
+ method === 'Fetch.continueWithAuth'
+ && (params as { authChallengeResponse?: { response?: string } } | undefined)
+ ?.authChallengeResponse?.response === 'CancelAuth',
+ );
+ expect(cancels.length).toBeGreaterThanOrEqual(1);
+ });
+ await coordinator.dispose();
+ }, 20_000);
+
+ it('does not treat a transient CDP outage as a stopped browser', async () => {
+ // The HTTP endpoint refuses connections for a while (busy/stalled Chrome)
+ // and then recovers — a still-live browser, not an exited one.
+ let refuseUntil = Date.now() + 600;
+ const server = createServer((req, res) => {
+ if (Date.now() < refuseUntil) {
+ req.destroy();
+ return;
+ }
+ if (req.url !== '/json/version') {
+ res.writeHead(404).end();
+ return;
+ }
+ const address = server.address() as AddressInfo;
+ res.setHeader('content-type', 'application/json');
+ res.end(JSON.stringify({
+ webSocketDebuggerUrl: `ws://127.0.0.1:${address.port}/devtools/browser/test`,
+ }));
+ });
+ const port = await listen(server);
+
+ // The websocket handshake fails while the endpoint is refusing, so this
+ // takes the "cannot connect" path — which must NOT report success once the
+ // endpoint proves reachable again.
+ await expect(closeAdoptedManagedBrowser(
+ `http://127.0.0.1:${port}`,
+ '/managed/browser/Cindy/user-data',
+ )).resolves.toBe(false);
+ expect(refuseUntil).toBeLessThan(Date.now());
+ // Runs the full quiescence deadline rather than returning early on the
+ // first failed probe — that is the point of the check.
+ }, 20_000);
+
+ it('refuses to close an adopted CDP browser with a different profile identity', async () => {
+ const cdp = await createFakeCdp({ reportedUserDataDir: '/other/browser/user-data' });
+
+ await expect(closeAdoptedManagedBrowser(
+ cdp.cdpUrl,
+ '/managed/browser/Cindy/user-data',
+ )).resolves.toBe(false);
+ expect(cdp.commands).not.toContainEqual(expect.objectContaining({ method: 'Browser.close' }));
+ });
+});
diff --git a/apps/desktop/src/main/mcp-integrations/browser-backend/external-chrome-backend.ts b/apps/desktop/src/main/mcp-integrations/browser-backend/external-chrome-backend.ts
index 1c0197fa2d..9f1dbc51da 100644
--- a/apps/desktop/src/main/mcp-integrations/browser-backend/external-chrome-backend.ts
+++ b/apps/desktop/src/main/mcp-integrations/browser-backend/external-chrome-backend.ts
@@ -1,52 +1,823 @@
-// External Chrome backend — delegates to the vendored `BrowserControlRuntime`.
-//
-// This is the existing (and, in Phase 1, only) backend. It exists so the host
-// can talk to *any* control target through the same `BrowserBackend` contract,
-// with an explicit backend identity added to status results. Other calls are
-// passed through, and `dispose` reuses the existing electron-free
-// `stopRuntimeForQuit` (which already swallows errors per the quit-path
-// contract — see browser-dispose.ts).
-
-import { stopRuntimeForQuit } from '../browser-dispose.js';
+// External Chrome backend — owns the managed browser process and its launch
+// route. The route is launch state, not a mutable per-request option.
+
+import {
+ browserProxyRouteKey,
+ parseBrowserProxyServer,
+ redactBrowserProxyRoute,
+ redactBrowserProxyText,
+ type BrowserControlRequest,
+ type BrowserControlResult,
+ type BrowserProxyRoute,
+} from '@cindy/browser-control-runtime';
+
import type {
BackendRequest,
BackendResult,
BackendRuntimeShape,
BrowserBackend,
} from './types.js';
+import {
+ BrowserProxyAuthCoordinator,
+ closeAdoptedManagedBrowser,
+ isManagedBrowserGone,
+} from './proxy-auth.js';
-/** Minimal logger surface used here — matches the unified logger's `warn`. */
interface BackendLogger {
warn(message: string, ...args: unknown[]): void;
}
+type MaybeLazy<T> = T | (() => T);
+
+export interface ExternalChromeBackendOptions {
+ /** Creates a runtime after the old browser has been stopped. */
+ createRuntime?: (route: BrowserProxyRoute) => BackendRuntimeShape;
+ /**
+ * Loopback CDP HTTP base used by the request-gate coordinator.
+ * May be lazy: Cindy-real can relocate off 18800 after construction.
+ */
+ cdpHttpUrl?: MaybeLazy<string>;
+ /**
+ * On-disk managed profile used to verify ownership before adopted-process
+ * cleanup. May be lazy so it follows Cindy vs Cindy-real.
+ */
+ managedUserDataDir?: MaybeLazy<string | undefined>;
+ createProxyAuth?: (
+ route: BrowserProxyRoute,
+ logger: BackendLogger,
+ onFailure: () => void,
+ ) => Pick<BrowserProxyAuthCoordinator, 'start' | 'dispose'>;
+ /** Test seam for closing a process the vendored runtime did not launch. */
+ closeAdoptedBrowser?: (cdpHttpUrl: string, expectedUserDataDir: string) => Promise<boolean>;
+ /** Non-destructive liveness probe; must not close the browser. */
+ isBrowserGone?: (cdpHttpUrl: string, managedUserDataDir?: string) => Promise<boolean>;
+}
+
+function invalidRequest(action: BrowserControlRequest['action'], message: string): BrowserControlResult {
+ return {
+ ok: false,
+ action,
+ errorCode: 'BROWSER_RUNTIME_INVALID_REQUEST',
+ message,
+ };
+}
+
+function actionWithProxy(result: BrowserControlResult, route: BrowserProxyRoute | undefined): BrowserControlResult {
+ const data = result.data && typeof result.data === 'object' && !Array.isArray(result.data)
+ ? { ...(result.data as Record<string, unknown>), proxy: redactBrowserProxyRoute(route) }
+ : { proxy: redactBrowserProxyRoute(route) };
+ return { ...result, data };
+}
+
+/**
+ * Whether an interaction failed because containment could not be completed —
+ * the runtime exhausted per-page, per-context and browser teardown and pages it
+ * never validated may still be live. Matched on the message because the
+ * vendored runtime reports policy outcomes as errors, not structured codes; the
+ * phrase is fixed in LOCAL_PATCHES alongside the code that raises it.
+ */
+function mentionsUntornDownBrowser(message: unknown): boolean {
+ return typeof message === 'string' && message.includes('could not be torn down');
+}
+
+function runningState(result: BrowserControlResult): 'running' | 'stopped' | 'unknown' {
+ if (!result.ok) return 'unknown';
+ const running = (result.data as { running?: unknown } | undefined)?.running;
+ if (running === true) return 'running';
+ if (running === false) return 'stopped';
+ return 'unknown';
+}
+
+function isRunning(result: BrowserControlResult): boolean {
+ return runningState(result) === 'running';
+}
+
+/**
+ * Liveness of the managed browser PROCESS, as opposed to `runningState`, which
+ * reports the vendored `running` field — and that field is `cdpReady`, i.e.
+ * transport readiness. A busy-but-alive Chrome that misses the readiness probe
+ * reports `running: false`, so `'stopped'` never means "no process".
+ *
+ * Every decision that would tear down a route, attribute an implicit launch, or
+ * adopt a stranger must branch on this instead:
+ * - `running` — cheap signal said running; trustworthy, no probe needed.
+ * - `gone` — independently verified absent (non-destructive probe).
+ * - `unproven` — readiness says stopped but absence is NOT established.
+ * Always fail closed here; never treat it as `gone`.
+ */
+type Liveness = 'running' | 'gone' | 'unproven';
+
+/**
+ * The queue covers every external-browser call, not only start/stop. Runtime
+ * configuration is process-global in the vendored adapter, so serializing all
+ * calls prevents a route snapshot from changing underneath an unrelated call.
+ */
export class ExternalChromeBackend implements BrowserBackend {
readonly kind = 'external' as const;
+ private runtime: BackendRuntimeShape;
+ private route: BrowserProxyRoute | undefined;
+ private auth: Pick<BrowserProxyAuthCoordinator, 'start' | 'dispose'> | undefined;
+ private transition: Promise<void> = Promise.resolve();
+ private used = false;
+ private routeBlocked = false;
+ /**
+ * Set when a failed start leaves a runtime whose configured route no longer
+ * matches `route` (which never committed). A later verified stop must then
+ * replace the runtime with direct config instead of trusting `route`.
+ */
+ private forceDirectOnReset = false;
+ /**
+ * Route the current runtime is *configured* for, as opposed to `route` (the
+ * route of a browser confirmed to be running). Used to attribute an implicit
+ * launch — `open`/`tabs` can start the browser without going through
+ * `start`, which would otherwise leave `route` unknown and make the next
+ * same-route `start` destroy the user's tabs as if adopting a stranger.
+ */
+ private runtimeRoute: BrowserProxyRoute = { mode: 'direct' };
+ /**
+ * Whether the browser was verifiably stopped while this runtime was current.
+ * Only then can a later implicit launch be attributed to us; a process that
+ * predates our ownership keeps an unknown route and the adopt-or-refuse path.
+ */
+ private runtimeOwnsNextLaunch = false;
+ /**
+ * True only when `routeBlocked` was set by an UNPROVEN liveness reading (a
+ * readiness probe that missed while the process may still be alive). Such a
+ * block is transient and must clear once the browser answers again.
+ *
+ * Blocks from any other cause — proxy-auth failure, an unverifiable stop, a
+ * failed restart — are NOT transient: they mean the route can no longer be
+ * trusted, and only a verified stop may lift them. Never clear those here.
+ */
+ private routeBlockedByUnprovenLiveness = false;
+ private quiescing = false;
constructor(
- private readonly runtime: BackendRuntimeShape,
+ runtime: BackendRuntimeShape,
private readonly logger: BackendLogger,
- ) {}
+ private readonly options: ExternalChromeBackendOptions = {},
+ ) {
+ this.runtime = runtime;
+ }
+
+ private resolveCdpHttpUrl(): string {
+ const value = this.options.cdpHttpUrl;
+ if (typeof value === 'function') return value();
+ return value ?? 'http://127.0.0.1:18800';
+ }
+
+ private resolveManagedUserDataDir(): string | undefined {
+ const value = this.options.managedUserDataDir;
+ if (typeof value === 'function') return value();
+ return value;
+ }
async call(request: BackendRequest): Promise<BackendResult> {
- const result = await this.runtime.call(request);
+ if (this.quiescing && request.action !== 'stop') {
+ return this.withBackendIdentity(request, {
+ ok: false,
+ action: request.action,
+ errorCode: 'BROWSER_RUNTIME_UNAVAILABLE',
+ message: 'managed browser is shutting down; new calls are not accepted',
+ });
+ }
+ return this.withBackendIdentity(request, await this.enqueue(() => this.handleCall(request)));
+ }
+
+ /**
+ * Both backends identify themselves explicitly in `status`; the agent must
+ * not confuse the Cindy Chrome profile with the sidebar's embedded browser.
+ * Applied at the outer boundary so every status path — including the
+ * quiescence rejection and each route-liveness branch — carries it.
+ */
+ private withBackendIdentity(request: BackendRequest, result: BackendResult): BackendResult {
if (request.action !== 'status') return result;
- // Both backends identify themselves explicitly; the agent must not confuse
- // the Cindy Chrome profile with the sidebar's embedded browser.
const data = result.data && typeof result.data === 'object' ? result.data : {};
return { ...result, data: { ...data, backend: this.kind } };
}
+ /** Close the quit-time admission gate before enqueueing the final stop. */
+ beginQuiescence(): void {
+ this.quiescing = true;
+ }
+
+ async dispose(): Promise<void> {
+ return this.enqueue(async () => {
+ if (!this.used) return;
+ try {
+ const stopped = await this.stopBrowser({ action: 'stop' });
+ if (!stopped.ok) {
+ this.logger.warn('managed browser stop during dispose failed', {
+ errorCode: stopped.errorCode,
+ message: redactBrowserProxyText(stopped.message ?? ''),
+ });
+ }
+ } catch (err) {
+ this.routeBlocked = true;
+ this.logger.warn('managed browser stop during dispose threw', redactBrowserProxyText(err));
+ }
+ });
+ }
+
+ getEffectiveProxy(): ReturnType<typeof redactBrowserProxyRoute> {
+ return redactBrowserProxyRoute(this.route);
+ }
+
+ private async handleCall(request: BackendRequest): Promise<BackendResult> {
+ if (
+ (request.proxyServer !== undefined || request.proxyAllowedHostnames !== undefined)
+ && request.action !== 'start'
+ ) {
+ return invalidRequest(
+ request.action,
+ 'proxyServer and proxyAllowedHostnames are only valid for action=start',
+ );
+ }
+
+ // `start` is admitted through a TRANSIENT block. Such a block only means a
+ // readiness probe missed while the process stayed alive, and `startInRoute`
+ // has its own same-route liveness check that keeps the user's tabs. Without
+ // this, Settings' "打开 Agent 专用浏览器" — which calls `start` after seeing
+ // `running: false` — fails and tells the user to stop a browser that is
+ // actually healthy. A HARD block (auth failure, unverifiable stop, an
+ // untorn-down browser) still refuses everything but status/stop: there the
+ // route itself is untrusted and only a verified stop may lift it.
+ const transientBlock = this.routeBlocked && this.routeBlockedByUnprovenLiveness;
+ if (
+ this.routeBlocked
+ && request.action !== 'status'
+ && request.action !== 'stop'
+ && !(transientBlock && request.action === 'start')
+ ) {
+ return {
+ ok: false,
+ action: request.action,
+ errorCode: 'BROWSER_RUNTIME_UNAVAILABLE',
+ message: 'managed browser route is unknown after a failed restart; stop it before retrying',
+ };
+ }
+
+ if (request.action === 'start') {
+ let requested: BrowserProxyRoute;
+ try {
+ requested = parseBrowserProxyServer(
+ request.proxyServer,
+ request.proxyAllowedHostnames,
+ );
+ } catch (err) {
+ return invalidRequest(request.action, redactBrowserProxyText(err));
+ }
+ return this.startInRoute(requested);
+ }
+ if (request.action === 'stop') {
+ return this.stopBrowser(request);
+ }
+
+ // Many actions launch the browser implicitly — anything that resolves a tab
+ // goes through the vendored ensureTabAvailable/ensureBrowserAvailable path,
+ // not just open/tabs. Attributing such a launch requires knowing the
+ // browser was NOT already running before the call: then the process is ours
+ // and its route is this runtime's config. Without this, the next same-route
+ // `start` treats our own browser as a stranger and closes the user's tabs
+ // to "apply" a route already in effect.
+ //
+ // Infer from before/after status rather than an action allowlist: the list
+ // of launching actions is a vendored implementation detail that drifts.
+ // `runtimeOwnsNextLaunch` short-circuits the probe after a verified stop;
+ // the probe itself only runs while the route is unknown, so it costs at
+ // most one extra call per action until the first launch is attributed.
+ // `status` is excluded because it cannot launch anything and its own
+ // result already reports the state — probing before it would just double
+ // every status call.
+ //
+ // Absence must be VERIFIED, not inferred from readiness: a surviving Chrome
+ // whose probe timed out reads as stopped, and attributing its next action to
+ // this runtime would label a stranger's process with our route.
+ let mayOwnImplicitLaunch = false;
+ if (this.route === undefined && request.action !== 'status') {
+ if (this.runtimeOwnsNextLaunch) {
+ mayOwnImplicitLaunch = true;
+ } else if ((await this.resolveLiveness()) === 'gone') {
+ mayOwnImplicitLaunch = true;
+ } else {
+ // A process is alive but its route is unknown — e.g. Cindy restarted
+ // and inherited a Chrome launched by a previous proxied start. Skipping
+ // attribution is not enough: running the action anyway attaches to that
+ // process, so traffic egresses through the OLD proxy while this backend
+ // reports direct, and the previous instance's lifetime CDP request gate
+ // is gone with no way to reinstate it. Fail closed and require an
+ // explicit start (which adopts or replaces it) or a stop.
+ return {
+ ok: false,
+ action: request.action,
+ errorCode: 'BROWSER_RUNTIME_UNAVAILABLE',
+ message: 'managed browser route is unknown for a running browser; start or stop it before other actions',
+ };
+ }
+ }
+
+ const result = await this.runtime.call(this.withoutProxy(request));
+ if (typeof result.status === 'number') this.used = true;
+ // The auth coordinator's fail-closed teardown runs DETACHED from this queue
+ // (see BrowserProxyAuthCoordinator.teardown), so the route can become
+ // untrusted while this very call is awaiting the runtime — and the vendored
+ // availability path may meanwhile have auto-launched a replacement Chrome
+ // that never got a request gate. The admission guard above only protects
+ // calls that had not started yet, so re-check here and fail closed rather
+ // than handing back data from a browser we can no longer vouch for.
+ //
+ // `status` is deliberately exempt: it is handled below and must keep
+ // reporting — it is how the UI shows the blocked route, and how a merely
+ // transient block gets cleared again. (`start`/`stop` already returned.)
+ if (this.routeBlocked && request.action !== 'status') {
+ return {
+ ok: false,
+ action: request.action,
+ errorCode: 'BROWSER_RUNTIME_UNAVAILABLE',
+ message: 'managed browser route became untrusted during this call; stop it before retrying',
+ };
+ }
+ // Not gated on result.ok: an action can launch Chrome and *then* fail
+ // (e.g. snapshot resolves a tab before rejecting an invalid label/format
+ // combination). The browser is ours either way, so attribute from the
+ // post-call status rather than from whether the action succeeded.
+ if (this.route === undefined && mayOwnImplicitLaunch) {
+ // Most actions (`open` returns a tab object, `tabs` a list) carry no
+ // `running` field, so their state reads as 'unknown'. Ask `status`
+ // explicitly rather than inferring launch from a response shape.
+ const state = runningState(result) === 'running'
+ ? 'running'
+ : runningState(await this.runtime.call({ action: 'status' }));
+ if (state === 'running') {
+ this.route = this.runtimeRoute;
+ this.runtimeOwnsNextLaunch = false;
+ // An action can launch Chrome and then fail without a numeric status,
+ // which is what `used` is normally set from. Establishing a running
+ // browser here IS the proof that we own one, so record it or dispose()
+ // takes its `if (!this.used) return` path and leaves a headed Chrome
+ // alive after Cindy quits.
+ this.used = true;
+ }
+ }
+ if (request.action === 'status') {
+ // `status` is a PASSIVE poll (availability card, Settings login-browser
+ // check), so every branch here must be non-destructive — never the
+ // `Browser.close` that ownership verification uses.
+ const liveness = await this.resolveLiveness(result);
+ if (liveness === 'running') {
+ // Clear ONLY a block this path set from an unproven reading: the
+ // process is demonstrably alive on the route we still hold, so leaving
+ // it blocked would strand every action but status/stop forever. A block
+ // from auth failure or an unverifiable stop means the route itself is
+ // untrusted and must survive until a verified stop.
+ if (this.routeBlockedByUnprovenLiveness && this.route) {
+ this.routeBlocked = false;
+ this.routeBlockedByUnprovenLiveness = false;
+ }
+ return actionWithProxy(result, this.routeBlocked ? undefined : this.route);
+ }
+ if (liveness === 'gone') {
+ await this.disposeAuth();
+ this.resetStoppedRuntime();
+ return actionWithProxy(result, undefined);
+ }
+ // `unproven`: readiness says stopped but the process is not verifiably
+ // gone. Applies to DIRECT routes too — clearing a live direct route makes
+ // the next start treat our own browser as a stranger and close the user's
+ // tabs. Keep the route and refuse ordinary traffic until a verified stop.
+ if (this.route) {
+ // Only claim the transient flag when THIS branch is what blocks the
+ // route. A block already in place came from a cause only a verified
+ // stop may lift (auth failure, an unverifiable stop, an untorn-down
+ // browser); marking it transient here would let the next `running`
+ // status clear it above, re-admitting `tabs`/`navigate` on a process
+ // whose CDP request gate is already dead. Passive status polling from
+ // the availability card is enough to hit that sequence.
+ if (!this.routeBlocked) {
+ this.routeBlockedByUnprovenLiveness = true;
+ }
+ this.routeBlocked = true;
+ return actionWithProxy(result, this.route);
+ }
+ return actionWithProxy(result, undefined);
+ }
+ // The runtime can validate and quarantine pages, but it cannot verify that
+ // a browser process exited — only the host owns teardown. When it reports
+ // that every containment step failed and unvalidated pages may still be
+ // live, the route can no longer be trusted: block it until a verified stop.
+ // Not an `unproven liveness` block, so a later status must NOT clear it.
+ if (!result.ok && mentionsUntornDownBrowser(result.message)) {
+ this.routeBlocked = true;
+ this.routeBlockedByUnprovenLiveness = false;
+ // Blocking only stops FUTURE backend calls. The pages that survived
+ // containment are already loaded and keep executing and reaching the
+ // network — and in direct mode there is no lifetime request gate to catch
+ // them. The runtime cannot end a process; the host can, so do it here
+ // rather than leaving them live until someone happens to call stop.
+ try {
+ const stopped = await this.stopBrowser({ action: 'stop' });
+ if (!stopped.ok) {
+ this.logger.warn('browser teardown after popup containment failure could not be verified');
+ }
+ } catch (err) {
+ this.logger.warn(
+ 'browser teardown after popup containment failure threw',
+ redactBrowserProxyText(err),
+ );
+ }
+ // Deliberately NOT re-asserting the block afterwards. A verified stop
+ // means the surviving pages are gone, which is the whole objective here —
+ // there is nothing left to distrust, and resetStoppedRuntime has already
+ // cleared the route. If the stop could NOT be verified it leaves the
+ // block in place itself, which is the case that must stay blocked.
+ }
+ return result;
+ }
+
+ private async startInRoute(requested: BrowserProxyRoute): Promise<BackendResult> {
+ const requestedKey = browserProxyRouteKey(requested);
+ const currentStatus = await this.runtime.call({ action: 'status' });
+ if (typeof currentStatus.status === 'number') this.used = true;
+ const state = runningState(currentStatus);
+ // Defence in depth: `handleCall` already refuses `start` while the route is
+ // blocked, so this branch is not reachable in that state today. Keep the
+ // guard anyway — the idempotent shortcut must never hand back success for a
+ // route whose request gate is gone, and that invariant should not depend on
+ // an admission check several frames up staying exactly as it is.
+ // `running` is READINESS, not liveness: a busy browser reports false while
+ // very much alive. Falling through on that would take an owned, unchanged
+ // route into stopCurrentRuntime() and relaunch — destroying the user's open
+ // tabs to "apply" a route already in effect. So when the route matches,
+ // confirm the process is actually gone before treating this as a restart.
+ const sameRoute = this.route && browserProxyRouteKey(this.route) === requestedKey;
+ // Only a HARD block disqualifies the idempotent shortcut. A transient block
+ // means a readiness probe missed while the process stayed alive, which is
+ // precisely what the liveness check below re-establishes; treating it as
+ // disqualifying would relaunch — and destroy the user's tabs — every time
+ // Settings opens the agent browser after a busy-Chrome status poll.
+ const hardBlocked = this.routeBlocked && !this.routeBlockedByUnprovenLiveness;
+ const sameRouteAlive = sameRoute
+ && !hardBlocked
+ && (state === 'running' || (await this.resolveLiveness(currentStatus)) !== 'gone');
+ if (sameRouteAlive) {
+ // The process is confirmed alive on the route we still hold, so a block
+ // this path was allowed past — transient by definition — has served its
+ // purpose and must lift; otherwise ordinary traffic stays refused until
+ // some later status poll happens to clear it.
+ if (this.routeBlockedByUnprovenLiveness) {
+ this.routeBlocked = false;
+ this.routeBlockedByUnprovenLiveness = false;
+ }
+ return actionWithProxy({
+ ok: true,
+ action: 'start',
+ status: currentStatus?.status ?? 200,
+ data: currentStatus?.data,
+ }, this.route);
+ }
+
+ // An unowned/pre-existing process has an unknown route. Vendored `stop`
+ // cannot terminate it because process ownership is in-memory, so close it
+ // through the dedicated loopback browser CDP endpoint and verify it exited.
+ // `state === 'stopped'` only means the CDP readiness probe failed (the
+ // vendored status sets running:cdpReady), not that no process exists. An
+ // adopted Chrome whose handshake merely timed out would otherwise skip
+ // ownership cleanup here, and the new runtime's longer ensureBrowserAvailable
+ // retry could attach to that same process and report success — committing a
+ // route whose proxy/PAC launch arguments were never applied. Require
+ // verified absence before trusting 'stopped' on an unknown route.
+ const processMayExist = state !== 'stopped'
+ || (!this.route && (await this.resolveLiveness(currentStatus)) !== 'gone');
+
+ if (processMayExist && !this.route) {
+ const cdpHttpUrl = this.resolveCdpHttpUrl();
+ const expectedUserDataDir = this.resolveManagedUserDataDir();
+ if (!expectedUserDataDir) {
+ return {
+ ok: false,
+ action: 'start',
+ errorCode: 'BROWSER_RUNTIME_ACTION_FAILED',
+ message: 'cannot apply browser proxy route because the pre-existing browser identity cannot be verified',
+ };
+ }
+ const closed = await (this.options.closeAdoptedBrowser ?? closeAdoptedManagedBrowser)(
+ cdpHttpUrl,
+ expectedUserDataDir,
+ );
+ if (!closed) {
+ return {
+ ok: false,
+ action: 'start',
+ errorCode: 'BROWSER_RUNTIME_ACTION_FAILED',
+ message: 'cannot apply browser proxy route because the pre-existing managed browser could not be stopped',
+ };
+ }
+ await this.disposeAuth();
+ this.route = undefined;
+ } else if (processMayExist || this.route) {
+ const stopped = await this.stopCurrentRuntime();
+ if (!stopped.ok) return { ...stopped, action: 'start' };
+ }
+
+ const createRuntime = this.options.createRuntime;
+ if (!createRuntime) {
+ if (requested.mode === 'proxied') {
+ return invalidRequest('start', 'the active browser backend cannot apply proxyServer');
+ }
+ return invalidRequest('start', 'managed browser runtime factory is unavailable');
+ }
+
+ let nextRuntime: BackendRuntimeShape;
+ try {
+ nextRuntime = createRuntime(requested);
+ } catch (err) {
+ this.resetStoppedRuntime();
+ return {
+ ok: false,
+ action: 'start',
+ errorCode: 'BROWSER_RUNTIME_INVALID_REQUEST',
+ message: redactBrowserProxyText(err),
+ };
+ }
+ this.runtime = nextRuntime;
+ this.runtimeRoute = requested;
+ this.runtimeOwnsNextLaunch = false;
+ this.route = undefined;
+ this.used = true;
+ let started: BrowserControlResult;
+ try {
+ started = await nextRuntime.call({ action: 'start' });
+ } catch (err) {
+ await this.stopAndForget(nextRuntime);
+ return {
+ ok: false,
+ action: 'start',
+ errorCode: 'BROWSER_RUNTIME_ACTION_FAILED',
+ message: redactBrowserProxyText(err),
+ };
+ }
+ if (!started.ok) {
+ await this.stopAndForget(nextRuntime);
+ return {
+ ...started,
+ action: 'start',
+ message: redactBrowserProxyText(started.message ?? 'browser start failed'),
+ };
+ }
+ this.routeBlocked = false;
+
+ // Every proxied launch gets the lifetime CDP guard: it enforces the
+ // fail-closed HTTPS + hostname allowlist at the request level for all
+ // targets (startup tabs, popups, timer/meta-refresh navigations) and
+ // additionally answers proxy auth challenges when credentials exist.
+ if (requested.mode === 'proxied') {
+ const onFailure = () => {
+ this.routeBlocked = true;
+ // Not a readiness blip: the route is untrusted until a verified stop.
+ this.routeBlockedByUnprovenLiveness = false;
+ };
+ const coordinator = this.options.createProxyAuth?.(requested, this.logger, onFailure)
+ ?? new BrowserProxyAuthCoordinator(
+ requested,
+ this.logger,
+ onFailure,
+ undefined,
+ this.resolveManagedUserDataDir(),
+ );
+ try {
+ await coordinator.start(this.resolveCdpHttpUrl());
+ } catch (err) {
+ await coordinator.dispose();
+ await this.stopAndForget(nextRuntime);
+ return {
+ ok: false,
+ action: 'start',
+ errorCode: 'BROWSER_RUNTIME_ACTION_FAILED',
+ message: redactBrowserProxyText(err),
+ };
+ }
+ if (this.routeBlocked) {
+ await coordinator.dispose();
+ await this.stopAndForget(nextRuntime);
+ return {
+ ok: false,
+ action: 'start',
+ errorCode: 'BROWSER_RUNTIME_ACTION_FAILED',
+ message: 'proxy authentication failed while the managed browser was starting',
+ };
+ }
+ this.auth = coordinator;
+ }
+
+ this.route = requested;
+ return actionWithProxy(started, requested);
+ }
+
+ private async stopBrowser(request: BackendRequest): Promise<BackendResult> {
+ const result = await this.runtime.call(this.withoutProxy(request));
+ if (!result.ok) {
+ this.routeBlocked = true;
+ return actionWithProxy(result, this.route);
+ }
+
+ // `stopped: true` means "termination signals were sent", NOT "the process
+ // exited": stopOpenClawChrome breaks its wait as soon as proc.killed is set
+ // (which SIGTERM does synchronously), then SIGKILLs and returns without
+ // awaiting exit, and stopRunningBrowser reports stopped:true regardless.
+ // Readiness is not exit either — a busy Chrome reports running:false while
+ // still alive. Confirm absence independently before releasing the proxy
+ // guard, or a survivor keeps serving the old route while we reset to direct.
+ let stoppedSafely = (await this.resolveLiveness()) === 'gone';
+ // An adopted process (Cindy restarted while its managed Chrome stayed
+ // alive) cannot be terminated by the vendored stop: its ownership state is
+ // in-memory and empty, so `stop` reports ok with stopped:false forever.
+ // Fall back to the same verified CDP close `start` uses, otherwise the
+ // backend is stuck until the user closes Chrome by hand.
+ if (!stoppedSafely && !this.route) {
+ stoppedSafely = await this.closeAdoptedBrowserIfManaged();
+ }
+ if (stoppedSafely) {
+ await this.disposeAuth();
+ this.resetStoppedRuntime();
+ // The vendored result can still say stopped:false when the status probe
+ // or adopted-process cleanup is what proved the exit. Report what was
+ // actually verified, so callers do not retry a completed stop.
+ return actionWithProxy({
+ ...result,
+ data: { ...(result.data as Record<string, unknown> | undefined), stopped: true },
+ }, undefined);
+ }
+ this.routeBlocked = true;
+ return actionWithProxy({
+ ok: false,
+ action: 'stop',
+ errorCode: 'BROWSER_RUNTIME_ACTION_FAILED',
+ message: 'managed browser stop could not be verified',
+ }, this.route);
+ }
+
/**
- * Quit-time cleanup. Stops the managed Chrome process so it does not outlive
- * the app. Delegates to `stopRuntimeForQuit`, which logs-and-swallows so the
- * disposer chain cannot stall here.
- *
- * Idempotent: a follow-up `stop` against an already-stopped runtime is a
- * no-op at the vendored layer; safe to call multiple times across backend
- * switches and app quit.
+ * Close a pre-existing managed browser through the loopback CDP endpoint,
+ * verifying profile identity first. Returns false when identity cannot be
+ * established or the process would not exit, so callers stay fail-closed.
*/
- dispose(): Promise<void> {
- return stopRuntimeForQuit(this.runtime, this.logger);
+ /**
+ * Whether the managed browser is verifiably gone, without touching it.
+ * Fails closed: an endpoint that answers, or an inconclusive probe, means
+ * "still running".
+ */
+ /**
+ * Resolve process liveness once, so no caller has to decide for itself
+ * whether a `'stopped'` readiness signal can be trusted. Pass the result of a
+ * call that already carries state to avoid a redundant `status` round trip.
+ */
+ private async resolveLiveness(known?: BrowserControlResult): Promise<Liveness> {
+ const cheap = known ? runningState(known) : 'unknown';
+ if (cheap === 'running') return 'running';
+ const state = cheap === 'unknown'
+ ? runningState(await this.runtime.call({ action: 'status' }))
+ : cheap;
+ if (state === 'running') return 'running';
+ // Readiness says stopped/unknown — that is not proof of absence, so ask the
+ // non-destructive probe. Anything short of verified absence is `unproven`.
+ return (await this.confirmBrowserGone()) ? 'gone' : 'unproven';
+ }
+
+ private async confirmBrowserGone(): Promise<boolean> {
+ try {
+ return await (this.options.isBrowserGone ?? isManagedBrowserGone)(
+ this.resolveCdpHttpUrl(),
+ );
+ } catch (err) {
+ this.logger.warn('managed browser liveness probe failed', redactBrowserProxyText(err));
+ return false;
+ }
+ }
+
+ private async closeAdoptedBrowserIfManaged(): Promise<boolean> {
+ const expectedUserDataDir = this.resolveManagedUserDataDir();
+ if (!expectedUserDataDir) return false;
+ try {
+ return await (this.options.closeAdoptedBrowser ?? closeAdoptedManagedBrowser)(
+ this.resolveCdpHttpUrl(),
+ expectedUserDataDir,
+ );
+ } catch (err) {
+ this.logger.warn('managed browser adopted close failed', redactBrowserProxyText(err));
+ return false;
+ }
+ }
+
+ private async stopCurrentRuntime(): Promise<BackendResult> {
+ const stopped = await this.runtime.call({ action: 'stop' });
+ if (!stopped.ok) {
+ this.routeBlocked = true;
+ this.logger.warn('managed browser route transition stop failed', {
+ errorCode: stopped.errorCode,
+ message: redactBrowserProxyText(stopped.message ?? ''),
+ });
+ return {
+ ok: false,
+ action: 'start',
+ errorCode: 'BROWSER_RUNTIME_ACTION_FAILED',
+ message: 'cannot change browser proxy route because the current browser could not be stopped',
+ };
+ }
+ // Require verified absence before handing the route to a new launch. The
+ // vendored `stopped: true` only means signals were sent, so it cannot skip
+ // this check: a survivor would keep serving the old route under a new one.
+ if ((await this.resolveLiveness()) !== 'gone') {
+ this.routeBlocked = true;
+ return {
+ ok: false,
+ action: 'start',
+ errorCode: 'BROWSER_RUNTIME_ACTION_FAILED',
+ message: 'cannot change browser proxy route because a pre-existing browser process could not be stopped',
+ };
+ }
+ await this.disposeAuth();
+ return stopped;
+ }
+
+ private async stopAndForget(runtime: BackendRuntimeShape): Promise<void> {
+ let stoppedSafely = true;
+ try {
+ const stopped = await runtime.call({ action: 'stop' });
+ if (!stopped.ok) {
+ stoppedSafely = false;
+ } else {
+ // resolveLiveness() probes the shared managed endpoint, which is what
+ // this runtime launched — readiness alone would again mistake a busy
+ // browser for an exited one, and the vendored `stopped: true` only
+ // reports that signals were sent, not that the process exited.
+ stoppedSafely = (await this.resolveLiveness()) === 'gone';
+ }
+ } catch (err) {
+ stoppedSafely = false;
+ this.logger.warn('managed browser cleanup after failed start threw', redactBrowserProxyText(err));
+ }
+ if (this.runtime === runtime) {
+ if (stoppedSafely) {
+ this.resetStoppedRuntime(true);
+ } else {
+ // The runtime may still be configured for the requested route even
+ // though the route never committed; remember that the next verified
+ // stop must rebuild a direct runtime instead of trusting `route`.
+ this.route = undefined;
+ this.used = true;
+ this.routeBlocked = true;
+ this.forceDirectOnReset = true;
+ }
+ }
+ }
+
+ private resetStoppedRuntime(forceDirect = false): void {
+ const replaceWithDirect =
+ forceDirect || this.forceDirectOnReset || this.route?.mode === 'proxied';
+ this.route = undefined;
+ this.used = false;
+ this.routeBlockedByUnprovenLiveness = false;
+ // The browser was verifiably stopped while we held this runtime, so the
+ // next launch through it is ours and its route is known.
+ this.runtimeOwnsNextLaunch = true;
+ if (!replaceWithDirect) {
+ this.routeBlocked = false;
+ return;
+ }
+ const createRuntime = this.options.createRuntime;
+ if (!createRuntime) {
+ this.routeBlocked = true;
+ return;
+ }
+ try {
+ this.runtime = createRuntime({ mode: 'direct' });
+ this.runtimeRoute = { mode: 'direct' };
+ this.routeBlocked = false;
+ this.forceDirectOnReset = false;
+ } catch (err) {
+ this.routeBlocked = true;
+ this.logger.warn('managed browser direct runtime reset failed', redactBrowserProxyText(err));
+ }
+ }
+
+ private async disposeAuth(): Promise<void> {
+ const auth = this.auth;
+ this.auth = undefined;
+ await auth?.dispose();
+ }
+
+ private withoutProxy(request: BackendRequest): BrowserControlRequest {
+ const {
+ proxyServer: _proxyServer,
+ proxyAllowedHostnames: _proxyAllowedHostnames,
+ ...rest
+ } = request;
+ return rest;
+ }
+
+ private enqueue<T>(operation: () => Promise<T>): Promise<T> {
+ const result = this.transition.then(operation, operation);
+ this.transition = result.then(() => undefined, () => undefined);
+ return result;
}
}
diff --git a/apps/desktop/src/main/mcp-integrations/browser-backend/proxy-auth.ts b/apps/desktop/src/main/mcp-integrations/browser-backend/proxy-auth.ts
new file mode 100644
index 0000000000..1ff24c09ed
--- /dev/null
+++ b/apps/desktop/src/main/mcp-integrations/browser-backend/proxy-auth.ts
@@ -0,0 +1,938 @@
+import { execFile } from 'node:child_process';
+import { createConnection } from 'node:net';
+import { promisify } from 'node:util';
+
+import WebSocket from 'ws';
+
+import { findPortOwnerPids, killPortOwner } from '../../cindy-brain/portReclaim.js';
+
+import {
+ isBrowserProxyRequestUrlAllowedAsync,
+ managedProfilePidOwnsCdpPort,
+ pidIsManagedChromeForProfile,
+ readManagedProfileOwnerPid,
+ type BrowserProxyRoute,
+ type LookupFn,
+} from '@cindy/browser-control-runtime';
+
+type CdpResponse = {
+ id?: number;
+ result?: unknown;
+ error?: { message?: string };
+ method?: string;
+ params?: Record<string, unknown>;
+ sessionId?: string;
+};
+
+type Pending = {
+ resolve: (value: unknown) => void;
+ reject: (error: Error) => void;
+ timer: ReturnType<typeof setTimeout>;
+};
+
+const execFileAsync = promisify(execFile);
+
+const COMMAND_TIMEOUT_MS = 10_000;
+
+/**
+ * Target types that can originate network requests and therefore need their own
+ * Fetch gate: interception is per target/session, so a worker without it would
+ * reach the proxy unfiltered. Non-network targets are merely resumed.
+ */
+const NETWORK_CAPABLE_TARGET_TYPES = new Set([
+ 'page',
+ 'iframe',
+ 'service_worker',
+ 'shared_worker',
+ 'worker',
+ 'shared_storage_worklet',
+ 'worklet',
+]);
+
+function isNetworkCapableTargetType(type: unknown): boolean {
+ return typeof type === 'string' && NETWORK_CAPABLE_TARGET_TYPES.has(type);
+}
+
+async function fetchBrowserWebSocketUrl(cdpHttpUrl: string): Promise<string> {
+ const base = new URL(cdpHttpUrl);
+ if (
+ base.protocol !== 'http:'
+ || !['127.0.0.1', 'localhost', '[::1]', '::1'].includes(base.hostname)
+ ) {
+ throw new Error('managed browser CDP endpoint must be loopback HTTP');
+ }
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), COMMAND_TIMEOUT_MS);
+ try {
+ const response = await fetch(`${base.toString().replace(/\/$/, '')}/json/version`, {
+ signal: controller.signal,
+ });
+ if (!response.ok) throw new Error('CDP endpoint unavailable');
+ const body = (await response.json()) as { webSocketDebuggerUrl?: unknown };
+ if (typeof body.webSocketDebuggerUrl !== 'string' || !body.webSocketDebuggerUrl) {
+ throw new Error('CDP websocket endpoint unavailable');
+ }
+ const ws = new URL(body.webSocketDebuggerUrl);
+ if (
+ ws.protocol !== 'ws:'
+ || !['127.0.0.1', 'localhost', '[::1]', '::1'].includes(ws.hostname)
+ || ws.port !== base.port
+ || !ws.pathname.startsWith('/devtools/browser/')
+ || ws.username
+ || ws.password
+ || ws.search
+ || ws.hash
+ ) {
+ throw new Error('CDP websocket endpoint is not the managed loopback browser');
+ }
+ return ws.toString();
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+async function isCdpReachable(cdpHttpUrl: string): Promise<boolean> {
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), 250);
+ try {
+ const response = await fetch(`${cdpHttpUrl.replace(/\/$/, '')}/json/version`, {
+ signal: controller.signal,
+ });
+ return response.ok;
+ } catch {
+ return false;
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+/**
+ * How long the CDP endpoint must stay continuously unreachable before the
+ * browser counts as gone.
+ *
+ * A single failed probe only proves the endpoint did not answer within its
+ * timeout, which a busy-but-alive Chrome also produces; a short burst of
+ * failures proves little more. Requiring an uninterrupted unreachable window
+ * distinguishes a real exit from a stall, at the cost of a bounded delay on
+ * the (already slow) teardown path. Any successful probe resets the window.
+ */
+/**
+ * Upper bound on tracked proxy-auth challenges. Sized well above any realistic
+ * number of simultaneously-challenging requests so eviction only ever reclaims
+ * entries whose requests are long finished.
+ */
+const MAX_TRACKED_AUTH_ATTEMPTS = 512;
+
+const CDP_GONE_CONFIRM_WINDOW_MS = 1_500;
+const CDP_GONE_PROBE_INTERVAL_MS = 100;
+
+/**
+ * Whether no live Chrome owns the managed profile.
+ *
+ * The CDP port is the floor, on every platform. A bare TCP connect (not an HTTP
+ * request) is what separates "process gone" from "process busy": accepting a
+ * connection happens in the socket layer, so a Chrome stalled on its main
+ * thread still completes it while failing to answer `/json/version`.
+ *
+ * The profile's SingletonLock is deliberately NOT consulted here. It cannot
+ * substitute for the port in either direction:
+ * - null does not mean absent — `readCurrentHostSingletonPid` also returns
+ * null when the lock is missing, unreadable, malformed, or records another
+ * hostname, all reachable with a live browser. Windows never writes one at
+ * all. Trusting null would report `gone` and let the request guard be
+ * disposed while Chrome still serves the old route.
+ * - a live PID does not mean present — the lock survives a crash and the OS
+ * recycles PIDs, so it can name an unrelated process and block the route
+ * until that process exits or the user clears the lock by hand.
+ *
+ * The lock is still used for TERMINATION, where it supplies a candidate PID —
+ * but there it is paired with a command-line identity check before anything is
+ * signalled.
+ */
+async function confirmNoManagedChromeProcess(cdpHttpUrl: string): Promise<boolean> {
+ return !(await isCdpPortListening(cdpHttpUrl));
+}
+
+/**
+ * Whether a command line carries this exact argument, respecting token
+ * boundaries.
+ *
+ * A substring test is not sufficient: `--user-data-dir=/p/Cindy` is a prefix of
+ * `--user-data-dir=/p/Cindy-backup`, so `includes` would accept an unrelated
+ * browser and hand it to a process kill. The argument must be delimited by
+ * whitespace or quotes on both sides (or sit at a string edge).
+ */
+export function commandLineHasExactArgument(commandLine: string, argument: string): boolean {
+ let offset = commandLine.indexOf(argument);
+ while (offset >= 0) {
+ const before = offset === 0 ? '' : commandLine[offset - 1];
+ const after = commandLine[offset + argument.length] ?? '';
+ if ((!before || /[\s"']/.test(before)) && (!after || /[\s"']/.test(after))) return true;
+ offset = commandLine.indexOf(argument, offset + 1);
+ }
+ return false;
+}
+
+/**
+ * Windows command-line identity for a PID.
+ *
+ * The vendored `readManagedProcessCommandLine` only implements Linux (/proc)
+ * and macOS (ps), returning null on win32 — so the shared identity verifier
+ * always answers "not ours" there, which would silently disable the very
+ * teardown this platform needs. Query Win32_Process for the command line so
+ * the same profile/port proof can be applied.
+ *
+ * Returns null on any failure, so callers treat an unknown identity as "do not
+ * signal" rather than assuming ownership.
+ */
+async function readWindowsProcessCommandLine(pid: number): Promise<string | null> {
+ try {
+ const powershell = `${process.env.SystemRoot ?? 'C:\\Windows'}`
+ + '\\System32\\WindowsPowerShell\\v1.0\\powershell.exe';
+ const { stdout } = await execFileAsync(
+ powershell,
+ [
+ '-NoProfile',
+ '-NonInteractive',
+ '-Command',
+ `$p = Get-CimInstance Win32_Process -Filter "ProcessId=${pid}" -ErrorAction Stop; `
+ + 'if ($p) { [string]$p.CommandLine }',
+ ],
+ { encoding: 'utf8', timeout: 5_000, windowsHide: true, maxBuffer: 64 * 1024 },
+ );
+ const text = stdout.trim();
+ return text === '' ? null : text;
+ } catch {
+ return null;
+ }
+}
+
+/** Whether a PID is a Chrome launched for exactly this profile and CDP port. */
+async function isManagedChromeProcess(params: {
+ pid: number;
+ cdpPort: number;
+ userDataDir: string;
+}): Promise<boolean> {
+ if (process.platform !== 'win32') {
+ return pidIsManagedChromeForProfile(params);
+ }
+ const commandLine = await readWindowsProcessCommandLine(params.pid);
+ if (!commandLine) return false;
+ // Same two proofs the POSIX path requires: our profile AND our debug port.
+ // Exact-argument matching, not substring: `--user-data-dir=<dir>` is a prefix
+ // of `--user-data-dir=<dir>-backup`, and this result feeds `taskkill /T /F`.
+ return commandLineHasExactArgument(commandLine, `--user-data-dir=${params.userDataDir}`)
+ && commandLineHasExactArgument(commandLine, `--remote-debugging-port=${params.cdpPort}`);
+}
+
+/**
+ * Whether anything still holds the CDP port.
+ *
+ * Deliberately a bare TCP connect, not an HTTP request: accepting a connection
+ * is handled by the OS/socket layer, so a Chrome stalled on its main thread
+ * still completes it while failing to answer `/json/version`. That difference
+ * is the whole point — it separates "process gone" from "process busy".
+ */
+async function isCdpPortListening(cdpHttpUrl: string): Promise<boolean> {
+ let target: URL;
+ try {
+ target = new URL(cdpHttpUrl);
+ } catch {
+ return false;
+ }
+ const port = Number(target.port || 80);
+ const host = target.hostname.replace(/^\[|\]$/g, '');
+ return await new Promise<boolean>((resolve) => {
+ let settled = false;
+ const finish = (listening: boolean) => {
+ if (settled) return;
+ settled = true;
+ try { socket.destroy(); } catch { /* best effort */ }
+ resolve(listening);
+ };
+ const socket = createConnection({ port, host });
+ socket.setTimeout(1_000);
+ socket.once('connect', () => finish(true));
+ socket.once('timeout', () => finish(true)); // reachable but unresponsive
+ socket.once('error', () => finish(false));
+ });
+}
+
+/**
+ * Whether the CDP endpoint is verifiably gone, not merely slow to answer.
+ * Fails closed: if the window cannot be established before the deadline, the
+ * caller must treat the browser as still running.
+ */
+async function confirmCdpGone(cdpHttpUrl: string): Promise<boolean> {
+ const deadline = Date.now() + COMMAND_TIMEOUT_MS;
+ let unreachableSince: number | undefined;
+ while (Date.now() < deadline) {
+ if (await isCdpReachable(cdpHttpUrl)) {
+ unreachableSince = undefined;
+ } else {
+ unreachableSince ??= Date.now();
+ if (Date.now() - unreachableSince >= CDP_GONE_CONFIRM_WINDOW_MS) {
+ // Endpoint silence is not process death: a Chrome stalled on its main
+ // thread stops answering while still alive, and calling that "gone"
+ // releases the request gate and lets the survivor be re-attributed to a
+ // new route. Require the OS to agree before declaring an exit.
+ return await confirmNoManagedChromeProcess(cdpHttpUrl);
+ }
+ }
+ await new Promise((resolve) => setTimeout(resolve, CDP_GONE_PROBE_INTERVAL_MS));
+ }
+ return false;
+}
+
+/**
+ * Close an adopted browser through its browser-level CDP endpoint.
+ *
+ * Vendored `stop` cannot terminate a process that predates its in-memory
+ * ownership state. A route transition must not re-adopt such a process and
+ * claim the new route, so the host explicitly closes it and verifies the CDP
+ * listener is gone before relaunching.
+ */
+/**
+ * Non-destructive liveness probe: whether the managed browser's CDP endpoint
+ * is verifiably gone. Issues no commands, so it is safe on passive paths such
+ * as a status poll — unlike {@link closeAdoptedManagedBrowser}, which proves
+ * ownership by actually closing the browser.
+ */
+export async function isManagedBrowserGone(cdpHttpUrl: string): Promise<boolean> {
+ return await confirmCdpGone(cdpHttpUrl);
+}
+
+export async function closeAdoptedManagedBrowser(
+ cdpHttpUrl: string,
+ expectedUserDataDir: string,
+): Promise<boolean> {
+ let wsUrl: string;
+ try {
+ wsUrl = await fetchBrowserWebSocketUrl(cdpHttpUrl);
+ } catch {
+ // A failed handshake does not prove the browser exited — the endpoint may
+ // be briefly unavailable while Chrome is busy. Treating that as "stopped"
+ // would unblock the route and mis-report a surviving process (possibly on
+ // an unknown proxy route) as direct. Require the endpoint to stay
+ // unreachable across the full quiescence window before claiming success.
+ return await confirmCdpGone(cdpHttpUrl);
+ }
+
+ const socket = new WebSocket(wsUrl, { handshakeTimeout: COMMAND_TIMEOUT_MS });
+ let commandSent = false;
+ const expectedCdpPort = new URL(cdpHttpUrl).port || '80';
+ const closeRequested = new Promise<boolean>((resolve) => {
+ const timer = setTimeout(() => {
+ try { socket.terminate(); } catch { /* best effort */ }
+ resolve(false);
+ }, COMMAND_TIMEOUT_MS);
+ const finish = (value: boolean) => {
+ clearTimeout(timer);
+ resolve(value);
+ };
+ socket.once('open', () => {
+ // SystemInfo.getInfo exposes the browser command line over CDP. Verify
+ // both Cindy's stable profile path and this listener's port before
+ // closing an adopted process; a loopback DevTools endpoint alone does
+ // not establish ownership.
+ // https://chromedevtools.github.io/devtools-protocol/tot/SystemInfo/#method-getInfo
+ socket.send(JSON.stringify({ id: 1, method: 'SystemInfo.getInfo' }), (error) => {
+ if (error) finish(false);
+ });
+ });
+ socket.on('message', (data) => {
+ try {
+ const message = JSON.parse(Buffer.isBuffer(data) ? data.toString('utf8') : String(data)) as CdpResponse;
+ if (message.id === 1) {
+ const commandLine = (message.result as { commandLine?: unknown } | undefined)?.commandLine;
+ const owned = typeof commandLine === 'string'
+ && commandLineHasExactArgument(commandLine, `--remote-debugging-port=${expectedCdpPort}`)
+ && commandLineHasExactArgument(commandLine, `--user-data-dir=${expectedUserDataDir}`);
+ if (!owned) {
+ finish(false);
+ return;
+ }
+ commandSent = true;
+ socket.send(JSON.stringify({ id: 2, method: 'Browser.close' }), (error) => {
+ if (error) finish(false);
+ });
+ } else if (message.id === 2) {
+ finish(!message.error);
+ }
+ } catch {
+ // Ignore unrelated/malformed events while Chrome is exiting.
+ }
+ });
+ socket.once('close', () => finish(commandSent));
+ socket.once('error', () => finish(false));
+ });
+ const requested = await closeRequested;
+ if (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING) {
+ try { socket.close(); } catch { /* best effort */ }
+ }
+ if (!requested) return false;
+
+ return await confirmCdpGone(cdpHttpUrl);
+}
+
+/**
+ * Lifetime CDP guard for a proxied browser launch.
+ *
+ * CDP Fetch is enabled on every network-capable target (startup tabs, popups,
+ * subframes, and workers — interception is per session, so a worker without
+ * its own gate would reach the proxy unfiltered) for the whole browser
+ * lifetime, and every paused request is checked against the fail-closed launch
+ * policy: HTTPS only, to a hostname on the per-start allowlist. HTTP proxy authentication rides the
+ * same channel — challenges are answered in memory with Fetch.continueWithAuth
+ * so credentials never reach Chrome's command line.
+ *
+ * Known limitation: CDP Fetch does not intercept WebSocket handshakes, so WS
+ * egress is not blocked at this layer (navigation-level guards still gate the
+ * pages that could open one).
+ */
+export class BrowserProxyAuthCoordinator {
+ private socket: WebSocket | undefined;
+ private nextId = 1;
+ private readonly pending = new Map<number, Pending>();
+ private readonly authAttempts = new Map<string, number>();
+ private readonly sessions = new Set<string>();
+ private readonly targetSetups = new Map<string, Promise<void>>();
+ private readonly sessionTargets = new Map<string, string>();
+ private readonly eventTasks = new Set<Promise<void>>();
+ private closing = false;
+ private failed = false;
+ private cdpHttpUrl: string | undefined;
+ /**
+ * In-flight failClosed() work. It runs detached from the backend's serial
+ * queue, so dispose() must await it: otherwise a `stop` + `start` can land a
+ * new Chrome on the same profile/port while the old cleanup is still running,
+ * and that cleanup would then terminate the replacement.
+ */
+ private teardown: Promise<void> | undefined;
+
+ constructor(
+ private readonly route: BrowserProxyRoute,
+ private readonly logger: { warn(message: string, ...args: unknown[]): void },
+ private readonly onFailure: () => void = () => {},
+ /** Test seam only; production uses the platform resolver. */
+ private readonly lookupFn?: LookupFn,
+ /** Managed profile path; required to close the browser if our socket dies. */
+ private readonly managedUserDataDir?: string,
+ ) {}
+
+ private get hasCredentials(): boolean {
+ return this.route.username !== undefined || this.route.password !== undefined;
+ }
+
+ async start(cdpHttpUrl: string): Promise<void> {
+ if (this.route.mode !== 'proxied') return;
+ // Retained for teardown: if this coordinator's own socket dies, closing the
+ // browser needs an endpoint it can reach over a fresh connection.
+ this.cdpHttpUrl = cdpHttpUrl;
+ let wsUrl: string;
+ try {
+ wsUrl = await fetchBrowserWebSocketUrl(cdpHttpUrl);
+ } catch {
+ throw new Error('proxy authentication setup could not reach the managed browser');
+ }
+
+ const socket = new WebSocket(wsUrl, { handshakeTimeout: COMMAND_TIMEOUT_MS });
+ this.socket = socket;
+ socket.on('message', (data) => this.handleMessage(data));
+ socket.on('error', (error) => {
+ if (!this.closing) {
+ this.logger.warn('browser proxy authentication channel failed', { error: String(error) });
+ this.rejectPending(new Error('proxy authentication channel failed'));
+ void this.beginTeardown();
+ }
+ });
+ socket.on('close', () => {
+ if (!this.closing) {
+ this.rejectPending(new Error('proxy authentication channel closed'));
+ void this.beginTeardown();
+ }
+ });
+ await new Promise<void>((resolve, reject) => {
+ const onOpen = () => {
+ cleanup();
+ resolve();
+ };
+ const onError = () => {
+ cleanup();
+ reject(new Error('proxy authentication channel could not open'));
+ };
+ const onClose = () => {
+ cleanup();
+ reject(new Error('proxy authentication channel closed before setup'));
+ };
+ const cleanup = () => {
+ socket.off('open', onOpen);
+ socket.off('error', onError);
+ socket.off('close', onClose);
+ };
+ socket.once('open', onOpen);
+ socket.once('error', onError);
+ socket.once('close', onClose);
+ });
+
+ await this.command('Target.setDiscoverTargets', { discover: true });
+ await this.command('Target.setAutoAttach', {
+ autoAttach: true,
+ waitForDebuggerOnStart: true,
+ flatten: true,
+ });
+ const targets = await this.command('Target.getTargets') as {
+ targetInfos?: Array<{ targetId?: string; type?: string }>;
+ };
+ for (const target of targets.targetInfos ?? []) {
+ if (target.targetId && isNetworkCapableTargetType(target.type)) {
+ await this.attach(target.targetId);
+ }
+ }
+ // CDP messages are ordered on the browser WebSocket. A final command acts
+ // as a barrier: every auto-attach event received before its response has
+ // registered an event task, which must settle before startup is committed.
+ await this.command('Target.getTargets');
+ await this.drainEventTasks();
+ if (this.failed) throw new Error('proxy authentication setup failed');
+ }
+
+ async dispose(): Promise<void> {
+ // Settle any detached teardown BEFORE marking this coordinator closed, so
+ // the caller cannot start a replacement browser while old cleanup is still
+ // able to kill it. Awaited first because failClosed() itself bails once
+ // `closing` is set — flipping the flag first would abandon work midway.
+ const teardown = this.teardown;
+ this.teardown = undefined;
+ if (teardown) await teardown.catch(() => undefined);
+ this.closing = true;
+ this.rejectPending(new Error('proxy authentication channel closed'));
+ const socket = this.socket;
+ this.socket = undefined;
+ if (socket && (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING)) {
+ try {
+ socket.close();
+ } catch {
+ // Socket teardown is best effort.
+ }
+ }
+ this.sessions.clear();
+ this.authAttempts.clear();
+ this.targetSetups.clear();
+ this.sessionTargets.clear();
+ this.eventTasks.clear();
+ }
+
+ private async attach(targetId: string): Promise<void> {
+ const existing = this.targetSetups.get(targetId);
+ if (existing) return existing;
+ let result: { sessionId?: string };
+ try {
+ result = await this.command('Target.attachToTarget', { targetId, flatten: true }) as {
+ sessionId?: string;
+ };
+ } catch (error) {
+ // A target can disappear between discovery and attachment, while an
+ // auto-attach event can also win the race and prepare it first. Recheck
+ // both states; a still-live network-capable target without the Fetch gate
+ // must fail startup rather than being silently skipped.
+ const targets = await this.command('Target.getTargets') as {
+ targetInfos?: Array<{ targetId?: string; type?: string }>;
+ };
+ await this.drainEventTasks();
+ const autoAttached = this.targetSetups.get(targetId);
+ if (autoAttached) {
+ await autoAttached;
+ return;
+ }
+ const stillLive = (targets.targetInfos ?? []).some(
+ (target) => target.targetId === targetId && isNetworkCapableTargetType(target.type),
+ );
+ if (stillLive) throw error;
+ return;
+ }
+ // Once attachment succeeds, Fetch.enable is part of the authentication
+ // readiness handshake. Propagate failure so start fails closed rather than
+ // reporting an authenticated route with no challenge handler installed.
+ if (result.sessionId) await this.setupTarget(targetId, result.sessionId);
+ }
+
+ private setupTarget(targetId: string, sessionId: string): Promise<void> {
+ const existing = this.targetSetups.get(targetId);
+ if (existing) return existing;
+ const setup = (async () => {
+ this.sessionTargets.set(sessionId, targetId);
+ await this.enableFetch(sessionId);
+ // Auto-attach only covers targets related to the session it was set on,
+ // so the browser-level call does NOT reach a page's own dedicated/shared
+ // workers. Without this recursion such a worker never raises
+ // attachedToTarget, never gets Fetch enabled, and its HTTPS requests skip
+ // the DNS/private-address gate entirely — leaving only the hostname-only
+ // PAC. Playwright does the same thing (setAutoAttach per page session and
+ // per worker session, crPage.js), which is what makes nested targets
+ // reachable at all.
+ //
+ // Before runIfWaitingForDebugger: a target paused at start must not be
+ // resumed until its own children will be caught too.
+ await this.command('Target.setAutoAttach', {
+ autoAttach: true,
+ waitForDebuggerOnStart: true,
+ flatten: true,
+ }, sessionId);
+ // This is harmless for an already-running target and is required for
+ // auto-attached targets paused before their first network request. Do
+ // not resume when Fetch setup fails: the page must never run without
+ // the authenticated-proxy challenge handler installed.
+ await this.command('Runtime.runIfWaitingForDebugger', {}, sessionId);
+ })();
+ this.targetSetups.set(targetId, setup);
+ setup.catch(() => {
+ if (this.targetSetups.get(targetId) === setup) this.targetSetups.delete(targetId);
+ this.sessionTargets.delete(sessionId);
+ });
+ return setup;
+ }
+
+ private async enableFetch(sessionId: string): Promise<void> {
+ if (this.sessions.has(sessionId)) return;
+ this.sessions.add(sessionId);
+ try {
+ await this.command('Fetch.enable', { handleAuthRequests: this.hasCredentials }, sessionId);
+ } catch (error) {
+ this.sessions.delete(sessionId);
+ throw error;
+ }
+ }
+
+ private handleMessage(data: WebSocket.RawData): void {
+ let message: CdpResponse;
+ try {
+ message = JSON.parse(Buffer.isBuffer(data) ? data.toString('utf8') : String(data)) as CdpResponse;
+ } catch {
+ return;
+ }
+ if (typeof message.id === 'number') {
+ const pending = this.pending.get(message.id);
+ if (!pending) return;
+ this.pending.delete(message.id);
+ clearTimeout(pending.timer);
+ if (message.error?.message) pending.reject(new Error('CDP proxy authentication command failed'));
+ else pending.resolve(message.result);
+ return;
+ }
+ const task = this.handleEvent(message);
+ this.eventTasks.add(task);
+ void task.finally(() => this.eventTasks.delete(task)).catch(() => {});
+ }
+
+ private async handleEvent(message: CdpResponse): Promise<void> {
+ const params = message.params ?? {};
+ if (message.method === 'Target.attachedToTarget') {
+ const sessionId = typeof params.sessionId === 'string' ? params.sessionId : undefined;
+ const targetInfo = params.targetInfo as { targetId?: string; type?: string } | undefined;
+ if (sessionId) {
+ try {
+ if (isNetworkCapableTargetType(targetInfo?.type) && targetInfo?.targetId) {
+ await this.setupTarget(targetInfo.targetId, sessionId);
+ } else {
+ await this.command('Runtime.runIfWaitingForDebugger', {}, sessionId);
+ }
+ } catch {
+ this.logger.warn('browser proxy authentication could not prepare a new browser target');
+ // Through the shared task, not failClosed() directly. During startup
+ // this is awaited by start(); afterwards it runs as a loose event
+ // task, so a teardown begun here must be visible to dispose() —
+ // otherwise a stop+start can land a replacement browser that this
+ // cleanup then kills.
+ await this.beginTeardown();
+ }
+ }
+ return;
+ }
+ if (message.method === 'Target.detachedFromTarget') {
+ const sessionId = typeof params.sessionId === 'string' ? params.sessionId : undefined;
+ if (sessionId) {
+ this.sessions.delete(sessionId);
+ const targetId = this.sessionTargets.get(sessionId);
+ this.sessionTargets.delete(sessionId);
+ if (targetId) this.targetSetups.delete(targetId);
+ for (const key of this.authAttempts.keys()) {
+ if (key.startsWith(`${sessionId}:`)) this.authAttempts.delete(key);
+ }
+ }
+ return;
+ }
+ if (message.method === 'Fetch.requestPaused') {
+ const requestId = typeof params.requestId === 'string' ? params.requestId : undefined;
+ if (requestId && message.sessionId) {
+ // Lifetime request-level enforcement of the fail-closed launch policy:
+ // HTTPS to an allowlisted hostname continues; everything else fails
+ // before egress, regardless of how the navigation was initiated
+ // (startup tab, manual address bar, timer, meta refresh, popup).
+ const request = params.request as { url?: unknown } | undefined;
+ const requestUrl = typeof request?.url === 'string' ? request.url : '';
+ const allowed = await isBrowserProxyRequestUrlAllowedAsync(requestUrl, this.route, {
+ ...(this.lookupFn ? { lookupFn: this.lookupFn } : {}),
+ });
+ try {
+ if (allowed) {
+ await this.command('Fetch.continueRequest', { requestId }, message.sessionId);
+ } else {
+ await this.command(
+ 'Fetch.failRequest',
+ { requestId, errorReason: 'BlockedByClient' },
+ message.sessionId,
+ );
+ }
+ } catch {
+ // The request may have been cancelled while the browser restarted.
+ }
+ }
+ return;
+ }
+ if (message.method === 'Fetch.authRequired') {
+ const requestId = typeof params.requestId === 'string' ? params.requestId : undefined;
+ const challenge = params.authChallenge as { source?: string } | undefined;
+ if (!requestId || !message.sessionId) return;
+ const attemptKey = `${message.sessionId}:${requestId}`;
+ const attempts = (this.authAttempts.get(attemptKey) ?? 0) + 1;
+ this.authAttempts.set(attemptKey, attempts);
+ this.evictOldestAuthAttempts();
+ const response = challenge?.source !== 'Proxy'
+ ? 'Default'
+ : this.hasCredentials && attempts === 1
+ ? 'ProvideCredentials'
+ : 'CancelAuth';
+ try {
+ await this.command(
+ 'Fetch.continueWithAuth',
+ {
+ requestId,
+ authChallengeResponse: {
+ response,
+ ...(response === 'ProvideCredentials'
+ ? { username: this.route.username ?? '', password: this.route.password ?? '' }
+ : {}),
+ },
+ },
+ message.sessionId,
+ );
+ } catch {
+ // The request failure is surfaced by the browser navigation itself.
+ }
+ if (response !== 'ProvideCredentials') this.authAttempts.delete(attemptKey);
+ }
+ }
+
+ /**
+ * Bound the challenge-attempt map without depending on CDP event ordering.
+ *
+ * There is no documented guarantee that `Fetch.requestPaused` follows the
+ * `Fetch.authRequired` for a given request, nor that it fires exactly once,
+ * so it cannot serve as a completion signal: deleting on it could drop a
+ * live counter and let a repeat challenge re-send credentials. Instead cap
+ * the map and evict oldest-first — Map preserves insertion order, and only
+ * the newest entries can belong to challenges still in flight. The cap is
+ * far above any plausible concurrent-challenge count, so a real retry is
+ * never evicted before its second challenge arrives.
+ */
+ private evictOldestAuthAttempts(): void {
+ while (this.authAttempts.size > MAX_TRACKED_AUTH_ATTEMPTS) {
+ const oldest = this.authAttempts.keys().next();
+ if (oldest.done) return;
+ this.authAttempts.delete(oldest.value);
+ }
+ }
+
+ /**
+ * Start teardown once, and keep the promise that is actually doing the work.
+ *
+ * A dropped socket fires `error` and then `close`, so this runs twice. The
+ * second `failClosed()` returns immediately — `failed` is set synchronously
+ * before its first await — and assigning that already-resolved promise over
+ * `this.teardown` would make `dispose()` await nothing, reopening the window
+ * where a replacement browser gets killed by the old cleanup. Only the first
+ * call's promise is retained.
+ */
+ private beginTeardown(): Promise<void> {
+ this.teardown ??= this.failClosed();
+ // Returned so callers that CAN wait (the startup path) do, while
+ // fire-and-forget callers still register the same task for dispose().
+ return this.teardown;
+ }
+
+ private async failClosed(): Promise<void> {
+ if (this.failed || this.closing) return;
+ this.failed = true;
+ // Block the host route before attempting browser teardown. Browser.close
+ // can itself fail if the CDP channel is already unhealthy; the host must
+ // still refuse ordinary traffic until a later stop is verified.
+ this.onFailure();
+ await this.command('Browser.close').catch(() => {});
+ // The common failure IS a dead socket — command() rejects outright when the
+ // channel is not OPEN, so the call above is a no-op precisely when teardown
+ // matters most. Blocking the host only stops future host calls; pages and
+ // workers already running keep their network access, and with this guard
+ // gone the DNS/private-address check is gone with it, leaving the
+ // hostname-only PAC. Close over a fresh connection instead.
+ await this.closeBrowserWithoutOwnSocket();
+ }
+
+ /**
+ * Terminate the browser without relying on this coordinator's socket.
+ *
+ * `closeAdoptedManagedBrowser` dials the CDP endpoint anew and verifies exit,
+ * so it still works when our own channel has dropped. Ownership is checked
+ * against the managed profile there, so this cannot close a stranger.
+ */
+ private async closeBrowserWithoutOwnSocket(): Promise<void> {
+ const cdpHttpUrl = this.cdpHttpUrl;
+ const expectedUserDataDir = this.managedUserDataDir;
+ if (!cdpHttpUrl || !expectedUserDataDir) return;
+ let closed = false;
+ try {
+ closed = await closeAdoptedManagedBrowser(cdpHttpUrl, expectedUserDataDir);
+ } catch {
+ closed = false;
+ }
+ if (closed) return;
+ // A `false` return is not an edge case here — it is the expected outcome
+ // when CDP itself is the thing that broke. Leaving it there keeps a browser
+ // running whose Fetch gate died with the connection: blocking new host
+ // calls does nothing about pages that are already loaded and still
+ // reaching the network. Every CDP-based remedy has now failed, so fall
+ // through to the OS.
+ await this.terminateManagedChromeProcess(expectedUserDataDir);
+ }
+
+ /**
+ * Terminate the managed browser without CDP, then verify it is gone.
+ *
+ * Only reachable once both the coordinator's socket and a fresh CDP
+ * connection have failed.
+ *
+ * The lock records a PID; it does not prove that PID is still Chrome. A crash
+ * can leave the lock behind and the OS recycles PIDs, so signalling on the
+ * lock alone can SIGKILL an unrelated process — the one failure here that is
+ * worse than doing nothing. Require positive identity first: the PID must
+ * actually hold the CDP port. No probe, no signal (Windows has neither lock
+ * nor probe), leaving the host's verified-stop requirement as the backstop.
+ */
+ private async terminateManagedChromeProcess(managedUserDataDir: string): Promise<void> {
+ // Belt-and-braces against killing a replacement browser. dispose() awaits
+ // this work before it flips `closing`, so the ordinary path cannot race;
+ // this covers a dispose that lands while the await chain is already
+ // unwinding. Every identity check below would PASS for a legitimately
+ // restarted Chrome — same profile, same port — so "is it ours" cannot
+ // distinguish the two and only sequencing can.
+ if (this.closing) return;
+ const cdpPort = Number(new URL(this.cdpHttpUrl ?? 'http://127.0.0.1:18800').port || 80);
+ const pid = readManagedProfileOwnerPid(managedUserDataDir);
+ if (pid === null) {
+ // No usable lock. Windows never writes one, but this is also reached on
+ // macOS/Linux when the lock is missing, unreadable, or names a dead PID —
+ // so this path is not Windows-only and cannot assume anything about the
+ // platform.
+ //
+ // Resolve the owner from the loopback CDP port, then VERIFY it. Holding
+ // the port is not identity: Chrome may have exited and any other program
+ // can take a fixed port, and there is a reuse window between the lookup
+ // and the kill. So each candidate must present a command line carrying
+ // both our --user-data-dir and our --remote-debugging-port, re-checked
+ // immediately before signalling.
+ //
+ // killPortOwner refuses protected/self PIDs and uses `taskkill /T`, which
+ // matters because Chrome's renderer children would otherwise be orphaned.
+ const reclaimLogger = {
+ info: (message: string, meta?: Record<string, unknown>) => this.logger.warn(message, meta),
+ warn: (message: string, meta?: Record<string, unknown>) => this.logger.warn(message, meta),
+ };
+ for (const owner of await findPortOwnerPids(cdpPort)) {
+ if (!(await isManagedChromeProcess({
+ pid: owner,
+ cdpPort,
+ userDataDir: managedUserDataDir,
+ }))) {
+ this.logger.warn('skipping CDP port owner: not the managed browser', { pid: owner });
+ continue;
+ }
+ await killPortOwner(owner, reclaimLogger);
+ }
+ // Issuing the kill is not exit. taskkill can fail on permissions, lose a
+ // race, or return an error, and killPortOwner reports that as false —
+ // which the loop above deliberately does not act on per-PID, since a
+ // partial failure still leaves the port to check. Verify centrally
+ // instead: if the port is still held, nothing was actually torn down and
+ // the caller must keep treating this route as untrusted.
+ if (await isCdpPortListening(this.cdpHttpUrl ?? 'http://127.0.0.1:18800')) {
+ this.logger.warn(
+ 'managed browser survived proxy-guard teardown; route stays blocked until a verified stop',
+ );
+ }
+ return;
+ }
+ // Port ownership alone is not identity — verify the process is a Chrome
+ // launched for THIS profile and port before signalling it.
+ const lockedPidIsOurs = async (): Promise<boolean> => managedProfilePidOwnsCdpPort(pid, cdpPort)
+ && await isManagedChromeProcess({ pid, cdpPort, userDataDir: managedUserDataDir });
+ if (!(await lockedPidIsOurs())) {
+ this.logger.warn(
+ 'skipping managed browser termination: locked PID is not the managed browser',
+ );
+ return;
+ }
+ for (const signal of ['SIGTERM', 'SIGKILL'] as const) {
+ // Revalidate at the TOP of each iteration, immediately before signalling.
+ // Checking after the kill and before the sleep is not equivalent: the
+ // window that matters is the delay itself, during which SIGTERM can take
+ // effect and the OS can hand the PID to something else. A verdict taken
+ // before that wait is stale by the time SIGKILL is sent.
+ if (!(await lockedPidIsOurs())) return;
+ try {
+ process.kill(pid, signal);
+ } catch {
+ // Already gone, or not ours to signal; the next check is the arbiter.
+ }
+ await new Promise((resolve) => setTimeout(resolve, 250));
+ }
+ if (readManagedProfileOwnerPid(managedUserDataDir) !== null) {
+ this.logger.warn(
+ 'managed browser survived proxy-guard teardown; route stays blocked until a verified stop',
+ );
+ }
+ }
+
+ private async drainEventTasks(): Promise<void> {
+ await Promise.allSettled([...this.eventTasks]);
+ }
+
+ private command(method: string, params?: Record<string, unknown>, sessionId?: string): Promise<unknown> {
+ const socket = this.socket;
+ if (!socket || socket.readyState !== WebSocket.OPEN) {
+ return Promise.reject(new Error('proxy authentication channel is not open'));
+ }
+ const id = this.nextId++;
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => {
+ this.pending.delete(id);
+ reject(new Error('proxy authentication command timed out'));
+ }, COMMAND_TIMEOUT_MS);
+ this.pending.set(id, { resolve, reject, timer });
+ try {
+ socket.send(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }));
+ } catch {
+ clearTimeout(timer);
+ this.pending.delete(id);
+ reject(new Error('proxy authentication command failed'));
+ }
+ });
+ }
+
+ private rejectPending(error: Error): void {
+ for (const [id, pending] of this.pending) {
+ clearTimeout(pending.timer);
+ pending.reject(error);
+ this.pending.delete(id);
+ }
+ }
+}
diff --git a/apps/desktop/src/main/mcp-integrations/browser-backend/rsb-webview-backend.ts b/apps/desktop/src/main/mcp-integrations/browser-backend/rsb-webview-backend.ts
index 3a85877810..7e987ee2c8 100644
--- a/apps/desktop/src/main/mcp-integrations/browser-backend/rsb-webview-backend.ts
+++ b/apps/desktop/src/main/mcp-integrations/browser-backend/rsb-webview-backend.ts
@@ -363,6 +363,13 @@ export class RsbWebviewBackend implements BrowserBackend {
return this.handleDoctor(request);
case 'start':
case 'stop':
+ if (request.proxyServer !== undefined) {
+ return actionFailed(
+ request.action,
+ 'proxyServer is unsupported by the embedded browser backend; switch to the managed browser backend',
+ 'BROWSER_RUNTIME_INVALID_REQUEST',
+ );
+ }
// Webview lifecycle is owned by the RSB itself — these are no-ops.
return actionOk(request.action, { ready: true });
case 'profiles':
diff --git a/apps/desktop/src/main/mcp-integrations/browser-managed-config.ts b/apps/desktop/src/main/mcp-integrations/browser-managed-config.ts
index 81204fb4db..40eef8988a 100644
--- a/apps/desktop/src/main/mcp-integrations/browser-managed-config.ts
+++ b/apps/desktop/src/main/mcp-integrations/browser-managed-config.ts
@@ -1,4 +1,9 @@
-import type { BrowserRuntimeConfig } from '@cindy/browser-control-runtime';
+import nodePath from 'node:path';
+
+import {
+ parseBrowserProxyServer,
+ type BrowserRuntimeConfig,
+} from '@cindy/browser-control-runtime';
/**
* Managed profile identity. The profile key is the on-disk folder
@@ -55,6 +60,33 @@ const MANAGED_DRIVER = 'openclaw' as const;
*/
export const MANAGED_CDP_PORT = 18800;
+/** Loopback CDP URL + on-disk profile used by the request-gate coordinator. */
+export function managedBrowserGuardIdentity(input: {
+ runtimeDir: string;
+ useRealProfile: boolean;
+ cdpPort?: number;
+}): { cdpHttpUrl: string; managedUserDataDir: string } {
+ const profile = input.useRealProfile ? REAL_MANAGED_PROFILE : MANAGED_PROFILE;
+ const cdpPort = input.cdpPort ?? MANAGED_CDP_PORT;
+ return {
+ cdpHttpUrl: `http://127.0.0.1:${cdpPort}`,
+ managedUserDataDir: nodePath.join(input.runtimeDir, 'browser', profile, 'user-data'),
+ };
+}
+
+export interface ManagedBrowserConfigOptions {
+ /** Credential-free launch proxy URL. Credentials stay in the host auth coordinator. */
+ proxyServer?: string;
+ /** Public DNS patterns allowed for page navigation through the explicit proxy. */
+ proxyAllowedHostnames?: readonly string[];
+ /** Consent-gated snapshot of the user's everyday browser logins. */
+ useRealProfile?: boolean;
+ /** Chromium binary for the snapshot profile; omitted for the isolated profile. */
+ executablePath?: string;
+ /** Override the managed CDP port (used when Cindy-real relocates off 18800). */
+ cdpPort?: number;
+}
+
/**
* Default ("managed") config: a single playwright-launched Chrome profile, headed,
* with a STABLE persistent user-data-dir (logins survive across sessions). This is
@@ -72,24 +104,160 @@ export const MANAGED_CDP_PORT = 18800;
* remain in force. The dedicated profile and consented login-copy rules stay
* independent of network reachability.
*/
-export function buildManagedConfig(options?: {
- useRealProfile?: boolean;
- executablePath?: string;
- cdpPort?: number;
-}): BrowserRuntimeConfig {
- const useRealProfile = options?.useRealProfile === true;
+/**
+ * Launch arguments for a proxied start.
+ *
+ * The CDP guard cannot attach until Chrome's DevTools endpoint is up, so a
+ * persistent profile restoring tabs (or starting a service worker) could emit
+ * requests through the proxy during that window. Chrome therefore enforces the
+ * allowlist itself from process start: a PAC script routes allowlisted hosts to
+ * the proxy and returns an unreachable directive for everything else, so
+ * pre-attach requests fail instead of egressing.
+ *
+ * PAC is the ONLY proxy flag. Chromium picks exactly one proxy mode from the
+ * command line, in fixed precedence (`--no-proxy-server`, then
+ * `--proxy-pac-url`, then `--proxy-auto-detect`, then `--proxy-server`;
+ * ChromeCommandLinePrefStore::ApplyProxyMode), so a `--proxy-server` next to
+ * the PAC would be dead configuration — and a reader who trusted it would
+ * expect fixed-proxy semantics the browser never applies. The proxy address
+ * lives inside the PAC directive instead, and the vendored mode detection
+ * treats `--proxy-pac-url` as an explicit proxy route on its own.
+ *
+ * PAC is a launch-time floor, not the ceiling: the CDP guard still applies the
+ * HTTPS-only rule, the same allowlist, and DNS-answer verification per request
+ * once attached. Because CDP Fetch never sees WebSocket handshakes, PAC is
+ * also the only layer that can refuse a private-address WSS target.
+ */
+function buildProxyLaunchArgs(
+ proxyServer: string,
+ allowedHostnames: readonly string[] | undefined,
+): string[] {
+ const patterns = allowedHostnames ?? [];
+ // JSON-encode every host pattern: PAC is JavaScript, so the allowlist must
+ // never be interpolated as raw source.
+ const allowlistLiteral = JSON.stringify(patterns);
+ const proxyLiteral = JSON.stringify(proxyServerToPacDirective(proxyServer));
+ const pac = [
+ 'function FindProxyForURL(url, host){',
+ `var a=${allowlistLiteral};`,
+ // Encrypted-only, matching the CDP guard: a cleartext request must fail at
+ // the launch floor too, not just once the coordinator has attached.
+ // Chrome passes WebSocket URLs to PAC with their ws:/wss: scheme intact
+ // (verified against Chrome 151), so wss:// must be admitted explicitly or
+ // real-time apps on allowlisted hosts break — and CDP Fetch cannot rescue
+ // them, since it does not intercept WebSocket handshakes.
+ 'var u=String(url||"").toLowerCase();',
+ 'if(u.slice(0,8)!=="https://"&&u.slice(0,6)!=="wss://")return "PROXY 0.0.0.0:0";',
+ 'host=(host||"").toLowerCase().replace(/\\.+$/,"");',
+ // PAC-side address check. CDP Fetch never sees this traffic during the
+ // pre-attach window, and never sees WebSocket handshakes at all, so the
+ // request-level DNS gate in proxy.ts cannot cover either path.
+ //
+ // dnsResolve / isInNet are Netscape PAC builtins that Chromium implements:
+ // https://chromium.googlesource.com/chromium/src/+/HEAD/net/docs/proxy.md
+ // https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Proxy_servers_and_tunneling/Proxy_Auto-Configuration_PAC_file
+ // dnsResolve is IPv4-only and returns "" on failure. Empty / unresolvable
+ // answers fail closed (same as the CDP DNS gate). 198.18.0.0/15 is exempt
+ // to match allowRfc2544BenchmarkRange (Clash/Surge/sing-box fake-IP).
+ 'function v4b(ip){',
+ 'if(isInNet(ip,"198.18.0.0","255.254.0.0"))return false;',
+ 'return isInNet(ip,"0.0.0.0","255.0.0.0")||isInNet(ip,"10.0.0.0","255.0.0.0")||isInNet(ip,"127.0.0.0","255.0.0.0")||isInNet(ip,"169.254.0.0","255.255.0.0")||isInNet(ip,"172.16.0.0","255.240.0.0")||isInNet(ip,"192.168.0.0","255.255.0.0")||isInNet(ip,"100.64.0.0","255.192.0.0")||isInNet(ip,"192.0.0.0","255.255.255.0")||isInNet(ip,"192.0.2.0","255.255.255.0")||isInNet(ip,"198.51.100.0","255.255.255.0")||isInNet(ip,"203.0.113.0","255.255.255.0")||isInNet(ip,"224.0.0.0","240.0.0.0")||isInNet(ip,"240.0.0.0","240.0.0.0");',
+ '}',
+ 'function blocked(){',
+ 'var h=host;if(h.charAt(0)==="[")h=h.slice(1,h.length-1);',
+ 'if(h.indexOf(":")>=0){',
+ 'if(h==="::1"||h==="0:0:0:0:0:0:0:1")return true;',
+ 'if(h.slice(0,5)==="fe80:")return true;',
+ 'if(h.indexOf("::ffff:")===0)return v4b(h.slice(7));',
+ 'return false;',
+ '}',
+ 'var ip=dnsResolve(host);',
+ 'if(!ip)return true;',
+ 'return v4b(ip);',
+ '}',
+ 'for(var i=0;i<a.length;i++){',
+ 'var p=a[i].toLowerCase();',
+ 'if(p.indexOf("*.")===0){var s=p.slice(2);',
+ 'if(s&&host!==s&&host.length>s.length&&host.slice(-(s.length+1))==="."+s){',
+ `if(blocked())return "PROXY 0.0.0.0:0";return ${proxyLiteral};}}`,
+ 'else if(host===p){',
+ `if(blocked())return "PROXY 0.0.0.0:0";return ${proxyLiteral};}`,
+ '}',
+ // No DIRECT fallback: a blocked host must fail, never leak around the proxy.
+ 'return "PROXY 0.0.0.0:0";',
+ '}',
+ ].join('');
+ return [
+ `--proxy-pac-url=data:application/x-ns-proxy-autoconfig;base64,${Buffer.from(pac, 'utf8').toString('base64')}`,
+ // WebRTC negotiates over UDP outside the HTTP/SOCKS proxy, so neither the
+ // PAC nor the CDP request gate observes it: an allowlisted page could open
+ // an RTCPeerConnection and disclose the machine's real IP while the route
+ // reports "proxied". This policy suppresses host candidates that would not
+ // traverse the proxy (verified on Chrome 151: the LAN-IP host candidate is
+ // emitted without it and absent with it). Note the flag has NO `--force-`
+ // prefix — `--force-webrtc-ip-handling-policy` is silently ignored.
+ '--webrtc-ip-handling-policy=disable_non_proxied_udp',
+ ];
+}
+
+/** Render a canonical proxy URL as a PAC return directive. */
+function proxyServerToPacDirective(proxyServer: string): string {
+ const parsed = new URL(proxyServer);
+ // `host` keeps IPv6 brackets (`[::1]:1080`). `hostname` strips them, which
+ // produces an invalid PAC SOCKS/PROXY token.
+ const hostPort = parsed.host;
+ switch (parsed.protocol) {
+ case 'https:':
+ return `HTTPS ${hostPort}`;
+ case 'socks5:':
+ case 'socks:':
+ return `SOCKS5 ${hostPort}`;
+ case 'socks4:':
+ return `SOCKS ${hostPort}`;
+ default:
+ return `PROXY ${hostPort}`;
+ }
+}
+
+export function buildManagedConfig(options: ManagedBrowserConfigOptions = {}): BrowserRuntimeConfig {
+ const route = parseBrowserProxyServer(options.proxyServer, options.proxyAllowedHostnames);
+ const proxyServer = route.mode === 'proxied' ? route.server : undefined;
+ const useRealProfile = options.useRealProfile === true;
const defaultProfile = useRealProfile ? REAL_MANAGED_PROFILE : MANAGED_PROFILE;
- const executablePath = options?.executablePath;
- const cdpPort = options?.cdpPort ?? MANAGED_CDP_PORT;
+ const executablePath = options.executablePath;
+ const cdpPort = options.cdpPort ?? MANAGED_CDP_PORT;
return {
browser: {
enabled: true,
defaultProfile,
headless: false, // headed so the user can see + log into sites
...(executablePath ? { executablePath } : {}),
- ssrfPolicy: {
- dangerouslyAllowPrivateNetwork: true,
- },
+ ...(proxyServer ? { extraArgs: buildProxyLaunchArgs(proxyServer, route.allowedHostnames) } : {}),
+ // Two different contracts, so two different policies:
+ // - DIRECT is the agent's own browser, where reaching the intranet is a
+ // deliberate product decision (see the posture note above).
+ // - PROXIED is an explicit "only these public hosts, through this
+ // operator-chosen egress" contract. Granting private-network access
+ // there would contradict the allowlist the caller just asked for, and
+ // would leave the per-request DNS check as the only layer catching an
+ // allowlisted name that resolves inward.
+ //
+ // The ONLY exemption proxied mode keeps is RFC 2544's 198.18.0.0/15,
+ // which Clash/Surge/sing-box hand out as fake IPs. That range is
+ // reserved for benchmarking, so nothing legitimate is reachable there
+ // and exempting it cannot expose a real service. IPv6 ULA
+ // (`allowIpv6UniqueLocalRange`) is deliberately NOT exempted: fc00::/7
+ // is where real internal services live, the flag cannot tell a fake IP
+ // from one of them, and a mixed public-A/private-AAAA record would
+ // otherwise pass the PAC's IPv4 `dnsResolve` check and then be accepted
+ // on its private AAAA. Whatever is forwarded here must match the proxy
+ // request gate in proxy.ts, so both layers judge a hostname alike.
+ ssrfPolicy: route.mode === 'proxied'
+ ? {
+ allowRfc2544BenchmarkRange: true,
+ ...(route.allowedHostnames ? { hostnameAllowlist: [...route.allowedHostnames] } : {}),
+ }
+ : { dangerouslyAllowPrivateNetwork: true },
profiles: {
[defaultProfile]: {
driver: MANAGED_DRIVER,
diff --git a/apps/desktop/src/main/mcp-integrations/browser.ts b/apps/desktop/src/main/mcp-integrations/browser.ts
index 5476c1a434..9b59f8da62 100644
--- a/apps/desktop/src/main/mcp-integrations/browser.ts
+++ b/apps/desktop/src/main/mcp-integrations/browser.ts
@@ -12,6 +12,7 @@ import { app, ipcMain } from 'electron';
import {
createBrowserControlRuntime,
setBrowserControlRuntimeConfig,
+ type BrowserProxyRoute,
type BrowserControlRuntime,
} from '@cindy/browser-control-runtime';
@@ -19,13 +20,13 @@ import { createLogger } from '../logger.js';
import { extractBrowserAvailability, type BrowserAvailability } from './browser-availability.js';
import { loadUserBrowserRecipes, type UserRecipesResult } from '../browser-recipes/loader.js';
import { writeUserRecipe, type WriteUserRecipeResult } from '../browser-recipes/writer.js';
-import { stopRuntimeForQuitIfUsed, trackBrowserRuntimeUsage } from './browser-dispose.js';
import {
BrowserBackendController,
BrowserBackendHealthService,
ExternalChromeBackend,
RsbWebviewBackend,
type BackendKind,
+ type BrowserBackend,
} from './browser-backend/index.js';
import { getRsbBrowserBridge } from '../rsb-browser-bridge/index.js';
import {
@@ -40,16 +41,22 @@ import {
setActiveRsbSessionId,
} from '../rsb-browser-bridge/active-session.js';
import { requireObject, optionalNullableString } from '../utils/ipcValidate.js';
-import { buildManagedConfig, MANAGED_PROFILE } from './browser-managed-config.js';
import {
- activeManagedProfileName,
+ buildManagedConfig,
+ MANAGED_CDP_PORT,
+ MANAGED_PROFILE,
+ managedBrowserGuardIdentity,
+ type ManagedBrowserConfigOptions,
+} from './browser-managed-config.js';
+import {
+ assertManagedBrowserStopped,
cleanupCopiedLoginsThen,
+ RealProfileError,
createBrowserProfileLifecycleQueue,
managedConfigPatchBeforeStop,
FOREIGN_AGENT_BROWSER_ERROR,
probeOsSourceProfileReadAccess,
readCopiedLoginsCdpPort,
- stopManagedBrowserForProfile,
wrapRuntimeWithRealProfile,
wrapRuntimeWithProfileLifecycleQueue,
} from './browser-real-profile/index.js';
@@ -97,58 +104,147 @@ function realProfileRuntimeDir(): string {
return process.env.XDT_BROWSER_RUNTIME_DIR ?? '';
}
+const browserRuntimeLogSink = (
+ level: 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal',
+ scope: string,
+ args: unknown[],
+) => {
+ const hostLevel = level === 'trace' ? 'debug' : level === 'fatal' ? 'error' : level;
+ const fn = (logger[hostLevel] ?? logger.info).bind(logger);
+ fn(`[${scope}]`, ...args);
+};
+
+/** Last proxy launch options, so real-profile applyConfig cannot drop them. */
+let lastProxyLaunch: {
+ proxyServer?: string;
+ proxyAllowedHostnames?: readonly string[];
+} = {};
+
+/** Last applied profile identity, so the CDP guard follows Cindy-real / relocated ports. */
+let lastManagedIdentity = {
+ useRealProfile: false,
+ cdpPort: MANAGED_CDP_PORT,
+};
+
+function rememberManagedIdentity(opts: ManagedBrowserConfigOptions): void {
+ if (typeof opts.useRealProfile === 'boolean') {
+ lastManagedIdentity.useRealProfile = opts.useRealProfile;
+ if (!opts.useRealProfile && opts.cdpPort === undefined) {
+ lastManagedIdentity.cdpPort = MANAGED_CDP_PORT;
+ }
+ }
+ if (typeof opts.cdpPort === 'number') {
+ lastManagedIdentity.cdpPort = opts.cdpPort;
+ }
+}
+
+function currentGuardIdentity(): { cdpHttpUrl: string; managedUserDataDir?: string } {
+ const runtimeDir = realProfileRuntimeDir();
+ if (!runtimeDir) {
+ return { cdpHttpUrl: `http://127.0.0.1:${lastManagedIdentity.cdpPort}` };
+ }
+ return managedBrowserGuardIdentity({
+ runtimeDir,
+ useRealProfile: lastManagedIdentity.useRealProfile,
+ cdpPort: lastManagedIdentity.cdpPort,
+ });
+}
+
+function applyManagedConfig(opts: ManagedBrowserConfigOptions): void {
+ if ('proxyServer' in opts || 'proxyAllowedHostnames' in opts) {
+ lastProxyLaunch = {
+ proxyServer: opts.proxyServer,
+ proxyAllowedHostnames: opts.proxyAllowedHostnames,
+ };
+ }
+ const merged = { ...lastProxyLaunch, ...opts };
+ rememberManagedIdentity(merged);
+ setBrowserControlRuntimeConfig(buildManagedConfig(merged));
+}
+
+function currentRealProfileLaunchOpts(): {
+ useRealProfile: boolean;
+ cdpPort?: number;
+} {
+ const useRealProfile = readBrowserBackendSettings().useRealProfile === true;
+ const remembered = useRealProfile ? readCopiedLoginsCdpPort(realProfileRuntimeDir()) : null;
+ return {
+ useRealProfile,
+ ...(remembered ? { cdpPort: remembered } : {}),
+ };
+}
+
+function wrapManagedRuntime(inner: BrowserControlRuntime) {
+ return wrapRuntimeWithRealProfile(inner, {
+ isEnabled: () => readBrowserBackendSettings().useRealProfile,
+ getRuntimeDir: realProfileRuntimeDir,
+ applyConfig: (opts) => {
+ applyManagedConfig({ ...lastProxyLaunch, ...opts });
+ },
+ });
+}
+
+/** Create an immutable-config runtime for one managed-browser launch route. */
+function createManagedRuntime(route: BrowserProxyRoute): BrowserControlRuntime {
+ lastProxyLaunch = {
+ proxyServer: route.mode === 'proxied' ? route.server : undefined,
+ proxyAllowedHostnames: route.allowedHostnames,
+ };
+ const merged = {
+ ...currentRealProfileLaunchOpts(),
+ ...lastProxyLaunch,
+ };
+ rememberManagedIdentity(merged);
+ return wrapManagedRuntime(
+ createBrowserControlRuntime({
+ config: buildManagedConfig(merged),
+ logSink: browserRuntimeLogSink,
+ }),
+ ) as BrowserControlRuntime;
+}
+
const initialUseRealProfile = readBrowserBackendSettings().useRealProfile;
const rememberedCopiedLoginsCdpPort = initialUseRealProfile
? readCopiedLoginsCdpPort(realProfileRuntimeDir())
: null;
-
-// Single shared runtime for the desktop process. Boots with the managed profile
-// (electron-free, safe at module-eval); logs route into the unified logger.
-//
-// `vendoredRuntime` is the raw upstream object behind a thin usage-tracking
-// wrapper (see `trackBrowserRuntimeUsage`): every consumer in this module —
-// the `ExternalChromeBackend` (behind the lifecycle controller, which is what
-// @cindy/mcps via `getBrowserMcpDeps` and host helpers below receive), the
-// availability probe and the login helper — calls through the wrapper, so
-// `disposeBrowserRuntime` can tell whether the runtime saw ANY traffic this
-// session. We never hand the raw object out; swapping the active backend in
-// Backend switching and recovery stay behind the process-wide controller.
-const vendoredRuntime = trackBrowserRuntimeUsage(
- createBrowserControlRuntime({
- config: buildManagedConfig({
- useRealProfile: initialUseRealProfile,
- ...(rememberedCopiedLoginsCdpPort ? { cdpPort: rememberedCopiedLoginsCdpPort } : {}),
- }),
- logSink: (level, scope, args) => {
- // Bind to `logger`: the unified logger's methods rely on `this`, and calling
- // a detached `logger[level]` reference would lose it (undefined in strict
- // mode) and silently break the browser runtime's log channel.
- const fn = (logger[level] ?? logger.info).bind(logger);
- fn(`[${scope}]`, ...args);
- },
+lastManagedIdentity = {
+ useRealProfile: initialUseRealProfile === true,
+ cdpPort: rememberedCopiedLoginsCdpPort ?? MANAGED_CDP_PORT,
+};
+
+const directBrowserRuntime = createBrowserControlRuntime({
+ config: buildManagedConfig({
+ proxyServer: undefined,
+ useRealProfile: initialUseRealProfile,
+ ...(rememberedCopiedLoginsCdpPort ? { cdpPort: rememberedCopiedLoginsCdpPort } : {}),
}),
+ logSink: browserRuntimeLogSink,
+});
+
+const externalChromeBackend = new ExternalChromeBackend(
+ wrapManagedRuntime(directBrowserRuntime),
+ logger,
+ {
+ createRuntime: createManagedRuntime,
+ cdpHttpUrl: () => currentGuardIdentity().cdpHttpUrl,
+ managedUserDataDir: () => currentGuardIdentity().managedUserDataDir,
+ },
);
/**
- * Consent-gated snapshot wrapper sits *outside* usage tracking: a failed
- * copy must not count as "runtime used", or quit-time `stop` would boot
- * Playwright just to shut it down.
+ * Real-profile consent switches (`setBrowserUseRealProfile`, reset, quit) must
+ * be serialized with every external-browser call. The backend serializes its
+ * own calls, but a consent switch stops the browser and swaps directories, so
+ * it must not interleave with a call the backend has already admitted: the
+ * queue wraps the backend from outside. Code that already runs inside the
+ * queue talks to `externalChromeBackend` directly (re-entering would deadlock).
*/
-const realProfileRuntime = wrapRuntimeWithRealProfile(vendoredRuntime, {
- isEnabled: () => readBrowserBackendSettings().useRealProfile,
- getRuntimeDir: realProfileRuntimeDir,
- applyConfig: (opts) => {
- setBrowserControlRuntimeConfig(buildManagedConfig(opts));
- },
-});
-
const browserProfileLifecycleQueue = createBrowserProfileLifecycleQueue();
-const externalRuntime = wrapRuntimeWithProfileLifecycleQueue(
- realProfileRuntime,
- browserProfileLifecycleQueue,
-);
-
-const externalBackend = new ExternalChromeBackend(externalRuntime, logger);
+const externalBackend: BrowserBackend = {
+ kind: 'external',
+ call: wrapRuntimeWithProfileLifecycleQueue(externalChromeBackend, browserProfileLifecycleQueue).call,
+ dispose: () => browserProfileLifecycleQueue.run(() => externalChromeBackend.dispose()),
+};
type SessionUploadRootResolver = (sessionId: string) => Promise<string[]>;
@@ -292,9 +388,27 @@ async function stopExternalRuntimeIfUsed(): Promise<void> {
rememberedCdpPort: useRealProfile ? readCopiedLoginsCdpPort(realProfileRuntimeDir()) : null,
});
if (patch) {
- setBrowserControlRuntimeConfig(buildManagedConfig(patch));
+ applyManagedConfig({ ...lastProxyLaunch, ...patch });
+ }
+ // Inside the lifecycle queue: talk to the inner backend. It verifies process
+ // absence and resets the proxy route, which a raw runtime stop would skip.
+ const status = await externalChromeBackend.call({ action: 'status' });
+ // Do NOT gate the stop on the vendored `running` flag. That flag is CDP
+ // readiness, and an inherited Cindy-real Chrome (Cindy restarted while it
+ // stayed up) reports `running: false` with a null pid, because vendored
+ // status fills pid only from in-process state. Skipping the stop there lets
+ // the caller delete the copied-logins directory under a live browser: on
+ // POSIX the unlink succeeds while Chrome keeps writing cookies and passwords
+ // into the now-unlinked files. The backend's stop is idempotent and proves
+ // absence itself, so always issue it and require it to succeed.
+ const stop = await externalChromeBackend.call({ action: 'stop' });
+ assertManagedBrowserStopped({ status, stop });
+ if (!stop.ok) {
+ throw new RealProfileError(
+ 'STOP_FAILED',
+ 'Could not stop the agent browser before changing copied logins.',
+ );
}
- await stopManagedBrowserForProfile(vendoredRuntime, activeManagedProfileName(useRealProfile));
}
/**
@@ -313,7 +427,7 @@ async function applyBrowserUseRealProfile(enabled: boolean): Promise<boolean> {
} else {
writeBrowserUseRealProfile(true);
}
- setBrowserControlRuntimeConfig(buildManagedConfig({ useRealProfile: enabled }));
+ applyManagedConfig({ ...lastProxyLaunch, useRealProfile: enabled });
return readBrowserBackendSettings().useRealProfile;
}
@@ -361,7 +475,7 @@ export function getBrowserMcpDeps(): {
* Probe whether a local browser is available (drives the Settings UI's
* "未检测到本机浏览器 / 下载 Chrome" cell).
*
- * **Always** goes to the vendored runtime, NOT the active controller — this probe asks
+ * **Always** goes to the external managed-browser backend, NOT the active controller — this probe asks
* "did the user install Chrome on their machine?", which is purely a property
* of the EXTERNAL backend. The RSB-webview backend uses Electron's bundled
* Chromium and is always available; routing through the active controller would make the
@@ -369,7 +483,7 @@ export function getBrowserMcpDeps(): {
* backend selected, even on a machine with Chrome installed.
*/
export async function getBrowserAvailability(): Promise<BrowserAvailability> {
- const res = await externalRuntime.call({ action: 'status' });
+ const res = await externalBackend.call({ action: 'status' });
return extractBrowserAvailability(res.data);
}
@@ -485,29 +599,53 @@ export async function openBrowserForLogin(): Promise<void> {
// doing so raced with Chrome's own initial tab on a cold start and produced a
// duplicate tab on the first open.
//
- // **Always** goes to the vendored runtime, NOT the active controller — "打开 Agent 专用浏
+ // **Always** goes to the external managed-browser backend, NOT the active controller — "打开 Agent 专用浏
// 览器" is the external Chrome workflow: user clicks it to log into sites in
// the dedicated `Cindy` profile. If the user picked the rsb-webview backend
// they don't need this button at all (logins go through the sidebar webview);
// routing through the active controller would either no-op (rsb backend's `start` is a
// no-op) or open the wrong thing.
- const started = await externalRuntime.call({ action: 'start' });
- if (!started.ok) {
- const reason = browserOpenForLoginErrorCodeFromData(started.data);
- if (reason) throw new BrowserOpenForLoginError(reason);
- if (
- started.message === FOREIGN_AGENT_BROWSER_ERROR ||
- started.message?.includes('Another Cindy')
- ) {
- throw new BrowserOpenForLoginError(FOREIGN_AGENT_BROWSER_ERROR);
+ // `start` without proxyServer is an explicit request for direct mode. Probe
+ // first so opening the login browser never tears down an already-running
+ // caller-selected proxy route just to raise its window.
+ const status = await externalBackend.call({ action: 'status' });
+ if (!status.ok) {
+ throw new Error(
+ status.message === FOREIGN_AGENT_BROWSER_ERROR || status.message?.includes('Another Cindy')
+ ? FOREIGN_AGENT_BROWSER_ERROR
+ : (status.message ?? `browser status failed (HTTP ${status.status ?? '?'})`),
+ );
+ }
+ const running = (status.data as { running?: unknown } | undefined)?.running;
+ if (running !== true && running !== false) {
+ throw new Error('browser status did not report whether the managed browser is running');
+ }
+ // A running browser whose route is unknown — Cindy restarted and inherited a
+ // Chrome from a previous launch — cannot be driven: ordinary actions are
+ // refused until the route is re-established, so skipping `start` here would
+ // make this return success while raise below silently failed and the window
+ // never came forward. `start` is the only path that adopts or replaces such a
+ // process and reinstates its request guard, so run it in that case too.
+ const proxyMode = (status.data as { proxy?: { mode?: unknown } } | undefined)?.proxy?.mode;
+ if (!running || proxyMode === 'unknown') {
+ const started = await externalBackend.call({ action: 'start' });
+ if (!started.ok) {
+ const reason = browserOpenForLoginErrorCodeFromData(started.data);
+ if (reason) throw new BrowserOpenForLoginError(reason);
+ if (
+ started.message === FOREIGN_AGENT_BROWSER_ERROR ||
+ started.message?.includes('Another Cindy')
+ ) {
+ throw new BrowserOpenForLoginError(FOREIGN_AGENT_BROWSER_ERROR);
+ }
+ throw new Error('Agent browser failed to start.');
}
- throw new Error('Agent browser failed to start.');
}
// Occupancy is handled inside start (relocate CDP instead of attaching).
// Do not re-probe status.running here: vendored `running` means "CDP is
// reachable", and pid/userDataDir can still be missing or point at a
// leftover Chrome on 18800 after a successful start of *this* window.
- await raiseAgentBrowserWindow(externalRuntime);
+ await raiseAgentBrowserWindow(externalBackend);
}
/**
@@ -515,13 +653,13 @@ export async function openBrowserForLogin(): Promise<void> {
*
* Registered into the lifecycle disposer chain (bootstrap-electron.ts
* `onQuit('browser-runtime', …, 'async')`). The managed browser is a lazily
- * spawned process owned by the vendored runtime; nothing else sends `stop`, so
+ * spawned process owned by the external managed-browser backend; nothing else sends `stop`, so
* without this the headed Chrome + its locked user-data-dir survive app
* quit / crash / dev-reload, and the next launch has to recover a stale
- * SingletonLock. Goes through the electron-free `stopRuntimeForQuitIfUsed`
- * (which swallows errors — see browser-dispose.ts).
+ * SingletonLock. Goes through the external backend's serialized disposer,
+ * which swallows errors.
*
- * NOTE (Windows): the vendored stop sends SIGTERM→SIGKILL to the launched Chrome
+ * NOTE (Windows): the managed runtime stop sends SIGTERM→SIGKILL to the launched Chrome
* process. Chromium's child renderer/GPU processes normally exit with their
* parent, but full process-tree teardown on win32 is not yet verified — if
* orphans are observed, add a host-side `taskkill /F /T /PID <pid>` fallback here
@@ -530,25 +668,19 @@ export async function openBrowserForLogin(): Promise<void> {
* not run on the auto-update relaunch path; stale-lock recovery covers that case.
*/
export function disposeBrowserRuntime(): Promise<void> {
- // Always stop the vendored Chrome directly, NOT through the active controller.
+ // Always stop the external managed Chrome directly, NOT through the active controller.
// The controller may currently point at RsbWebviewBackend, whose dispose only
// releases control listeners and does not own the external Chrome process. If
// we only dispose through the active backend, a user who switched to external Chrome and back
- // leaves a headed Chrome process surviving app quit (the vendored runtime
+ // leaves a headed Chrome process surviving app quit (the external backend
// doesn't know about the swap and Phase 5 swap-time dispose already ran;
// a stale-lock recovery on next launch is the symptom).
//
- // Short-circuit via the usage tracker: the vendored dispatch bridge boots
- // the browser control service (dynamic playwright import included) before
- // routing ANY action, `stop` included — so on a session that never touched
- // the browser runtime, an unconditional stop would START services during
- // quit, which is an exit-hang amplifier. If the runtime WAS used, `stop` is
- // idempotent and safe regardless of which backend is currently active.
- return browserProfileLifecycleQueue.run(() =>
- stopRuntimeForQuitIfUsed(
- vendoredRuntime,
- logger,
- activeManagedProfileName(readBrowserBackendSettings().useRealProfile),
- ),
- );
+ // The external backend tracks whether its runtime was used and skips an
+ // unnecessary stop for a browser-less session. If it was used, stop is
+ // idempotent and safe even when the active backend is the embedded webview.
+ // `externalBackend.dispose` runs under the profile lifecycle queue so quit
+ // cannot interleave with an in-flight consent switch.
+ externalChromeBackend.beginQuiescence();
+ return externalBackend.dispose();
}
diff --git a/apps/desktop/src/main/messagePersistBroadcaster.ts b/apps/desktop/src/main/messagePersistBroadcaster.ts
index 68c3f192ce..1671493a9c 100644
--- a/apps/desktop/src/main/messagePersistBroadcaster.ts
+++ b/apps/desktop/src/main/messagePersistBroadcaster.ts
@@ -57,6 +57,7 @@ import { commitMessageMediaRefs } from './cindy-media/chatAttachments.js';
import { takeMediaToolResult } from './mcp-integrations/mediaToolResultFallback.js';
import { capToolResultTextForPersist } from '../shared/toolResultPersistCap.js';
import { redactSensitiveText } from '@cindy/maker-shared/error-redaction';
+import { parseBrowserProxyServer } from '@cindy/browser-control-runtime';
import {
isAgentTaskToolName,
normalizeAgentTaskTerminalStatus,
@@ -71,6 +72,128 @@ import { parseToolLoopErrorDetails, type ToolLoopErrorDetails } from '@cindy/mak
const log = createLogger('messagePersistBroadcaster');
+const REDACTED_PROXY_SERVER = '[REDACTED]';
+
+function redactProxyServerInput(value: unknown): unknown {
+ if (typeof value !== 'string') return REDACTED_PROXY_SERVER;
+ try {
+ // The parser rejects any userinfo (authenticated proxies are unsupported),
+ // so a value that parses is a clean, credential-free proxy URL — safe to
+ // keep verbatim for legibility. Anything with credentials or otherwise
+ // malformed throws and is redacted whole.
+ parseBrowserProxyServer(value);
+ return value;
+ } catch {
+ return REDACTED_PROXY_SERVER;
+ }
+}
+
+function redactBrowserCallArgs(args: unknown): unknown {
+ if (typeof args === 'string') {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(args);
+ } catch {
+ return args.includes('proxyServer') ? REDACTED_PROXY_SERVER : args;
+ }
+ const redacted = redactBrowserCallArgs(parsed);
+ return redacted === parsed ? args : JSON.stringify(redacted);
+ }
+ if (!args || typeof args !== 'object' || Array.isArray(args)) return args;
+ const record = args as Record<string, unknown>;
+ if (!Object.prototype.hasOwnProperty.call(record, 'proxyServer')) return args;
+ const proxyServer = redactProxyServerInput(record.proxyServer);
+ return proxyServer === record.proxyServer ? args : { ...record, proxyServer };
+}
+
+/**
+ * Tool names that can carry a browser `proxyServer`: the browser MCP tool
+ * itself and the Pi gateway that wraps it. Anything else — `apply_patch`, a
+ * shell command, a free-form dynamic tool — is passed through untouched.
+ *
+ * Without this gate the non-JSON string fallback below redacts an ENTIRE input
+ * that merely contains the text `proxyServer`, so editing a file that mentions
+ * the identifier would blank that tool call in the live UI, the persisted
+ * record, and the rehydrated history.
+ *
+ * Matched EXACTLY, never as a substring. A custom MCP id may contain `__`
+ * (the id regex allows underscores), so a third-party server registered as
+ * `cindy_browser__evil` produces `mcp__cindy_browser__evil__call_tool` — which
+ * a substring test reads as the first-party browser. `mcp-tool-target.ts`
+ * documents that exact name as the reason attribution must not be naive.
+ * There the consequence is inheriting first-party trust; here it is having an
+ * unrelated tool's input blanked in the UI and history. Same root cause.
+ */
+const PROXY_SERVER_CARRYING_TOOLS = new Set([
+ 'browser',
+ 'cindy_browser',
+ 'cindy_mcp_call_tool',
+ // Claude Code's MCP tool id form...
+ 'mcp__cindy_browser__call_tool',
+ // ...and Codex's, which its translator builds as `mcp:${server}:${tool}`
+ // (agents/codex/translator.ts). Missing this form meant a local Codex
+ // session's browser call skipped redaction entirely, so a credential-bearing
+ // proxyServer was persisted and broadcast before the browser tool rejected it.
+ 'mcp:cindy_browser:call_tool',
+ // Codex's APPROVAL identity is a third form: the elicitation path names the
+ // server alone, with no tool suffix (agents/codex/index.ts), and nests the
+ // real call under `toolParams`. Without it an Ask-mode permission request
+ // carries the credential into the Desktop / device-link / IM card.
+ 'mcp:cindy_browser',
+]);
+
+function mayCarryProxyServer(toolName: string): boolean {
+ return PROXY_SERVER_CARRYING_TOOLS.has(toolName);
+}
+
+/** Remove proxy userinfo before tool inputs cross a persistence or UI boundary. */
+export function redactToolInputForUntrustedBoundary(toolName: string, input: unknown): unknown {
+ // An empty name marks an internal recursive call on an already-identified
+ // browser input; only top-level calls carry a real tool name to check.
+ if (toolName !== '' && !mayCarryProxyServer(toolName)) return input;
+ if (typeof input === 'string') {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(input);
+ } catch {
+ return input.includes('proxyServer') ? REDACTED_PROXY_SERVER : input;
+ }
+ const redacted = redactToolInputForUntrustedBoundary('', parsed);
+ return redacted === parsed ? input : JSON.stringify(redacted);
+ }
+ if (!input || typeof input !== 'object' || Array.isArray(input)) return input;
+ const record = input as Record<string, unknown>;
+ let redacted: Record<string, unknown> = record;
+ if (Object.prototype.hasOwnProperty.call(record, 'proxyServer')) {
+ const proxyServer = redactProxyServerInput(record.proxyServer);
+ if (proxyServer !== record.proxyServer) redacted = { ...redacted, proxyServer };
+ }
+ // Codex MCP approval envelope: `{ serverName, message, toolName, toolParams,
+ // toolParamsDisplay }`. The browser arguments live one level down under
+ // `toolParams`, with a rendered copy under `toolParamsDisplay`; neither is
+ // reached by the checks above. Safe to recurse with an empty name here — the
+ // top-level tool name already identified this as a browser envelope.
+ for (const field of ['toolParams', 'toolParamsDisplay'] as const) {
+ if (!Object.prototype.hasOwnProperty.call(record, field)) continue;
+ const redactedField = redactToolInputForUntrustedBoundary('', record[field]);
+ if (redactedField !== record[field]) redacted = { ...redacted, [field]: redactedField };
+ }
+ if (record.name === 'browser') {
+ const redactedArgs = redactBrowserCallArgs(record.args);
+ if (redactedArgs !== record.args) redacted = { ...redacted, args: redactedArgs };
+ } else if (record.server === 'cindy_browser' && record.tool === 'call_tool') {
+ // Pi MCP gateway envelope: call_tool({server, tool, args}) wraps the real
+ // tool input one level deeper than a direct call_tool({name, args}).
+ // Match the exact server/tool, not merely their types: recursing with an
+ // empty name re-enters past the mayCarryProxyServer gate, so a shape-only
+ // check would let any unrelated MCP call have an `args.proxyServer` field
+ // rewritten — blanking that tool call in the live UI and persisted record.
+ const redactedArgs = redactToolInputForUntrustedBoundary('', record.args);
+ if (redactedArgs !== record.args) redacted = { ...redacted, args: redactedArgs };
+ }
+ return redacted;
+}
+
/** 每会话当前在飞的 assistant 文本 block:分配一次 persistId、累积全文,边界落库后清。 */
interface AssistantBlock {
persistId: string;
@@ -1034,6 +1157,7 @@ export function onToolUseEvent(
const createdAt = Date.now();
const toolUseId = typeof data.toolUseId === 'string' ? data.toolUseId : '';
const toolName = typeof data.toolName === 'string' ? data.toolName : '';
+ const persistedInput = redactToolInputForUntrustedBoundary(toolName, data.input);
if (scope === 'turn' && getSessionDbAgentKind(sessionId) === 'codex') {
const planUpdate = parseCodexPlanUpdate(data);
@@ -1083,7 +1207,7 @@ export function onToolUseEvent(
enqueueVisibleDbMessage(`tool_use:${sessionId}:${persistId}`, sessionId, {
clientId: persistId,
role: 'tool_use',
- content: { toolUseId, toolName, input: data.input },
+ content: { toolUseId, toolName, input: persistedInput },
toolUseId: toolUseId || undefined,
agentMeta: persistedMeta,
createdAt,
@@ -1095,20 +1219,20 @@ export function onToolUseEvent(
rememberToolUseId(sessionId, toolUseId, createdAt);
getOrCreateSessionMap(toolUseInfoBySession, sessionId).set(toolUseId, {
toolName,
- input: data.input,
+ input: persistedInput,
});
}
const existingPersistId = isUpdatableToolUse(toolName) && toolUseId
? updatableToolUsePersistIdBySession.get(sessionId)?.get(toolUseId)
: undefined;
if (existingPersistId) {
- const content = { toolUseId, toolName, input: data.input };
+ const content = { toolUseId, toolName, input: persistedInput };
enqueueWrite(`tool_use_update:${sessionId}:${existingPersistId}`, () =>
updateDbMessageContent(sessionId, existingPersistId, content),
);
// 同一 turn 的第二次 update_plan 走这条复用分支,按-turn 缓存必须跟着刷新:
// 终态写入优先读它,停在首版快照会把已更新的计划整行盖回第一版(review P1)。
- rememberCodexPlanRow(sessionId, toolName, toolUseId, existingPersistId, data.input);
+ rememberCodexPlanRow(sessionId, toolName, toolUseId, existingPersistId, persistedInput);
notePersistedMessage(sessionId, 'tool_use', existingPersistId);
return existingPersistId;
}
@@ -1124,7 +1248,7 @@ export function onToolUseEvent(
enqueueVisibleDbMessage(`tool_use:${sessionId}:${persistId}`, sessionId, {
clientId: persistId,
role: 'tool_use',
- content: { toolUseId, toolName, input: data.input },
+ content: { toolUseId, toolName, input: persistedInput },
toolUseId: toolUseId || undefined,
agentMeta: meta,
createdAt,
@@ -1132,7 +1256,7 @@ export function onToolUseEvent(
if (isUpdatableToolUse(toolName) && toolUseId) {
rememberUpdatableToolUsePersistId(sessionId, toolUseId, persistId);
}
- rememberCodexPlanRow(sessionId, toolName, toolUseId, persistId, data.input);
+ rememberCodexPlanRow(sessionId, toolName, toolUseId, persistId, persistedInput);
notePersistedMessage(sessionId, 'tool_use', persistId);
return persistId;
}
diff --git a/packages/browser-control-runtime/src/__tests__/chrome-launch-proxy.test.ts b/packages/browser-control-runtime/src/__tests__/chrome-launch-proxy.test.ts
new file mode 100644
index 0000000000..81ad58cccb
--- /dev/null
+++ b/packages/browser-control-runtime/src/__tests__/chrome-launch-proxy.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it } from 'vitest';
+
+import { hasExplicitChromeProxyRoutingArg } from '../_generated/extension/src/browser/browser-proxy-mode.js';
+import { buildOpenClawChromeLaunchArgs } from '../_generated/extension/src/browser/chrome.js';
+import {
+ resolveBrowserConfig,
+ resolveProfile,
+} from '../_generated/extension/src/browser/config.js';
+
+function launchArgs(extraArgs: string[]): string[] {
+ const resolved = resolveBrowserConfig({
+ enabled: true,
+ defaultProfile: 'Cindy',
+ headless: true,
+ extraArgs,
+ profiles: {
+ Cindy: { driver: 'openclaw', cdpPort: 18800, color: '#00D9C5' },
+ },
+ });
+ const profile = resolveProfile(resolved, 'Cindy');
+ if (!profile) throw new Error('test profile did not resolve');
+ return buildOpenClawChromeLaunchArgs({
+ resolved,
+ profile,
+ userDataDir: '/tmp/cindy-browser-proxy-test',
+ platform: 'linux',
+ env: { DISPLAY: ':99' },
+ });
+}
+
+describe('managed Chrome proxy launch arguments', () => {
+ it('retains explicit direct mode', () => {
+ const args = launchArgs([]);
+ expect(args).toContain('--no-proxy-server');
+ expect(args.some((arg) => arg.startsWith('--proxy-server'))).toBe(false);
+ });
+
+ it('treats a PAC-only launch as the explicit proxy route', () => {
+ // The host emits only `--proxy-pac-url` for a proxied start (Chromium
+ // ignores `--proxy-server` next to a PAC). That single flag must be enough
+ // to suppress the direct-mode default and to count as explicit routing
+ // for the navigation guard's proxy-mode detection.
+ const pacArg = 'data:application/x-ns-proxy-autoconfig;base64,ZnVuY3Rpb24gRmluZFByb3h5Rm9yVVJMKCl7fQ==';
+ const args = launchArgs([`--proxy-pac-url=${pacArg}`]);
+ expect(args).not.toContain('--no-proxy-server');
+ expect(args.some((arg) => arg.startsWith('--proxy-server'))).toBe(false);
+ expect(args.filter((arg) => arg.startsWith('--proxy-pac-url'))).toEqual([
+ `--proxy-pac-url=${pacArg}`,
+ ]);
+ expect(hasExplicitChromeProxyRoutingArg([`--proxy-pac-url=${pacArg}`])).toBe(true);
+ });
+});
diff --git a/packages/browser-control-runtime/src/__tests__/interaction-proxy-policy.test.ts b/packages/browser-control-runtime/src/__tests__/interaction-proxy-policy.test.ts
new file mode 100644
index 0000000000..7f998d6c64
--- /dev/null
+++ b/packages/browser-control-runtime/src/__tests__/interaction-proxy-policy.test.ts
@@ -0,0 +1,1308 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ assertBrowserNavigationResultAllowed: vi.fn(async () => undefined),
+ assertPageNavigationCompletedSafely: vi.fn(async (_opts?: { page?: unknown }) => undefined),
+ closeBlockedNavigationTarget: vi.fn(async () => undefined),
+ getPageForTargetId: vi.fn(),
+ quarantineTargetWithoutClosing: vi.fn(async () => undefined),
+ refLocator: vi.fn(),
+}));
+
+vi.mock('../_generated/extension/src/browser/navigation-guard.js', () => ({
+ assertBrowserNavigationResultAllowed: mocks.assertBrowserNavigationResultAllowed,
+ withBrowserNavigationPolicy: (
+ ssrfPolicy: unknown,
+ options?: { browserProxyMode?: string },
+ ) => ({
+ ...(ssrfPolicy ? { ssrfPolicy } : {}),
+ ...(options?.browserProxyMode ? { browserProxyMode: options.browserProxyMode } : {}),
+ }),
+}));
+
+vi.mock('../_generated/extension/src/browser/pw-session.js', () => ({
+ assertPageNavigationCompletedSafely: mocks.assertPageNavigationCompletedSafely,
+ closeBlockedNavigationTarget: mocks.closeBlockedNavigationTarget,
+ quarantineTargetWithoutClosing: mocks.quarantineTargetWithoutClosing,
+ createObservedDialogAbortSignalForPage: () => ({ signal: undefined, cleanup: vi.fn() }),
+ ensurePageState: vi.fn(),
+ forceDisconnectPlaywrightForTarget: vi.fn(async () => undefined),
+ getPageForTargetId: mocks.getPageForTargetId,
+ isBrowserObservedDialogBlockedError: () => false,
+ markObservedDialogsHandledRemotelyForPage: vi.fn(),
+ refLocator: mocks.refLocator,
+ restoreRoleRefsForTarget: vi.fn(),
+}));
+
+vi.mock('../_generated/extension/src/browser/paths.js', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ resolveStrictExistingUploadPaths: async ({ requestedPaths }: { requestedPaths: string[] }) => ({
+ ok: true,
+ paths: requestedPaths,
+ }),
+}));
+
+import {
+ executeActViaPlaywright,
+ setInputFilesViaPlaywright,
+} from '../_generated/extension/src/browser/pw-tools-core.interactions.js';
+
+describe('Playwright interaction proxy navigation policy', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('carries explicit proxy mode into main-frame and subframe checks', async () => {
+ let currentUrl = 'https://start.example/';
+ let navigationListener: ((frame: { url(): string }) => void) | undefined;
+ const mainFrame = { url: () => currentUrl };
+ const subframe = { url: () => 'https://static.allowed.example/frame' };
+ const page = {
+ url: () => currentUrl,
+ mainFrame: () => mainFrame,
+ on: vi.fn((_event: string, listener: (frame: { url(): string }) => void) => {
+ navigationListener = listener;
+ }),
+ off: vi.fn(),
+ };
+ const locator = {
+ click: vi.fn(async () => {
+ navigationListener?.(subframe);
+ currentUrl = 'https://allowed.example/next';
+ navigationListener?.(mainFrame);
+ }),
+ };
+ mocks.getPageForTargetId.mockResolvedValue(page);
+ mocks.refLocator.mockReturnValue(locator);
+
+ await executeActViaPlaywright({
+ cdpUrl: 'http://127.0.0.1:18800',
+ targetId: 'page-1',
+ action: { kind: 'click', ref: 'e1' },
+ ssrfPolicy: { hostnameAllowlist: ['*.allowed.example'] },
+ browserProxyMode: 'explicit-browser-proxy',
+ });
+
+ expect(mocks.assertBrowserNavigationResultAllowed).toHaveBeenCalledWith({
+ url: 'https://static.allowed.example/frame',
+ ssrfPolicy: { hostnameAllowlist: ['*.allowed.example'] },
+ browserProxyMode: 'explicit-browser-proxy',
+ });
+ expect(mocks.assertPageNavigationCompletedSafely).toHaveBeenCalledWith(
+ expect.objectContaining({
+ page,
+ ssrfPolicy: { hostnameAllowlist: ['*.allowed.example'] },
+ browserProxyMode: 'explicit-browser-proxy',
+ }),
+ );
+ });
+
+ it.each([
+ ['hover', { kind: 'hover', ref: 'e1' }],
+ ['scrollIntoView', { kind: 'scrollIntoView', ref: 'e1' }],
+ ['drag', { kind: 'drag', startRef: 'e1', endRef: 'e2' }],
+ ['wait', { kind: 'wait', timeMs: 1 }],
+ ['resize', { kind: 'resize', width: 800, height: 600 }],
+ ] as const)(
+ 'guards script navigation triggered by %s with the proxy policy',
+ async (_label, action) => {
+ let currentUrl = 'https://start.example/';
+ const mainFrame = { url: () => currentUrl };
+ const navigate = async () => {
+ currentUrl = 'https://allowed.example/next';
+ };
+ const page = {
+ url: () => currentUrl,
+ mainFrame: () => mainFrame,
+ on: vi.fn(),
+ off: vi.fn(),
+ waitForTimeout: vi.fn(navigate),
+ setViewportSize: vi.fn(navigate),
+ };
+ const locator = {
+ hover: vi.fn(navigate),
+ scrollIntoViewIfNeeded: vi.fn(navigate),
+ dragTo: vi.fn(navigate),
+ };
+ mocks.getPageForTargetId.mockResolvedValue(page);
+ mocks.refLocator.mockReturnValue(locator);
+
+ await executeActViaPlaywright({
+ cdpUrl: 'http://127.0.0.1:18800',
+ targetId: 'page-1',
+ action: action as never,
+ ssrfPolicy: { hostnameAllowlist: ['*.allowed.example'] },
+ browserProxyMode: 'explicit-browser-proxy',
+ });
+
+ expect(mocks.assertPageNavigationCompletedSafely).toHaveBeenCalledWith(
+ expect.objectContaining({
+ page,
+ ssrfPolicy: { hostnameAllowlist: ['*.allowed.example'] },
+ browserProxyMode: 'explicit-browser-proxy',
+ }),
+ );
+ },
+ );
+
+ it('validates popups opened during a guarded interaction against the proxy policy', async () => {
+ let currentUrl = 'https://start.example/';
+ const mainFrame = { url: () => currentUrl };
+ let contextPageListener: ((page: unknown) => void) | undefined;
+ const popup = {
+ url: () => 'https://evil.example/popup',
+ mainFrame: () => ({ url: () => 'https://evil.example/popup' }),
+ opener: async () => page,
+ on: vi.fn(),
+ off: vi.fn(),
+ };
+ const context = {
+ on: vi.fn((_event: string, listener: (page: unknown) => void) => {
+ contextPageListener = listener;
+ }),
+ off: vi.fn(),
+ };
+ const page = {
+ url: () => currentUrl,
+ mainFrame: () => mainFrame,
+ on: vi.fn(),
+ off: vi.fn(),
+ context: () => context,
+ };
+ const locator = {
+ click: vi.fn(async () => {
+ // Deferred like setTimeout(() => window.open(...)): the popup arrives
+ // after the action promise resolves, inside the delayed grace window.
+ setTimeout(() => contextPageListener?.(popup), 50);
+ }),
+ };
+ mocks.getPageForTargetId.mockResolvedValue(page);
+ mocks.refLocator.mockReturnValue(locator);
+
+ await executeActViaPlaywright({
+ cdpUrl: 'http://127.0.0.1:18800',
+ targetId: 'page-1',
+ action: { kind: 'click', ref: 'e1' },
+ ssrfPolicy: { hostnameAllowlist: ['*.allowed.example'] },
+ browserProxyMode: 'explicit-browser-proxy',
+ });
+
+ expect(mocks.assertPageNavigationCompletedSafely).toHaveBeenCalledWith(
+ expect.objectContaining({
+ page: popup,
+ ssrfPolicy: { hostnameAllowlist: ['*.allowed.example'] },
+ browserProxyMode: 'explicit-browser-proxy',
+ }),
+ );
+ });
+
+ it('detaches the popup listener even when navigation validation rejects', async () => {
+ let currentUrl = 'https://start.example/';
+ const mainFrame = { url: () => currentUrl };
+ const context = { on: vi.fn(), off: vi.fn() };
+ const page = {
+ url: () => currentUrl,
+ mainFrame: () => mainFrame,
+ on: vi.fn(),
+ off: vi.fn(),
+ context: () => context,
+ };
+ const locator = {
+ click: vi.fn(async () => {
+ currentUrl = 'https://blocked.example/next';
+ }),
+ };
+ mocks.getPageForTargetId.mockResolvedValue(page);
+ mocks.refLocator.mockReturnValue(locator);
+ mocks.assertPageNavigationCompletedSafely.mockRejectedValueOnce(
+ new Error('Navigation blocked: proxied browser navigation requires HTTPS'),
+ );
+
+ await expect(executeActViaPlaywright({
+ cdpUrl: 'http://127.0.0.1:18800',
+ targetId: 'page-1',
+ action: { kind: 'click', ref: 'e1' },
+ ssrfPolicy: { hostnameAllowlist: ['*.allowed.example'] },
+ browserProxyMode: 'explicit-browser-proxy',
+ })).rejects.toThrow(/Navigation blocked/);
+
+ // A policy deny must not leak the context listener: otherwise every blocked
+ // interaction retains all tabs opened afterwards.
+ expect(context.on).toHaveBeenCalledTimes(1);
+ expect(context.off).toHaveBeenCalledTimes(1);
+ expect(context.off).toHaveBeenCalledWith('page', context.on.mock.calls[0]?.[1]);
+ });
+
+ it('still validates popups when the main-frame navigation is denied', async () => {
+ let currentUrl = 'https://start.example/';
+ const mainFrame = { url: () => currentUrl };
+ let contextPageListener: ((page: unknown) => void) | undefined;
+ const popup = {
+ url: () => 'https://evil.example/popup',
+ mainFrame: () => ({ url: () => 'https://evil.example/popup' }),
+ opener: async () => page,
+ on: vi.fn(),
+ off: vi.fn(),
+ };
+ const context = {
+ on: vi.fn((_event: string, listener: (page: unknown) => void) => {
+ contextPageListener = listener;
+ }),
+ off: vi.fn(),
+ };
+ const page = {
+ url: () => currentUrl,
+ mainFrame: () => mainFrame,
+ on: vi.fn(),
+ off: vi.fn(),
+ context: () => context,
+ };
+ const locator = {
+ click: vi.fn(async () => {
+ // Both a denied main-frame navigation and a new tab.
+ currentUrl = 'https://blocked.example/next';
+ contextPageListener?.(popup);
+ }),
+ };
+ mocks.getPageForTargetId.mockResolvedValue(page);
+ mocks.refLocator.mockReturnValue(locator);
+ mocks.assertPageNavigationCompletedSafely.mockRejectedValueOnce(
+ new Error('Navigation blocked: main frame'),
+ );
+
+ // The main-frame denial is what the caller asked for, so it wins.
+ await expect(executeActViaPlaywright({
+ cdpUrl: 'http://127.0.0.1:18800',
+ targetId: 'page-1',
+ action: { kind: 'click', ref: 'e1' },
+ ssrfPolicy: { hostnameAllowlist: ['*.allowed.example'] },
+ browserProxyMode: 'explicit-browser-proxy',
+ })).rejects.toThrow(/main frame/);
+
+ // ...but the popup must still have been checked, not left live.
+ expect(mocks.assertPageNavigationCompletedSafely).toHaveBeenCalledWith(
+ expect.objectContaining({ page: popup }),
+ );
+ expect(context.off).toHaveBeenCalledTimes(1);
+ });
+
+ it('validates every popup even when an earlier popup is denied', async () => {
+ const currentUrl = 'https://start.example/';
+ const mainFrame = { url: () => currentUrl };
+ let contextPageListener: ((page: unknown) => void) | undefined;
+ // `isClosed` reports real closure — that, not the helper's resolution, is
+ // what the code accepts as containment. One shared mock closes whichever
+ // page it is handed, so each popup reports its own state.
+ const closedPages = new WeakSet<object>();
+ mocks.closeBlockedNavigationTarget.mockImplementation(async ({ page: target }) => {
+ closedPages.add(target as object);
+ });
+ const makePopup = (url: string) => {
+ const popup = {
+ url: () => url,
+ mainFrame: () => ({ url: () => url }),
+ opener: async () => page,
+ on: vi.fn(),
+ off: vi.fn(),
+ isClosed: () => closedPages.has(popup),
+ };
+ return popup;
+ };
+ const firstPopup = makePopup('https://denied-one.example/a');
+ const secondPopup = makePopup('https://denied-two.example/b');
+ const context = {
+ on: vi.fn((_event: string, listener: (page: unknown) => void) => {
+ contextPageListener = listener;
+ }),
+ off: vi.fn(),
+ };
+ const page = {
+ url: () => currentUrl,
+ mainFrame: () => mainFrame,
+ on: vi.fn(),
+ off: vi.fn(),
+ context: () => context,
+ };
+ const locator = {
+ click: vi.fn(async () => {
+ contextPageListener?.(firstPopup);
+ contextPageListener?.(secondPopup);
+ }),
+ };
+ mocks.getPageForTargetId.mockResolvedValue(page);
+ mocks.refLocator.mockReturnValue(locator);
+ // First popup is denied; the second must still be checked.
+ mocks.assertPageNavigationCompletedSafely.mockRejectedValueOnce(
+ new Error('Navigation blocked: popup one'),
+ );
+
+ await expect(executeActViaPlaywright({
+ cdpUrl: 'http://127.0.0.1:18800',
+ targetId: 'page-1',
+ action: { kind: 'click', ref: 'e1' },
+ ssrfPolicy: { hostnameAllowlist: ['*.allowed.example'] },
+ browserProxyMode: 'explicit-browser-proxy',
+ })).rejects.toThrow(/popup one/);
+
+ for (const popup of [firstPopup, secondPopup]) {
+ expect(mocks.assertPageNavigationCompletedSafely).toHaveBeenCalledWith(
+ expect.objectContaining({ page: popup }),
+ );
+ }
+ // The denied popup is torn down fail-closed; the popup that passed
+ // validation stays open.
+ expect(mocks.closeBlockedNavigationTarget).toHaveBeenCalledTimes(1);
+ expect(mocks.closeBlockedNavigationTarget).toHaveBeenCalledWith(
+ expect.objectContaining({ page: firstPopup }),
+ );
+ });
+
+ it('closes a rejected popup fail-closed before rethrowing the denial', async () => {
+ // A policy deny on a popup only quarantines inside the assertion helper
+ // (it never closes), and interaction popups never reach the navigate-style
+ // close path — without an explicit close here the denied page would keep
+ // executing after the listener detaches.
+ const currentUrl = 'https://start.example/';
+ let contextPageListener: ((page: unknown) => void) | undefined;
+ let popupClosed = false;
+ const popup = {
+ url: () => 'https://evil.example/popup',
+ mainFrame: () => ({ url: () => 'https://evil.example/popup' }),
+ opener: async () => page,
+ on: vi.fn(),
+ off: vi.fn(),
+ isClosed: () => popupClosed,
+ };
+ const context = {
+ on: vi.fn((_event: string, listener: (page: unknown) => void) => {
+ contextPageListener = listener;
+ }),
+ off: vi.fn(),
+ };
+ const page = {
+ url: () => currentUrl,
+ mainFrame: () => ({ url: () => currentUrl }),
+ opener: async () => page,
+ on: vi.fn(),
+ off: vi.fn(),
+ context: () => context,
+ };
+ const locator = {
+ click: vi.fn(async () => {
+ contextPageListener?.(popup);
+ }),
+ };
+ mocks.getPageForTargetId.mockResolvedValue(page);
+ mocks.refLocator.mockReturnValue(locator);
+ mocks.closeBlockedNavigationTarget.mockImplementation(async () => {
+ popupClosed = true;
+ });
+ mocks.assertPageNavigationCompletedSafely.mockImplementation(async ({ page: checked }) => {
+ if (checked === popup) throw new Error('Navigation blocked: popup denied');
+ });
+
+ await expect(executeActViaPlaywright({
+ cdpUrl: 'http://127.0.0.1:18800',
+ targetId: 'page-1',
+ action: { kind: 'click', ref: 'e1' },
+ ssrfPolicy: { hostnameAllowlist: ['*.allowed.example'] },
+ browserProxyMode: 'explicit-browser-proxy',
+ })).rejects.toThrow(/popup denied/);
+
+ expect(mocks.closeBlockedNavigationTarget).toHaveBeenCalledWith(
+ expect.objectContaining({
+ cdpUrl: 'http://127.0.0.1:18800',
+ page: popup,
+ }),
+ );
+ // A hung close must not leak the context listener either.
+ expect(context.off).toHaveBeenCalledTimes(1);
+ });
+
+ it('waits for a slow lineage answer instead of treating the popup as a stranger', async () => {
+ // The ownership probe is async. A popup whose opener() is slow must not be
+ // classified as "not ours" and skipped: the sweep index only moves forward,
+ // so it would detach the listener leaving an action-created popup live,
+ // unvalidated and unreported. It has to be waited for, then contained.
+ const currentUrl = 'https://start.example/';
+ let contextPageListener: ((page: unknown) => void) | undefined;
+ let releaseOpener: (() => void) | undefined;
+ const slowPopup: Record<string, unknown> = {
+ url: () => 'https://evil.example/popup',
+ mainFrame: () => ({ url: () => 'https://evil.example/popup' }),
+ on: vi.fn(),
+ off: vi.fn(),
+ isClosed: () => false,
+ };
+ const context = {
+ on: vi.fn((_event: string, listener: (page: unknown) => void) => {
+ contextPageListener = listener;
+ }),
+ off: vi.fn(),
+ close: vi.fn(async () => undefined),
+ browser: vi.fn(() => ({ close: vi.fn(async () => undefined) })),
+ };
+ const page = {
+ url: () => currentUrl,
+ mainFrame: () => ({ url: () => currentUrl }),
+ on: vi.fn(),
+ off: vi.fn(),
+ context: () => context,
+ };
+ // Resolves only once the test releases it, well after the popup arrives.
+ slowPopup.opener = () => new Promise((resolve) => {
+ releaseOpener = () => resolve(page);
+ });
+ mocks.getPageForTargetId.mockResolvedValue(page);
+ mocks.refLocator.mockReturnValue({
+ click: vi.fn(async () => {
+ contextPageListener?.(slowPopup);
+ setTimeout(() => releaseOpener?.(), 20);
+ }),
+ });
+ mocks.assertPageNavigationCompletedSafely.mockImplementation(async ({ page: checked }) => {
+ if (checked === slowPopup) throw new Error('Navigation blocked: slow popup');
+ });
+
+ await expect(executeActViaPlaywright({
+ cdpUrl: 'http://127.0.0.1:18800',
+ targetId: 'page-1',
+ action: { kind: 'click', ref: 'e1' },
+ ssrfPolicy: { hostnameAllowlist: ['*.allowed.example'] },
+ browserProxyMode: 'explicit-browser-proxy',
+ })).rejects.toThrow(/slow popup/);
+
+ // Proven ours once the opener resolved, so it was validated and contained.
+ expect(mocks.assertPageNavigationCompletedSafely).toHaveBeenCalledWith(
+ expect.objectContaining({ page: slowPopup }),
+ );
+ expect(mocks.closeBlockedNavigationTarget).toHaveBeenCalledWith(
+ expect.objectContaining({ page: slowPopup }),
+ );
+ });
+
+ it('ignores tabs the user opened during the action', async () => {
+ // The managed context is persistent and shared with the user. A tab they
+ // open mid-action reports no opener, so it is not ours: it must never be
+ // validated (which on denial would quarantine and CLOSE their tab) and must
+ // not drag the context/browser teardown in either.
+ const currentUrl = 'https://start.example/';
+ let contextPageListener: ((page: unknown) => void) | undefined;
+ const userTab = {
+ url: () => 'https://mail.example/inbox',
+ mainFrame: () => ({ url: () => 'https://mail.example/inbox' }),
+ on: vi.fn(),
+ off: vi.fn(),
+ opener: async () => null, // user-opened: no opener
+ isClosed: () => false,
+ };
+ const context = {
+ on: vi.fn((_event: string, listener: (page: unknown) => void) => {
+ contextPageListener = listener;
+ }),
+ off: vi.fn(),
+ close: vi.fn(async () => undefined),
+ browser: vi.fn(() => ({ close: vi.fn(async () => undefined) })),
+ };
+ const page = {
+ url: () => currentUrl,
+ mainFrame: () => ({ url: () => currentUrl }),
+ on: vi.fn(),
+ off: vi.fn(),
+ context: () => context,
+ };
+ mocks.getPageForTargetId.mockResolvedValue(page);
+ mocks.refLocator.mockReturnValue({
+ click: vi.fn(async () => {
+ contextPageListener?.(userTab);
+ }),
+ });
+ // Would deny the user's tab if it were ever checked.
+ mocks.assertPageNavigationCompletedSafely.mockImplementation(async ({ page: checked }) => {
+ if (checked === userTab) throw new Error('Navigation blocked: user tab');
+ });
+
+ await expect(executeActViaPlaywright({
+ cdpUrl: 'http://127.0.0.1:18800',
+ targetId: 'page-1',
+ action: { kind: 'click', ref: 'e1' },
+ ssrfPolicy: { hostnameAllowlist: ['*.allowed.example'] },
+ browserProxyMode: 'explicit-browser-proxy',
+ })).resolves.not.toThrow();
+
+ expect(mocks.assertPageNavigationCompletedSafely).not.toHaveBeenCalledWith(
+ expect.objectContaining({ page: userTab }),
+ );
+ expect(mocks.closeBlockedNavigationTarget).not.toHaveBeenCalled();
+ expect(context.close).not.toHaveBeenCalled();
+ expect(context.off).toHaveBeenCalledTimes(1);
+ });
+
+ it('escalates when the close helper resolves but the page did not close', async () => {
+ // closeBlockedNavigationTarget swallows page.close() rejections and resolves
+ // anyway, so its resolution proves nothing. A page that is still open after
+ // it returns must be treated as uncontained, exactly like a timeout.
+ const currentUrl = 'https://start.example/';
+ let contextPageListener: ((page: unknown) => void) | undefined;
+ const popup = {
+ url: () => 'https://evil.example/popup',
+ mainFrame: () => ({ url: () => 'https://evil.example/popup' }),
+ opener: async () => page,
+ on: vi.fn(),
+ off: vi.fn(),
+ isClosed: () => false, // refused to close, despite the helper resolving
+ };
+ const context = {
+ on: vi.fn((_event: string, listener: (page: unknown) => void) => {
+ contextPageListener = listener;
+ }),
+ off: vi.fn(),
+ close: vi.fn(async () => undefined),
+ browser: vi.fn(() => ({ close: vi.fn(async () => undefined) })),
+ };
+ const page = {
+ url: () => currentUrl,
+ mainFrame: () => ({ url: () => currentUrl }),
+ opener: async () => page,
+ on: vi.fn(),
+ off: vi.fn(),
+ context: () => context,
+ };
+ mocks.getPageForTargetId.mockResolvedValue(page);
+ mocks.refLocator.mockReturnValue({
+ click: vi.fn(async () => {
+ contextPageListener?.(popup);
+ }),
+ });
+ mocks.closeBlockedNavigationTarget.mockResolvedValue(undefined);
+ mocks.assertPageNavigationCompletedSafely.mockImplementation(async ({ page: checked }) => {
+ if (checked === popup) throw new Error('Navigation blocked: popup denied');
+ });
+
+ await expect(executeActViaPlaywright({
+ cdpUrl: 'http://127.0.0.1:18800',
+ targetId: 'page-1',
+ action: { kind: 'click', ref: 'e1' },
+ ssrfPolicy: { hostnameAllowlist: ['*.allowed.example'] },
+ browserProxyMode: 'explicit-browser-proxy',
+ })).rejects.toThrow(/popup denied/);
+
+ // A resolved-but-ineffective close must still climb the ladder.
+ expect(context.close).toHaveBeenCalledTimes(1);
+ });
+
+ it('escalates to context teardown when a denied popup will not close', async () => {
+ // A close that hangs is NOT containment: the denied page is still live and
+ // scriptable once the listener detaches. The per-popup path must climb the
+ // same ladder the overflow path uses rather than treating its own timeout
+ // as success.
+ const currentUrl = 'https://start.example/';
+ let contextPageListener: ((page: unknown) => void) | undefined;
+ const popup = {
+ url: () => 'https://evil.example/popup',
+ mainFrame: () => ({ url: () => 'https://evil.example/popup' }),
+ opener: async () => page,
+ on: vi.fn(),
+ off: vi.fn(),
+ };
+ const context = {
+ on: vi.fn((_event: string, listener: (page: unknown) => void) => {
+ contextPageListener = listener;
+ }),
+ off: vi.fn(),
+ close: vi.fn(async () => undefined),
+ browser: vi.fn(() => ({ close: vi.fn(async () => undefined) })),
+ };
+ const page = {
+ url: () => currentUrl,
+ mainFrame: () => ({ url: () => currentUrl }),
+ opener: async () => page,
+ on: vi.fn(),
+ off: vi.fn(),
+ context: () => context,
+ };
+ mocks.getPageForTargetId.mockResolvedValue(page);
+ mocks.refLocator.mockReturnValue({
+ click: vi.fn(async () => {
+ contextPageListener?.(popup);
+ }),
+ });
+ mocks.assertPageNavigationCompletedSafely.mockImplementation(async ({ page: checked }) => {
+ if (checked === popup) throw new Error('Navigation blocked: popup denied');
+ });
+ // The page refuses to close. Note the production helper SWALLOWS this
+ // rejection and resolves anyway, so the code must not infer success from it.
+ mocks.closeBlockedNavigationTarget.mockResolvedValue(undefined);
+
+ // The context DOES close, so containment succeeded overall — the caller
+ // still sees the policy denial, not a teardown failure.
+ await expect(executeActViaPlaywright({
+ cdpUrl: 'http://127.0.0.1:18800',
+ targetId: 'page-1',
+ action: { kind: 'click', ref: 'e1' },
+ ssrfPolicy: { hostnameAllowlist: ['*.allowed.example'] },
+ browserProxyMode: 'explicit-browser-proxy',
+ })).rejects.toThrow(/popup denied/);
+
+ expect(context.close).toHaveBeenCalledTimes(1);
+ expect(context.off).toHaveBeenCalledTimes(1);
+ });
+
+ it('reports an untorn-down browser when no teardown can contain a denied popup', async () => {
+ // Page, context and browser all refuse. This is the only signal the host
+ // uses to distrust the whole route (mentionsUntornDownBrowser), so it must
+ // outrank the ordinary policy denial — otherwise the route stays usable
+ // while pages we never contained keep executing.
+ const currentUrl = 'https://start.example/';
+ let contextPageListener: ((page: unknown) => void) | undefined;
+ const popup = {
+ url: () => 'https://evil.example/popup',
+ mainFrame: () => ({ url: () => 'https://evil.example/popup' }),
+ opener: async () => page,
+ on: vi.fn(),
+ off: vi.fn(),
+ };
+ const browserClose = vi.fn(async () => {
+ throw new Error('browser close failed');
+ });
+ const context = {
+ on: vi.fn((_event: string, listener: (page: unknown) => void) => {
+ contextPageListener = listener;
+ }),
+ off: vi.fn(),
+ close: vi.fn(async () => {
+ throw new Error('context close failed');
+ }),
+ browser: vi.fn(() => ({ close: browserClose })),
+ };
+ const page = {
+ url: () => currentUrl,
+ mainFrame: () => ({ url: () => currentUrl }),
+ opener: async () => page,
+ on: vi.fn(),
+ off: vi.fn(),
+ context: () => context,
+ };
+ mocks.getPageForTargetId.mockResolvedValue(page);
+ mocks.refLocator.mockReturnValue({
+ click: vi.fn(async () => {
+ contextPageListener?.(popup);
+ }),
+ });
+ mocks.assertPageNavigationCompletedSafely.mockImplementation(async ({ page: checked }) => {
+ if (checked === popup) throw new Error('Navigation blocked: popup denied');
+ });
+ // Resolves without the page actually closing — the real helper's catch.
+ mocks.closeBlockedNavigationTarget.mockResolvedValue(undefined);
+
+ await expect(executeActViaPlaywright({
+ cdpUrl: 'http://127.0.0.1:18800',
+ targetId: 'page-1',
+ action: { kind: 'click', ref: 'e1' },
+ ssrfPolicy: { hostnameAllowlist: ['*.allowed.example'] },
+ browserProxyMode: 'explicit-browser-proxy',
+ })).rejects.toThrow(/could not be torn down/);
+
+ expect(context.close).toHaveBeenCalledTimes(1);
+ expect(browserClose).toHaveBeenCalledTimes(1);
+ expect(context.off).toHaveBeenCalledTimes(1);
+ });
+
+ it('validates a popup opened by another popup during its grace window', async () => {
+ // The listener must stay attached across popup validation: a popup can open
+ // a further popup inside its own 250ms window, and detaching early would
+ // leave that second-generation tab uncollected and unvalidated.
+ const currentUrl = 'https://start.example/';
+ let contextPageListener: ((page: unknown) => void) | undefined;
+ const mkPopup = (url: string, onObserve?: () => void) => {
+ let observed = false;
+ return {
+ // Stays at about:blank on first read so the delayed-navigation observer
+ // actually waits, then reports the real URL — the window during which a
+ // further popup can appear.
+ url: () => {
+ if (!observed) { observed = true; onObserve?.(); return 'about:blank'; }
+ return url;
+ },
+ mainFrame: () => ({ url: () => url }),
+ opener: async () => page,
+ on: vi.fn(),
+ off: vi.fn(),
+ };
+ };
+ const second = mkPopup('https://second.example/b');
+ // The second popup appears ASYNCHRONOUSLY while the first one's grace
+ // window is running — i.e. after the old code had already detached the
+ // context listener, so `second` would never be collected at all.
+ let spawned = false;
+ const first = mkPopup('https://first.example/a', () => {
+ if (spawned) return;
+ spawned = true;
+ setTimeout(() => contextPageListener?.(second), 20);
+ });
+ // off() must actually DETACH, or the test cannot tell the fixed code from
+ // the broken code — a mock that keeps the listener callable would let a
+ // late popup through either way.
+ const context = {
+ on: vi.fn((_event: string, listener: (page: unknown) => void) => {
+ contextPageListener = listener;
+ }),
+ off: vi.fn(() => { contextPageListener = undefined; }),
+ };
+ const page = {
+ url: () => currentUrl,
+ mainFrame: () => ({ url: () => currentUrl }),
+ opener: async () => page,
+ on: vi.fn(),
+ off: vi.fn(),
+ context: () => context,
+ };
+ mocks.getPageForTargetId.mockResolvedValue(page);
+ mocks.refLocator.mockReturnValue({
+ click: vi.fn(async () => { contextPageListener?.(first); }),
+ });
+
+ await executeActViaPlaywright({
+ cdpUrl: 'http://127.0.0.1:18800',
+ targetId: 'page-1',
+ action: { kind: 'click', ref: 'e1' },
+ ssrfPolicy: { hostnameAllowlist: ['*.allowed.example'] },
+ browserProxyMode: 'explicit-browser-proxy',
+ });
+
+ for (const popup of [first, second]) {
+ expect(mocks.assertPageNavigationCompletedSafely).toHaveBeenCalledWith(
+ expect.objectContaining({ page: popup }),
+ );
+ }
+ // Detach happens once, only after the whole chain has drained.
+ expect(context.off).toHaveBeenCalledTimes(1);
+ });
+
+ it('terminates and closes the remainder when a popup chain never stops growing', async () => {
+ // An allowlisted page can make every popup open another inside its own
+ // grace window. Draining that queue unbounded never empties: the action
+ // would hang forever, and the backend serializes browser calls, so a later
+ // stop — and dispose at quit — would queue behind it indefinitely.
+ const currentUrl = 'https://start.example/';
+ let contextPageListener: ((page: unknown) => void) | undefined;
+ const closed: string[] = [];
+ let created = 0;
+ const spawnPopup = (): Record<string, unknown> => {
+ const id = `popup-${created += 1}`;
+ let observed = false;
+ return {
+ url: () => {
+ if (!observed) {
+ observed = true;
+ // Each popup spawns another while its own grace window runs.
+ setTimeout(() => contextPageListener?.(spawnPopup()), 5);
+ return 'about:blank';
+ }
+ return `https://chain.example/${id}`;
+ },
+ mainFrame: () => ({ url: () => `https://chain.example/${id}` }),
+ opener: async () => page,
+ on: vi.fn(),
+ off: vi.fn(),
+ close: vi.fn(async () => { closed.push(id); }),
+ };
+ };
+ const context = {
+ on: vi.fn((_e: string, listener: (page: unknown) => void) => { contextPageListener = listener; }),
+ off: vi.fn(() => { contextPageListener = undefined; }),
+ };
+ const page = {
+ url: () => currentUrl,
+ mainFrame: () => ({ url: () => currentUrl }),
+ opener: async () => page,
+ on: vi.fn(),
+ off: vi.fn(),
+ context: () => context,
+ };
+ mocks.getPageForTargetId.mockResolvedValue(page);
+ mocks.refLocator.mockReturnValue({
+ click: vi.fn(async () => { contextPageListener?.(spawnPopup()); }),
+ });
+
+ // The assertion that matters is that this RESOLVES at all.
+ await expect(executeActViaPlaywright({
+ cdpUrl: 'http://127.0.0.1:18800',
+ targetId: 'page-1',
+ action: { kind: 'click', ref: 'e1' },
+ ssrfPolicy: { hostnameAllowlist: ['*.allowed.example'] },
+ browserProxyMode: 'explicit-browser-proxy',
+ })).rejects.toThrow(/validation budget/);
+
+ // Popups past the budget must be closed, not left live and unvalidated —
+ // that would be the very bug the drain exists to prevent.
+ expect(closed.length).toBeGreaterThan(0);
+ expect(context.off).toHaveBeenCalledTimes(1);
+ }, 20_000);
+
+ it('returns even when an overflow popup never finishes closing', async () => {
+ // Bounding validation is not enough: quarantining the overflow serially
+ // awaited every close(), so one unresponsive popup would keep the action —
+ // and the serialized stop/quit cleanup behind it — pending indefinitely.
+ const currentUrl = 'https://start.example/';
+ let contextPageListener: ((page: unknown) => void) | undefined;
+ let created = 0;
+ const spawnPopup = (): Record<string, unknown> => {
+ const id = `popup-${created += 1}`;
+ let observed = false;
+ return {
+ url: () => {
+ if (!observed) {
+ observed = true;
+ setTimeout(() => contextPageListener?.(spawnPopup()), 5);
+ return 'about:blank';
+ }
+ return `https://chain.example/${id}`;
+ },
+ mainFrame: () => ({ url: () => `https://chain.example/${id}` }),
+ opener: async () => page,
+ on: vi.fn(),
+ off: vi.fn(),
+ // Never settles: the close budget, not the page, must end the wait.
+ close: vi.fn(() => new Promise<void>(() => {})),
+ };
+ };
+ const context = {
+ on: vi.fn((_e: string, listener: (page: unknown) => void) => { contextPageListener = listener; }),
+ off: vi.fn(() => { contextPageListener = undefined; }),
+ };
+ const page = {
+ url: () => currentUrl,
+ mainFrame: () => ({ url: () => currentUrl }),
+ opener: async () => page,
+ on: vi.fn(),
+ off: vi.fn(),
+ context: () => context,
+ };
+ mocks.getPageForTargetId.mockResolvedValue(page);
+ mocks.refLocator.mockReturnValue({
+ click: vi.fn(async () => { contextPageListener?.(spawnPopup()); }),
+ });
+
+ await expect(executeActViaPlaywright({
+ cdpUrl: 'http://127.0.0.1:18800',
+ targetId: 'page-1',
+ action: { kind: 'click', ref: 'e1' },
+ ssrfPolicy: { hostnameAllowlist: ['*.allowed.example'] },
+ browserProxyMode: 'explicit-browser-proxy',
+ })).rejects.toThrow(/validation budget/);
+
+ expect(context.off).toHaveBeenCalledTimes(1);
+ // Returning is not enough: a popup whose close() never completes must still
+ // have been quarantined, or it stays live and selectable having never been
+ // URL-checked — and in direct mode no lifetime CDP gate would catch it.
+ expect(mocks.quarantineTargetWithoutClosing).toHaveBeenCalled();
+ }, 20_000);
+
+ it('quarantines popups that arrive during the overflow cleanup window', async () => {
+ // The inner cleanup loop never awaits, so on its own it drains the queue as
+ // it stands and returns before the event loop can deliver another page
+ // event. A popup created while the closes are pending would then be left
+ // live, unvalidated and unquarantined once the listener detaches.
+ const currentUrl = 'https://start.example/';
+ let contextPageListener: ((page: unknown) => void) | undefined;
+ let created = 0;
+ let lateSpawned = false;
+ const quarantined: string[] = [];
+ mocks.quarantineTargetWithoutClosing.mockImplementation(async ({ page }: { page: { url(): string } }) => {
+ quarantined.push(page.url());
+ // Once cleanup begins, deliver one more popup asynchronously — it can
+ // only be seen if the drain yields and re-reads the queue.
+ if (!lateSpawned) {
+ lateSpawned = true;
+ setTimeout(() => contextPageListener?.(mkLate()), 0);
+ }
+ });
+ const mkLate = () => ({
+ url: () => 'https://late.example/arrived-during-cleanup',
+ mainFrame: () => ({ url: () => 'https://late.example/arrived-during-cleanup' }),
+ opener: async () => page,
+ on: vi.fn(),
+ off: vi.fn(),
+ close: vi.fn(async () => {}),
+ });
+ const spawnPopup = (): Record<string, unknown> => {
+ const id = `popup-${created += 1}`;
+ let observed = false;
+ return {
+ url: () => {
+ if (!observed) {
+ observed = true;
+ setTimeout(() => contextPageListener?.(spawnPopup()), 5);
+ return 'about:blank';
+ }
+ return `https://chain.example/${id}`;
+ },
+ mainFrame: () => ({ url: () => `https://chain.example/${id}` }),
+ opener: async () => page,
+ on: vi.fn(),
+ off: vi.fn(),
+ close: vi.fn(async () => {}),
+ };
+ };
+ const context = {
+ on: vi.fn((_e: string, listener: (page: unknown) => void) => { contextPageListener = listener; }),
+ off: vi.fn(() => { contextPageListener = undefined; }),
+ };
+ const page = {
+ url: () => currentUrl,
+ mainFrame: () => ({ url: () => currentUrl }),
+ opener: async () => page,
+ on: vi.fn(),
+ off: vi.fn(),
+ context: () => context,
+ };
+ mocks.getPageForTargetId.mockResolvedValue(page);
+ mocks.refLocator.mockReturnValue({
+ click: vi.fn(async () => { contextPageListener?.(spawnPopup()); }),
+ });
+
+ await expect(executeActViaPlaywright({
+ cdpUrl: 'http://127.0.0.1:18800',
+ targetId: 'page-1',
+ action: { kind: 'click', ref: 'e1' },
+ ssrfPolicy: { hostnameAllowlist: ['*.allowed.example'] },
+ browserProxyMode: 'explicit-browser-proxy',
+ })).rejects.toThrow(/validation budget/);
+
+ expect(quarantined).toContain('https://late.example/arrived-during-cleanup');
+ expect(context.off).toHaveBeenCalledTimes(1);
+ }, 20_000);
+
+ it('closes the whole context when cleanup bounds leave popups unaccounted for', async () => {
+ // The count/time bounds end cleanup, then the listener detaches. Anything
+ // still queued was never validated and never quarantined — in direct mode
+ // nothing else will ever check it. Per-page cleanup has already failed to
+ // keep up at that point, so the context itself must fail closed.
+ const currentUrl = 'https://start.example/';
+ let contextPageListener: ((page: unknown) => void) | undefined;
+ let created = 0;
+ const mk = (): Record<string, unknown> => {
+ const id = `popup-${created += 1}`;
+ let observed = false;
+ return {
+ url: () => {
+ if (!observed) {
+ observed = true;
+ // Append several per turn so the queue outruns any bound.
+ for (let i = 0; i < 8; i += 1) {
+ setTimeout(() => contextPageListener?.(mk()), 0);
+ }
+ return 'about:blank';
+ }
+ return `https://chain.example/${id}`;
+ },
+ mainFrame: () => ({ url: () => `https://chain.example/${id}` }),
+ opener: async () => page,
+ on: vi.fn(),
+ off: vi.fn(),
+ close: vi.fn(() => new Promise<void>(() => {})),
+ };
+ };
+ const contextClose = vi.fn(async () => {});
+ const context = {
+ on: vi.fn((_e: string, listener: (page: unknown) => void) => { contextPageListener = listener; }),
+ off: vi.fn(() => { contextPageListener = undefined; }),
+ close: contextClose,
+ };
+ const page = {
+ url: () => currentUrl,
+ mainFrame: () => ({ url: () => currentUrl }),
+ opener: async () => page,
+ on: vi.fn(),
+ off: vi.fn(),
+ context: () => context,
+ };
+ mocks.getPageForTargetId.mockResolvedValue(page);
+ mocks.refLocator.mockReturnValue({
+ click: vi.fn(async () => { contextPageListener?.(mk()); }),
+ });
+
+ await expect(executeActViaPlaywright({
+ cdpUrl: 'http://127.0.0.1:18800',
+ targetId: 'page-1',
+ action: { kind: 'click', ref: 'e1' },
+ ssrfPolicy: { hostnameAllowlist: ['*.allowed.example'] },
+ browserProxyMode: 'explicit-browser-proxy',
+ })).rejects.toThrow(/validation budget/);
+
+ expect(contextClose).toHaveBeenCalled();
+ }, 30_000);
+
+ it('tears down the browser when the context itself will not close', async () => {
+ // Closing the context is the fail-closed remedy for unaccounted popups. If
+ // that call rejects or never settles, swallowing it and detaching the
+ // listener leaves the same live, never-validated pages — so an unresponsive
+ // context must not be able to preserve the bypass.
+ const currentUrl = 'https://start.example/';
+ let contextPageListener: ((page: unknown) => void) | undefined;
+ let created = 0;
+ const mk = (): Record<string, unknown> => {
+ const id = `popup-${created += 1}`;
+ let observed = false;
+ return {
+ url: () => {
+ if (!observed) {
+ observed = true;
+ for (let i = 0; i < 8; i += 1) {
+ setTimeout(() => contextPageListener?.(mk()), 0);
+ }
+ return 'about:blank';
+ }
+ return `https://chain.example/${id}`;
+ },
+ mainFrame: () => ({ url: () => `https://chain.example/${id}` }),
+ opener: async () => page,
+ on: vi.fn(),
+ off: vi.fn(),
+ close: vi.fn(() => new Promise<void>(() => {})),
+ };
+ };
+ const browserClose = vi.fn(async () => {});
+ const context = {
+ on: vi.fn((_e: string, listener: (page: unknown) => void) => { contextPageListener = listener; }),
+ off: vi.fn(() => { contextPageListener = undefined; }),
+ // Never settles — the deadline, not the context, ends the wait.
+ close: vi.fn(() => new Promise<void>(() => {})),
+ browser: () => ({ close: browserClose }),
+ };
+ const page = {
+ url: () => currentUrl,
+ mainFrame: () => ({ url: () => currentUrl }),
+ opener: async () => page,
+ on: vi.fn(),
+ off: vi.fn(),
+ context: () => context,
+ };
+ mocks.getPageForTargetId.mockResolvedValue(page);
+ mocks.refLocator.mockReturnValue({
+ click: vi.fn(async () => { contextPageListener?.(mk()); }),
+ });
+
+ await expect(executeActViaPlaywright({
+ cdpUrl: 'http://127.0.0.1:18800',
+ targetId: 'page-1',
+ action: { kind: 'click', ref: 'e1' },
+ ssrfPolicy: { hostnameAllowlist: ['*.allowed.example'] },
+ browserProxyMode: 'explicit-browser-proxy',
+ })).rejects.toThrow(/validation budget/);
+
+ expect(browserClose).toHaveBeenCalled();
+ }, 30_000);
+
+ it('reports an untorn-down browser distinctly so the host can block the route', async () => {
+ // The runtime can close pages and contexts but cannot verify a process
+ // exited — only the host owns teardown. When even browser.close() fails,
+ // saying "policy denied" would hide that unvalidated pages may still be
+ // live, so the message has to be distinguishable.
+ const currentUrl = 'https://start.example/';
+ let contextPageListener: ((page: unknown) => void) | undefined;
+ let created = 0;
+ const mk = (): Record<string, unknown> => {
+ const id = `popup-${created += 1}`;
+ let observed = false;
+ return {
+ url: () => {
+ if (!observed) {
+ observed = true;
+ for (let i = 0; i < 8; i += 1) {
+ setTimeout(() => contextPageListener?.(mk()), 0);
+ }
+ return 'about:blank';
+ }
+ return `https://chain.example/${id}`;
+ },
+ mainFrame: () => ({ url: () => `https://chain.example/${id}` }),
+ opener: async () => page,
+ on: vi.fn(),
+ off: vi.fn(),
+ close: vi.fn(() => new Promise<void>(() => {})),
+ };
+ };
+ const context = {
+ on: vi.fn((_e: string, listener: (page: unknown) => void) => { contextPageListener = listener; }),
+ off: vi.fn(() => { contextPageListener = undefined; }),
+ close: vi.fn(() => new Promise<void>(() => {})),
+ // Browser teardown also fails — nothing in-process can contain this.
+ browser: () => ({ close: vi.fn(async () => { throw new Error('browser gone rogue'); }) }),
+ };
+ const page = {
+ url: () => currentUrl,
+ mainFrame: () => ({ url: () => currentUrl }),
+ opener: async () => page,
+ on: vi.fn(),
+ off: vi.fn(),
+ context: () => context,
+ };
+ mocks.getPageForTargetId.mockResolvedValue(page);
+ mocks.refLocator.mockReturnValue({
+ click: vi.fn(async () => { contextPageListener?.(mk()); }),
+ });
+
+ await expect(executeActViaPlaywright({
+ cdpUrl: 'http://127.0.0.1:18800',
+ targetId: 'page-1',
+ action: { kind: 'click', ref: 'e1' },
+ ssrfPolicy: { hostnameAllowlist: ['*.allowed.example'] },
+ browserProxyMode: 'explicit-browser-proxy',
+ })).rejects.toThrow(/could not be torn down/);
+ }, 30_000);
+
+ it('tears down when the queue drained but every close is still hanging', async () => {
+ // popupIndex only records that a close was ISSUED, and quarantine is pure
+ // bookkeeping (quarantineTargetWithoutClosing never closes a page). So a
+ // fully-drained queue whose closes all hang looked completely handled,
+ // teardown was skipped, and every one of those popups stayed live and
+ // scriptable after the listener detached.
+ const currentUrl = 'https://start.example/';
+ let contextPageListener: ((page: unknown) => void) | undefined;
+ // A SMALL, finite burst: the queue drains well within the bounds, so the
+ // only thing that can trigger teardown is the unsettled closes.
+ const mk = (id: string) => ({
+ url: () => `https://chain.example/${id}`,
+ mainFrame: () => ({ url: () => `https://chain.example/${id}` }),
+ opener: async () => page,
+ on: vi.fn(),
+ off: vi.fn(),
+ close: vi.fn(() => new Promise<void>(() => {})),
+ });
+ const contextClose = vi.fn(async () => {});
+ const context = {
+ on: vi.fn((_e: string, listener: (page: unknown) => void) => { contextPageListener = listener; }),
+ off: vi.fn(() => { contextPageListener = undefined; }),
+ close: contextClose,
+ };
+ const page = {
+ url: () => currentUrl,
+ mainFrame: () => ({ url: () => currentUrl }),
+ opener: async () => page,
+ on: vi.fn(),
+ off: vi.fn(),
+ context: () => context,
+ };
+ mocks.getPageForTargetId.mockResolvedValue(page);
+ // Overflow the VALIDATION cap (32) with a finite burst so cleanup runs,
+ // then let the queue drain fully while the closes never settle.
+ mocks.refLocator.mockReturnValue({
+ click: vi.fn(async () => {
+ for (let i = 0; i < 40; i += 1) contextPageListener?.(mk(`p${i}`));
+ }),
+ });
+
+ await expect(executeActViaPlaywright({
+ cdpUrl: 'http://127.0.0.1:18800',
+ targetId: 'page-1',
+ action: { kind: 'click', ref: 'e1' },
+ ssrfPolicy: { hostnameAllowlist: ['*.allowed.example'] },
+ browserProxyMode: 'explicit-browser-proxy',
+ })).rejects.toThrow(/validation budget/);
+
+ expect(contextClose).toHaveBeenCalled();
+ }, 40_000);
+
+ it('reports a containment failure ahead of a denied main-frame navigation', async () => {
+ // An adversarial page can easily arrange both at once. The navigation
+ // denial is the safe outcome — a request was refused. The containment
+ // failure says pages we never validated are still live, and it is the only
+ // signal the host uses to distrust the route, so it must win.
+ // The URL must actually CHANGE for a navigation to be observed at all —
+ // otherwise the guard never runs and there is no navigationError to outrank.
+ let currentUrl = 'https://start.example/';
+ const mainFrame = { url: () => currentUrl };
+ let contextPageListener: ((page: unknown) => void) | undefined;
+ let created = 0;
+ const mk = (): Record<string, unknown> => {
+ const id = `popup-${created += 1}`;
+ let observed = false;
+ return {
+ url: () => {
+ if (!observed) {
+ observed = true;
+ for (let i = 0; i < 8; i += 1) setTimeout(() => contextPageListener?.(mk()), 0);
+ return 'about:blank';
+ }
+ return `https://chain.example/${id}`;
+ },
+ mainFrame: () => ({ url: () => `https://chain.example/${id}` }),
+ opener: async () => page,
+ on: vi.fn(),
+ off: vi.fn(),
+ close: vi.fn(() => new Promise<void>(() => {})),
+ };
+ };
+ const context = {
+ on: vi.fn((_e: string, listener: (page: unknown) => void) => { contextPageListener = listener; }),
+ off: vi.fn(() => { contextPageListener = undefined; }),
+ close: vi.fn(() => new Promise<void>(() => {})),
+ browser: () => ({ close: vi.fn(async () => { throw new Error('browser gone rogue'); }) }),
+ };
+ const page = {
+ url: () => currentUrl,
+ mainFrame: () => mainFrame,
+ on: vi.fn(),
+ off: vi.fn(),
+ context: () => context,
+ };
+ mocks.getPageForTargetId.mockResolvedValue(page);
+ mocks.refLocator.mockReturnValue({
+ click: vi.fn(async () => {
+ currentUrl = 'https://blocked.example/next'; // observable navigation
+ contextPageListener?.(mk());
+ }),
+ });
+ // The main-frame navigation is ALSO denied.
+ mocks.assertPageNavigationCompletedSafely.mockImplementation(async ({ page: p }: { page: unknown }) => {
+ if (p === page) throw new Error('Navigation blocked: main frame');
+ });
+
+ await expect(executeActViaPlaywright({
+ cdpUrl: 'http://127.0.0.1:18800',
+ targetId: 'page-1',
+ action: { kind: 'click', ref: 'e1' },
+ ssrfPolicy: { hostnameAllowlist: ['*.allowed.example'] },
+ browserProxyMode: 'explicit-browser-proxy',
+ })).rejects.toThrow(/could not be torn down/);
+ }, 30_000);
+
+ it('guards script navigation triggered by a direct input file upload', async () => {
+ let currentUrl = 'https://start.example/';
+ const mainFrame = { url: () => currentUrl };
+ const page = {
+ url: () => currentUrl,
+ mainFrame: () => mainFrame,
+ on: vi.fn(),
+ off: vi.fn(),
+ };
+ const locator = {
+ setInputFiles: vi.fn(async () => {
+ currentUrl = 'https://allowed.example/after-upload';
+ }),
+ elementHandle: vi.fn(async () => null),
+ };
+ mocks.getPageForTargetId.mockResolvedValue(page);
+ mocks.refLocator.mockReturnValue(locator);
+
+ await setInputFilesViaPlaywright({
+ cdpUrl: 'http://127.0.0.1:18800',
+ targetId: 'page-1',
+ inputRef: 'e1',
+ paths: ['/tmp/upload.txt'],
+ ssrfPolicy: { hostnameAllowlist: ['*.allowed.example'] },
+ browserProxyMode: 'explicit-browser-proxy',
+ });
+
+ expect(locator.setInputFiles).toHaveBeenCalledWith(['/tmp/upload.txt']);
+ expect(mocks.assertPageNavigationCompletedSafely).toHaveBeenCalledWith(
+ expect.objectContaining({
+ page,
+ ssrfPolicy: { hostnameAllowlist: ['*.allowed.example'] },
+ browserProxyMode: 'explicit-browser-proxy',
+ }),
+ );
+ });
+});
diff --git a/packages/browser-control-runtime/src/__tests__/proxy.test.ts b/packages/browser-control-runtime/src/__tests__/proxy.test.ts
new file mode 100644
index 0000000000..b800a9f7c4
--- /dev/null
+++ b/packages/browser-control-runtime/src/__tests__/proxy.test.ts
@@ -0,0 +1,367 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ isBrowserProxyRequestUrlAllowed,
+ isBrowserProxyRequestUrlAllowedAsync,
+ parseBrowserProxyServer,
+ redactBrowserProxyRoute,
+ redactBrowserProxyText,
+ resetBrowserProxyDnsVerdictCache,
+} from '../proxy.js';
+
+describe('browser proxy normalization', () => {
+ it('canonicalizes Chromium-supported proxy URL forms', () => {
+ expect(parseBrowserProxyServer('HTTP://Proxy.Example:80')).toEqual({
+ mode: 'proxied',
+ server: 'http://proxy.example',
+ });
+ expect(parseBrowserProxyServer('socks5://[2001:db8::1]:1080')).toEqual({
+ mode: 'proxied',
+ server: 'socks5://[2001:db8::1]:1080',
+ });
+ expect(parseBrowserProxyServer(undefined)).toEqual({ mode: 'direct' });
+ });
+
+ it('canonicalizes and carries a bounded public hostname allowlist', () => {
+ expect(parseBrowserProxyServer('http://proxy.example:8080', [
+ '*.EXAMPLE.COM',
+ 'auth.example.com',
+ 'auth.example.com',
+ ])).toEqual({
+ mode: 'proxied',
+ server: 'http://proxy.example:8080',
+ allowedHostnames: ['*.example.com', 'auth.example.com'],
+ });
+ });
+
+ it('rejects authenticated proxy URLs (userinfo is not supported)', () => {
+ // Authenticated proxies cannot be supported safely over connectOverCDP —
+ // the only credential channel also leaks to untrusted origins — so userinfo
+ // is a loud parse-time rejection rather than a silent no-auth launch.
+ for (const raw of [
+ 'http://u%2Fser:p%40ss%3Aword%[email protected]:8080',
+ 'http://user:[email protected]:8080',
+ 'http://[email protected]:8080',
+ 'https://user:[email protected]:8443',
+ 'socks5://user:[email protected]:1080',
+ ]) {
+ expect(() => parseBrowserProxyServer(raw), raw).toThrow(/invalid proxyServer/);
+ }
+ });
+
+ it('rejects oversized proxy input before any destructive route change', () => {
+ // WHATWG URL happily accepts a hostname of hundreds of thousands of chars.
+ // Parsing must reject it, because a route switch stops the running browser
+ // FIRST and only then builds the PAC/argv — so oversized input that fails
+ // later costs the user their tabs.
+ const longLabel = 'a'.repeat(64); // one over the 63-char DNS label limit
+ const longName = `${'a'.repeat(60)}.`.repeat(5) + 'example.com';
+ expect(() => parseBrowserProxyServer(`http://${longLabel}.example.com:8080`))
+ .toThrow(/at most 63 characters/);
+ expect(() => parseBrowserProxyServer(`http://${'a'.repeat(300)}:8080`))
+ .toThrow(/invalid proxyServer/);
+ expect(() => parseBrowserProxyServer(`http://proxy.example:8080?${'a'.repeat(5000)}`))
+ .toThrow(/invalid proxyServer/);
+ // Allowlist entries are bounded the same way.
+ expect(() => parseBrowserProxyServer('http://proxy.example:8080', [`${longLabel}.example.com`]))
+ .toThrow(/at most 63 characters/);
+ expect(() => parseBrowserProxyServer('http://proxy.example:8080', [longName + '.' + 'b'.repeat(250)]))
+ .toThrow(/at most 253 characters/);
+ // A normal name at the boundary still parses.
+ expect(parseBrowserProxyServer('http://proxy.example:8080', ['a'.repeat(63) + '.example.com']))
+ .toMatchObject({ mode: 'proxied' });
+ });
+
+ it('rejects empty and non-LDH DNS labels before any destructive route change', () => {
+ // WHATWG URL preserves these hostnames verbatim, so without a label check
+ // they pass parsing, the route switch stops the running browser, and only
+ // then does PAC/DNS matching fail — losing the user's tabs.
+ for (const hostname of [
+ 'example..com',
+ '_foo.example.com',
+ '-foo.example.com',
+ 'foo-.example.com',
+ 'foo_bar.example.com',
+ ]) {
+ expect(() => parseBrowserProxyServer('http://proxy.example:8080', [hostname]), hostname)
+ .toThrow(/invalid proxyServer/);
+ expect(() => parseBrowserProxyServer('http://proxy.example:8080', [`*.${hostname}`]), hostname)
+ .toThrow(/invalid proxyServer/);
+ expect(() => parseBrowserProxyServer(`http://${hostname}:8080`), hostname)
+ .toThrow(/invalid proxyServer/);
+ }
+ // Trailing-dot FQDNs have an empty final label; strictness beats a dead route.
+ expect(() => parseBrowserProxyServer('http://proxy.example.:8080'))
+ .toThrow(/invalid proxyServer/);
+ // Hyphens inside a label stay legal, as do IP-literal proxy hosts.
+ expect(parseBrowserProxyServer('http://proxy.example:8080', ['foo-bar.example.com']))
+ .toMatchObject({ mode: 'proxied', allowedHostnames: ['foo-bar.example.com'] });
+ expect(parseBrowserProxyServer('http://10.0.0.1:8080'))
+ .toEqual({ mode: 'proxied', server: 'http://10.0.0.1:8080' });
+ expect(parseBrowserProxyServer('socks5://[2001:db8::1]:1080'))
+ .toEqual({ mode: 'proxied', server: 'socks5://[2001:db8::1]:1080' });
+ });
+
+ it('never surfaces credentials in the redacted route', () => {
+ const route = parseBrowserProxyServer('http://proxy.example:8080');
+ expect(route).toEqual({ mode: 'proxied', server: 'http://proxy.example:8080' });
+ expect(redactBrowserProxyRoute(route)).toEqual({
+ mode: 'proxied',
+ server: 'http://proxy.example:8080',
+ });
+ });
+
+ it.each([
+ '',
+ 'proxy.example:8080',
+ 'http://proxy.example:',
+ 'ftp://proxy.example:21',
+ 'http://proxy.example:8080/path',
+ 'http://proxy.example:8080/.',
+ 'http://proxy.example:8080/%2e',
+ 'http://proxy.example:8080//',
+ 'http://proxy.example:8080?token=secret',
+ 'http://proxy.example:8080#fragment',
+ 'http://proxy.example:8080,direct://',
+ 'http://proxy.example:99999',
+ 'socks5://user:[email protected]:1080',
+ ])('rejects ambiguous or unsupported value %s', (value) => {
+ expect(() => parseBrowserProxyServer(value)).toThrow(/invalid proxyServer/);
+ });
+
+ it.each([
+ ['http://proxy.example:8080', ['localhost']],
+ ['http://proxy.example:8080', ['127.0.0.1']],
+ ['http://proxy.example:8080', ['example.com:443']],
+ ['http://proxy.example:8080', ['https://example.com']],
+ ['http://proxy.example:8080', ['example.com/path']],
+ [undefined, ['example.com']],
+ ] as const)('rejects unsafe or detached hostname allowlists', (proxy, hostnames) => {
+ expect(() => parseBrowserProxyServer(proxy, hostnames)).toThrow(/invalid proxyServer/);
+ });
+
+ describe('request-level proxy policy', () => {
+ const proxied = parseBrowserProxyServer('http://proxy.example:8080', [
+ 'allowed.example',
+ '*.wild.example',
+ ]);
+
+ it.each([
+ ['https://allowed.example/page', true],
+ ['https://ALLOWED.example./page', true],
+ ['https://sub.wild.example/a', true],
+ ['https://deep.sub.wild.example/a', true],
+ ['https://wild.example/a', false],
+ ['https://notallowed.example/a', false],
+ ['https://allowed.example.evil.test/a', false],
+ ['http://allowed.example/page', false],
+ ['ftp://allowed.example/page', false],
+ ['not a url', false],
+ ['', false],
+ ])('applies HTTPS + allowlist policy to %s', (url, expected) => {
+ expect(isBrowserProxyRequestUrlAllowed(url, proxied)).toBe(expected);
+ });
+
+ it('blocks private literals and internal names that slip past the allowlist', () => {
+ // The allowlist is a NAME list, so it cannot by itself keep a request off
+ // a private target. Apply the same host/IP policy the navigation guard
+ // uses, so an allowlisted-looking request cannot reach loopback, RFC1918
+ // or cloud-metadata addresses through the proxy.
+ const route = parseBrowserProxyServer('http://proxy.example:8080', [
+ '*.example.com',
+ 'metadata.google.internal.example.com',
+ ]);
+ // A wildcard cannot be exploited into a literal/internal target.
+ for (const host of ['127.0.0.1', '192.168.1.1', '10.0.0.1', 'localhost']) {
+ expect(
+ isBrowserProxyRequestUrlAllowed(`https://${host}/`, route),
+ host,
+ ).toBe(false);
+ }
+ // A genuinely public allowlisted host is still permitted.
+ expect(isBrowserProxyRequestUrlAllowed('https://auth.example.com/', route)).toBe(true);
+ });
+
+ it('blocks everything when a proxied route carries no allowlist', () => {
+ const noAllowlist = parseBrowserProxyServer('http://proxy.example:8080');
+ expect(isBrowserProxyRequestUrlAllowed('https://anything.example/', noAllowlist)).toBe(false);
+ });
+
+ it('does not constrain direct routes', () => {
+ expect(isBrowserProxyRequestUrlAllowed('http://anything.example/', { mode: 'direct' })).toBe(
+ true,
+ );
+ });
+ });
+
+ describe('request-level DNS verification', () => {
+ const route = parseBrowserProxyServer('http://proxy.example:8080', [
+ 'allowed.example',
+ '*.wild.example',
+ ]);
+ const lookupOf = (address: string) =>
+ vi.fn(async () => [{ address, family: address.includes(':') ? 6 : 4 }]) as never;
+
+ beforeEach(() => {
+ resetBrowserProxyDnsVerdictCache();
+ });
+
+ it('rejects an allowlisted name that resolves to a private address', async () => {
+ // The textual allowlist cannot see this: `allowed.example` matches, but
+ // the answer points inward (the `127.0.0.1.nip.io` class of bypass).
+ expect(isBrowserProxyRequestUrlAllowed('https://allowed.example/', route)).toBe(true);
+ await expect(
+ isBrowserProxyRequestUrlAllowedAsync('https://allowed.example/', route, {
+ lookupFn: lookupOf('127.0.0.1'),
+ }),
+ ).resolves.toBe(false);
+ });
+
+ it.each(['10.0.0.5', '192.168.1.10', '169.254.169.254', '::1'])(
+ 'rejects a private answer %s',
+ async (address) => {
+ await expect(
+ isBrowserProxyRequestUrlAllowedAsync('https://sub.wild.example/', route, {
+ lookupFn: lookupOf(address),
+ }),
+ ).resolves.toBe(false);
+ },
+ );
+
+ it('permits an allowlisted name that resolves publicly', async () => {
+ await expect(
+ isBrowserProxyRequestUrlAllowedAsync('https://allowed.example/', route, {
+ lookupFn: lookupOf('93.184.216.34'),
+ }),
+ ).resolves.toBe(true);
+ });
+
+ it('denies name-level failures without paying a lookup', async () => {
+ const lookupFn = lookupOf('93.184.216.34');
+ // Not on the allowlist, and plain HTTP: both must be refused by the cheap
+ // check, so DNS is never consulted.
+ await expect(
+ isBrowserProxyRequestUrlAllowedAsync('https://notallowed.example/', route, { lookupFn }),
+ ).resolves.toBe(false);
+ await expect(
+ isBrowserProxyRequestUrlAllowedAsync('http://allowed.example/', route, { lookupFn }),
+ ).resolves.toBe(false);
+ expect(lookupFn).not.toHaveBeenCalled();
+ });
+
+ it('fails closed when the name does not resolve at all', async () => {
+ await expect(
+ isBrowserProxyRequestUrlAllowedAsync('https://allowed.example/', route, {
+ lookupFn: vi.fn(async () => { throw new Error('ENOTFOUND'); }) as never,
+ }),
+ ).resolves.toBe(false);
+ });
+
+ it('never caches an allow, so a rebind is caught on the very next request', async () => {
+ // Caching a positive verdict would hand an attacker a stable bypass:
+ // answer publicly once, then repoint at loopback and every request in the
+ // window skips resolution while the proxy connects to the new answer.
+ let clock = 1_000;
+ const now = () => clock;
+ const publicLookup = lookupOf('93.184.216.34');
+ for (let i = 0; i < 3; i += 1) {
+ await expect(
+ isBrowserProxyRequestUrlAllowedAsync('https://allowed.example/page', route, {
+ lookupFn: publicLookup,
+ now,
+ }),
+ ).resolves.toBe(true);
+ }
+ // Every allowed request re-resolves — no window where the answer is assumed.
+ expect(publicLookup).toHaveBeenCalledTimes(3);
+
+ // Rebind with the clock UNCHANGED: no TTL has lapsed, and it is still
+ // refused immediately.
+ await expect(
+ isBrowserProxyRequestUrlAllowedAsync('https://allowed.example/page', route, {
+ lookupFn: lookupOf('127.0.0.1'),
+ now,
+ }),
+ ).resolves.toBe(false);
+ });
+
+ it('caches denials, then re-resolves once the TTL lapses', async () => {
+ let clock = 1_000;
+ const now = () => clock;
+ const privateLookup = lookupOf('127.0.0.1');
+ for (let i = 0; i < 3; i += 1) {
+ await expect(
+ isBrowserProxyRequestUrlAllowedAsync('https://allowed.example/page', route, {
+ lookupFn: privateLookup,
+ now,
+ }),
+ ).resolves.toBe(false);
+ }
+ // A denial IS cached: repeated blocked requests must not each pay a lookup.
+ expect(privateLookup).toHaveBeenCalledTimes(1);
+
+ // But a stale denial must not outlive its TTL — a name can recover.
+ clock += 30_001;
+ await expect(
+ isBrowserProxyRequestUrlAllowedAsync('https://allowed.example/page', route, {
+ lookupFn: lookupOf('93.184.216.34'),
+ now,
+ }),
+ ).resolves.toBe(true);
+ });
+
+ it('permits the IPv4 fake-IP range but never private IPv6', async () => {
+ // Clash/Surge/sing-box resolve ordinary public hostnames into
+ // 198.18.0.0/15. The managed config grants the navigation guard that same
+ // exemption; without it here proxy mode is unusable on such a machine and
+ // the two layers would disagree about the same hostname. The range is
+ // reserved for benchmarking, so exempting it reaches no real service.
+ resetBrowserProxyDnsVerdictCache();
+ await expect(
+ isBrowserProxyRequestUrlAllowedAsync('https://allowed.example/', route, {
+ lookupFn: lookupOf('198.18.0.5'),
+ }),
+ ).resolves.toBe(true);
+ // IPv6 ULA is NOT exempted: fc00::/7 is where real internal services live
+ // and the range cannot be told apart from a fake IP, so an allowlisted
+ // name answering with a private AAAA must still be refused.
+ for (const address of ['fd00::1', 'fc00::1']) {
+ resetBrowserProxyDnsVerdictCache();
+ await expect(
+ isBrowserProxyRequestUrlAllowedAsync('https://allowed.example/', route, {
+ lookupFn: lookupOf(address),
+ }),
+ address,
+ ).resolves.toBe(false);
+ }
+ // The exemption is narrow: ordinary private ranges stay blocked.
+ resetBrowserProxyDnsVerdictCache();
+ await expect(
+ isBrowserProxyRequestUrlAllowedAsync('https://allowed.example/', route, {
+ lookupFn: lookupOf('192.168.1.10'),
+ }),
+ ).resolves.toBe(false);
+ });
+
+ it('does not constrain direct routes', async () => {
+ const lookupFn = lookupOf('127.0.0.1');
+ await expect(
+ isBrowserProxyRequestUrlAllowedAsync('http://anything.example/', { mode: 'direct' }, {
+ lookupFn,
+ }),
+ ).resolves.toBe(true);
+ expect(lookupFn).not.toHaveBeenCalled();
+ });
+ });
+
+ it('redacts reserved-character credentials from arbitrary errors', () => {
+ const raw =
+ 'dial http://u%2Fser:p%40ss%3Aword%[email protected]:8080 and http://user:p@[email protected] failed';
+ const redacted = redactBrowserProxyText(raw);
+ expect(redacted).not.toContain('u%2Fser');
+ expect(redacted).not.toContain('p%40ss');
+ expect(redacted).not.toContain('p@ss');
+ expect(redacted).toContain('http://[REDACTED]@proxy.example:8080');
+ expect(redacted).toContain('http://[REDACTED]@other.example');
+ });
+});
diff --git a/packages/browser-control-runtime/src/__tests__/runtime.test.ts b/packages/browser-control-runtime/src/__tests__/runtime.test.ts
index c97604b2c7..9c33b222e6 100644
--- a/packages/browser-control-runtime/src/__tests__/runtime.test.ts
+++ b/packages/browser-control-runtime/src/__tests__/runtime.test.ts
@@ -30,6 +30,39 @@ describe('createBrowserControlRuntime — request planning + dispatch', () => {
expect(plan.query).toMatchObject({ targetId: 't1', maxChars: 500, timeoutMs: 9000 });
});
+ it('accepts proxyServer only for start and does not forward it to the vendored route', () => {
+ expect(planDispatch({ action: 'start', proxyServer: 'http://proxy.test:8080' })).toEqual({
+ method: 'POST',
+ path: '/start',
+ body: {},
+ });
+ expect(() => planDispatch({ action: 'status', proxyServer: 'http://proxy.test:8080' }))
+ .toThrow(/only valid for action=start/);
+ });
+
+ it('rejects a credentialed proxyServer at the planning layer', () => {
+ // Authenticated proxies are unsupported; the rejection must happen before
+ // any dispatch is planned, not deeper in the launch path.
+ expect(() => planDispatch({ action: 'start', proxyServer: 'http://u:[email protected]:8080' }))
+ .toThrow(/authenticated proxies are not supported/);
+ });
+
+ it('validates and does not forward proxy navigation policy', () => {
+ expect(planDispatch({
+ action: 'start',
+ proxyServer: 'http://proxy.test:8080',
+ proxyAllowedHostnames: ['*.example.com'],
+ })).toEqual({
+ method: 'POST',
+ path: '/start',
+ body: {},
+ });
+ expect(() => planDispatch({
+ action: 'status',
+ proxyAllowedHostnames: ['*.example.com'],
+ })).toThrow(/only valid for action=start/);
+ });
+
it('forwards act timeoutMs into the /act body (top-level, or nested wins)', () => {
// The /act normalizer reads body.timeoutMs; a raw act call carries it at the
// top level and must not be dropped.
diff --git a/packages/browser-control-runtime/src/__tests__/ssrf-guard.test.ts b/packages/browser-control-runtime/src/__tests__/ssrf-guard.test.ts
index a013b43013..f62e3ff3c6 100644
--- a/packages/browser-control-runtime/src/__tests__/ssrf-guard.test.ts
+++ b/packages/browser-control-runtime/src/__tests__/ssrf-guard.test.ts
@@ -4,6 +4,8 @@ import {
fetchSingleHopWithSsrFGuard,
fetchWithSsrFGuard,
} from '../shim/ssrf-runtime.js';
+import { assertBrowserNavigationAllowed } from '../_generated/extension/src/browser/navigation-guard.js';
+import { withAllowedHostname } from '../_generated/extension/src/browser/ssrf-policy-helpers.js';
import {
isBlockedHostnameOrIp,
isPrivateIpAddress,
@@ -75,6 +77,53 @@ describe('vendored SSRF decision primitives', () => {
);
});
+describe('proxied browser navigation policy', () => {
+ it('fails closed without an explicit public-hostname allowlist', async () => {
+ await expect(assertBrowserNavigationAllowed({
+ url: 'https://auth.example.com/authorize',
+ browserProxyMode: 'explicit-browser-proxy',
+ ssrfPolicy: {},
+ lookupFn: lookupAddresses([{ address: '8.8.8.8', family: 4 }]),
+ })).rejects.toThrow(/requires an explicit public-hostname allowlist/);
+ });
+
+ it('blocks cleartext navigation even when the proxy destination is allowlisted', async () => {
+ await expect(assertBrowserNavigationAllowed({
+ url: 'http://auth.example.com/authorize',
+ browserProxyMode: 'explicit-browser-proxy',
+ ssrfPolicy: { hostnameAllowlist: ['*.example.com'] },
+ lookupFn: lookupAddresses([{ address: '8.8.8.8', family: 4 }]),
+ })).rejects.toThrow(/requires HTTPS/);
+ });
+
+ it('allows an allowlisted proxy destination after public DNS validation', async () => {
+ await expect(assertBrowserNavigationAllowed({
+ url: 'https://auth.example.com/authorize',
+ browserProxyMode: 'explicit-browser-proxy',
+ ssrfPolicy: { hostnameAllowlist: ['*.example.com'] },
+ lookupFn: lookupAddresses([{ address: '8.8.8.8', family: 4 }]),
+ })).resolves.toBeUndefined();
+ });
+
+ it('blocks private DNS answers even for an allowlisted proxy destination', async () => {
+ await expect(assertBrowserNavigationAllowed({
+ url: 'https://auth.example.com/authorize',
+ browserProxyMode: 'explicit-browser-proxy',
+ ssrfPolicy: { hostnameAllowlist: ['*.example.com'] },
+ lookupFn: lookupAddresses([{ address: '127.0.0.1', family: 4 }]),
+ })).rejects.toThrow(/blocked/i);
+ });
+
+ it('blocks a public destination outside the proxy allowlist', async () => {
+ await expect(assertBrowserNavigationAllowed({
+ url: 'https://example.com/',
+ browserProxyMode: 'explicit-browser-proxy',
+ ssrfPolicy: { hostnameAllowlist: ['*.example.com'] },
+ lookupFn: lookupAddresses([{ address: '8.8.8.8', family: 4 }]),
+ })).rejects.toThrow(/allowlist/i);
+ });
+});
+
describe('fetchWithSsrFGuard thin shell', () => {
it('rejects non-http(s) schemes before any network access', async () => {
await expect(
@@ -224,3 +273,32 @@ describe('fetchWithSsrFGuard thin shell', () => {
).rejects.not.toThrow(/blocked|not in allowlist/i);
});
});
+
+describe('one-off hostname grants under a strict allowlist', () => {
+ // Regression: a per-start proxyAllowedHostnames lands in `hostnameAllowlist`,
+ // but the CDP endpoint's own exemption used to write only `allowedHostnames`.
+ // The loopback endpoint was therefore blocked by the very allowlist meant for
+ // page navigation, and EVERY proxied navigation failed with
+ // "browser endpoint blocked by policy". Found by end-to-end run, not units.
+ it('grants the loopback CDP endpoint through both policy fields', () => {
+ const granted = withAllowedHostname(
+ { hostnameAllowlist: ['example.com'] },
+ '127.0.0.1',
+ );
+ expect(granted.allowedHostnames).toContain('127.0.0.1');
+ expect(granted.hostnameAllowlist).toContain('127.0.0.1');
+ // The caller's own allowlist entries must survive the grant.
+ expect(granted.hostnameAllowlist).toContain('example.com');
+ });
+
+ it('does not invent an allowlist when the policy has none', () => {
+ // An absent/empty allowlist means "no allowlist", not "allow only this
+ // host" — inventing one here would silently narrow an unrestricted policy
+ // to a single host. Absent stays absent; empty stays empty (which
+ // matchesHostnameAllowlist also treats as unrestricted).
+ expect(withAllowedHostname({}, '127.0.0.1').hostnameAllowlist).toBeUndefined();
+ expect(
+ withAllowedHostname({ hostnameAllowlist: [] }, '127.0.0.1').hostnameAllowlist,
+ ).toEqual([]);
+ });
+});
diff --git a/packages/browser-control-runtime/src/_generated/extension/src/browser/chrome.ts b/packages/browser-control-runtime/src/_generated/extension/src/browser/chrome.ts
index 29537960de..7fc189d398 100644
--- a/packages/browser-control-runtime/src/_generated/extension/src/browser/chrome.ts
+++ b/packages/browser-control-runtime/src/_generated/extension/src/browser/chrome.ts
@@ -449,6 +449,80 @@ function readCurrentHostSingletonPid(userDataDir: string, hostname = os.hostname
return lock.pid;
}
+/**
+ * PID of the live Chrome owning this managed profile, or null if none.
+ *
+ * Reads the profile's SingletonLock and confirms the process actually exists,
+ * so callers can distinguish "the process is gone" from "the CDP endpoint went
+ * quiet" — a busy or stalled Chrome produces the latter while still running.
+ */
+export function readManagedProfileOwnerPid(userDataDir: string): number | null {
+ return readCurrentHostSingletonPid(userDataDir);
+}
+
+/**
+ * Whether this exact PID holds the CDP port.
+ *
+ * Positive identity, unlike the lock alone: the lock records a PID that the OS
+ * may since have recycled, so anything destructive must confirm the process it
+ * is about to signal is really the browser. Returns false on platforms with no
+ * probe (Windows), which keeps callers fail-safe rather than fail-destructive.
+ */
+export function managedProfilePidOwnsCdpPort(pid: number, cdpPort: number): boolean {
+ return pidListensOnPort(pid, cdpPort);
+}
+
+/**
+ * Whether this PID is a Chrome launched for exactly this profile and port.
+ *
+ * Identity from the process itself, not inferred from what it happens to hold:
+ * holding a port proves only that something is listening, and a port freed by
+ * an exited Chrome can be taken over by anything. Required before anything
+ * destructive — the command line must carry both our --user-data-dir and our
+ * --remote-debugging-port. Returns false wherever the command line cannot be
+ * read, so callers fail safe rather than fail destructive.
+ */
+export function pidIsManagedChromeForProfile(params: {
+ pid: number;
+ cdpPort: number;
+ userDataDir: string;
+}): boolean {
+ if (!processExists(params.pid)) return false;
+ const command = readManagedProcessCommandLine(params.pid);
+ if (!command) return false;
+ return (
+ managedCommandHasExactArg(command, `--remote-debugging-port=${params.cdpPort}`) &&
+ managedCommandHasExactArg(command, `--user-data-dir=${params.userDataDir}`)
+ );
+}
+
+/**
+ * Exact-argument match for a process command line.
+ *
+ * NOT processCommandHasArg: that falls back to `text.includes` when argv is
+ * unavailable, which it always is on Darwin (ps yields a flat string). A
+ * substring test accepts `--user-data-dir=<dir>-backup` for `<dir>`, and this
+ * result gates SIGTERM/SIGKILL — so an unrelated Chrome could be killed. Where
+ * argv exists the element comparison is already exact; otherwise require a
+ * whitespace or quote delimiter on both sides.
+ */
+function managedCommandHasExactArg(
+ command: { argv: string[] | null; text: string },
+ expected: string,
+): boolean {
+ if (command.argv) {
+ return command.argv.includes(expected);
+ }
+ let offset = command.text.indexOf(expected);
+ while (offset >= 0) {
+ const before = offset === 0 ? "" : command.text[offset - 1];
+ const after = command.text[offset + expected.length] ?? "";
+ if ((!before || /[\s"']/.test(before)) && (!after || /[\s"']/.test(after))) return true;
+ offset = command.text.indexOf(expected, offset + 1);
+ }
+ return false;
+}
+
function clearChromeSingletonArtifacts(userDataDir: string) {
for (const basename of CHROME_SINGLETON_LOCK_PATHS) {
try {
diff --git a/packages/browser-control-runtime/src/_generated/extension/src/browser/navigation-guard.ts b/packages/browser-control-runtime/src/_generated/extension/src/browser/navigation-guard.ts
index de777842c1..7bf71f9948 100644
--- a/packages/browser-control-runtime/src/_generated/extension/src/browser/navigation-guard.ts
+++ b/packages/browser-control-runtime/src/_generated/extension/src/browser/navigation-guard.ts
@@ -131,15 +131,30 @@ export async function assertBrowserNavigationAllowed(
);
}
- // Browser proxy routing hides the final connect target from this process.
- // Only block when the browser profile is known to be proxy-routed; Gateway
- // provider proxy env alone is not proof of browser page proxy behavior.
+ // An explicit browser proxy resolves and connects outside this process, so
+ // local DNS pinning alone cannot prove the final connect target. Keep proxy
+ // navigation fail-closed unless the caller supplied a narrow public-hostname
+ // allowlist for this launch. The normal policy resolver below still rejects
+ // blocked names and private/special-use DNS answers for every permitted host.
if (
opts.browserProxyMode === "explicit-browser-proxy" &&
- !isPrivateNetworkAllowedByPolicy(opts.ssrfPolicy)
+ parsed.protocol !== "https:"
) {
throw new InvalidBrowserNavigationUrlError(
- "Navigation blocked: strict browser SSRF policy cannot be enforced while this browser profile is proxy-routed",
+ "Navigation blocked: proxied browser navigation requires HTTPS",
+ );
+ }
+ const proxyHostnameAllowlist = (opts.ssrfPolicy?.hostnameAllowlist ?? [])
+ .map((pattern) => normalizeHostname(pattern))
+ .filter(Boolean);
+ if (
+ opts.browserProxyMode === "explicit-browser-proxy" &&
+ !isPrivateNetworkAllowedByPolicy(opts.ssrfPolicy) &&
+ (proxyHostnameAllowlist.length === 0 ||
+ !matchesHostnameAllowlist(normalizeHostname(parsed.hostname), proxyHostnameAllowlist))
+ ) {
+ throw new InvalidBrowserNavigationUrlError(
+ "Navigation blocked: proxied browser navigation requires an explicit public-hostname allowlist",
);
}
diff --git a/packages/browser-control-runtime/src/_generated/extension/src/browser/pw-session.ts b/packages/browser-control-runtime/src/_generated/extension/src/browser/pw-session.ts
index 0c67290439..b47f8a28a8 100644
--- a/packages/browser-control-runtime/src/_generated/extension/src/browser/pw-session.ts
+++ b/packages/browser-control-runtime/src/_generated/extension/src/browser/pw-session.ts
@@ -1284,6 +1284,22 @@ async function quarantineBlockedTarget(opts: {
}
}
+/**
+ * Mark a target unusable WITHOUT closing it.
+ *
+ * closeBlockedNavigationTarget awaits page.close(), which an adversarial or
+ * hung page can stall indefinitely. Quarantine is the part that must not
+ * depend on the page cooperating: marking is synchronous bookkeeping, so a
+ * target can be made unselectable even when its close never returns.
+ */
+export async function quarantineTargetWithoutClosing(opts: {
+ cdpUrl: string;
+ page: Page;
+ targetId?: string;
+}): Promise<void> {
+ await quarantineBlockedTarget(opts);
+}
+
// Quarantine and close a tab that OpenClaw itself navigated to a blocked URL.
// Only callers that own the navigation lifecycle (gotoPageWithNavigationGuard
// and the navigate-style entry points that wrap it) may invoke this — closing
diff --git a/packages/browser-control-runtime/src/_generated/extension/src/browser/pw-tools-core.interactions.ts b/packages/browser-control-runtime/src/_generated/extension/src/browser/pw-tools-core.interactions.ts
index f63ea5302c..64a5f1a1c4 100644
--- a/packages/browser-control-runtime/src/_generated/extension/src/browser/pw-tools-core.interactions.ts
+++ b/packages/browser-control-runtime/src/_generated/extension/src/browser/pw-tools-core.interactions.ts
@@ -23,17 +23,20 @@ import { normalizeBrowserEvaluateFunctionSource } from "./evaluate-source.js";
import { DEFAULT_FILL_FIELD_TYPE } from "./form-fields.js";
import {
assertBrowserNavigationResultAllowed,
+ type BrowserNavigationPolicyOptions,
withBrowserNavigationPolicy,
} from "./navigation-guard.js";
import { resolveStrictExistingUploadPaths } from "./paths.js";
import {
assertPageNavigationCompletedSafely,
+ closeBlockedNavigationTarget,
createObservedDialogAbortSignalForPage,
ensurePageState,
forceDisconnectPlaywrightForTarget,
getPageForTargetId,
isBrowserObservedDialogBlockedError,
markObservedDialogsHandledRemotelyForPage,
+ quarantineTargetWithoutClosing,
refLocator,
restoreRoleRefsForTarget,
} from "./pw-session.js";
@@ -61,6 +64,24 @@ type TargetOpts = {
const INTERACTION_NAVIGATION_GRACE_MS = 250;
+// Bounds for draining the popup chain after an interaction. The queue is
+// adversarial — validating a popup can append another — so it needs a ceiling
+// on both count and wall-clock, or a page that opens one popup per grace
+// window keeps the action (and every serialized call behind it) alive forever.
+const POPUP_CHAIN_MAX_VALIDATIONS = 32;
+const POPUP_CHAIN_DRAIN_BUDGET_MS = 5_000;
+// Quarantining the overflow needs its own bounds: an unresponsive close() must
+// not keep the action pending any more than an endless popup chain may.
+const POPUP_CHAIN_MAX_CLOSES = 256;
+const POPUP_CHAIN_CLOSE_BUDGET_MS = 2_000;
+
+// The one message the host matches on to distrust the whole route
+// (`mentionsUntornDownBrowser` in external-chrome-backend.ts). Every path that
+// fails to contain a page must report exactly this, or the host keeps serving
+// a route whose pages are still live.
+const UNTORN_DOWN_BROWSER_MESSAGE =
+ "Navigation blocked: popup chain exceeded the validation budget and the browser could not be torn down; unvalidated pages may still be live";
+
type NavigationObservablePage = Pick<Page, "url"> & {
mainFrame?: () => Frame;
on?: (event: "framenavigated", listener: (frame: Frame) => void) => unknown;
@@ -157,8 +178,12 @@ function isMainFrameNavigation(page: NavigationObservablePage, frame: Frame): bo
async function assertSubframeNavigationAllowed(
frameUrl: string,
ssrfPolicy?: SsrFPolicy,
+ browserProxyMode?: BrowserNavigationPolicyOptions["browserProxyMode"],
): Promise<void> {
- if (!ssrfPolicy || (!frameUrl.startsWith("http://") && !frameUrl.startsWith("https://"))) {
+ if (
+ (!ssrfPolicy && !browserProxyMode) ||
+ (!frameUrl.startsWith("http://") && !frameUrl.startsWith("https://"))
+ ) {
// Non-network frame URLs like about:blank and about:srcdoc do not cross the
// browser SSRF boundary, so they should not trigger the navigation policy.
return;
@@ -166,7 +191,7 @@ async function assertSubframeNavigationAllowed(
await assertBrowserNavigationResultAllowed({
url: frameUrl,
- ...withBrowserNavigationPolicy(ssrfPolicy),
+ ...withBrowserNavigationPolicy(ssrfPolicy, { browserProxyMode }),
});
}
@@ -188,13 +213,18 @@ async function assertObservedDelayedNavigations(opts: {
cdpUrl: string;
page: Page;
ssrfPolicy?: SsrFPolicy;
+ browserProxyMode?: BrowserNavigationPolicyOptions["browserProxyMode"];
targetId?: string;
observed: ObservedDelayedNavigations;
}): Promise<void> {
let subframeError: unknown;
try {
for (const frameUrl of opts.observed.subframes) {
- await assertSubframeNavigationAllowed(frameUrl, opts.ssrfPolicy);
+ await assertSubframeNavigationAllowed(
+ frameUrl,
+ opts.ssrfPolicy,
+ opts.browserProxyMode,
+ );
}
} catch (err) {
subframeError = err;
@@ -205,6 +235,7 @@ async function assertObservedDelayedNavigations(opts: {
page: opts.page,
response: null,
ssrfPolicy: opts.ssrfPolicy,
+ browserProxyMode: opts.browserProxyMode,
targetId: opts.targetId,
});
}
@@ -268,9 +299,10 @@ function scheduleDelayedInteractionNavigationGuard(opts: {
page: Page;
previousUrl: string;
ssrfPolicy?: SsrFPolicy;
+ browserProxyMode?: BrowserNavigationPolicyOptions["browserProxyMode"];
targetId?: string;
}): Promise<void> {
- if (!opts.ssrfPolicy) {
+ if (!opts.ssrfPolicy && !opts.browserProxyMode) {
return Promise.resolve();
}
const page = opts.page as unknown as NavigationObservablePage;
@@ -280,6 +312,7 @@ function scheduleDelayedInteractionNavigationGuard(opts: {
page: opts.page,
response: null,
ssrfPolicy: opts.ssrfPolicy,
+ browserProxyMode: opts.browserProxyMode,
targetId: opts.targetId,
});
}
@@ -318,6 +351,7 @@ function scheduleDelayedInteractionNavigationGuard(opts: {
cdpUrl: opts.cdpUrl,
page: opts.page,
ssrfPolicy: opts.ssrfPolicy,
+ browserProxyMode: opts.browserProxyMode,
targetId: opts.targetId,
observed: { mainFrameNavigated: true, subframes },
}).then(() => settle(), settle);
@@ -328,6 +362,7 @@ function scheduleDelayedInteractionNavigationGuard(opts: {
cdpUrl: opts.cdpUrl,
page: opts.page,
ssrfPolicy: opts.ssrfPolicy,
+ browserProxyMode: opts.browserProxyMode,
targetId: opts.targetId,
observed: {
mainFrameNavigated: didCrossDocumentUrlChange(page, opts.previousUrl),
@@ -354,9 +389,10 @@ async function assertInteractionNavigationCompletedSafely<T>(opts: {
page: Page;
previousUrl: string;
ssrfPolicy?: SsrFPolicy;
+ browserProxyMode?: BrowserNavigationPolicyOptions["browserProxyMode"];
targetId?: string;
}): Promise<T> {
- if (!opts.ssrfPolicy) {
+ if (!opts.ssrfPolicy && !opts.browserProxyMode) {
return await opts.action();
}
// Phase 1: keep a framenavigated listener alive for the entire duration of the
@@ -364,6 +400,93 @@ async function assertInteractionNavigationCompletedSafely<T>(opts: {
// Using a fixed pre-action timer would expire before the action finishes for
// slow interactions, silently bypassing the SSRF guard.
const navPage = opts.page as unknown as NavigationObservablePage;
+ const pageContext = (
+ opts.page as unknown as {
+ context?: () => { on?: (event: string, listener: (page: Page) => void) => void; off?: (event: string, listener: (page: Page) => void) => void; close?: () => Promise<void>; browser?: () => { close?: () => Promise<void> } | undefined };
+ }
+ ).context?.();
+ const popupsDuringAction: Page[] = [];
+ // The context is PERSISTENT and shared with the user, who can open tabs at
+ // any moment — as can any unrelated producer. The page event fires for all of
+ // them, so tracking every new page would let the drain below validate, and on
+ // denial CLOSE, a tab the user opened themselves; a busy stream of them could
+ // even escalate to tearing down the whole context. Only pages that descend
+ // from the page being acted on are ours to police.
+ //
+ // opener() is async and this listener must stay synchronous (an await here
+ // would drop events), so kick the probe off on arrival and record the answer;
+ // consumers below wait for the probe of the page they are about to touch.
+ const openerOfPopup = new Map<unknown, unknown>();
+ const popupOwnershipProbe = new Map<unknown, Promise<void>>();
+ const popupOwnershipPending = new Set<unknown>();
+ const onContextPage = (newPage: Page) => {
+ popupsDuringAction.push(newPage);
+ const opener = (newPage as unknown as { opener?: () => Promise<Page | null> }).opener;
+ if (typeof opener !== "function") return;
+ popupOwnershipPending.add(newPage);
+ popupOwnershipProbe.set(
+ newPage,
+ Promise.resolve()
+ .then(() => opener.call(newPage))
+ .then(
+ (parent) => {
+ if (parent) openerOfPopup.set(newPage, parent);
+ },
+ () => undefined,
+ )
+ .then(() => {
+ popupOwnershipPending.delete(newPage);
+ }),
+ );
+ };
+ /**
+ * Whether this page's lineage question has been ANSWERED yet. A pending probe
+ * is not the same as "not ours": treating it that way would let a popup the
+ * action opened slip past the cleanup below, unvalidated and still live.
+ */
+ const ownershipAnswered = (page: unknown): boolean => !popupOwnershipPending.has(page);
+ /**
+ * Settle outstanding lineage probes, re-checking after every round: a popup
+ * can open a child while we await, and that child's probe is registered after
+ * any snapshot we took, so a single allSettled would never wait for it.
+ * Bounded by the caller's deadline so an unresponsive page cannot hold the
+ * action — and the serialized stop/quit behind it — open.
+ */
+ const settleOwnershipProbes = async (deadline: Promise<void>): Promise<void> => {
+ let expired = false;
+ void deadline.then(() => {
+ expired = true;
+ });
+ while (!expired && popupOwnershipPending.size > 0) {
+ const outstanding = [...popupOwnershipPending]
+ .map((page) => popupOwnershipProbe.get(page))
+ .filter((probe): probe is Promise<void> => probe !== undefined);
+ if (outstanding.length === 0) return;
+ await Promise.race([Promise.allSettled(outstanding), deadline]);
+ }
+ };
+ /**
+ * Whether a page's opener chain reaches the page being acted on. Walks the
+ * chain so a popup opened BY a popup still counts as ours, and is bounded so
+ * a cycle or an absurdly deep chain cannot hang the drain.
+ *
+ * Fails closed toward the USER's data: a page whose lineage we could not
+ * establish is treated as not ours, so it is never validated and never
+ * closed. Anything the action itself opened does report an opener.
+ */
+ const descendsFromActedPage = (page: unknown): boolean => {
+ let cursor = page;
+ for (let hops = 0; hops < POPUP_CHAIN_MAX_VALIDATIONS; hops += 1) {
+ const parent = openerOfPopup.get(cursor);
+ if (parent === undefined) return false;
+ if (parent === opts.page) return true;
+ cursor = parent;
+ }
+ return false;
+ };
+ if (pageContext && typeof pageContext.on === "function") {
+ pageContext.on("page", onContextPage);
+ }
let navigatedDuringAction = false;
const subframeNavigationsDuringAction: string[] = [];
const onFrameNavigated = (frame: Frame) => {
@@ -403,18 +526,25 @@ async function assertInteractionNavigationCompletedSafely<T>(opts: {
let subframeError: unknown;
try {
for (const frameUrl of subframeNavigationsDuringAction) {
- await assertSubframeNavigationAllowed(frameUrl, opts.ssrfPolicy);
+ await assertSubframeNavigationAllowed(
+ frameUrl,
+ opts.ssrfPolicy,
+ opts.browserProxyMode,
+ );
}
} catch (err) {
subframeError = err;
}
+ let navigationError: unknown;
+ try {
if (navigationObserved) {
await assertPageNavigationCompletedSafely({
cdpUrl: opts.cdpUrl,
page: opts.page,
response: null,
ssrfPolicy: opts.ssrfPolicy,
+ browserProxyMode: opts.browserProxyMode,
targetId: opts.targetId,
});
} else if (actionError) {
@@ -427,6 +557,7 @@ async function assertInteractionNavigationCompletedSafely<T>(opts: {
cdpUrl: opts.cdpUrl,
page: opts.page,
ssrfPolicy: opts.ssrfPolicy,
+ browserProxyMode: opts.browserProxyMode,
targetId: opts.targetId,
observed,
});
@@ -440,14 +571,336 @@ async function assertInteractionNavigationCompletedSafely<T>(opts: {
page: opts.page,
previousUrl: opts.previousUrl,
ssrfPolicy: opts.ssrfPolicy,
+ browserProxyMode: opts.browserProxyMode,
targetId: opts.targetId,
});
}
+ } catch (err) {
+ navigationError = err;
+ }
+ // NOTE: the context listener stays attached across popup validation below —
+ // a popup can open a further popup inside its own grace window, and
+ // detaching here would leave that second-generation tab uncollected and
+ // unvalidated (in direct mode nothing else would catch it).
+ let popupError: unknown;
+ // Shared last-resort teardown for pages we could not contain individually.
+ // Both the per-popup close failure and the overflow path escalate through
+ // this, so a stuck page has exactly one ladder: context close, then browser
+ // close.
+ //
+ // Only a resolved CONTEXT close proves containment from in here: its pages
+ // are gone with it. A resolved BROWSER close proves only that the call
+ // returned — the process can still be alive with pages running, and nothing
+ // in this runtime can observe process exit. So browser close reports
+ // "unproven" and the caller raises the untorn-down signal, which is what
+ // makes the host run its own verified process teardown.
+ const tearDownUncontainedPages = async (
+ deadline?: Promise<void>,
+ ): Promise<"contained" | "unproven"> => {
+ const closeContext = (
+ pageContext as unknown as { close?: () => Promise<void> } | undefined
+ )?.close;
+ if (typeof closeContext === "function") {
+ const contextClosed = await Promise.race([
+ Promise.resolve()
+ .then(() => closeContext.call(pageContext))
+ .then(
+ () => true,
+ () => false,
+ ),
+ // A caller that already burned its budget passes no deadline: racing a
+ // fired one would resolve instantly and prove nothing.
+ deadline
+ ? deadline.then(() => false)
+ : new Promise<boolean>((resolve) => {
+ const timer = setTimeout(() => resolve(false), POPUP_CHAIN_CLOSE_BUDGET_MS);
+ (timer as unknown as { unref?: () => void }).unref?.();
+ }),
+ ]);
+ if (contextClosed) return "contained";
+ }
+ // The context would not close (rejected, or still not settled at the
+ // deadline), so live pages that were never validated survive and the
+ // listener is about to detach. Every per-page and per-context remedy has
+ // now failed, so try the browser. Give this its own budget.
+ const browserOf = (
+ pageContext as unknown as { browser?: () => { close?: () => Promise<void> } | undefined }
+ | undefined
+ )?.browser;
+ const browser = typeof browserOf === "function" ? browserOf.call(pageContext) : undefined;
+ if (!browser || typeof browser.close !== "function") return "unproven";
+ await Promise.race([
+ Promise.resolve()
+ .then(() => browser.close?.())
+ .then(
+ () => undefined,
+ () => undefined,
+ ),
+ new Promise<void>((resolve) => {
+ const timer = setTimeout(resolve, POPUP_CHAIN_CLOSE_BUDGET_MS);
+ (timer as unknown as { unref?: () => void }).unref?.();
+ }),
+ ]);
+ // Deliberately NOT reporting success on a resolved close: the host owns
+ // process teardown and must verify the exit itself.
+ return "unproven";
+ };
+ try {
+ // Drain the chain rather than a snapshot: validating a popup can append
+ // more entries to popupsDuringAction, so index forward as it grows.
+ //
+ // BOUNDED, because the queue is adversarial: each iteration awaits a
+ // ~250ms grace window, so a page that opens one popup per window appends
+ // at least as fast as this drains and the loop never empties. That would
+ // hang the action forever — and the backend serializes every browser call,
+ // so a later stop (and dispose at quit) would queue behind it indefinitely.
+ // On overrun, stop validating and CLOSE the remainder: leaving them live
+ // would be the unvalidated-tab bug this drain exists to prevent.
+ const drainDeadline = Date.now() + POPUP_CHAIN_DRAIN_BUDGET_MS;
+ let popupIndex = 0;
+ for (
+ ;
+ popupIndex < popupsDuringAction.length
+ && popupIndex < POPUP_CHAIN_MAX_VALIDATIONS
+ && Date.now() < drainDeadline;
+ popupIndex += 1
+ ) {
+ const popupPage = popupsDuringAction[popupIndex]!;
+ // Wait for this page's lineage answer, then skip anything PROVEN not to
+ // be ours: validating it could quarantine or close one of the user's own
+ // tabs, which is strictly worse than not policing a page we never opened.
+ // A page that never answered is not proven either way, so it stays in
+ // scope here and the overflow cleanup below decides its fate.
+ await popupOwnershipProbe.get(popupPage);
+ if (ownershipAnswered(popupPage) && !descendsFromActedPage(popupPage)) continue;
+ // Per popup, not around the loop: a denial on the first popup must not
+ // leave later ones unvalidated and selectable on a denied URL. Keep the
+ // first error and keep going.
+ try {
+ // A popup starts at about:blank; reuse the delayed-navigation observer
+ // so a still-loading popup gets the same grace window before
+ // validation, and a policy deny quarantines/closes the popup target
+ // like any other block.
+ const observedPopup = await observeDelayedInteractionNavigation(
+ popupPage as unknown as NavigationObservablePage,
+ "about:blank",
+ );
+ await assertObservedDelayedNavigations({
+ cdpUrl: opts.cdpUrl,
+ page: popupPage,
+ ssrfPolicy: opts.ssrfPolicy,
+ browserProxyMode: opts.browserProxyMode,
+ observed: observedPopup,
+ });
+ } catch (err) {
+ if (popupError === undefined) popupError = err;
+ // Fail closed on the rejected popup itself. A policy deny above only
+ // quarantines — assertPageNavigationCompletedSafely never closes; that
+ // step belongs to callers that own the navigation lifecycle — and this
+ // popup was created BY the action, not by the user, so it is ours to
+ // tear down. Left open, the denied page keeps executing after the
+ // context listener detaches (in direct mode no lifetime request gate
+ // remains to catch it).
+ //
+ // Bounded, because close() can hang forever on an adversarial page.
+ // But a timeout is NOT success: the page is still live and scriptable.
+ // Escalate exactly like the overflow path — context, then browser —
+ // and if none of that works, report the untorn-down browser so the
+ // host distrusts the route instead of returning an ordinary denial.
+ await Promise.race([
+ closeBlockedNavigationTarget({
+ cdpUrl: opts.cdpUrl,
+ page: popupPage as Page,
+ }).then(
+ () => undefined,
+ () => undefined,
+ ),
+ new Promise<void>((resolve) => {
+ const timer = setTimeout(resolve, POPUP_CHAIN_CLOSE_BUDGET_MS);
+ (timer as unknown as { unref?: () => void }).unref?.();
+ }),
+ ]);
+ // Ask the PAGE whether it closed, rather than trusting the call to have
+ // reported it. closeBlockedNavigationTarget swallows page.close()
+ // rejections internally (pw-session.ts), so it resolves even when the
+ // page refused to go — reading its resolution as success would silently
+ // skip the escalation for exactly the pages that need it. A page that
+ // cannot answer isClosed() has not proven anything either, so it counts
+ // as uncontained too.
+ const isClosed = (popupPage as { isClosed?: () => boolean }).isClosed;
+ const popupClosed = typeof isClosed === "function" && isClosed.call(popupPage) === true;
+ if (!popupClosed && (await tearDownUncontainedPages()) !== "contained") {
+ popupError = new Error(UNTORN_DOWN_BROWSER_MESSAGE);
+ break;
+ }
+ }
+ }
+ // Settle outstanding lineage probes before the sweep below: it runs
+ // synchronously (so pending page events can still enqueue) and must be able
+ // to tell our popups from the user's without awaiting per page. Bounded on
+ // its own budget, and repeated internally so a child popup that arrives
+ // mid-await is waited on too.
+ const ownershipDeadline = new Promise<void>((resolve) => {
+ const timer = setTimeout(resolve, POPUP_CHAIN_CLOSE_BUDGET_MS);
+ (timer as unknown as { unref?: () => void }).unref?.();
+ });
+ await settleOwnershipProbes(ownershipDeadline);
+ // A page whose probe never answered counts as OURS. Once the budget above
+ // is spent the browser is already failing to answer, and dropping such a
+ // page would mean the listener detaches with an unvalidated, never-closed
+ // popup and no untorn-down signal for the host — silently
+ // losing containment. The user's genuinely own tabs answer opener() with
+ // null promptly, so they are still excluded.
+ const isOursOrUnanswered = (page: unknown): boolean =>
+ descendsFromActedPage(page) || !ownershipAnswered(page);
+ const ownedPagesRemain = (): boolean => {
+ for (let i = popupIndex; i < popupsDuringAction.length; i += 1) {
+ if (isOursOrUnanswered(popupsDuringAction[i]!)) return true;
+ }
+ return false;
+ };
+ if (ownedPagesRemain()) {
+ // Quarantine must be bounded too, for the same reason the drain above is:
+ // a burst of popups, or one unresponsive close(), would otherwise keep
+ // this action — and the serialized stop/quit cleanup behind it — pending
+ // indefinitely. Close concurrently under a single deadline rather than
+ // serially awaiting each one, and re-read the queue (not a snapshot) so
+ // popups appended while these closes run are quarantined too.
+ const closeDeadline = new Promise<void>((resolve) => {
+ const timer = setTimeout(resolve, POPUP_CHAIN_CLOSE_BUDGET_MS);
+ // Do not hold the process open on this timer.
+ (timer as unknown as { unref?: () => void }).unref?.();
+ });
+ const closing: Array<Promise<void>> = [];
+ let deadlineReached = false;
+ void closeDeadline.then(() => { deadlineReached = true; });
+ // Outer loop so newly-arrived popups are picked up: the inner loop never
+ // awaits, so on its own it drains the queue as it stands and returns
+ // before the event loop can deliver another page event. Yielding
+ // between sweeps is what actually lets the queue grow and be re-read;
+ // without it a popup created during cleanup would be left live,
+ // unvalidated and unquarantined once the listener detaches.
+ while (
+ !deadlineReached
+ && popupIndex < popupsDuringAction.length
+ && closing.length < POPUP_CHAIN_MAX_CLOSES
+ ) {
+ for (
+ ;
+ popupIndex < popupsDuringAction.length
+ && closing.length < POPUP_CHAIN_MAX_CLOSES;
+ popupIndex += 1
+ ) {
+ const unvalidated = popupsDuringAction[popupIndex]!;
+ // A page that arrived mid-sweep may not have answered opener() yet.
+ // Do NOT advance past it: this index only moves forward, so skipping
+ // it here would strand an action-created popup that proves ours a
+ // moment later — unvalidated, unquarantined, and invisible to
+ // ownedPagesRemain(). Stop the sweep instead; the yield below lets
+ // the probe settle and the outer loop retries the same page, all
+ // still under closeDeadline.
+ if (!ownershipAnswered(unvalidated)) break;
+ // Same boundary as the drain: the user's own tabs are not ours to
+ // quarantine or close, however far behind this cleanup falls.
+ if (!descendsFromActedPage(unvalidated)) continue;
+ // Quarantine BEFORE closing, and do not make it conditional on the
+ // close succeeding: close() can hang forever on an adversarial page,
+ // and when the deadline below fires we would otherwise leave a live,
+ // never-validated popup selectable — in direct mode there is no
+ // lifetime CDP request gate to catch it afterwards. Marking is
+ // synchronous bookkeeping, so it completes regardless.
+ closing.push(
+ quarantineTargetWithoutClosing({
+ cdpUrl: opts.cdpUrl,
+ page: unvalidated as Page,
+ })
+ .catch(() => undefined)
+ .then(() => (unvalidated as { close?: () => Promise<void> }).close?.())
+ .then(
+ () => undefined,
+ () => undefined,
+ ),
+ );
+ }
+ // Hand control back so pending page events can enqueue, then re-check.
+ // Racing the deadline keeps this bounded even against a page that
+ // appends a new popup on every turn.
+ await Promise.race([
+ new Promise<void>((resolve) => {
+ const timer = setTimeout(resolve, 0);
+ (timer as unknown as { unref?: () => void }).unref?.();
+ }),
+ closeDeadline,
+ ]);
+ }
+ // Never await a popup's close() unbounded: a hung page must not outrank
+ // returning from the interaction.
+ //
+ // Track whether they actually finished. popupIndex only records that a
+ // close was ISSUED, and quarantine is bookkeeping that never closes a
+ // page (see quarantineTargetWithoutClosing), so a fully-drained queue
+ // whose closes all hang would otherwise look fully handled while every
+ // one of those popups is still live and scriptable.
+ const allClosesSettled = await Promise.race([
+ Promise.all(closing).then(() => true),
+ closeDeadline.then(() => false),
+ ]);
+ // If the bounds cut us off with popups still unaccounted for, they were
+ // neither validated nor quarantined and the listener is about to detach —
+ // in direct mode nothing else would ever check them. Per-page cleanup has
+ // already failed to keep up here, so fail closed on the whole context
+ // rather than leaving live, never-validated pages behind.
+ if (ownedPagesRemain() || !allClosesSettled) {
+ // Nothing reachable from this process can shut the browser down, and a
+ // resolved close() would only prove the call returned, not that the
+ // process exited. Say so explicitly rather than reporting a generic
+ // policy denial: the host owns process teardown and must treat this
+ // route as untrusted until it verifies an exit itself.
+ if ((await tearDownUncontainedPages(closeDeadline)) !== "contained") {
+ popupError = new Error(UNTORN_DOWN_BROWSER_MESSAGE);
+ }
+ }
+ if (popupError === undefined) {
+ popupError = new Error(
+ "Navigation blocked: popup chain exceeded the validation budget; remaining popups were closed",
+ );
+ }
+ }
+ } finally {
+ // Always detach: a throw here would otherwise leak the listener, retaining
+ // every tab opened afterwards for the life of the context.
+ if (pageContext && typeof pageContext.off === "function") {
+ pageContext.off("page", onContextPage);
+ }
+ }
+
+ // A containment failure outranks EVERYTHING. Ordinary denials describe a
+ // request that was refused — the safe outcome. This one says pages we never
+ // validated are still live and could not be torn down, and it is the only
+ // signal the host uses to distrust the route. If a denied main-frame
+ // navigation happened in the same interaction (easy for an adversarial page
+ // to arrange), reporting that instead would leave the route usable while
+ // those pages keep running.
+ if (popupError && /could not be torn down/.test(String((popupError as Error)?.message ?? ""))) {
+ throw toLintErrorObject(popupError, "Non-Error thrown");
+ }
+
+ // Otherwise policy denials outrank the action's own error, and the main-frame
+ // denial outranks subframe/popup denials, so the caller sees the navigation it
+ // asked for being refused. All were still evaluated above.
+ if (navigationError) {
+ throw toLintErrorObject(navigationError, "Non-Error thrown");
+ }
+
if (subframeError) {
throw toLintErrorObject(subframeError, "Non-Error thrown");
}
+ if (popupError) {
+ throw toLintErrorObject(popupError, "Non-Error thrown");
+ }
+
if (actionError) {
throw toLintErrorObject(actionError, "Non-Error thrown");
}
@@ -544,6 +997,7 @@ export async function clickViaPlaywright(opts: {
delayMs?: number;
timeoutMs?: number;
ssrfPolicy?: SsrFPolicy;
+ browserProxyMode?: BrowserNavigationPolicyOptions["browserProxyMode"];
signal?: AbortSignal;
}): Promise<void> {
const resolved = requireRefOrSelector(opts.ref, opts.selector);
@@ -633,6 +1087,7 @@ export async function clickViaPlaywright(opts: {
page,
previousUrl,
ssrfPolicy: opts.ssrfPolicy,
+ browserProxyMode: opts.browserProxyMode,
targetId: opts.targetId,
});
} catch (err) {
@@ -655,6 +1110,7 @@ export async function clickCoordsViaPlaywright(opts: {
delayMs?: number;
timeoutMs?: number;
ssrfPolicy?: SsrFPolicy;
+ browserProxyMode?: BrowserNavigationPolicyOptions["browserProxyMode"];
signal?: AbortSignal;
}): Promise<void> {
const page = await getRestoredPageForTarget(opts);
@@ -677,6 +1133,7 @@ export async function clickCoordsViaPlaywright(opts: {
page,
previousUrl,
ssrfPolicy: opts.ssrfPolicy,
+ browserProxyMode: opts.browserProxyMode,
targetId: opts.targetId,
}).finally(cleanup);
}
@@ -688,6 +1145,8 @@ export async function hoverViaPlaywright(opts: {
ref?: string;
selector?: string;
timeoutMs?: number;
+ ssrfPolicy?: SsrFPolicy;
+ browserProxyMode?: BrowserNavigationPolicyOptions["browserProxyMode"];
signal?: AbortSignal;
}): Promise<void> {
const resolved = requireRefOrSelector(opts.ref, opts.selector);
@@ -696,16 +1155,27 @@ export async function hoverViaPlaywright(opts: {
const locator = resolved.ref
? refLocator(page, requireRef(resolved.ref))
: page.locator(resolved.selector!);
+ const previousUrl = page.url();
const { abortPromise, cleanup } = createAbortPromise(opts.signal);
const reconcileRemoteDialog = () => reconcileRemoteDialogAfterActionSettled(page, opts.signal);
try {
- await awaitActionWithAbort(
- locator.hover({
- timeout: resolveInteractionTimeoutMs(opts.timeoutMs),
- }),
- abortPromise,
- reconcileRemoteDialog,
- );
+ await assertInteractionNavigationCompletedSafely({
+ action: async () => {
+ await awaitActionWithAbort(
+ locator.hover({
+ timeout: resolveInteractionTimeoutMs(opts.timeoutMs),
+ }),
+ abortPromise,
+ reconcileRemoteDialog,
+ );
+ },
+ cdpUrl: opts.cdpUrl,
+ page,
+ previousUrl,
+ ssrfPolicy: opts.ssrfPolicy,
+ browserProxyMode: opts.browserProxyMode,
+ targetId: opts.targetId,
+ });
} catch (err) {
throw toFriendlyInteractionError(err, label);
} finally {
@@ -722,6 +1192,8 @@ export async function dragViaPlaywright(opts: {
endRef?: string;
endSelector?: string;
timeoutMs?: number;
+ ssrfPolicy?: SsrFPolicy;
+ browserProxyMode?: BrowserNavigationPolicyOptions["browserProxyMode"];
signal?: AbortSignal;
}): Promise<void> {
const resolvedStart = requireRefOrSelector(opts.startRef, opts.startSelector);
@@ -735,16 +1207,27 @@ export async function dragViaPlaywright(opts: {
: page.locator(resolvedEnd.selector!);
const startLabel = resolvedStart.ref ?? resolvedStart.selector!;
const endLabel = resolvedEnd.ref ?? resolvedEnd.selector!;
+ const previousUrl = page.url();
const { abortPromise, cleanup } = createAbortPromise(opts.signal);
const reconcileRemoteDialog = () => reconcileRemoteDialogAfterActionSettled(page, opts.signal);
try {
- await awaitActionWithAbort(
- startLocator.dragTo(endLocator, {
- timeout: resolveInteractionTimeoutMs(opts.timeoutMs),
- }),
- abortPromise,
- reconcileRemoteDialog,
- );
+ await assertInteractionNavigationCompletedSafely({
+ action: async () => {
+ await awaitActionWithAbort(
+ startLocator.dragTo(endLocator, {
+ timeout: resolveInteractionTimeoutMs(opts.timeoutMs),
+ }),
+ abortPromise,
+ reconcileRemoteDialog,
+ );
+ },
+ cdpUrl: opts.cdpUrl,
+ page,
+ previousUrl,
+ ssrfPolicy: opts.ssrfPolicy,
+ browserProxyMode: opts.browserProxyMode,
+ targetId: opts.targetId,
+ });
} catch (err) {
throw toFriendlyInteractionError(err, `${startLabel} -> ${endLabel}`);
} finally {
@@ -761,6 +1244,7 @@ export async function selectOptionViaPlaywright(opts: {
values: string[];
timeoutMs?: number;
ssrfPolicy?: SsrFPolicy;
+ browserProxyMode?: BrowserNavigationPolicyOptions["browserProxyMode"];
signal?: AbortSignal;
}): Promise<void> {
const resolved = requireRefOrSelector(opts.ref, opts.selector);
@@ -790,6 +1274,7 @@ export async function selectOptionViaPlaywright(opts: {
page,
previousUrl,
ssrfPolicy: opts.ssrfPolicy,
+ browserProxyMode: opts.browserProxyMode,
targetId: opts.targetId,
});
} catch (err) {
@@ -806,6 +1291,7 @@ export async function pressKeyViaPlaywright(opts: {
key: string;
delayMs?: number;
ssrfPolicy?: SsrFPolicy;
+ browserProxyMode?: BrowserNavigationPolicyOptions["browserProxyMode"];
signal?: AbortSignal;
}): Promise<void> {
const key = normalizeOptionalString(opts.key) ?? "";
@@ -832,6 +1318,7 @@ export async function pressKeyViaPlaywright(opts: {
page,
previousUrl,
ssrfPolicy: opts.ssrfPolicy,
+ browserProxyMode: opts.browserProxyMode,
targetId: opts.targetId,
});
} finally {
@@ -850,6 +1337,7 @@ export async function typeViaPlaywright(opts: {
slowly?: boolean;
timeoutMs?: number;
ssrfPolicy?: SsrFPolicy;
+ browserProxyMode?: BrowserNavigationPolicyOptions["browserProxyMode"];
signal?: AbortSignal;
}): Promise<void> {
const resolved = requireRefOrSelector(opts.ref, opts.selector);
@@ -889,6 +1377,7 @@ export async function typeViaPlaywright(opts: {
page,
previousUrl,
ssrfPolicy: opts.ssrfPolicy,
+ browserProxyMode: opts.browserProxyMode,
targetId: opts.targetId,
});
} else {
@@ -911,6 +1400,7 @@ export async function typeViaPlaywright(opts: {
page,
previousUrl,
ssrfPolicy: opts.ssrfPolicy,
+ browserProxyMode: opts.browserProxyMode,
targetId: opts.targetId,
});
}
@@ -928,6 +1418,7 @@ export async function fillFormViaPlaywright(opts: {
fields: BrowserFormField[];
timeoutMs?: number;
ssrfPolicy?: SsrFPolicy;
+ browserProxyMode?: BrowserNavigationPolicyOptions["browserProxyMode"];
signal?: AbortSignal;
}): Promise<void> {
const page = await getRestoredPageForTarget(opts);
@@ -966,6 +1457,7 @@ export async function fillFormViaPlaywright(opts: {
page,
previousUrl,
ssrfPolicy: opts.ssrfPolicy,
+ browserProxyMode: opts.browserProxyMode,
targetId: opts.targetId,
});
} catch (err) {
@@ -987,6 +1479,7 @@ export async function fillFormViaPlaywright(opts: {
page,
previousUrl,
ssrfPolicy: opts.ssrfPolicy,
+ browserProxyMode: opts.browserProxyMode,
targetId: opts.targetId,
});
} catch (err) {
@@ -1003,6 +1496,7 @@ export async function evaluateViaPlaywright(opts: {
cdpUrl: string;
targetId?: string;
ssrfPolicy?: SsrFPolicy;
+ browserProxyMode?: BrowserNavigationPolicyOptions["browserProxyMode"];
fn: string;
ref?: string;
timeoutMs?: number;
@@ -1048,12 +1542,13 @@ export async function evaluateViaPlaywright(opts: {
try {
const previousUrl = page.url();
- if (opts.ssrfPolicy) {
+ if (opts.ssrfPolicy || opts.browserProxyMode) {
await assertPageNavigationCompletedSafely({
cdpUrl: opts.cdpUrl,
page,
response: null,
ssrfPolicy: opts.ssrfPolicy,
+ browserProxyMode: opts.browserProxyMode,
targetId: opts.targetId,
});
}
@@ -1098,6 +1593,7 @@ export async function evaluateViaPlaywright(opts: {
page,
previousUrl,
ssrfPolicy: opts.ssrfPolicy,
+ browserProxyMode: opts.browserProxyMode,
targetId: opts.targetId,
});
return result;
@@ -1140,6 +1636,7 @@ export async function evaluateViaPlaywright(opts: {
page,
previousUrl,
ssrfPolicy: opts.ssrfPolicy,
+ browserProxyMode: opts.browserProxyMode,
targetId: opts.targetId,
});
return result;
@@ -1155,6 +1652,8 @@ export async function scrollIntoViewViaPlaywright(opts: {
ref?: string;
selector?: string;
timeoutMs?: number;
+ ssrfPolicy?: SsrFPolicy;
+ browserProxyMode?: BrowserNavigationPolicyOptions["browserProxyMode"];
signal?: AbortSignal;
}): Promise<void> {
const resolved = requireRefOrSelector(opts.ref, opts.selector);
@@ -1165,14 +1664,25 @@ export async function scrollIntoViewViaPlaywright(opts: {
const locator = resolved.ref
? refLocator(page, requireRef(resolved.ref))
: page.locator(resolved.selector!);
+ const previousUrl = page.url();
const { abortPromise, cleanup } = createAbortPromise(opts.signal);
const reconcileRemoteDialog = () => reconcileRemoteDialogAfterActionSettled(page, opts.signal);
try {
- await awaitActionWithAbort(
- locator.scrollIntoViewIfNeeded({ timeout }),
- abortPromise,
- reconcileRemoteDialog,
- );
+ await assertInteractionNavigationCompletedSafely({
+ action: async () => {
+ await awaitActionWithAbort(
+ locator.scrollIntoViewIfNeeded({ timeout }),
+ abortPromise,
+ reconcileRemoteDialog,
+ );
+ },
+ cdpUrl: opts.cdpUrl,
+ page,
+ previousUrl,
+ ssrfPolicy: opts.ssrfPolicy,
+ browserProxyMode: opts.browserProxyMode,
+ targetId: opts.targetId,
+ });
} catch (err) {
throw toFriendlyInteractionError(err, label);
} finally {
@@ -1192,6 +1702,8 @@ export async function waitForViaPlaywright(opts: {
loadState?: "load" | "domcontentloaded" | "networkidle";
fn?: string;
timeoutMs?: number;
+ ssrfPolicy?: SsrFPolicy;
+ browserProxyMode?: BrowserNavigationPolicyOptions["browserProxyMode"];
signal?: AbortSignal;
}): Promise<void> {
const page = await getPageForTargetId(opts);
@@ -1203,7 +1715,10 @@ export async function waitForViaPlaywright(opts: {
await awaitActionWithAbort(stepPromise, abortPromise, reconcileRemoteDialog);
};
+ const previousUrl = page.url();
try {
+ await assertInteractionNavigationCompletedSafely({
+ action: async () => {
if (typeof opts.timeMs === "number" && Number.isFinite(opts.timeMs)) {
await waitForStep(
page.waitForTimeout(
@@ -1248,6 +1763,14 @@ export async function waitForViaPlaywright(opts: {
await waitForStep(page.waitForFunction(fn, { timeout }));
}
}
+ },
+ cdpUrl: opts.cdpUrl,
+ page,
+ previousUrl,
+ ssrfPolicy: opts.ssrfPolicy,
+ browserProxyMode: opts.browserProxyMode,
+ targetId: opts.targetId,
+ });
} finally {
cleanup();
}
@@ -1467,6 +1990,8 @@ export async function setInputFilesViaPlaywright(opts: {
inputRef?: string;
element?: string;
paths: string[];
+ ssrfPolicy?: SsrFPolicy;
+ browserProxyMode?: BrowserNavigationPolicyOptions["browserProxyMode"];
}): Promise<void> {
const page = await getPageForTargetId(opts);
ensurePageState(page);
@@ -1490,22 +2015,33 @@ export async function setInputFilesViaPlaywright(opts: {
}
const resolvedPaths = resolvedResult.paths;
- try {
- await locator.setInputFiles(resolvedPaths);
- } catch (err) {
- throw toFriendlyInteractionError(err, inputRef || element);
- }
- try {
- const handle = await locator.elementHandle();
- if (handle) {
- await handle.evaluate((el) => {
- el.dispatchEvent(new Event("input", { bubbles: true }));
- el.dispatchEvent(new Event("change", { bubbles: true }));
- });
- }
- } catch {
- // Best-effort for sites that don't react to setInputFiles alone.
- }
+ const previousUrl = page.url();
+ await assertInteractionNavigationCompletedSafely({
+ action: async () => {
+ try {
+ await locator.setInputFiles(resolvedPaths);
+ } catch (err) {
+ throw toFriendlyInteractionError(err, inputRef || element);
+ }
+ try {
+ const handle = await locator.elementHandle();
+ if (handle) {
+ await handle.evaluate((el) => {
+ el.dispatchEvent(new Event("input", { bubbles: true }));
+ el.dispatchEvent(new Event("change", { bubbles: true }));
+ });
+ }
+ } catch {
+ // Best-effort for sites that don't react to setInputFiles alone.
+ }
+ },
+ cdpUrl: opts.cdpUrl,
+ page,
+ previousUrl,
+ ssrfPolicy: opts.ssrfPolicy,
+ browserProxyMode: opts.browserProxyMode,
+ targetId: opts.targetId,
+ });
}
async function executeSingleAction(
@@ -1514,6 +2050,7 @@ async function executeSingleAction(
targetId?: string,
evaluateEnabled?: boolean,
ssrfPolicy?: SsrFPolicy,
+ browserProxyMode?: BrowserNavigationPolicyOptions["browserProxyMode"],
depth = 0,
signal?: AbortSignal,
): Promise<unknown> {
@@ -1536,6 +2073,7 @@ async function executeSingleAction(
delayMs: action.delayMs,
timeoutMs: action.timeoutMs,
ssrfPolicy,
+ browserProxyMode,
signal,
});
break;
@@ -1550,6 +2088,7 @@ async function executeSingleAction(
delayMs: action.delayMs,
timeoutMs: action.timeoutMs,
ssrfPolicy,
+ browserProxyMode,
signal,
});
break;
@@ -1564,6 +2103,7 @@ async function executeSingleAction(
slowly: action.slowly,
timeoutMs: action.timeoutMs,
ssrfPolicy,
+ browserProxyMode,
signal,
});
break;
@@ -1574,6 +2114,7 @@ async function executeSingleAction(
key: action.key,
delayMs: action.delayMs,
ssrfPolicy,
+ browserProxyMode,
signal,
});
break;
@@ -1584,6 +2125,8 @@ async function executeSingleAction(
ref: action.ref,
selector: action.selector,
timeoutMs: action.timeoutMs,
+ ssrfPolicy,
+ browserProxyMode,
signal,
});
break;
@@ -1594,6 +2137,8 @@ async function executeSingleAction(
ref: action.ref,
selector: action.selector,
timeoutMs: action.timeoutMs,
+ ssrfPolicy,
+ browserProxyMode,
signal,
});
break;
@@ -1606,6 +2151,8 @@ async function executeSingleAction(
endRef: action.endRef,
endSelector: action.endSelector,
timeoutMs: action.timeoutMs,
+ ssrfPolicy,
+ browserProxyMode,
signal,
});
break;
@@ -1618,6 +2165,7 @@ async function executeSingleAction(
values: action.values,
timeoutMs: action.timeoutMs,
ssrfPolicy,
+ browserProxyMode,
signal,
});
break;
@@ -1628,17 +2176,32 @@ async function executeSingleAction(
fields: action.fields,
timeoutMs: action.timeoutMs,
ssrfPolicy,
+ browserProxyMode,
signal,
});
break;
- case "resize":
- await resizeViewportViaPlaywright({
+ case "resize": {
+ const resizePage = await getPageForTargetId({ cdpUrl, targetId: effectiveTargetId });
+ ensurePageState(resizePage);
+ const resizePreviousUrl = resizePage.url();
+ await assertInteractionNavigationCompletedSafely({
+ action: async () => {
+ await resizeViewportViaPlaywright({
+ cdpUrl,
+ targetId: effectiveTargetId,
+ width: action.width,
+ height: action.height,
+ });
+ },
cdpUrl,
+ page: resizePage,
+ previousUrl: resizePreviousUrl,
+ ssrfPolicy,
+ browserProxyMode,
targetId: effectiveTargetId,
- width: action.width,
- height: action.height,
});
break;
+ }
case "wait":
if (action.fn && !evaluateEnabled) {
throw new Error("wait --fn is disabled by config (browser.evaluateEnabled=false)");
@@ -1654,6 +2217,8 @@ async function executeSingleAction(
loadState: action.loadState,
fn: action.fn,
timeoutMs: action.timeoutMs,
+ ssrfPolicy,
+ browserProxyMode,
signal,
});
break;
@@ -1665,6 +2230,7 @@ async function executeSingleAction(
cdpUrl,
targetId: effectiveTargetId,
ssrfPolicy,
+ browserProxyMode,
fn: action.fn,
ref: action.ref,
timeoutMs: action.timeoutMs,
@@ -1681,6 +2247,7 @@ async function executeSingleAction(
cdpUrl,
targetId: effectiveTargetId,
ssrfPolicy,
+ browserProxyMode,
actions: action.actions,
stopOnError: action.stopOnError,
evaluateEnabled,
@@ -1701,6 +2268,7 @@ export async function executeActViaPlaywright(opts: {
targetId?: string;
evaluateEnabled?: boolean;
ssrfPolicy?: SsrFPolicy;
+ browserProxyMode?: BrowserNavigationPolicyOptions["browserProxyMode"];
signal?: AbortSignal;
}): Promise<{
result?: unknown;
@@ -1723,6 +2291,7 @@ export async function executeActViaPlaywright(opts: {
cdpUrl: opts.cdpUrl,
targetId: opts.targetId,
ssrfPolicy: opts.ssrfPolicy,
+ browserProxyMode: opts.browserProxyMode,
actions: opts.action.actions,
stopOnError: opts.action.stopOnError,
evaluateEnabled: opts.evaluateEnabled,
@@ -1736,6 +2305,7 @@ export async function executeActViaPlaywright(opts: {
opts.targetId,
opts.evaluateEnabled,
opts.ssrfPolicy,
+ opts.browserProxyMode,
0,
dialogAbort.signal,
);
@@ -1761,6 +2331,7 @@ export async function batchViaPlaywright(opts: {
stopOnError?: boolean;
evaluateEnabled?: boolean;
ssrfPolicy?: SsrFPolicy;
+ browserProxyMode?: BrowserNavigationPolicyOptions["browserProxyMode"];
depth?: number;
signal?: AbortSignal;
}): Promise<{ results: Array<{ ok: boolean; error?: string }> }> {
@@ -1783,6 +2354,7 @@ export async function batchViaPlaywright(opts: {
opts.targetId,
opts.evaluateEnabled,
opts.ssrfPolicy,
+ opts.browserProxyMode,
depth,
opts.signal,
);
diff --git a/packages/browser-control-runtime/src/_generated/extension/src/browser/routes/agent.act.hooks.ts b/packages/browser-control-runtime/src/_generated/extension/src/browser/routes/agent.act.hooks.ts
index 1a9b5463ee..b84fb459a8 100644
--- a/packages/browser-control-runtime/src/_generated/extension/src/browser/routes/agent.act.hooks.ts
+++ b/packages/browser-control-runtime/src/_generated/extension/src/browser/routes/agent.act.hooks.ts
@@ -13,6 +13,7 @@ import { resolveExistingUploadPaths } from "../paths.js";
import { getBrowserProfileCapabilities } from "../profile-capabilities.js";
import type { BrowserRouteContext } from "../server-context.js";
import {
+ browserNavigationPolicyForProfile,
readBody,
requirePwAi,
resolveTargetIdFromBody,
@@ -99,6 +100,7 @@ export function registerBrowserAgentActHookRoutes(
await pw.setInputFilesViaPlaywright({
cdpUrl,
targetId: tab.targetId,
+ ...browserNavigationPolicyForProfile(ctx, profileCtx),
inputRef,
element,
paths: resolvedPaths,
@@ -114,7 +116,7 @@ export function registerBrowserAgentActHookRoutes(
await pw.clickViaPlaywright({
cdpUrl,
targetId: tab.targetId,
- ssrfPolicy: ctx.state().resolved.ssrfPolicy,
+ ...browserNavigationPolicyForProfile(ctx, profileCtx),
ref,
});
}
diff --git a/packages/browser-control-runtime/src/_generated/extension/src/browser/routes/agent.act.ts b/packages/browser-control-runtime/src/_generated/extension/src/browser/routes/agent.act.ts
index b5d2df7569..09ddbaabe3 100644
--- a/packages/browser-control-runtime/src/_generated/extension/src/browser/routes/agent.act.ts
+++ b/packages/browser-control-runtime/src/_generated/extension/src/browser/routes/agent.act.ts
@@ -41,6 +41,7 @@ import { registerBrowserAgentActHookRoutes } from "./agent.act.hooks.js";
import { normalizeActRequest, validateBatchTargetIds } from "./agent.act.normalize.js";
import { type ActKind, isActKind } from "./agent.act.shared.js";
import {
+ browserNavigationPolicyForProfile,
readBody,
requirePwAi,
resolveTargetIdFromBody,
@@ -91,11 +92,14 @@ async function assertExistingSessionPostInteractionNavigationAllowed(params: {
userDataDir?: string;
targetId: string;
ssrfPolicy?: BrowserNavigationPolicyOptions["ssrfPolicy"];
+ browserProxyMode?: BrowserNavigationPolicyOptions["browserProxyMode"];
listTabs: () => Promise<Array<{ targetId: string; url: string }>>;
initialTabTargetIds: ReadonlySet<string>;
}): Promise<void> {
- const ssrfPolicyOpts = withBrowserNavigationPolicy(params.ssrfPolicy);
- if (!ssrfPolicyOpts.ssrfPolicy) {
+ const ssrfPolicyOpts = withBrowserNavigationPolicy(params.ssrfPolicy, {
+ browserProxyMode: params.browserProxyMode,
+ });
+ if (!ssrfPolicyOpts.ssrfPolicy && !ssrfPolicyOpts.browserProxyMode) {
return;
}
const listTabs = params.listTabs;
@@ -410,10 +414,11 @@ export function registerBrowserAgentActRoutes(
enforceCurrentUrlAllowed: shouldEnforceCurrentUrlForAct(action),
run: async ({ profileCtx, cdpUrl, tab, resolveTabUrl }) => {
const evaluateEnabled = ctx.state().resolved.evaluateEnabled;
- const ssrfPolicy = ctx.state().resolved.ssrfPolicy;
+ const navigationPolicy = browserNavigationPolicyForProfile(ctx, profileCtx);
+ const ssrfPolicy = navigationPolicy.ssrfPolicy;
const isExistingSession = getBrowserProfileCapabilities(profileCtx.profile).usesChromeMcp;
const hasNavigationResultPolicy = Boolean(
- withBrowserNavigationPolicy(ssrfPolicy).ssrfPolicy,
+ navigationPolicy.ssrfPolicy || navigationPolicy.browserProxyMode,
);
const jsonOk = async (
extra?: Record<string, unknown>,
@@ -462,6 +467,7 @@ export function registerBrowserAgentActRoutes(
profile: profileCtx.profile,
targetId: tab.targetId,
ssrfPolicy,
+ browserProxyMode: navigationPolicy.browserProxyMode,
listTabs: () => profileCtx.listTabs(),
initialTabTargetIds,
};
@@ -676,6 +682,7 @@ export function registerBrowserAgentActRoutes(
targetId: tab.targetId,
evaluateEnabled,
ssrfPolicy,
+ browserProxyMode: navigationPolicy.browserProxyMode,
signal: req.signal,
});
if (result.blockedByDialog) {
diff --git a/packages/browser-control-runtime/src/_generated/extension/src/browser/ssrf-policy-helpers.ts b/packages/browser-control-runtime/src/_generated/extension/src/browser/ssrf-policy-helpers.ts
index cf5bfe7a2e..c562cf3da2 100644
--- a/packages/browser-control-runtime/src/_generated/extension/src/browser/ssrf-policy-helpers.ts
+++ b/packages/browser-control-runtime/src/_generated/extension/src/browser/ssrf-policy-helpers.ts
@@ -15,5 +15,14 @@ export function withAllowedHostname(
return {
...ssrfPolicy,
allowedHostnames: uniqueStrings([...(ssrfPolicy?.allowedHostnames ?? []), hostname]),
+ // A one-off grant must grant through BOTH policy fields: exact-host trust
+ // (allowedHostnames) and, when a strict hostnameAllowlist is active, the
+ // allowlist match itself. Otherwise a per-start proxyAllowedHostnames
+ // blocks the browser's own loopback CDP endpoint, and every proxied
+ // navigation fails before it starts. An absent/empty allowlist stays
+ // empty: it means "no allowlist", not "allow only this host".
+ ...(ssrfPolicy?.hostnameAllowlist?.length
+ ? { hostnameAllowlist: uniqueStrings([...ssrfPolicy.hostnameAllowlist, hostname]) }
+ : {}),
};
}
diff --git a/packages/browser-control-runtime/src/index.ts b/packages/browser-control-runtime/src/index.ts
index dcc1e8033b..35ef1418a1 100644
--- a/packages/browser-control-runtime/src/index.ts
+++ b/packages/browser-control-runtime/src/index.ts
@@ -14,6 +14,17 @@ export type {
BrowserSnapshotMode,
BrowserSnapshotRefs,
} from './types.js';
+export {
+ browserProxyRouteKey,
+ isBrowserProxyRequestUrlAllowed,
+ isBrowserProxyRequestUrlAllowedAsync,
+ resetBrowserProxyDnsVerdictCache,
+ parseBrowserProxyServer,
+ redactBrowserProxyRoute,
+ redactBrowserProxyText,
+ type BrowserProxyRoute,
+ type LookupFn,
+} from './proxy.js';
export { createUnavailableBrowserRuntime } from './unavailable.js';
export {
createBrowserControlRuntime,
@@ -26,6 +37,11 @@ export {
export { setBrowserRuntimeConfig as setBrowserControlRuntimeConfig } from './shim/runtime-config-snapshot.js';
export { refreshBrowserRuntimeConfigDir } from './shim/_local/text-utils.js';
export { isPublicHttpResourceUrl } from './resource-url-policy.js';
+export {
+ managedProfilePidOwnsCdpPort,
+ pidIsManagedChromeForProfile,
+ readManagedProfileOwnerPid,
+} from './_generated/extension/src/browser/chrome.js';
// Re-export the effective-config type under a neutral name so host code stays
// free of the vendored type's product-specific identifier.
export type {
diff --git a/packages/browser-control-runtime/src/proxy.ts b/packages/browser-control-runtime/src/proxy.ts
new file mode 100644
index 0000000000..c302b34705
--- /dev/null
+++ b/packages/browser-control-runtime/src/proxy.ts
@@ -0,0 +1,391 @@
+import {
+ isBlockedHostnameOrIp,
+ matchesHostnameAllowlist,
+ normalizeHostname,
+ resolvePinnedHostnameWithPolicy,
+ type LookupFn,
+} from './shim/security-runtime.js';
+
+export type { LookupFn };
+
+/**
+ * Browser proxy routes accepted by the neutral browser-control contract.
+ *
+ * The credential fields are intentionally in-memory only. Callers must use
+ * `server` for launch arguments and safe reporting; username/password are
+ * consumed by an authentication coordinator and are never serialized.
+ */
+export interface BrowserProxyRoute {
+ readonly mode: 'direct' | 'proxied';
+ readonly server?: string;
+ readonly username?: string;
+ readonly password?: string;
+ /** Public navigation hostnames explicitly permitted while this proxy is active. */
+ readonly allowedHostnames?: readonly string[];
+}
+
+const SUPPORTED_SCHEMES = new Set(['http:', 'https:', 'socks:', 'socks4:', 'socks5:']);
+const MAX_ALLOWED_HOSTNAMES = 32;
+// DNS limits (RFC 1035): 253 chars per name, 63 per label. WHATWG URL accepts
+// far longer hostnames, and oversized input is not merely invalid — parsing
+// succeeds, `startInRoute` stops the running browser, and only then does the
+// PAC/argv built from it risk exceeding the platform command-line limit,
+// losing the user's tabs to a launch failure. Reject at the parse boundary,
+// before anything destructive happens.
+const MAX_HOSTNAME_LENGTH = 253;
+const MAX_DNS_LABEL_LENGTH = 63;
+const MAX_PROXY_SERVER_LENGTH = 2_048;
+// LDH (RFC 952/1123): letters, digits, hyphen; a label must not start or end
+// with a hyphen. Both call sites see lowercase input (allowlist entries are
+// lowercased before this check, proxy hosts come from URL.hostname), and IDNs
+// arrive here already punycoded, so the ASCII form is the complete alphabet.
+const DNS_LABEL_PATTERN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
+
+function assertValidDnsName(hostname: string, what: string): void {
+ if (hostname.length > MAX_HOSTNAME_LENGTH) {
+ throw invalidProxy(`${what} must be at most ${MAX_HOSTNAME_LENGTH} characters`);
+ }
+ for (const label of hostname.split('.')) {
+ // WHATWG URL preserves empty and non-LDH labels (`example..com`,
+ // `_foo.example.com`, `-foo.example.com`), so length checks alone would
+ // pass names that later fail PAC/DNS matching — after the route switch has
+ // already stopped the running browser. Reject them here, fail-closed.
+ if (label.length === 0) {
+ throw invalidProxy(`${what} must not contain empty DNS labels`);
+ }
+ if (label.length > MAX_DNS_LABEL_LENGTH) {
+ throw invalidProxy(`${what} labels must be at most ${MAX_DNS_LABEL_LENGTH} characters`);
+ }
+ if (!DNS_LABEL_PATTERN.test(label)) {
+ throw invalidProxy(
+ `${what} labels must contain only letters, digits, and non-edge hyphens`,
+ );
+ }
+ }
+}
+
+function invalidProxy(message: string): Error {
+ return new Error(`invalid proxyServer: ${message}`);
+}
+
+function parseAllowedProxyHostname(raw: string): string {
+ const value = raw.trim().toLowerCase();
+ if (!value || /[\s\u0000-\u001f\u007f]/.test(value)) {
+ throw invalidProxy('allowed hostnames must be non-empty DNS names without whitespace');
+ }
+ const wildcard = value.startsWith('*.');
+ const hostname = wildcard ? value.slice(2) : value;
+ if (!hostname || hostname === 'localhost' || hostname.endsWith('.localhost')) {
+ throw invalidProxy('allowed hostnames must be public DNS names');
+ }
+ assertValidDnsName(hostname, 'allowed hostnames');
+ let parsed: URL;
+ try {
+ parsed = new URL(`https://${hostname}`);
+ } catch {
+ throw invalidProxy('allowed hostnames must be valid DNS names');
+ }
+ if (
+ parsed.hostname !== hostname
+ || parsed.port
+ || parsed.username
+ || parsed.password
+ || parsed.pathname !== '/'
+ || parsed.search
+ || parsed.hash
+ ) {
+ throw invalidProxy('allowed hostnames must not include a scheme, port, path, or credentials');
+ }
+ if (
+ !hostname.includes('.')
+ || hostname.startsWith('.')
+ || hostname.endsWith('.')
+ || /^\d+(?:\.\d+){3}$/.test(hostname)
+ || hostname.includes(':')
+ || hostname.endsWith('.local')
+ || hostname.endsWith('.internal')
+ ) {
+ throw invalidProxy('allowed hostnames must be public DNS names, not IP or local-network targets');
+ }
+ return wildcard ? `*.${hostname}` : hostname;
+}
+
+function parseAllowedProxyHostnames(raw: unknown): readonly string[] | undefined {
+ if (raw === undefined || raw === null) return undefined;
+ if (!Array.isArray(raw) || raw.length === 0 || raw.length > MAX_ALLOWED_HOSTNAMES) {
+ throw invalidProxy(`allowed hostnames must contain 1-${MAX_ALLOWED_HOSTNAMES} DNS patterns`);
+ }
+ const normalized = Array.from(new Set(raw.map((value) => {
+ if (typeof value !== 'string') {
+ throw invalidProxy('allowed hostnames must be strings');
+ }
+ return parseAllowedProxyHostname(value);
+ })));
+ return normalized.toSorted();
+}
+
+/** Parse and canonicalize a per-start proxy route without exposing credentials. */
+export function parseBrowserProxyServer(
+ raw: unknown,
+ rawAllowedHostnames?: unknown,
+): BrowserProxyRoute {
+ if (raw === undefined || raw === null) {
+ if (rawAllowedHostnames !== undefined && rawAllowedHostnames !== null) {
+ throw invalidProxy('allowed hostnames require proxyServer');
+ }
+ return { mode: 'direct' };
+ }
+ if (typeof raw !== 'string') {
+ throw invalidProxy('expected a URL string');
+ }
+ const value = raw.trim();
+ if (!value || /[\s\u0000-\u001f\u007f]/.test(value)) {
+ throw invalidProxy('must be a non-empty URL without whitespace');
+ }
+ if (value.length > MAX_PROXY_SERVER_LENGTH) {
+ throw invalidProxy(`must be at most ${MAX_PROXY_SERVER_LENGTH} characters`);
+ }
+ if (value.includes(',') || value.includes(';') || value.includes('"') || value.includes("'")) {
+ throw invalidProxy('proxy lists and argument quoting are not supported');
+ }
+
+ // Validate the caller's spelling before WHATWG URL canonicalization. Inputs
+ // such as `/.` and `/%2e` normalize to `/`; accepting them would violate the
+ // authority-only contract while looking indistinguishable after parsing.
+ const schemeSeparator = value.indexOf('://');
+ const authorityAndSuffix = schemeSeparator >= 0 ? value.slice(schemeSeparator + 3) : '';
+ const authority = authorityAndSuffix.endsWith('/')
+ ? authorityAndSuffix.slice(0, -1)
+ : authorityAndSuffix;
+ if (!authority || /[/?#]/.test(authority)) {
+ throw invalidProxy('path, query, and fragment are not supported');
+ }
+ const hostPort = authority.slice(authority.lastIndexOf('@') + 1);
+ if (hostPort.startsWith('[')) {
+ const closingBracket = hostPort.indexOf(']');
+ if (closingBracket < 0) throw invalidProxy('port is malformed');
+ const suffix = hostPort.slice(closingBracket + 1);
+ if (suffix !== '' && !/^:\d+$/.test(suffix)) {
+ throw invalidProxy('port is malformed');
+ }
+ } else {
+ const colon = hostPort.lastIndexOf(':');
+ if (colon >= 0 && !/^\d+$/.test(hostPort.slice(colon + 1))) {
+ throw invalidProxy('port is malformed');
+ }
+ }
+
+ let parsed: URL;
+ try {
+ parsed = new URL(value);
+ } catch {
+ throw invalidProxy('must use a supported proxy URL format');
+ }
+ if (!SUPPORTED_SCHEMES.has(parsed.protocol)) {
+ throw invalidProxy('scheme must be http, https, socks, socks4, or socks5');
+ }
+ if (!parsed.hostname || parsed.host === '') {
+ throw invalidProxy('host is required');
+ }
+ // IPv6 literals are bracketed by URL.hostname and carry no DNS labels.
+ if (!parsed.hostname.startsWith('[')) {
+ assertValidDnsName(parsed.hostname, 'proxy host');
+ }
+ if (parsed.port && (!/^\d+$/.test(parsed.port) || Number(parsed.port) > 65535)) {
+ throw invalidProxy('port is malformed');
+ }
+ if ((parsed.pathname !== '' && parsed.pathname !== '/') || parsed.search || parsed.hash) {
+ throw invalidProxy('path, query, and fragment are not supported');
+ }
+
+ // Authenticated proxies are NOT supported: the only mechanism that answers a
+ // proxy challenge over connectOverCDP (Playwright's context-wide
+ // setHTTPCredentials) also sends the credentials to any origin that returns
+ // WWW-Authenticate, and allowlisted page content is untrusted — a visited
+ // site could harvest the proxy credentials (verified against Chrome 151).
+ // Reject userinfo at the parse boundary so this is a loud, fail-closed error
+ // rather than a browser that silently launches without working auth. See the
+ // authenticated-proxy follow-up before re-enabling.
+ if (parsed.username !== '' || parsed.password !== '') {
+ throw invalidProxy('authenticated proxies are not supported; omit the username and password');
+ }
+ const allowedHostnames = parseAllowedProxyHostnames(rawAllowedHostnames);
+
+ // URL.host is already normalized (including bracketed IPv6 literals and a
+ // canonicalized port).
+ const server = `${parsed.protocol}//${parsed.host}`;
+ return {
+ mode: 'proxied',
+ server,
+ ...(allowedHostnames ? { allowedHostnames } : {}),
+ };
+}
+
+/** Return a stable route key suitable for idempotence checks. */
+export function browserProxyRouteKey(route: BrowserProxyRoute): string {
+ return JSON.stringify([
+ route.mode,
+ route.server ?? null,
+ route.username ?? null,
+ route.password ?? null,
+ route.allowedHostnames ?? null,
+ ]);
+}
+
+/** Safe status/result representation; credentials are deliberately omitted. */
+export function redactBrowserProxyRoute(route: BrowserProxyRoute | undefined): {
+ mode: 'direct' | 'proxied' | 'unknown';
+ server?: string;
+} {
+ if (!route) return { mode: 'unknown' };
+ return route.mode === 'direct'
+ ? { mode: 'direct' }
+ : { mode: 'proxied', server: route.server };
+}
+
+/**
+ * Whether a page request URL is permitted while a proxied route is active.
+ *
+ * Mirrors the vendored navigation guard's fail-closed explicit-proxy policy at
+ * the request level: HTTPS only, hostname must match the launch allowlist, and
+ * an absent/empty allowlist permits nothing. Uses the same normalization and
+ * wildcard semantics (`*.example.com` matches subdomains, not the apex) as the
+ * navigation-time checks so both layers agree.
+ */
+export function isBrowserProxyRequestUrlAllowed(
+ rawUrl: string,
+ route: BrowserProxyRoute,
+): boolean {
+ if (route.mode !== 'proxied') return true;
+ let parsed: URL;
+ try {
+ parsed = new URL(rawUrl);
+ } catch {
+ return false;
+ }
+ if (parsed.protocol !== 'https:') return false;
+ const hostname = normalizeHostname(parsed.hostname);
+ // An allowlist entry is only a NAME, so matching it does not prove the target
+ // is public. Apply the same host/IP policy the navigation guard uses, which
+ // rejects loopback/RFC1918/metadata literals and known-internal names.
+ //
+ // This name-only check is the first half of the gate; callers on the request
+ // path use `isBrowserProxyRequestUrlAllowedAsync`, which adds DNS-answer
+ // verification for names that only reveal a private address on resolution.
+ if (isBlockedHostnameOrIp(hostname)) return false;
+ const allowlist = (route.allowedHostnames ?? []).map((pattern) => normalizeHostname(pattern));
+ if (allowlist.length === 0) return false;
+ return matchesHostnameAllowlist(hostname, allowlist);
+}
+
+const dnsVerdictCache = new Map<string, { allowed: boolean; expiresAt: number }>();
+const DNS_VERDICT_TTL_MS = 30_000;
+const DNS_VERDICT_CACHE_MAX = 256;
+
+/**
+ * Request-level gate including DNS-answer verification.
+ *
+ * Extends {@link isBrowserProxyRequestUrlAllowed} by resolving the destination
+ * and rejecting private/special-use answers, so a name that passes the textual
+ * allowlist but resolves inward (`127.0.0.1.nip.io`, or a rebinding answer) is
+ * refused before the paused request is continued.
+ *
+ * SCOPE: this verifies what *this host* resolves. Under an explicit proxy the
+ * proxy performs its own resolution, so a proxy with split-horizon DNS can
+ * still map an allowlisted public name to an address only it can reach. That
+ * residual trust is inherent to delegating egress to an operator-chosen proxy —
+ * the same reason the vendored navigation guard demands an explicit allowlist
+ * for proxied navigation rather than relying on resolution alone.
+ *
+ * Only DENIALS are cached (short TTL, bounded). An allow is never cached: that
+ * would give a name whose DNS an attacker controls a stable window in which
+ * requests skip resolution entirely, which is precisely the rebinding this
+ * check exists to catch.
+ */
+export async function isBrowserProxyRequestUrlAllowedAsync(
+ rawUrl: string,
+ route: BrowserProxyRoute,
+ deps: { lookupFn?: LookupFn; now?: () => number } = {},
+): Promise<boolean> {
+ // Name-level policy first: cheap, and it denies most traffic without a lookup.
+ if (!isBrowserProxyRequestUrlAllowed(rawUrl, route)) return false;
+ if (route.mode !== 'proxied') return true;
+
+ let hostname: string;
+ try {
+ hostname = normalizeHostname(new URL(rawUrl).hostname);
+ } catch {
+ return false;
+ }
+
+ const now = deps.now ?? Date.now;
+ const cached = dnsVerdictCache.get(hostname);
+ // Only DENIALS are cached. Caching an allow would hand an attacker a stable
+ // bypass: an allowlisted name under their control answers publicly once,
+ // then repoints at loopback/RFC1918, and every request inside the window
+ // skips resolution here while the proxy connects to the new private answer.
+ // Re-resolving each time costs a lookup the OS resolver has usually already
+ // cached; a cached allow costs correctness.
+ if (cached && !cached.allowed && cached.expiresAt > now()) return false;
+
+ let allowed: boolean;
+ try {
+ // Deliberately NOT forwarding the route allowlist as `hostnameAllowlist`:
+ // that field grants exact-host trust and would skip the very private-answer
+ // check this call exists to perform.
+ //
+ // ONE range exemption is forwarded, and it must match what the managed
+ // config grants the navigation guard (browser-managed-config.ts) — a policy
+ // that differed from the guard's would mean the two layers disagree about
+ // the same hostname. It covers fake-IP DNS from Clash/Surge/sing-box, where
+ // ordinary public hostnames resolve into 198.18.0.0/15; without it this gate
+ // refuses every request on such a machine and proxy mode is unusable. That
+ // range is reserved for benchmarking, so exempting it cannot reach a real
+ // service.
+ //
+ // IPv6 ULA is deliberately NOT exempted here. fc00::/7 is where real
+ // internal services live and the flag cannot distinguish one from a fake
+ // IP, so exempting it would let an allowlisted name that answers with a
+ // private AAAA through — the exact inward resolution this call exists to
+ // refuse. An IPv6 fake-IP setup therefore has to use direct mode.
+ await resolvePinnedHostnameWithPolicy(hostname, {
+ ...(deps.lookupFn ? { lookupFn: deps.lookupFn } : {}),
+ policy: {
+ allowRfc2544BenchmarkRange: true,
+ },
+ });
+ allowed = true;
+ } catch {
+ // Blocked answer, or the name did not resolve — fail closed either way.
+ allowed = false;
+ }
+
+ if (allowed) {
+ // A name that previously resolved privately may legitimately recover, so a
+ // stale denial must not outlive its TTL either.
+ dnsVerdictCache.delete(hostname);
+ return true;
+ }
+ if (dnsVerdictCache.size >= DNS_VERDICT_CACHE_MAX) {
+ const oldest = dnsVerdictCache.keys().next();
+ if (!oldest.done) dnsVerdictCache.delete(oldest.value);
+ }
+ dnsVerdictCache.set(hostname, { allowed: false, expiresAt: now() + DNS_VERDICT_TTL_MS });
+ return false;
+}
+
+/** Test seam: drop cached DNS verdicts. */
+export function resetBrowserProxyDnsVerdictCache(): void {
+ dnsVerdictCache.clear();
+}
+
+/** Redact proxy URL credentials in arbitrary error/log text. */
+export function redactBrowserProxyText(value: unknown): string {
+ const text = value instanceof Error ? value.message : String(value);
+ return text.replace(/([a-z][a-z0-9+.-]*:\/\/)(\S+)/gi, (match, scheme: string, rest: string) => {
+ // Use the last delimiter so even malformed/unescaped @ in credentials is
+ // fully removed rather than leaving the password suffix visible.
+ const delimiter = rest.lastIndexOf('@');
+ return delimiter < 0 ? match : `${scheme}[REDACTED]@${rest.slice(delimiter + 1)}`;
+ });
+}
diff --git a/packages/browser-control-runtime/src/runtime.ts b/packages/browser-control-runtime/src/runtime.ts
index dc6f3d7612..53b6fb2a57 100644
--- a/packages/browser-control-runtime/src/runtime.ts
+++ b/packages/browser-control-runtime/src/runtime.ts
@@ -19,6 +19,7 @@ import type {
BrowserControlResult,
BrowserControlRuntime,
} from './types.js';
+import { parseBrowserProxyServer, redactBrowserProxyText } from './proxy.js';
type Method = 'GET' | 'POST' | 'DELETE';
interface DispatchPlan {
@@ -46,6 +47,18 @@ const DIAGNOSTIC_ACTIONS: ReadonlySet<BrowserControlAction> = new Set([
* Exported (pure) so the param-forwarding can be unit-tested as a regression
* net against future vendored re-syncs silently dropping fields. */
export function planDispatch(req: BrowserControlRequest): DispatchPlan {
+ if (
+ (req.proxyServer !== undefined || req.proxyAllowedHostnames !== undefined)
+ && req.action !== 'start'
+ ) {
+ throw new Error('proxyServer and proxyAllowedHostnames are only valid for action=start');
+ }
+ if (
+ req.action === 'start'
+ && (req.proxyServer !== undefined || req.proxyAllowedHostnames !== undefined)
+ ) {
+ parseBrowserProxyServer(req.proxyServer, req.proxyAllowedHostnames);
+ }
const profileQuery = req.profile ? { profile: req.profile } : undefined;
const withProfile = (q?: Record<string, unknown>): Record<string, unknown> | undefined => {
const merged = { ...profileQuery, ...q };
@@ -276,7 +289,7 @@ export function createBrowserControlRuntime(
}),
};
} catch (err) {
- const message = err instanceof Error ? err.message : String(err);
+ const message = redactBrowserProxyText(err);
const disabled = /browser control disabled/i.test(message);
return {
ok: false,
diff --git a/packages/browser-control-runtime/src/shim/security-runtime.ts b/packages/browser-control-runtime/src/shim/security-runtime.ts
index 0e44f4a7ea..5886f1a184 100644
--- a/packages/browser-control-runtime/src/shim/security-runtime.ts
+++ b/packages/browser-control-runtime/src/shim/security-runtime.ts
@@ -30,6 +30,7 @@ export { FsSafeError } from '../_generated/vendor/fs-safe/dist/errors.js';
// ── SSRF / hostname policy (real upstream ssrf.ts) ───────────────────────────
export {
SsrFBlockedError,
+ isBlockedHostnameOrIp,
isPrivateNetworkAllowedByPolicy,
matchesHostnameAllowlist,
resolvePinnedHostnameWithPolicy,
diff --git a/packages/browser-control-runtime/src/types.ts b/packages/browser-control-runtime/src/types.ts
index 20465b0d77..4464816a89 100644
--- a/packages/browser-control-runtime/src/types.ts
+++ b/packages/browser-control-runtime/src/types.ts
@@ -98,6 +98,10 @@ export interface BrowserActRequest {
export interface BrowserControlRequest {
action: BrowserControlAction;
+ /** Per-start proxy URL. Credentials are accepted only in-memory by the host. */
+ proxyServer?: string;
+ /** Public DNS patterns allowed for page navigation while proxyServer is active. */
+ proxyAllowedHostnames?: string[];
target?: BrowserControlTarget;
node?: string;
profile?: string;
diff --git a/packages/browser-control-runtime/upstream/MAINTAINING.md b/packages/browser-control-runtime/upstream/MAINTAINING.md
index f8b6337228..8aad57be64 100644
--- a/packages/browser-control-runtime/upstream/MAINTAINING.md
+++ b/packages/browser-control-runtime/upstream/MAINTAINING.md
@@ -24,7 +24,7 @@ agent 调 browser 工具
│ createBrowserMcpServer(deps).deps.getRuntime()
▼
[Layer 3] desktop host apps/desktop/src/main/mcp-integrations/browser.ts
- │ 单例 runtime = createBrowserControlRuntime({ config: buildManagedConfig() })
+ │ ExternalChromeBackend 串行化 start/stop + 每次 launch 的不可变 route config
▼
[Layer 1] vendored runtime packages/browser-control-runtime/
│ runtime.call(request) → _generated/ 里的 vendored dispatcher
@@ -40,7 +40,11 @@ playwright-core → 托管 Chrome(Cindy profile, 持久 user-data-dir)
## 3. 配置流(以及那个静默 bug)
-host 在 `browser-managed-config.ts` 用 `buildManagedConfig()` 造出 `{ browser: { enabled, defaultProfile:'Cindy', headless:false, ssrfPolicy:{ dangerouslyAllowPrivateNetwork:true }, profiles:{ Cindy:{ driver:'openclaw', color, cdpPort } } } }`,`browser.ts` 在模块求值时将其传给 `createBrowserControlRuntime({ config })`。Desktop 浏览器允许访问本机网络可达的所有 HTTP(S) 地址,包括 localhost、RFC1918、cloud metadata、link-local 与代理 fake-IP。这是明确的浏览器产品策略:Agent 的终端和页面内 JS 不受同一 Node guard 控制,不能把浏览器单独拦内网当成完整网络权限边界。协议校验、浏览器沙箱、网站权限和登录态隔离仍保留。该开关使用上游已有能力,不修改共享 SSRF 默认值或其它网络调用方;原有窄 fake-IP 配置及同步补丁继续为其它配置保留。runtime 内部把 config 存进 in-memory 配置快照;vendored dispatcher 每次请求经
+host 在 `browser-managed-config.ts` 用 `buildManagedConfig({proxyServer?})` 造出 `{ browser: { enabled, defaultProfile:'Cindy', headless:false, extraArgs?, ssrfPolicy, profiles:{ Cindy:{ driver:'openclaw', color, cdpPort } } } }`,`browser.ts` 在模块求值时将其传给 `createBrowserControlRuntime({ config })`。**`ssrfPolicy` 按 route 分两种**:direct 启动用 `dangerouslyAllowPrivateNetwork:true`——Desktop 浏览器允许访问本机网络可达的所有 HTTP(S) 地址,包括 localhost、RFC1918、cloud metadata、link-local 与代理 fake-IP;这是明确的浏览器产品策略:Agent 的终端和页面内 JS 不受同一 Node guard 控制,不能把浏览器单独拦内网当成完整网络权限边界。proxied 启动改用**唯一**的窄 fake-IP 开关 `allowRfc2544BenchmarkRange` 加 `hostnameAllowlist`:代理路由是「只走这些公网域名、经这个出口」的显式契约,同时放开内网会和调用方刚给的 allowlist 自相矛盾,并让逐请求 DNS 校验变成唯一兜底。`198.18.0.0/15` 是 RFC 2544 基准测试保留段、不存在合法目标服务,所以豁免它只放行 Surge/Clash/sing-box 的 fake-IP DNS,触达不到真实内网。
+
+> ⚠️ **不要恢复 `allowIpv6UniqueLocalRange`。** `fc00::/7` 正是真实内网服务所在,该开关无法把它与 fake IP 区分开;开启后 public-A / private-AAAA 混合记录会先通过 PAC 的 IPv4 `dnsResolve` 检查、再以私有 AAAA 被放行,直接击穿本 route 的「只走公网域名」边界。代价是使用 IPv6 fake-IP 的机器在代理模式下不可用——这类环境请走 direct 模式,安全边界上选 fail-closed。`browser-managed-config.ts` 与 `proxy.ts` 的请求闸门必须转发**同一份**策略,否则两层会对同一 hostname 判定不一致。
+
+上游 SSRF 层已支持这些字段但 config resolver 尚未透传,所以 `sync.mjs` 用 fail-loud `LOCAL_PATCHES` 保留它们。协议校验、浏览器沙箱、网站权限和登录态隔离在两种 route 下都保留。`ExternalChromeBackend` 把 direct/proxied route 当作浏览器进程 launch state:所有外置浏览器调用进入同一串行队列,route 变化时先停旧进程,再用不可变 base config + 新 route 创建 runtime;绝不在无关调用执行中修改共享 config。启动不带 `proxyServer` 是显式 direct,配置不含 proxy flag,生成 launcher 因而保留 `--no-proxy-server`。runtime 内部把 config 存进 in-memory 配置快照;vendored dispatcher 每次请求经
`getRuntimeConfigSourceSnapshot() ?? getRuntimeConfig()` 再取 `.browser` 拿到它。
> ⚠️ **不变量(踩过的最大的坑):** `src/shim/runtime-config-snapshot.ts` 的 `getRuntimeConfigSourceSnapshot()` **必须返回 `OpenClawConfig | null`**(默认 `return null`)。它一旦返回 `{config, source}` 这种 wrapper,上面的 `?? getRuntimeConfig()` 永远短路、`.browser` 取到 `undefined`,**host 注入的整份 config 被静默丢弃、runtime 跑纯 vendored 默认值**(于是 profile 显示成上游默认名、颜色/目录全不对)。由 `src/__tests__/runtime-config-application.test.ts` 守护——别删那条测试。
@@ -57,9 +61,68 @@ host 在 `browser-managed-config.ts` 用 `buildManagedConfig()` 造出 `{ browse
| 6 | profile 没有自定义头像 | Chrome 只认内置头像 / Google 账号头像,不能塞本地图 | 已知限制,接受;别为它改 vendored decorate |
| 7 | 改了 `browser-workflow.md` 但 agent 还按旧文案 | 这份 md 经 `?raw` 静态打进**进程内** MCP server;且 agent 只在调 `list_tools` 时读 rules | 改完要 **(a) 重启桌面端**(main/package 改动不热更)+ **(b) 开新 agent 会话**(老会话 context 里是旧 rules) |
| 8 | 远端 Codex 会话里浏览器不可用 | lizi MCP 桥接只对**本地** Codex 生效(见 §7) | 不是 bug;所有 `lizi_*` 工具对远端 Codex 都一样 |
-| 9 | 开了「使用我的浏览器登录态」但窗口仍是登出 | 快照把 `last_used` 的 cookie 放进 dest `Default`,却原样拷了 `Local State`;Chrome 按 `last_used` 打开空的 `Profile N` | 写入 dest `Local State` 时必须把 `last_used` / `last_active_profiles` / `profiles_order` 改成 `Default`,`info_cache` 只留 Default(元数据从源 last_used 挪过来),并删掉 dest 里其它 `Profile N` |
-| 10 | Chrome 右上角 chip 显示 `Cindy-real` / 源 profile 名 | 磁盘 key 必须是 `Cindy-real`;vendored decorate 默认用 `profile.name`(map key)。host 只改 Local State 不够,下次 launch 会盖回去 | `profiles[Cindy-real].displayName = "Cindy"`;`launchOpenClawChrome` 用 `displayName ?? name` decorate。快照写入时也把 `info_cache.Default.name` 写成 `Cindy` |
-| 11 | 已有完全磁盘访问仍弹「需要完全磁盘访问权限」 | 第一次 enable 在 macOS 无条件跑 `guideFullDiskAccessAfterReadDenied` | 同意拷贝之后先 `probeSourceRead`(只 open 源 Local State / Cookies,不拷贝、不回路径);`readable: true` 就跳过。真正快照 `REAL_PROFILE_READ_DENIED` 仍弹。不自动打开系统设置 |
+| 9 | 代理切换后仍走旧出口 / 并发 start-stop 互相踩配置 | route 被当成普通请求参数、或运行中改共享 config | route 是进程 launch state;所有 external call 串行;不同/未知 route 必须 stop→recreate→start,失败后不得继续服务旧 route |
+| 10 | 认证代理凭据出现在进程参数、日志、结果或数据库 | 曾接受带 userinfo 的 proxy URL | **不支持认证代理**:`parseBrowserProxyServer` 见到 userinfo 直接抛错,凭据因此根本进不来。tool input 跨持久化/UI 边界前仍走同一 parser 验证,不能解析(含带凭据)的整值替换为 `[REDACTED]`。想恢复支持前先读 §4.1 的那条不变量 |
+| 11 | 开了「使用我的浏览器登录态」但窗口仍是登出 | 快照把 `last_used` 的 cookie 放进 dest `Default`,却原样拷了 `Local State`;Chrome 按 `last_used` 打开空的 `Profile N` | 写入 dest `Local State` 时必须把 `last_used` / `last_active_profiles` / `profiles_order` 改成 `Default`,`info_cache` 只留 Default(元数据从源 last_used 挪过来),并删掉 dest 里其它 `Profile N` |
+| 12 | Chrome 右上角 chip 显示 `Cindy-real` / 源 profile 名 | 磁盘 key 必须是 `Cindy-real`;vendored decorate 默认用 `profile.name`(map key)。host 只改 Local State 不够,下次 launch 会盖回去 | `profiles[Cindy-real].displayName = "Cindy"`;`launchOpenClawChrome` 用 `displayName ?? name` decorate。快照写入时也把 `info_cache.Default.name` 写成 `Cindy` |
+| 13 | 已有完全磁盘访问仍弹「需要完全磁盘访问权限」 | 第一次 enable 在 macOS 无条件跑 `guideFullDiskAccessAfterReadDenied` | 同意拷贝之后先 `probeSourceRead`(只 open 源 Local State / Cookies,不拷贝、不回路径);`readable: true` 就跳过。真正快照 `REAL_PROFILE_READ_DENIED` 仍弹。不自动打开系统设置 |
+
+### 4.1 per-start 代理不变量
+
+- `proxyServer` 只允许 `action=start`;MCP 与 neutral runtime 边界都会拒绝其它 action。
+- 支持 Chromium URI 形式的 `http`、`https`、`socks`/`socks5`、`socks4`;禁止 proxy list、`DIRECT` fallback、路径、query、fragment 与命令行注入字符。SOCKS 认证不受 Chromium 支持,带凭据直接拒绝。
+- direct→direct、proxy A→proxy A 幂等;direct↔proxy、proxy A→proxy B 必须停旧进程后重建。无法证明已运行进程 route 时按 unknown 处理并安全重启。
+- proxied 启动**只下发 `--proxy-pac-url`**,代理地址写在 PAC 的 `PROXY`/`SOCKS5` 指令里;PAC 对非 allowlist host 返回 `PROXY 0.0.0.0:0`,没有 `DIRECT` 回退,代理不可达时 Chrome 请求失败,不得回退直连。新 route 启动或认证协调器失败时立即 stop,并保持 route unknown/stopped。
+- status/start 只暴露 `{proxy:{mode,server?}}`;server 无 userinfo/query。任何异常文本进入日志或 tool result 前再走中央 redaction。
+- **认证代理不支持,且这是实测后的有意决定。** 两条路都走不通(Chrome 151 实测):
+ 1. **host 侧 CDP 协调器**:Chrome 对同一 target 只把 `Fetch.authRequired` 投给**一个**
+ client;vendored 会话用 `connectOverCDP` 连接并在导航守卫里 `page.route("**")`,
+ 必然赢得拦截权,协调器永远收不到挑战(双 client 实测:事件只投给后连接的那个)。
+ 2. **Playwright `context.setHTTPCredentials`**:能应答代理挑战,但它是 **context 级、
+ 不区分挑战来源**——页面从**自身 origin** 返回 `WWW-Authenticate: Basic` 时 origin 会
+ 拿到同一份凭据(实测 origin 收到 `PROXYUSER:PROXYSECRET`)。allowlist 内页面内容不可信,
+ 等于把用户的代理凭据交给被访问站点。加 `httpCredentials.origin` 也救不了:该限制对代理
+ 挑战同样生效——scope 到代理等于没 scope,scope 到别处则代理 407 无人应答(实测 0 认证)。
+ 因此 `parseBrowserProxyServer` **在解析边界直接拒绝带 userinfo 的 URL**:宁可响亮报错,
+ 也不要启动一个"看起来配了认证代理、实际认证根本不工作"的浏览器。要恢复支持必须先找到
+ **只对代理挑战生效**的凭据通道(例如让 runtime 自己 launch 浏览器而非 `connectOverCDP`,
+ 用 launch 期的 `proxy:{username,password}`),并重新做 origin 泄漏验证。
+- 调用方的原生 Agent transcript 是 host 边界之前的上游记录:Claude/Codex 可能在 Cindy 收到 MCP 请求前已持久化模型生成的原始 tool input。由于本接口现在直接拒绝带 userinfo 的 URL,正常路径下不存在可被上游 transcript 保留的代理凭据;但调用方若**尝试**传入凭据,那次尝试仍可能留在其自身 transcript 里。
+- 自动附加的新 page 只有在 `Fetch.enable(handleAuthRequests:true)` 成功后才恢复执行;后续 target 安装认证处理器失败时关闭整个受管浏览器,不得继续报告一条可用的认证代理路由。
+- 后续 target 的认证安装失败要先把 host route 标成 blocked,再尝试 `Browser.close`;即使 CDP 关闭命令失败,普通调用与 `start` 仍须拒绝,直到 `stop` 被验证成功。
+- 认证协调器初始化期间的异步 target 失败不得被最终成功赋值覆盖;认证 CDP WebSocket 意外断开也必须立即把 route 标成 blocked。只有显式 dispose/stop 的主动断开可以忽略。
+- 认证启动返回前必须用 CDP 命令响应作为消息屏障,等待屏障前收到的 auto-attach 认证任务全部完成;屏障内失败时 `start` 必须失败,不能先报告代理可用再异步改成 unknown。
+- app 退出先关闭 `ExternalChromeBackend` 的新调用准入,再通过同一串行队列排空已准入调用并停止浏览器;退出清理开始后到达的 `start` 不得在 stop 后重新拉起 Chrome。
+- backend 切换/退出时只有验证 stop 成功后才能清 route、释放认证协调器并把 runtime 标成未使用;stop 失败或抛错必须保留清理所有权并进入 blocked 状态。
+- 已验证停止的 proxied runtime 不能留给 `open` 等普通动作隐式重启;清理 route 时同步换回 immutable direct runtime。路由幂等 key 必须用无碰撞 tuple 编码,不能用未转义分隔符拼接。
+- 关闭未知继承进程前不能只信任固定 loopback CDP 端口;必须通过 CDP `SystemInfo.getInfo` 同时核对受管 profile 的 `--user-data-dir` 与 `--remote-debugging-port`,身份不符或无法建立时拒绝关闭和重启。
+- **CDP 守卫身份必须跟本次 launch**:`ExternalChromeBackend` 不得把 `cdpHttpUrl` / `managedUserDataDir` 钉死成 `18800` + `browser/Cindy`。「使用我的浏览器登录态」走 `Cindy-real`,18800 被占时还会迁到 18801+。Fetch 门、liveness、adopted-close 与 fail-closed 杀进程必须在 **start 当下** 读取当前 profile 与 `cdpPort`(与 `applyManagedConfig` / `pickManagedCdpPort` 同一份);对不上就 fail closed,不要贴到残留 Chrome。
+- 继承的 `HTTP_PROXY`/`HTTPS_PROXY`/`ALL_PROXY`/`NO_PROXY` 清理仍由 vendored launcher 保持;CDP loopback 控制连接不经页面代理。
+- **`running` 是 `cdpReady`,不是进程存活。** vendored status 的 `running` 字段等于 CDP
+ readiness(`routes/basic.ts`),忙碌但活着的 Chrome 会报 `running:false`。因此
+ **`'stopped'` 永远不等于「没有进程」**。所有会拆路由、归因隐式启动、或收养陌生进程的判断
+ 必须走 `external-chrome-backend.ts` 的 `resolveLiveness()`,它只返回三态:
+ `running` / `gone`(经非破坏性探针独立验证缺席)/ `unproven`。**`unproven` 一律 fail
+ closed**——保留路由并 block,直到一次已验证的 stop;对 direct 路由同样适用(清掉一条还活着的
+ direct 路由,会让下一次 start 把我们自己的浏览器当陌生进程关掉,毁掉用户标签页)。
+ passive 路径(`status`)只能用非破坏性探针,绝不能发 `Browser.close`。
+- 因 `unproven` 设的 block 是**暂时的**,浏览器恢复应答后必须清除(否则除 status/stop 外
+ 永久不可用);而认证失败、stop 无法验证、restart 失败设的 block **不是**暂时的——那表示
+ 路由本身不可信,只有已验证的 stop 能解除。用 `routeBlockedByUnprovenLiveness` 区分,别把
+ 两者混成一个布尔。
+- 代理启动必须带 `--webrtc-ip-handling-policy=disable_non_proxied_udp`:WebRTC 走 UDP,
+ 既不经 PAC 也不进 CDP `Fetch`,页面可以在「已代理」状态下用 `RTCPeerConnection` 暴露本机真实
+ IP(Chrome 151 实测:不带该 flag 会吐出 LAN IP host candidate,带上则无 candidate)。
+ 注意**没有 `--force-` 前缀**——`--force-webrtc-ip-handling-policy` 会被静默忽略。
+- 代理不改变导航 SSRF 判定;fake-IP 两个既有窄豁免之外的 private/metadata/link-local 阻断不得放宽。
+- `navigate` 与 `click`/`type`/`press`/`select`/`fill`/`evaluate`/`hover`/`drag`/`scrollIntoView`/`wait` 等交互触发的主框架、子框架和延迟导航必须使用同一份 profile proxy mode + SSRF policy;不能只保护显式导航入口——凡可能触发脚本导航的交互(含 `setInputFiles` 直接上传后的 input/change 事件与 `resize` 视口变化,及交互期间经 window.open / target=_blank 打开的新 tab)都要走同一导航守卫。
+- **启动瞬间的下限由 PAC 兜底**:CDP 守卫要等 DevTools 端点起来才能 attach,持久 profile 恢复标签页/拉起 service worker 可能在这个窗口内出网。因此 proxied 启动同时下发 `--proxy-pac-url`(data: URL,base64),PAC 把 allowlist 内的 host 指向代理、其余一律返回不可达指令(**没有 DIRECT 回退**,否则会绕过代理直出);host 模式串必须 JSON 编码后再进 PAC 源码,不能字符串拼接。**不要再叠加 `--proxy-server`**:Chromium 从命令行只取一种代理模式,优先级固定为 `--no-proxy-server` > `--proxy-pac-url` > `--proxy-auto-detect` > `--proxy-server`(`ChromeCommandLinePrefStore::ApplyProxyMode`,Chrome 152 实测同 PAC 生效、fixed 代理不收任何 CONNECT),叠上去只是一条会误导读者的死配置;上游 `browser-proxy-mode.ts` 把 `--proxy-pac-url` 本身就当显式代理路由,导航守卫的 proxied 判定不依赖 `--proxy-server`。PAC 是下限不是上限,attach 之后仍由下面的 CDP 守卫逐请求执行 HTTPS + allowlist。
+- **请求级的终局判据是宿主的 lifetime CDP 守卫**(`apps/desktop/.../proxy-auth.ts`):proxied 启动一律安装,对**每个具备网络能力的** target(page / iframe / service_worker / shared_worker / worker / worklet,含启动时已存在的与 auto-attach 新建的)开 `Fetch`——拦截是 target/session 级的,漏装的 worker 会绕过闸门直出;非网络 target 只 resume 不开闸,并对每条 paused 请求执行 fail-closed 判据——仅 HTTPS 且 hostname 命中本次启动 allowlist 才 `continueRequest`,否则 `failRequest(BlockedByClient)`;无 allowlist 的 proxied 启动一律全拦。判据实现在 `proxy.ts` 的 `isBrowserProxyRequestUrlAllowedAsync`,与导航守卫共用同一套 normalize / 通配语义,两层必须同判。上面的交互级守卫是纵深防御(给调用方同步失败与 quarantine 语义),**不得**因为有请求级守卫就删掉,反之亦然。
+ - **allowlist 只是名字,必须再验 DNS 应答**:命中 allowlist 不等于目标是公网。`isBrowserProxyRequestUrlAllowedAsync` 先跑同步的名字判据(HTTPS + allowlist + 字面私网/内网名),再对通过者跑 `resolvePinnedHostnameWithPolicy`,拦掉「名字公网、解析结果指向内网」这一类(`127.0.0.1.nip.io`、rebinding 应答);解析不出来也一律 fail closed。调用这个解析时**不要**把本次 allowlist 当 `hostnameAllowlist` 传进去——那个字段是精确主机豁免,会跳过这里唯一要做的私网应答检查。判定按 hostname 缓存 30s(无缓存则每条 paused 请求都要查一次 DNS;无上限则 rebinding 应答会被永久钉住),TTL 到期必须重查。
+ - 残留信任:以上验的是**本机**的解析结果。explicit proxy 自己还会再解析一次,所以带 split-horizon DNS 的代理仍可把 allowlist 内的公网名映射到只有它够得到的地址。这是把出网委托给运营者选定代理的固有代价——也正是导航守卫在 proxied 模式下坚持要求显式 allowlist、而不肯只靠解析结果的原因。
+ - 已知边界:CDP `Fetch` **不拦截 WebSocket 握手**,故 WS 出网不由请求级守卫判定,而是由启动 PAC 兜底——Chrome 把 `ws:`/`wss:` 原样交给 PAC(已对 Chrome 151 实测),因此 PAC 必须显式放行 `wss://`(否则 allowlist 内站点的实时功能全断,且没有任何后续层能救回),并继续拦掉明文 `ws://`。改动 PAC 的 scheme 判据时**必须同时想清楚 WS**:这是唯一在管它的地方。
+ - **PAC 必须自己验 DNS 应答**:pre-attach 窗口和 WSS 都看不见 CDP 闸门,所以 PAC 在 hostname 命中 allowlist 之后还要 `dnsResolve` + `isInNet`(Netscape PAC / Chromium 实现,IPv4-only;解析失败 fail closed)。私网/特殊用途 IPv4 与 IPv6 loopback/link-local 字面量一律不可达指令;198.18.0.0/15 豁免以对齐 `allowRfc2544BenchmarkRange`。残留信任与 CDP 层相同:验的是本机解析,explicit proxy 自己还会再解析一次。
+- Settings 的“打开 Agent 专用浏览器”必须先读 `status`:已运行时只聚焦现有标签页,不能用无 `proxyServer` 的 `start` 把调用方选择的代理路由误切成直连;仅在确认 stopped 后才启动直连浏览器。**例外是 `proxy.mode === 'unknown'`**(Cindy 重启后继承了上次启动的 Chrome):此时没有任何已知路由可保护,而 backend 的 unknown-route 闸门会拒掉 `tabs`/`focus`,跳过 `start` 只会让这个按钮"成功返回但什么都没发生"。`start` 是唯一能收养/替换该进程并重装请求守卫的路径,这种情况必须执行。判据只认 `unknown`——`direct` 与 `proxied` 都是已知路由,照旧不得被直连 `start` 顶掉。
## 5. UI 开关模型(设置 →「自动操作」)
diff --git a/packages/browser-control-runtime/upstream/browser-runtime.lock.json b/packages/browser-control-runtime/upstream/browser-runtime.lock.json
index a93dd46826..fdc0fe0b04 100644
--- a/packages/browser-control-runtime/upstream/browser-runtime.lock.json
+++ b/packages/browser-control-runtime/upstream/browser-runtime.lock.json
@@ -22,6 +22,18 @@
"file": "extension/src/browser/chrome.executables.ts",
"desc": "classify macOS Google Chrome Beta within the Chrome-only fallback"
},
+ {
+ "file": "extension/src/browser/chrome.ts",
+ "desc": "expose managed-profile PID lookup so the host can confirm process exit from the OS, not from CDP endpoint silence (a stalled Chrome stops answering while still alive)"
+ },
+ {
+ "file": "extension/src/browser/chrome.ts",
+ "desc": "decorate Chrome chip with host displayName so Cindy-real stays disk-only"
+ },
+ {
+ "file": "extension/src/browser/chrome.ts",
+ "desc": "pass chipName into decorateOpenClawProfile instead of the disk key"
+ },
{
"file": "extension/src/browser/config.ts",
"desc": "preserve narrow fake-IP SSRF allowances from the host config without enabling general private-network access"
@@ -31,16 +43,44 @@
"desc": "skip upstream auto-injected \"openclaw\"/\"user\" profiles when the host provides its own (avoids CDP port 18800 collision with the managed profile + never drives the user's Chrome)"
},
{
- "file": "extension/src/browser/chrome.ts",
- "desc": "decorate Chrome chip with host displayName so Cindy-real stays disk-only"
+ "file": "extension/src/browser/navigation-guard.ts",
+ "desc": "allow explicit browser proxies only for public hostnames named in the strict hostname allowlist"
},
{
- "file": "extension/src/browser/chrome.ts",
- "desc": "pass chipName into decorateOpenClawProfile instead of the disk key"
+ "file": "extension/src/browser/pw-session.ts",
+ "desc": "export a non-blocking quarantine so the popup-overflow path can mark a target unusable without awaiting close() (a hung page must not keep the interaction pending)"
+ },
+ {
+ "file": "extension/src/browser/pw-tools-core.interactions.ts",
+ "desc": "propagate proxy mode through Playwright interaction navigation checks"
+ },
+ {
+ "file": "extension/src/browser/pw-tools-core.interactions.ts",
+ "desc": "guard direct input file uploads with the proxy navigation policy"
+ },
+ {
+ "file": "extension/src/browser/pw-tools-core.interactions.ts",
+ "desc": "guard hover/drag/scrollIntoView/wait interactions with the same proxy navigation policy"
+ },
+ {
+ "file": "extension/src/browser/routes/agent.act.hooks.ts",
+ "desc": "apply the effective browser proxy mode to file-chooser click navigation"
+ },
+ {
+ "file": "extension/src/browser/routes/agent.act.hooks.ts",
+ "desc": "apply the effective browser proxy mode to direct input file uploads"
+ },
+ {
+ "file": "extension/src/browser/routes/agent.act.ts",
+ "desc": "carry the effective browser proxy mode through interaction navigation guards"
+ },
+ {
+ "file": "extension/src/browser/ssrf-policy-helpers.ts",
+ "desc": "one-off hostname grants must also pass a strict hostnameAllowlist (else the loopback CDP endpoint is blocked by proxyAllowedHostnames and every proxied navigation fails)"
}
],
"fileCount": 335,
- "contentHash": "ec71c1f65b7239df32b0e861d8ac55a1dc55747487dae4fcf1ea4d16002c02ec",
+ "contentHash": "e159bab01eeb636292361f6755439f4826e447c3f1fe2a22e452d078ecfd8e4c",
"fsSafe": {
"package": "@openclaw/fs-safe",
"version": "0.4.0"
diff --git a/packages/lizi-mcps/src/browser/browserMcpServer.test.ts b/packages/lizi-mcps/src/browser/browserMcpServer.test.ts
index 5cfe24b849..0f75695160 100644
--- a/packages/lizi-mcps/src/browser/browserMcpServer.test.ts
+++ b/packages/lizi-mcps/src/browser/browserMcpServer.test.ts
@@ -159,6 +159,52 @@ describe('createBrowserMcpServer', () => {
await h.cleanup();
});
+ it('accepts proxyServer for start and forwards it unchanged to the host', async () => {
+ const h = await makeHarness();
+ const result = await h.client.callTool({
+ name: 'call_tool',
+ arguments: {
+ name: 'browser',
+ args: {
+ action: 'start',
+ proxyServer: 'http://proxy.example:8080',
+ proxyAllowedHostnames: ['auth.example.com', '*.service.example.com'],
+ },
+ },
+ });
+
+ expect(h.calls).toEqual([{
+ action: 'start',
+ proxyServer: 'http://proxy.example:8080',
+ proxyAllowedHostnames: ['auth.example.com', '*.service.example.com'],
+ }]);
+ expect(result.isError).not.toBe(true);
+ await h.cleanup();
+ });
+
+ it('rejects proxyServer for non-start actions without echoing credentials', async () => {
+ const h = await makeHarness();
+ const result = await h.client.callTool({
+ name: 'call_tool',
+ arguments: {
+ name: 'browser',
+ args: {
+ action: 'status',
+ proxyServer: 'http://proxy.example:8080',
+ },
+ },
+ });
+
+ expect(h.calls).toEqual([]);
+ const text = (result.content as Array<{ text: string }>)[0].text;
+ expect(JSON.parse(text)).toMatchObject({
+ ok: false,
+ errorCode: 'BROWSER_RUNTIME_INVALID_REQUEST',
+ });
+ expect(text).not.toMatch(/p%40ss/);
+ await h.cleanup();
+ });
+
it('passes through the network actions (requests / responseBody)', async () => {
const h = await makeHarness();
await h.client.callTool({
diff --git a/packages/lizi-mcps/src/browser/prompts/rules/browser-workflow.md b/packages/lizi-mcps/src/browser/prompts/rules/browser-workflow.md
index 446dae3d18..4d3e711dc9 100644
--- a/packages/lizi-mcps/src/browser/prompts/rules/browser-workflow.md
+++ b/packages/lizi-mcps/src/browser/prompts/rules/browser-workflow.md
@@ -46,6 +46,20 @@
5. **遇阻塞停下来报告**
- 撞到登录墙 / 验证码 / 2FA / 需要人工授权时:**停下来如实告诉用户**当前页面状态 + 需要他做什么,不要反复尝试或假装能绕过。
+#### 指定代理与出口验证
+
+当任务要求浏览器使用指定代理或网络出口时,必须在继续目标操作之前按顺序验证:
+
+> **不支持认证代理。** 带用户名/密码的 `proxyServer` 会被直接拒绝(报 `authenticated proxies are not supported`)。原因:在当前架构下唯一能应答代理挑战的凭据通道会把凭据一并发给返回 `WWW-Authenticate` 的**任意站点**,而 allowlist 内的页面内容本就不可信——那等于把用户的代理凭据交给被访问的站点。需要认证出口时,请在代理侧改用免密方式(如按来源 IP 放行)。
+
+1. 用指定代理启动独立外置浏览器:`{action:"start",proxyServer:"http://代理主机:端口",proxyAllowedHostnames:["出口IP检查页host","目标站host或*.目标域"]}`。代理模式下导航默认全部拒绝(fail-closed),只放行 `proxyAllowedHostnames` 里列出的公网 DNS 名称或 `*.example.com` 模式,且仅允许 HTTPS——所以**启动时就必须把出口检查页与目标站都列入**;该清单随本次启动固定,后续要访问新域名必须用新的 `start` 重启。清单在浏览器整个生命周期内于请求层强制执行(不只在工具发起的导航时检查),因此地址栏手输、定时器跳转、meta refresh、弹窗等任何出网都同样受限——被拦的请求会像网络失败一样在页面上报错。`proxyServer` 与 `proxyAllowedHostnames` 只允许用于 `start`;侧边栏内置浏览器不支持这些参数,遇到明确拒绝时不要继续。
+2. 调 `status`,确认 `data.proxy.mode === "proxied"`,并核对 `data.proxy.server` 是预期的代理地址。
+3. 仍通过本浏览器导航到可信的出口 IP 检查页,读取页面显示的公网 IP。
+4. 将公网 IP 与预期的代理出口 IP 比较。只有一致时才继续。
+5. 验证通过后再继续目标网站或后续操作。
+6. 任一环失败就 `stop` 并报告;**绝不绕过代理改用直连继续**。
+7. 任务完成后,可用不带 `proxyServer` 的 `{action:"start"}` 明确恢复普通直连模式。代理 A 切代理 B、代理切直连都会重启浏览器;重复同一代理则保持当前进程。
+
#### Token 效率(按"最省 → 兜底"的顺序选路)
1. **先查有没有现成配方**:操作某个站之前,**先 `action: "siteguide"`**——带 `site`(站点 host)看该站内置指南 / 配方;**不确定有哪些站时,`siteguide` 不带 `site` 会列出全部内置站点 + 可用配方目录**(`sites:[{site,recipes,auth}]`)。命中配方就 `action: "recipe"`(`recipeId`+`inputs`)一步跑完(最省最稳),优先于手动 snapshot/extract。注意 `siteguide` 是我们内置的站点指南,**不是去抓网站自己的 `/sitemap.xml`**——不要为此去 navigate / curl `sitemap.xml`。
2. **数据型页面优先读接口,别扒 DOM**:很多列表 / 详情背后是 JSON API,读接口比扒渲染后的 DOM 又稳又省。
@@ -63,6 +77,7 @@
- **`data.backend === "rsb-webview"` = Cindy 侧边栏内置浏览器**:页面活在 Cindy 的会话侧边栏里,不是一个常规浏览器窗口。侧边栏本身可能内嵌在主窗口、也可能被用户开成独立子窗口,`status` **不区分**这两种承载方式——所以请用户看页面时说"Cindy 的侧边栏(若你把侧边栏开成了独立窗口,就是那个窗口)",不要断言窗口存在或不存在。系统默认的自动化后端是独立外置浏览器,不是侧边栏。
- 仅此模式支持:`act:saveResource`(托管下载)、以及 `query` 语义元素查询(role / name / text / label / placeholder / testId / css)。在外置模式下用这两个会被 schema 或运行时门控直接拒掉,别当通用能力使。
- **`data.backend === "external"` = 独立外置浏览器**:一个专属持久自动化浏览器窗口(profile 显示为 "Cindy")。`act:saveResource` 与语义 `query` 在此模式不可用,元素定位改用 snapshot 的 `ref` 或 `selector`。旧宿主可能省略该字段,不要把缺少模式信息当成已使用内置浏览器。
+ - 此模式的 `status.data.proxy` 报告当前启动路由:`direct`、`proxied`(带脱敏 `server`)或无法确认继承进程路由时的 `unknown`。需要指定代理时必须重新调用 `start` 并检查结果,不要从已有 tab 猜测出口。代理模式下只有 `proxyAllowedHostnames` 列出的公网域名可导航,内网地址不在其中。
`setBackend` 与设置页修改同一个**全局、持久**选择,会影响其他正在使用浏览器的任务,旧模式的操作可能中断。仅按用户明确的模式要求切换,无需重复确认;不要因页面报错自行换模式。切换后重新 `tabs` / `snapshot`,不沿用旧模式的 targetId、ref 或登录态。宿主不支持切换或返回失败时如实说明,不能声称切换成功。
diff --git a/packages/lizi-mcps/src/browser/tools.ts b/packages/lizi-mcps/src/browser/tools.ts
index 856e4e455c..35f0bcf9f4 100644
--- a/packages/lizi-mcps/src/browser/tools.ts
+++ b/packages/lizi-mcps/src/browser/tools.ts
@@ -1,5 +1,6 @@
import {
isPublicHttpResourceUrl,
+ parseBrowserProxyServer,
type BrowserControlRequest,
type BrowserControlRuntime,
} from '@cindy/browser-control-runtime';
@@ -238,6 +239,12 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse
.enum(['external', 'rsb-webview'])
.optional()
.describe('仅 action=setBackend: 切换全局自动化目标并保存设置; 会影响其他任务,两种模式的登录态与标签页不互通'),
+ proxyServer: z.string().optional().describe(
+ 'action=start 时使用的代理 URL(如 http://host:port)。**不支持带用户名/密码的认证代理**,带 userinfo 会被直接拒绝',
+ ),
+ proxyAllowedHostnames: z.array(z.string()).min(1).max(32).optional().describe(
+ 'action=start 且启用代理时允许导航的公网 DNS 名称或 *.example.com 模式;代理模式默认禁止导航',
+ ),
profile: z.string().optional().describe('浏览器 profile 名;省略则使用默认隔离 profile'),
target: z.enum(['sandbox', 'host', 'node']).optional(),
node: z.string().optional(),
@@ -355,6 +362,22 @@ export function registerBrowserTools(registry: BrowserToolRegistry, deps: Browse
if (args.backend !== undefined) {
return errorResult(args.action, 'backend 仅用于 setBackend; 请先切换模式,再操作页面');
}
+ if (args.proxyServer !== undefined || args.proxyAllowedHostnames !== undefined) {
+ if (args.action !== 'start') {
+ return errorResult(
+ args.action,
+ 'proxyServer 与 proxyAllowedHostnames 仅可用于 action=start;其他操作请省略这些字段',
+ );
+ }
+ try {
+ parseBrowserProxyServer(args.proxyServer, args.proxyAllowedHostnames);
+ } catch (err) {
+ return errorResult(
+ args.action,
+ err instanceof Error ? err.message : 'proxyServer 不合法',
+ );
+ }
+ }
const runtime = getRuntime(deps);
// Block non-web schemes at the boundary: navigate/open to file:// /
// chrome:// / data: would let the agent reach local files or browser
diff --git a/scripts/browser-runtime/sync.mjs b/scripts/browser-runtime/sync.mjs
index cc5dffe2fb..710a16fee4 100644
--- a/scripts/browser-runtime/sync.mjs
+++ b/scripts/browser-runtime/sync.mjs
@@ -241,13 +241,1395 @@ function header(srcLabel) {
/**
* LOCAL PATCHES — durable edits to vendored upstream sources, re-applied on every
* sync so they survive the wipe-and-replace pipeline (editing _generated/ by hand
- * does NOT survive). Keyed by the _generated-relative path. Each patch is a literal
- * find/replace against the UPSTREAM source; a missing `find` anchor throws so an
- * upstream refactor surfaces loudly instead of silently dropping the patch (same
- * fail-loud philosophy as the manifest assertions). Keep these minimal and prefer
- * src/shim/* for anything that can live at the adapter boundary.
+ * does NOT survive). Keyed by the _generated-relative path. Patches use literal
+ * replacements or a bounded transform made only from exact-count replacements;
+ * missing/duplicate anchors throw so upstream refactors surface loudly instead of
+ * silently dropping a patch. Keep these minimal and prefer src/shim/* for anything
+ * that can live at the adapter boundary.
*/
const LOCAL_PATCHES = {
+ 'extension/src/browser/navigation-guard.ts': [
+ {
+ desc: 'allow explicit browser proxies only for public hostnames named in the strict hostname allowlist',
+ find: ` // Browser proxy routing hides the final connect target from this process.
+ // Only block when the browser profile is known to be proxy-routed; Gateway
+ // provider proxy env alone is not proof of browser page proxy behavior.
+ if (
+ opts.browserProxyMode === "explicit-browser-proxy" &&
+ !isPrivateNetworkAllowedByPolicy(opts.ssrfPolicy)
+ ) {
+ throw new InvalidBrowserNavigationUrlError(
+ "Navigation blocked: strict browser SSRF policy cannot be enforced while this browser profile is proxy-routed",
+ );
+ }`,
+ replace: ` // An explicit browser proxy resolves and connects outside this process, so
+ // local DNS pinning alone cannot prove the final connect target. Keep proxy
+ // navigation fail-closed unless the caller supplied a narrow public-hostname
+ // allowlist for this launch. The normal policy resolver below still rejects
+ // blocked names and private/special-use DNS answers for every permitted host.
+ if (
+ opts.browserProxyMode === "explicit-browser-proxy" &&
+ parsed.protocol !== "https:"
+ ) {
+ throw new InvalidBrowserNavigationUrlError(
+ "Navigation blocked: proxied browser navigation requires HTTPS",
+ );
+ }
+ const proxyHostnameAllowlist = (opts.ssrfPolicy?.hostnameAllowlist ?? [])
+ .map((pattern) => normalizeHostname(pattern))
+ .filter(Boolean);
+ if (
+ opts.browserProxyMode === "explicit-browser-proxy" &&
+ !isPrivateNetworkAllowedByPolicy(opts.ssrfPolicy) &&
+ (proxyHostnameAllowlist.length === 0 ||
+ !matchesHostnameAllowlist(normalizeHostname(parsed.hostname), proxyHostnameAllowlist))
+ ) {
+ throw new InvalidBrowserNavigationUrlError(
+ "Navigation blocked: proxied browser navigation requires an explicit public-hostname allowlist",
+ );
+ }`,
+ },
+ ],
+ 'extension/src/browser/routes/agent.act.ts': [
+ {
+ desc: 'carry the effective browser proxy mode through interaction navigation guards',
+ transform: (source) => applyExactReplacements(source, [
+ [
+ ` readBody,
+ requirePwAi,
+ resolveTargetIdFromBody,`,
+ ` browserNavigationPolicyForProfile,
+ readBody,
+ requirePwAi,
+ resolveTargetIdFromBody,`,
+ ],
+ [
+ ` ssrfPolicy?: BrowserNavigationPolicyOptions["ssrfPolicy"];
+ listTabs: () => Promise<Array<{ targetId: string; url: string }>>;`,
+ ` ssrfPolicy?: BrowserNavigationPolicyOptions["ssrfPolicy"];
+ browserProxyMode?: BrowserNavigationPolicyOptions["browserProxyMode"];
+ listTabs: () => Promise<Array<{ targetId: string; url: string }>>;`,
+ ],
+ [
+ ` const ssrfPolicyOpts = withBrowserNavigationPolicy(params.ssrfPolicy);`,
+ ` const ssrfPolicyOpts = withBrowserNavigationPolicy(params.ssrfPolicy, {
+ browserProxyMode: params.browserProxyMode,
+ });`,
+ ],
+ [
+ ` if (!ssrfPolicyOpts.ssrfPolicy) {
+ return;
+ }`,
+ ` if (!ssrfPolicyOpts.ssrfPolicy && !ssrfPolicyOpts.browserProxyMode) {
+ return;
+ }`,
+ ],
+ [
+ ` const evaluateEnabled = ctx.state().resolved.evaluateEnabled;
+ const ssrfPolicy = ctx.state().resolved.ssrfPolicy;
+ const isExistingSession = getBrowserProfileCapabilities(profileCtx.profile).usesChromeMcp;
+ const hasNavigationResultPolicy = Boolean(
+ withBrowserNavigationPolicy(ssrfPolicy).ssrfPolicy,
+ );`,
+ ` const evaluateEnabled = ctx.state().resolved.evaluateEnabled;
+ const navigationPolicy = browserNavigationPolicyForProfile(ctx, profileCtx);
+ const ssrfPolicy = navigationPolicy.ssrfPolicy;
+ const isExistingSession = getBrowserProfileCapabilities(profileCtx.profile).usesChromeMcp;
+ const hasNavigationResultPolicy = Boolean(
+ navigationPolicy.ssrfPolicy || navigationPolicy.browserProxyMode,
+ );`,
+ ],
+ [
+ ` targetId: tab.targetId,
+ ssrfPolicy,
+ listTabs: () => profileCtx.listTabs(),`,
+ ` targetId: tab.targetId,
+ ssrfPolicy,
+ browserProxyMode: navigationPolicy.browserProxyMode,
+ listTabs: () => profileCtx.listTabs(),`,
+ ],
+ [
+ ` evaluateEnabled,
+ ssrfPolicy,
+ signal: req.signal,`,
+ ` evaluateEnabled,
+ ssrfPolicy,
+ browserProxyMode: navigationPolicy.browserProxyMode,
+ signal: req.signal,`,
+ ],
+ ]),
+ },
+ ],
+ 'extension/src/browser/routes/agent.act.hooks.ts': [
+ {
+ desc: 'apply the effective browser proxy mode to file-chooser click navigation',
+ transform: (source) => applyExactReplacements(source, [
+ [
+ ` readBody,
+ requirePwAi,
+ resolveTargetIdFromBody,`,
+ ` browserNavigationPolicyForProfile,
+ readBody,
+ requirePwAi,
+ resolveTargetIdFromBody,`,
+ ],
+ [
+ ` cdpUrl,
+ targetId: tab.targetId,
+ ssrfPolicy: ctx.state().resolved.ssrfPolicy,
+ ref,`,
+ ` cdpUrl,
+ targetId: tab.targetId,
+ ...browserNavigationPolicyForProfile(ctx, profileCtx),
+ ref,`,
+ ],
+ ]),
+ },
+ {
+ desc: 'apply the effective browser proxy mode to direct input file uploads',
+ transform: (source) => applyExactReplacements(source, [
+ [
+ ` await pw.setInputFilesViaPlaywright({
+ cdpUrl,
+ targetId: tab.targetId,
+ inputRef,
+ element,
+ paths: resolvedPaths,
+ });`,
+ ` await pw.setInputFilesViaPlaywright({
+ cdpUrl,
+ targetId: tab.targetId,
+ ...browserNavigationPolicyForProfile(ctx, profileCtx),
+ inputRef,
+ element,
+ paths: resolvedPaths,
+ });`,
+ ],
+ ]),
+ },
+ ],
+ 'extension/src/browser/pw-tools-core.interactions.ts': [
+ {
+ desc: 'propagate proxy mode through Playwright interaction navigation checks',
+ transform: (source) => applyExactReplacements(source, [
+ [
+ ` assertBrowserNavigationResultAllowed,
+ withBrowserNavigationPolicy,`,
+ ` assertBrowserNavigationResultAllowed,
+ type BrowserNavigationPolicyOptions,
+ withBrowserNavigationPolicy,`,
+ ],
+ [
+ ` frameUrl: string,
+ ssrfPolicy?: SsrFPolicy,
+): Promise<void> {`,
+ ` frameUrl: string,
+ ssrfPolicy?: SsrFPolicy,
+ browserProxyMode?: BrowserNavigationPolicyOptions["browserProxyMode"],
+): Promise<void> {`,
+ ],
+ [
+ ` if (!ssrfPolicy || (!frameUrl.startsWith("http://") && !frameUrl.startsWith("https://"))) {`,
+ ` if (
+ (!ssrfPolicy && !browserProxyMode) ||
+ (!frameUrl.startsWith("http://") && !frameUrl.startsWith("https://"))
+ ) {`,
+ ],
+ [
+ ` ...withBrowserNavigationPolicy(ssrfPolicy),`,
+ ` ...withBrowserNavigationPolicy(ssrfPolicy, { browserProxyMode }),`,
+ ],
+ [
+ ` ssrfPolicy?: SsrFPolicy;
+ targetId?: string;`,
+ ` ssrfPolicy?: SsrFPolicy;
+ browserProxyMode?: BrowserNavigationPolicyOptions["browserProxyMode"];
+ targetId?: string;`,
+ 3,
+ ],
+ [
+ ` if (!opts.ssrfPolicy) {`,
+ ` if (!opts.ssrfPolicy && !opts.browserProxyMode) {`,
+ 2,
+ ],
+ [
+ `await assertSubframeNavigationAllowed(frameUrl, opts.ssrfPolicy);`,
+ `await assertSubframeNavigationAllowed(
+ frameUrl,
+ opts.ssrfPolicy,
+ opts.browserProxyMode,
+ );`,
+ 2,
+ ],
+ [
+ `
+ ssrfPolicy: opts.ssrfPolicy,
+ targetId: opts.targetId,`,
+ `
+ ssrfPolicy: opts.ssrfPolicy,
+ browserProxyMode: opts.browserProxyMode,
+ targetId: opts.targetId,`,
+ 8,
+ ],
+ [
+ `
+ ssrfPolicy: opts.ssrfPolicy,
+ targetId: opts.targetId,`,
+ `
+ ssrfPolicy: opts.ssrfPolicy,
+ browserProxyMode: opts.browserProxyMode,
+ targetId: opts.targetId,`,
+ 7,
+ ],
+ [
+ `
+ ssrfPolicy: opts.ssrfPolicy,
+ targetId: opts.targetId,`,
+ `
+ ssrfPolicy: opts.ssrfPolicy,
+ browserProxyMode: opts.browserProxyMode,
+ targetId: opts.targetId,`,
+ ],
+ [
+ `
+ ssrfPolicy: opts.ssrfPolicy,
+ targetId: opts.targetId,`,
+ `
+ ssrfPolicy: opts.ssrfPolicy,
+ browserProxyMode: opts.browserProxyMode,
+ targetId: opts.targetId,`,
+ ],
+ [
+ `
+ ssrfPolicy: opts.ssrfPolicy,
+ targetId: opts.targetId,`,
+ `
+ ssrfPolicy: opts.ssrfPolicy,
+ browserProxyMode: opts.browserProxyMode,
+ targetId: opts.targetId,`,
+ ],
+ [
+ ` ssrfPolicy?: SsrFPolicy;
+ signal?: AbortSignal;`,
+ ` ssrfPolicy?: SsrFPolicy;
+ browserProxyMode?: BrowserNavigationPolicyOptions["browserProxyMode"];
+ signal?: AbortSignal;`,
+ 7,
+ ],
+ [
+ ` ssrfPolicy?: SsrFPolicy;
+ fn: string;`,
+ ` ssrfPolicy?: SsrFPolicy;
+ browserProxyMode?: BrowserNavigationPolicyOptions["browserProxyMode"];
+ fn: string;`,
+ ],
+ [
+ ` ssrfPolicy?: SsrFPolicy;
+ depth?: number;`,
+ ` ssrfPolicy?: SsrFPolicy;
+ browserProxyMode?: BrowserNavigationPolicyOptions["browserProxyMode"];
+ depth?: number;`,
+ ],
+ [
+ ` if (opts.ssrfPolicy) {
+ await assertPageNavigationCompletedSafely({`,
+ ` if (opts.ssrfPolicy || opts.browserProxyMode) {
+ await assertPageNavigationCompletedSafely({`,
+ ],
+ [
+ ` evaluateEnabled?: boolean,
+ ssrfPolicy?: SsrFPolicy,
+ depth = 0,`,
+ ` evaluateEnabled?: boolean,
+ ssrfPolicy?: SsrFPolicy,
+ browserProxyMode?: BrowserNavigationPolicyOptions["browserProxyMode"],
+ depth = 0,`,
+ ],
+ [
+ `
+ ssrfPolicy,
+ signal,`,
+ `
+ ssrfPolicy,
+ browserProxyMode,
+ signal,`,
+ 6,
+ ],
+ [
+ ` ssrfPolicy,
+ fn: action.fn,`,
+ ` ssrfPolicy,
+ browserProxyMode,
+ fn: action.fn,`,
+ ],
+ [
+ ` ssrfPolicy,
+ actions: action.actions,`,
+ ` ssrfPolicy,
+ browserProxyMode,
+ actions: action.actions,`,
+ ],
+ [
+ ` ssrfPolicy: opts.ssrfPolicy,
+ actions: opts.action.actions,`,
+ ` ssrfPolicy: opts.ssrfPolicy,
+ browserProxyMode: opts.browserProxyMode,
+ actions: opts.action.actions,`,
+ ],
+ [
+ ` opts.evaluateEnabled,
+ opts.ssrfPolicy,
+ 0,`,
+ ` opts.evaluateEnabled,
+ opts.ssrfPolicy,
+ opts.browserProxyMode,
+ 0,`,
+ ],
+ [
+ ` opts.evaluateEnabled,
+ opts.ssrfPolicy,
+ depth,`,
+ ` opts.evaluateEnabled,
+ opts.ssrfPolicy,
+ opts.browserProxyMode,
+ depth,`,
+ ],
+ ]),
+ },
+ {
+ desc: 'guard direct input file uploads with the proxy navigation policy',
+ transform: (source) => applyExactReplacements(source, [
+ [
+ ` inputRef?: string;
+ element?: string;
+ paths: string[];
+}): Promise<void> {`,
+ ` inputRef?: string;
+ element?: string;
+ paths: string[];
+ ssrfPolicy?: SsrFPolicy;
+ browserProxyMode?: BrowserNavigationPolicyOptions["browserProxyMode"];
+}): Promise<void> {`,
+ ],
+ // input/change handlers can assign location after files are set; run
+ // both the file assignment and the event dispatch inside the guard.
+ [
+ ` try {
+ await locator.setInputFiles(resolvedPaths);
+ } catch (err) {
+ throw toFriendlyInteractionError(err, inputRef || element);
+ }
+ try {
+ const handle = await locator.elementHandle();
+ if (handle) {
+ await handle.evaluate((el) => {
+ el.dispatchEvent(new Event("input", { bubbles: true }));
+ el.dispatchEvent(new Event("change", { bubbles: true }));
+ });
+ }
+ } catch {
+ // Best-effort for sites that don't react to setInputFiles alone.
+ }
+}`,
+ ` const previousUrl = page.url();
+ await assertInteractionNavigationCompletedSafely({
+ action: async () => {
+ try {
+ await locator.setInputFiles(resolvedPaths);
+ } catch (err) {
+ throw toFriendlyInteractionError(err, inputRef || element);
+ }
+ try {
+ const handle = await locator.elementHandle();
+ if (handle) {
+ await handle.evaluate((el) => {
+ el.dispatchEvent(new Event("input", { bubbles: true }));
+ el.dispatchEvent(new Event("change", { bubbles: true }));
+ });
+ }
+ } catch {
+ // Best-effort for sites that don't react to setInputFiles alone.
+ }
+ },
+ cdpUrl: opts.cdpUrl,
+ page,
+ previousUrl,
+ ssrfPolicy: opts.ssrfPolicy,
+ browserProxyMode: opts.browserProxyMode,
+ targetId: opts.targetId,
+ });
+}`,
+ ],
+ ]),
+ },
+ {
+ desc: 'guard hover/drag/scrollIntoView/wait interactions with the same proxy navigation policy',
+ transform: (source) => applyExactReplacements(source, [
+ // hover + scrollIntoView share this options signature.
+ [
+ ` ref?: string;
+ selector?: string;
+ timeoutMs?: number;
+ signal?: AbortSignal;
+}): Promise<void> {`,
+ ` ref?: string;
+ selector?: string;
+ timeoutMs?: number;
+ ssrfPolicy?: SsrFPolicy;
+ browserProxyMode?: BrowserNavigationPolicyOptions["browserProxyMode"];
+ signal?: AbortSignal;
+}): Promise<void> {`,
+ 2,
+ ],
+ [
+ ` endRef?: string;
+ endSelector?: string;
+ timeoutMs?: number;
+ signal?: AbortSignal;`,
+ ` endRef?: string;
+ endSelector?: string;
+ timeoutMs?: number;
+ ssrfPolicy?: SsrFPolicy;
+ browserProxyMode?: BrowserNavigationPolicyOptions["browserProxyMode"];
+ signal?: AbortSignal;`,
+ ],
+ [
+ ` fn?: string;
+ timeoutMs?: number;
+ signal?: AbortSignal;`,
+ ` fn?: string;
+ timeoutMs?: number;
+ ssrfPolicy?: SsrFPolicy;
+ browserProxyMode?: BrowserNavigationPolicyOptions["browserProxyMode"];
+ signal?: AbortSignal;`,
+ ],
+ // hover: mouseover handlers can assign location; run the interaction
+ // navigation guard like click/press instead of skipping it.
+ [
+ ` const { abortPromise, cleanup } = createAbortPromise(opts.signal);
+ const reconcileRemoteDialog = () => reconcileRemoteDialogAfterActionSettled(page, opts.signal);
+ try {
+ await awaitActionWithAbort(
+ locator.hover({
+ timeout: resolveInteractionTimeoutMs(opts.timeoutMs),
+ }),
+ abortPromise,
+ reconcileRemoteDialog,
+ );
+ } catch (err) {`,
+ ` const previousUrl = page.url();
+ const { abortPromise, cleanup } = createAbortPromise(opts.signal);
+ const reconcileRemoteDialog = () => reconcileRemoteDialogAfterActionSettled(page, opts.signal);
+ try {
+ await assertInteractionNavigationCompletedSafely({
+ action: async () => {
+ await awaitActionWithAbort(
+ locator.hover({
+ timeout: resolveInteractionTimeoutMs(opts.timeoutMs),
+ }),
+ abortPromise,
+ reconcileRemoteDialog,
+ );
+ },
+ cdpUrl: opts.cdpUrl,
+ page,
+ previousUrl,
+ ssrfPolicy: opts.ssrfPolicy,
+ browserProxyMode: opts.browserProxyMode,
+ targetId: opts.targetId,
+ });
+ } catch (err) {`,
+ ],
+ // drag: dragstart/drop handlers can assign location.
+ [
+ ` const { abortPromise, cleanup } = createAbortPromise(opts.signal);
+ const reconcileRemoteDialog = () => reconcileRemoteDialogAfterActionSettled(page, opts.signal);
+ try {
+ await awaitActionWithAbort(
+ startLocator.dragTo(endLocator, {
+ timeout: resolveInteractionTimeoutMs(opts.timeoutMs),
+ }),
+ abortPromise,
+ reconcileRemoteDialog,
+ );
+ } catch (err) {`,
+ ` const previousUrl = page.url();
+ const { abortPromise, cleanup } = createAbortPromise(opts.signal);
+ const reconcileRemoteDialog = () => reconcileRemoteDialogAfterActionSettled(page, opts.signal);
+ try {
+ await assertInteractionNavigationCompletedSafely({
+ action: async () => {
+ await awaitActionWithAbort(
+ startLocator.dragTo(endLocator, {
+ timeout: resolveInteractionTimeoutMs(opts.timeoutMs),
+ }),
+ abortPromise,
+ reconcileRemoteDialog,
+ );
+ },
+ cdpUrl: opts.cdpUrl,
+ page,
+ previousUrl,
+ ssrfPolicy: opts.ssrfPolicy,
+ browserProxyMode: opts.browserProxyMode,
+ targetId: opts.targetId,
+ });
+ } catch (err) {`,
+ ],
+ // scrollIntoView: scroll handlers can assign location.
+ [
+ ` const { abortPromise, cleanup } = createAbortPromise(opts.signal);
+ const reconcileRemoteDialog = () => reconcileRemoteDialogAfterActionSettled(page, opts.signal);
+ try {
+ await awaitActionWithAbort(
+ locator.scrollIntoViewIfNeeded({ timeout }),
+ abortPromise,
+ reconcileRemoteDialog,
+ );
+ } catch (err) {`,
+ ` const previousUrl = page.url();
+ const { abortPromise, cleanup } = createAbortPromise(opts.signal);
+ const reconcileRemoteDialog = () => reconcileRemoteDialogAfterActionSettled(page, opts.signal);
+ try {
+ await assertInteractionNavigationCompletedSafely({
+ action: async () => {
+ await awaitActionWithAbort(
+ locator.scrollIntoViewIfNeeded({ timeout }),
+ abortPromise,
+ reconcileRemoteDialog,
+ );
+ },
+ cdpUrl: opts.cdpUrl,
+ page,
+ previousUrl,
+ ssrfPolicy: opts.ssrfPolicy,
+ browserProxyMode: opts.browserProxyMode,
+ targetId: opts.targetId,
+ });
+ } catch (err) {`,
+ ],
+ // wait: wait.fn and observed load states can land on a new location.
+ [
+ ` try {
+ if (typeof opts.timeMs === "number" && Number.isFinite(opts.timeMs)) {`,
+ ` const previousUrl = page.url();
+ try {
+ await assertInteractionNavigationCompletedSafely({
+ action: async () => {
+ if (typeof opts.timeMs === "number" && Number.isFinite(opts.timeMs)) {`,
+ ],
+ [
+ ` await waitForStep(page.waitForFunction(fn, { timeout }));
+ }
+ }
+ } finally {
+ cleanup();
+ }
+}`,
+ ` await waitForStep(page.waitForFunction(fn, { timeout }));
+ }
+ }
+ },
+ cdpUrl: opts.cdpUrl,
+ page,
+ previousUrl,
+ ssrfPolicy: opts.ssrfPolicy,
+ browserProxyMode: opts.browserProxyMode,
+ targetId: opts.targetId,
+ });
+ } finally {
+ cleanup();
+ }
+}`,
+ ],
+ // Popups: window.open / target=_blank tabs opened by a guarded
+ // interaction bypass the per-page framenavigated listener; collect
+ // them from the context and validate/quarantine before returning.
+ [
+ ` const navPage = opts.page as unknown as NavigationObservablePage;
+ let navigatedDuringAction = false;
+ const subframeNavigationsDuringAction: string[] = [];`,
+ ` const navPage = opts.page as unknown as NavigationObservablePage;
+ const pageContext = (
+ opts.page as unknown as {
+ context?: () => { on?: (event: string, listener: (page: Page) => void) => void; off?: (event: string, listener: (page: Page) => void) => void; close?: () => Promise<void>; browser?: () => { close?: () => Promise<void> } | undefined };
+ }
+ ).context?.();
+ const popupsDuringAction: Page[] = [];
+ // The context is PERSISTENT and shared with the user, who can open tabs at
+ // any moment — as can any unrelated producer. The page event fires for all of
+ // them, so tracking every new page would let the drain below validate, and on
+ // denial CLOSE, a tab the user opened themselves; a busy stream of them could
+ // even escalate to tearing down the whole context. Only pages that descend
+ // from the page being acted on are ours to police.
+ //
+ // opener() is async and this listener must stay synchronous (an await here
+ // would drop events), so kick the probe off on arrival and record the answer;
+ // consumers below wait for the probe of the page they are about to touch.
+ const openerOfPopup = new Map<unknown, unknown>();
+ const popupOwnershipProbe = new Map<unknown, Promise<void>>();
+ const popupOwnershipPending = new Set<unknown>();
+ const onContextPage = (newPage: Page) => {
+ popupsDuringAction.push(newPage);
+ const opener = (newPage as unknown as { opener?: () => Promise<Page | null> }).opener;
+ if (typeof opener !== "function") return;
+ popupOwnershipPending.add(newPage);
+ popupOwnershipProbe.set(
+ newPage,
+ Promise.resolve()
+ .then(() => opener.call(newPage))
+ .then(
+ (parent) => {
+ if (parent) openerOfPopup.set(newPage, parent);
+ },
+ () => undefined,
+ )
+ .then(() => {
+ popupOwnershipPending.delete(newPage);
+ }),
+ );
+ };
+ /**
+ * Whether this page's lineage question has been ANSWERED yet. A pending probe
+ * is not the same as "not ours": treating it that way would let a popup the
+ * action opened slip past the cleanup below, unvalidated and still live.
+ */
+ const ownershipAnswered = (page: unknown): boolean => !popupOwnershipPending.has(page);
+ /**
+ * Settle outstanding lineage probes, re-checking after every round: a popup
+ * can open a child while we await, and that child's probe is registered after
+ * any snapshot we took, so a single allSettled would never wait for it.
+ * Bounded by the caller's deadline so an unresponsive page cannot hold the
+ * action — and the serialized stop/quit behind it — open.
+ */
+ const settleOwnershipProbes = async (deadline: Promise<void>): Promise<void> => {
+ let expired = false;
+ void deadline.then(() => {
+ expired = true;
+ });
+ while (!expired && popupOwnershipPending.size > 0) {
+ const outstanding = [...popupOwnershipPending]
+ .map((page) => popupOwnershipProbe.get(page))
+ .filter((probe): probe is Promise<void> => probe !== undefined);
+ if (outstanding.length === 0) return;
+ await Promise.race([Promise.allSettled(outstanding), deadline]);
+ }
+ };
+ /**
+ * Whether a page's opener chain reaches the page being acted on. Walks the
+ * chain so a popup opened BY a popup still counts as ours, and is bounded so
+ * a cycle or an absurdly deep chain cannot hang the drain.
+ *
+ * Fails closed toward the USER's data: a page whose lineage we could not
+ * establish is treated as not ours, so it is never validated and never
+ * closed. Anything the action itself opened does report an opener.
+ */
+ const descendsFromActedPage = (page: unknown): boolean => {
+ let cursor = page;
+ for (let hops = 0; hops < POPUP_CHAIN_MAX_VALIDATIONS; hops += 1) {
+ const parent = openerOfPopup.get(cursor);
+ if (parent === undefined) return false;
+ if (parent === opts.page) return true;
+ cursor = parent;
+ }
+ return false;
+ };
+ if (pageContext && typeof pageContext.on === "function") {
+ pageContext.on("page", onContextPage);
+ }
+ let navigatedDuringAction = false;
+ const subframeNavigationsDuringAction: string[] = [];`,
+ ],
+ [
+ ` markObservedDialogsHandledRemotelyForPage,
+ refLocator,`,
+ ` markObservedDialogsHandledRemotelyForPage,
+ quarantineTargetWithoutClosing,
+ refLocator,`,
+ ],
+ [
+ ` assertPageNavigationCompletedSafely,
+ createObservedDialogAbortSignalForPage,`,
+ ` assertPageNavigationCompletedSafely,
+ closeBlockedNavigationTarget,
+ createObservedDialogAbortSignalForPage,`,
+ ],
+ [
+ `const INTERACTION_NAVIGATION_GRACE_MS = 250;`,
+ `const INTERACTION_NAVIGATION_GRACE_MS = 250;
+
+// Bounds for draining the popup chain after an interaction. The queue is
+// adversarial — validating a popup can append another — so it needs a ceiling
+// on both count and wall-clock, or a page that opens one popup per grace
+// window keeps the action (and every serialized call behind it) alive forever.
+const POPUP_CHAIN_MAX_VALIDATIONS = 32;
+const POPUP_CHAIN_DRAIN_BUDGET_MS = 5_000;
+// Quarantining the overflow needs its own bounds: an unresponsive close() must
+// not keep the action pending any more than an endless popup chain may.
+const POPUP_CHAIN_MAX_CLOSES = 256;
+const POPUP_CHAIN_CLOSE_BUDGET_MS = 2_000;
+
+// The one message the host matches on to distrust the whole route
+// (\`mentionsUntornDownBrowser\` in external-chrome-backend.ts). Every path that
+// fails to contain a page must report exactly this, or the host keeps serving
+// a route whose pages are still live.
+const UNTORN_DOWN_BROWSER_MESSAGE =
+ "Navigation blocked: popup chain exceeded the validation budget and the browser could not be torn down; unvalidated pages may still be live";`,
+ ],
+ // Capture (do not propagate) a main-navigation policy deny so the
+ // popup pass below still runs: an interaction can both navigate the
+ // main frame somewhere denied AND open a tab, and the popup must be
+ // validated/quarantined rather than left live. Precedence is resolved
+ // at the end. This also guarantees the context listener is detached on
+ // every path.
+ [
+ ` if (navigationObserved) {
+ await assertPageNavigationCompletedSafely({`,
+ ` let navigationError: unknown;
+ try {
+ if (navigationObserved) {
+ await assertPageNavigationCompletedSafely({`,
+ ],
+ [
+ ` if (subframeError) {
+ throw toLintErrorObject(subframeError, "Non-Error thrown");
+ }
+
+ if (actionError) {
+ throw toLintErrorObject(actionError, "Non-Error thrown");
+ }
+ return result as T;
+}`,
+ ` } catch (err) {
+ navigationError = err;
+ }
+ // NOTE: the context listener stays attached across popup validation below —
+ // a popup can open a further popup inside its own grace window, and
+ // detaching here would leave that second-generation tab uncollected and
+ // unvalidated (in direct mode nothing else would catch it).
+ let popupError: unknown;
+ // Shared last-resort teardown for pages we could not contain individually.
+ // Both the per-popup close failure and the overflow path escalate through
+ // this, so a stuck page has exactly one ladder: context close, then browser
+ // close.
+ //
+ // Only a resolved CONTEXT close proves containment from in here: its pages
+ // are gone with it. A resolved BROWSER close proves only that the call
+ // returned — the process can still be alive with pages running, and nothing
+ // in this runtime can observe process exit. So browser close reports
+ // "unproven" and the caller raises the untorn-down signal, which is what
+ // makes the host run its own verified process teardown.
+ const tearDownUncontainedPages = async (
+ deadline?: Promise<void>,
+ ): Promise<"contained" | "unproven"> => {
+ const closeContext = (
+ pageContext as unknown as { close?: () => Promise<void> } | undefined
+ )?.close;
+ if (typeof closeContext === "function") {
+ const contextClosed = await Promise.race([
+ Promise.resolve()
+ .then(() => closeContext.call(pageContext))
+ .then(
+ () => true,
+ () => false,
+ ),
+ // A caller that already burned its budget passes no deadline: racing a
+ // fired one would resolve instantly and prove nothing.
+ deadline
+ ? deadline.then(() => false)
+ : new Promise<boolean>((resolve) => {
+ const timer = setTimeout(() => resolve(false), POPUP_CHAIN_CLOSE_BUDGET_MS);
+ (timer as unknown as { unref?: () => void }).unref?.();
+ }),
+ ]);
+ if (contextClosed) return "contained";
+ }
+ // The context would not close (rejected, or still not settled at the
+ // deadline), so live pages that were never validated survive and the
+ // listener is about to detach. Every per-page and per-context remedy has
+ // now failed, so try the browser. Give this its own budget.
+ const browserOf = (
+ pageContext as unknown as { browser?: () => { close?: () => Promise<void> } | undefined }
+ | undefined
+ )?.browser;
+ const browser = typeof browserOf === "function" ? browserOf.call(pageContext) : undefined;
+ if (!browser || typeof browser.close !== "function") return "unproven";
+ await Promise.race([
+ Promise.resolve()
+ .then(() => browser.close?.())
+ .then(
+ () => undefined,
+ () => undefined,
+ ),
+ new Promise<void>((resolve) => {
+ const timer = setTimeout(resolve, POPUP_CHAIN_CLOSE_BUDGET_MS);
+ (timer as unknown as { unref?: () => void }).unref?.();
+ }),
+ ]);
+ // Deliberately NOT reporting success on a resolved close: the host owns
+ // process teardown and must verify the exit itself.
+ return "unproven";
+ };
+ try {
+ // Drain the chain rather than a snapshot: validating a popup can append
+ // more entries to popupsDuringAction, so index forward as it grows.
+ //
+ // BOUNDED, because the queue is adversarial: each iteration awaits a
+ // ~250ms grace window, so a page that opens one popup per window appends
+ // at least as fast as this drains and the loop never empties. That would
+ // hang the action forever — and the backend serializes every browser call,
+ // so a later stop (and dispose at quit) would queue behind it indefinitely.
+ // On overrun, stop validating and CLOSE the remainder: leaving them live
+ // would be the unvalidated-tab bug this drain exists to prevent.
+ const drainDeadline = Date.now() + POPUP_CHAIN_DRAIN_BUDGET_MS;
+ let popupIndex = 0;
+ for (
+ ;
+ popupIndex < popupsDuringAction.length
+ && popupIndex < POPUP_CHAIN_MAX_VALIDATIONS
+ && Date.now() < drainDeadline;
+ popupIndex += 1
+ ) {
+ const popupPage = popupsDuringAction[popupIndex]!;
+ // Wait for this page's lineage answer, then skip anything PROVEN not to
+ // be ours: validating it could quarantine or close one of the user's own
+ // tabs, which is strictly worse than not policing a page we never opened.
+ // A page that never answered is not proven either way, so it stays in
+ // scope here and the overflow cleanup below decides its fate.
+ await popupOwnershipProbe.get(popupPage);
+ if (ownershipAnswered(popupPage) && !descendsFromActedPage(popupPage)) continue;
+ // Per popup, not around the loop: a denial on the first popup must not
+ // leave later ones unvalidated and selectable on a denied URL. Keep the
+ // first error and keep going.
+ try {
+ // A popup starts at about:blank; reuse the delayed-navigation observer
+ // so a still-loading popup gets the same grace window before
+ // validation, and a policy deny quarantines/closes the popup target
+ // like any other block.
+ const observedPopup = await observeDelayedInteractionNavigation(
+ popupPage as unknown as NavigationObservablePage,
+ "about:blank",
+ );
+ await assertObservedDelayedNavigations({
+ cdpUrl: opts.cdpUrl,
+ page: popupPage,
+ ssrfPolicy: opts.ssrfPolicy,
+ browserProxyMode: opts.browserProxyMode,
+ observed: observedPopup,
+ });
+ } catch (err) {
+ if (popupError === undefined) popupError = err;
+ // Fail closed on the rejected popup itself. A policy deny above only
+ // quarantines — assertPageNavigationCompletedSafely never closes; that
+ // step belongs to callers that own the navigation lifecycle — and this
+ // popup was created BY the action, not by the user, so it is ours to
+ // tear down. Left open, the denied page keeps executing after the
+ // context listener detaches (in direct mode no lifetime request gate
+ // remains to catch it).
+ //
+ // Bounded, because close() can hang forever on an adversarial page.
+ // But a timeout is NOT success: the page is still live and scriptable.
+ // Escalate exactly like the overflow path — context, then browser —
+ // and if none of that works, report the untorn-down browser so the
+ // host distrusts the route instead of returning an ordinary denial.
+ await Promise.race([
+ closeBlockedNavigationTarget({
+ cdpUrl: opts.cdpUrl,
+ page: popupPage as Page,
+ }).then(
+ () => undefined,
+ () => undefined,
+ ),
+ new Promise<void>((resolve) => {
+ const timer = setTimeout(resolve, POPUP_CHAIN_CLOSE_BUDGET_MS);
+ (timer as unknown as { unref?: () => void }).unref?.();
+ }),
+ ]);
+ // Ask the PAGE whether it closed, rather than trusting the call to have
+ // reported it. closeBlockedNavigationTarget swallows page.close()
+ // rejections internally (pw-session.ts), so it resolves even when the
+ // page refused to go — reading its resolution as success would silently
+ // skip the escalation for exactly the pages that need it. A page that
+ // cannot answer isClosed() has not proven anything either, so it counts
+ // as uncontained too.
+ const isClosed = (popupPage as { isClosed?: () => boolean }).isClosed;
+ const popupClosed = typeof isClosed === "function" && isClosed.call(popupPage) === true;
+ if (!popupClosed && (await tearDownUncontainedPages()) !== "contained") {
+ popupError = new Error(UNTORN_DOWN_BROWSER_MESSAGE);
+ break;
+ }
+ }
+ }
+ // Settle outstanding lineage probes before the sweep below: it runs
+ // synchronously (so pending page events can still enqueue) and must be able
+ // to tell our popups from the user's without awaiting per page. Bounded on
+ // its own budget, and repeated internally so a child popup that arrives
+ // mid-await is waited on too.
+ const ownershipDeadline = new Promise<void>((resolve) => {
+ const timer = setTimeout(resolve, POPUP_CHAIN_CLOSE_BUDGET_MS);
+ (timer as unknown as { unref?: () => void }).unref?.();
+ });
+ await settleOwnershipProbes(ownershipDeadline);
+ // A page whose probe never answered counts as OURS. Once the budget above
+ // is spent the browser is already failing to answer, and dropping such a
+ // page would mean the listener detaches with an unvalidated, never-closed
+ // popup and no untorn-down signal for the host — silently
+ // losing containment. The user's genuinely own tabs answer opener() with
+ // null promptly, so they are still excluded.
+ const isOursOrUnanswered = (page: unknown): boolean =>
+ descendsFromActedPage(page) || !ownershipAnswered(page);
+ const ownedPagesRemain = (): boolean => {
+ for (let i = popupIndex; i < popupsDuringAction.length; i += 1) {
+ if (isOursOrUnanswered(popupsDuringAction[i]!)) return true;
+ }
+ return false;
+ };
+ if (ownedPagesRemain()) {
+ // Quarantine must be bounded too, for the same reason the drain above is:
+ // a burst of popups, or one unresponsive close(), would otherwise keep
+ // this action — and the serialized stop/quit cleanup behind it — pending
+ // indefinitely. Close concurrently under a single deadline rather than
+ // serially awaiting each one, and re-read the queue (not a snapshot) so
+ // popups appended while these closes run are quarantined too.
+ const closeDeadline = new Promise<void>((resolve) => {
+ const timer = setTimeout(resolve, POPUP_CHAIN_CLOSE_BUDGET_MS);
+ // Do not hold the process open on this timer.
+ (timer as unknown as { unref?: () => void }).unref?.();
+ });
+ const closing: Array<Promise<void>> = [];
+ let deadlineReached = false;
+ void closeDeadline.then(() => { deadlineReached = true; });
+ // Outer loop so newly-arrived popups are picked up: the inner loop never
+ // awaits, so on its own it drains the queue as it stands and returns
+ // before the event loop can deliver another page event. Yielding
+ // between sweeps is what actually lets the queue grow and be re-read;
+ // without it a popup created during cleanup would be left live,
+ // unvalidated and unquarantined once the listener detaches.
+ while (
+ !deadlineReached
+ && popupIndex < popupsDuringAction.length
+ && closing.length < POPUP_CHAIN_MAX_CLOSES
+ ) {
+ for (
+ ;
+ popupIndex < popupsDuringAction.length
+ && closing.length < POPUP_CHAIN_MAX_CLOSES;
+ popupIndex += 1
+ ) {
+ const unvalidated = popupsDuringAction[popupIndex]!;
+ // A page that arrived mid-sweep may not have answered opener() yet.
+ // Do NOT advance past it: this index only moves forward, so skipping
+ // it here would strand an action-created popup that proves ours a
+ // moment later — unvalidated, unquarantined, and invisible to
+ // ownedPagesRemain(). Stop the sweep instead; the yield below lets
+ // the probe settle and the outer loop retries the same page, all
+ // still under closeDeadline.
+ if (!ownershipAnswered(unvalidated)) break;
+ // Same boundary as the drain: the user's own tabs are not ours to
+ // quarantine or close, however far behind this cleanup falls.
+ if (!descendsFromActedPage(unvalidated)) continue;
+ // Quarantine BEFORE closing, and do not make it conditional on the
+ // close succeeding: close() can hang forever on an adversarial page,
+ // and when the deadline below fires we would otherwise leave a live,
+ // never-validated popup selectable — in direct mode there is no
+ // lifetime CDP request gate to catch it afterwards. Marking is
+ // synchronous bookkeeping, so it completes regardless.
+ closing.push(
+ quarantineTargetWithoutClosing({
+ cdpUrl: opts.cdpUrl,
+ page: unvalidated as Page,
+ })
+ .catch(() => undefined)
+ .then(() => (unvalidated as { close?: () => Promise<void> }).close?.())
+ .then(
+ () => undefined,
+ () => undefined,
+ ),
+ );
+ }
+ // Hand control back so pending page events can enqueue, then re-check.
+ // Racing the deadline keeps this bounded even against a page that
+ // appends a new popup on every turn.
+ await Promise.race([
+ new Promise<void>((resolve) => {
+ const timer = setTimeout(resolve, 0);
+ (timer as unknown as { unref?: () => void }).unref?.();
+ }),
+ closeDeadline,
+ ]);
+ }
+ // Never await a popup's close() unbounded: a hung page must not outrank
+ // returning from the interaction.
+ //
+ // Track whether they actually finished. popupIndex only records that a
+ // close was ISSUED, and quarantine is bookkeeping that never closes a
+ // page (see quarantineTargetWithoutClosing), so a fully-drained queue
+ // whose closes all hang would otherwise look fully handled while every
+ // one of those popups is still live and scriptable.
+ const allClosesSettled = await Promise.race([
+ Promise.all(closing).then(() => true),
+ closeDeadline.then(() => false),
+ ]);
+ // If the bounds cut us off with popups still unaccounted for, they were
+ // neither validated nor quarantined and the listener is about to detach —
+ // in direct mode nothing else would ever check them. Per-page cleanup has
+ // already failed to keep up here, so fail closed on the whole context
+ // rather than leaving live, never-validated pages behind.
+ if (ownedPagesRemain() || !allClosesSettled) {
+ // Nothing reachable from this process can shut the browser down, and a
+ // resolved close() would only prove the call returned, not that the
+ // process exited. Say so explicitly rather than reporting a generic
+ // policy denial: the host owns process teardown and must treat this
+ // route as untrusted until it verifies an exit itself.
+ if ((await tearDownUncontainedPages(closeDeadline)) !== "contained") {
+ popupError = new Error(UNTORN_DOWN_BROWSER_MESSAGE);
+ }
+ }
+ if (popupError === undefined) {
+ popupError = new Error(
+ "Navigation blocked: popup chain exceeded the validation budget; remaining popups were closed",
+ );
+ }
+ }
+ } finally {
+ // Always detach: a throw here would otherwise leak the listener, retaining
+ // every tab opened afterwards for the life of the context.
+ if (pageContext && typeof pageContext.off === "function") {
+ pageContext.off("page", onContextPage);
+ }
+ }
+
+ // A containment failure outranks EVERYTHING. Ordinary denials describe a
+ // request that was refused — the safe outcome. This one says pages we never
+ // validated are still live and could not be torn down, and it is the only
+ // signal the host uses to distrust the route. If a denied main-frame
+ // navigation happened in the same interaction (easy for an adversarial page
+ // to arrange), reporting that instead would leave the route usable while
+ // those pages keep running.
+ if (popupError && /could not be torn down/.test(String((popupError as Error)?.message ?? ""))) {
+ throw toLintErrorObject(popupError, "Non-Error thrown");
+ }
+
+ // Otherwise policy denials outrank the action's own error, and the main-frame
+ // denial outranks subframe/popup denials, so the caller sees the navigation it
+ // asked for being refused. All were still evaluated above.
+ if (navigationError) {
+ throw toLintErrorObject(navigationError, "Non-Error thrown");
+ }
+
+ if (subframeError) {
+ throw toLintErrorObject(subframeError, "Non-Error thrown");
+ }
+
+ if (popupError) {
+ throw toLintErrorObject(popupError, "Non-Error thrown");
+ }
+
+ if (actionError) {
+ throw toLintErrorObject(actionError, "Non-Error thrown");
+ }
+ return result as T;
+}`,
+ ],
+ // resize: page resize handlers can assign location; run the viewport
+ // change inside the same guard at the dispatch (the implementation
+ // lives in pw-tools-core.snapshot.ts, which cannot reach this
+ // file-private guard).
+ [
+ ` case "resize":
+ await resizeViewportViaPlaywright({
+ cdpUrl,
+ targetId: effectiveTargetId,
+ width: action.width,
+ height: action.height,
+ });
+ break;`,
+ ` case "resize": {
+ const resizePage = await getPageForTargetId({ cdpUrl, targetId: effectiveTargetId });
+ ensurePageState(resizePage);
+ const resizePreviousUrl = resizePage.url();
+ await assertInteractionNavigationCompletedSafely({
+ action: async () => {
+ await resizeViewportViaPlaywright({
+ cdpUrl,
+ targetId: effectiveTargetId,
+ width: action.width,
+ height: action.height,
+ });
+ },
+ cdpUrl,
+ page: resizePage,
+ previousUrl: resizePreviousUrl,
+ ssrfPolicy,
+ browserProxyMode,
+ targetId: effectiveTargetId,
+ });
+ break;
+ }`,
+ ],
+ // act dispatch: pass the policy into the four newly guarded branches.
+ [
+ ` case "hover":
+ await hoverViaPlaywright({
+ cdpUrl,
+ targetId: effectiveTargetId,
+ ref: action.ref,
+ selector: action.selector,
+ timeoutMs: action.timeoutMs,
+ signal,
+ });`,
+ ` case "hover":
+ await hoverViaPlaywright({
+ cdpUrl,
+ targetId: effectiveTargetId,
+ ref: action.ref,
+ selector: action.selector,
+ timeoutMs: action.timeoutMs,
+ ssrfPolicy,
+ browserProxyMode,
+ signal,
+ });`,
+ ],
+ [
+ ` case "scrollIntoView":
+ await scrollIntoViewViaPlaywright({
+ cdpUrl,
+ targetId: effectiveTargetId,
+ ref: action.ref,
+ selector: action.selector,
+ timeoutMs: action.timeoutMs,
+ signal,
+ });`,
+ ` case "scrollIntoView":
+ await scrollIntoViewViaPlaywright({
+ cdpUrl,
+ targetId: effectiveTargetId,
+ ref: action.ref,
+ selector: action.selector,
+ timeoutMs: action.timeoutMs,
+ ssrfPolicy,
+ browserProxyMode,
+ signal,
+ });`,
+ ],
+ [
+ ` case "drag":
+ await dragViaPlaywright({
+ cdpUrl,
+ targetId: effectiveTargetId,
+ startRef: action.startRef,
+ startSelector: action.startSelector,
+ endRef: action.endRef,
+ endSelector: action.endSelector,
+ timeoutMs: action.timeoutMs,
+ signal,
+ });`,
+ ` case "drag":
+ await dragViaPlaywright({
+ cdpUrl,
+ targetId: effectiveTargetId,
+ startRef: action.startRef,
+ startSelector: action.startSelector,
+ endRef: action.endRef,
+ endSelector: action.endSelector,
+ timeoutMs: action.timeoutMs,
+ ssrfPolicy,
+ browserProxyMode,
+ signal,
+ });`,
+ ],
+ [
+ ` loadState: action.loadState,
+ fn: action.fn,
+ timeoutMs: action.timeoutMs,
+ signal,
+ });`,
+ ` loadState: action.loadState,
+ fn: action.fn,
+ timeoutMs: action.timeoutMs,
+ ssrfPolicy,
+ browserProxyMode,
+ signal,
+ });`,
+ ],
+ ]),
+ },
+ ],
+ 'extension/src/browser/pw-session.ts': [
+ {
+ desc: 'export a non-blocking quarantine so the popup-overflow path can mark a target unusable without awaiting close() (a hung page must not keep the interaction pending)',
+ find: `// Quarantine and close a tab that OpenClaw itself navigated to a blocked URL.`,
+ replace: `/**
+ * Mark a target unusable WITHOUT closing it.
+ *
+ * closeBlockedNavigationTarget awaits page.close(), which an adversarial or
+ * hung page can stall indefinitely. Quarantine is the part that must not
+ * depend on the page cooperating: marking is synchronous bookkeeping, so a
+ * target can be made unselectable even when its close never returns.
+ */
+export async function quarantineTargetWithoutClosing(opts: {
+ cdpUrl: string;
+ page: Page;
+ targetId?: string;
+}): Promise<void> {
+ await quarantineBlockedTarget(opts);
+}
+
+// Quarantine and close a tab that OpenClaw itself navigated to a blocked URL.`,
+ },
+ ],
+ 'extension/src/browser/ssrf-policy-helpers.ts': [
+ {
+ desc: 'one-off hostname grants must also pass a strict hostnameAllowlist (else the loopback CDP endpoint is blocked by proxyAllowedHostnames and every proxied navigation fails)',
+ find: `export function withAllowedHostname(
+ ssrfPolicy: SsrFPolicy | undefined,
+ hostname: string,
+): SsrFPolicy {
+ return {
+ ...ssrfPolicy,
+ allowedHostnames: uniqueStrings([...(ssrfPolicy?.allowedHostnames ?? []), hostname]),
+ };
+}`,
+ replace: `export function withAllowedHostname(
+ ssrfPolicy: SsrFPolicy | undefined,
+ hostname: string,
+): SsrFPolicy {
+ return {
+ ...ssrfPolicy,
+ allowedHostnames: uniqueStrings([...(ssrfPolicy?.allowedHostnames ?? []), hostname]),
+ // A one-off grant must grant through BOTH policy fields: exact-host trust
+ // (allowedHostnames) and, when a strict hostnameAllowlist is active, the
+ // allowlist match itself. Otherwise a per-start proxyAllowedHostnames
+ // blocks the browser's own loopback CDP endpoint, and every proxied
+ // navigation fails before it starts. An absent/empty allowlist stays
+ // empty: it means "no allowlist", not "allow only this host".
+ ...(ssrfPolicy?.hostnameAllowlist?.length
+ ? { hostnameAllowlist: uniqueStrings([...ssrfPolicy.hostnameAllowlist, hostname]) }
+ : {}),
+ };
+}`,
+ },
+ ],
+ 'extension/src/browser/chrome.ts': [
+ {
+ desc: 'expose managed-profile PID lookup so the host can confirm process exit from the OS, not from CDP endpoint silence (a stalled Chrome stops answering while still alive)',
+ find: `function clearChromeSingletonArtifacts(userDataDir: string) {`,
+ replace: `/**
+ * PID of the live Chrome owning this managed profile, or null if none.
+ *
+ * Reads the profile's SingletonLock and confirms the process actually exists,
+ * so callers can distinguish "the process is gone" from "the CDP endpoint went
+ * quiet" — a busy or stalled Chrome produces the latter while still running.
+ */
+export function readManagedProfileOwnerPid(userDataDir: string): number | null {
+ return readCurrentHostSingletonPid(userDataDir);
+}
+
+/**
+ * Whether this exact PID holds the CDP port.
+ *
+ * Positive identity, unlike the lock alone: the lock records a PID that the OS
+ * may since have recycled, so anything destructive must confirm the process it
+ * is about to signal is really the browser. Returns false on platforms with no
+ * probe (Windows), which keeps callers fail-safe rather than fail-destructive.
+ */
+export function managedProfilePidOwnsCdpPort(pid: number, cdpPort: number): boolean {
+ return pidListensOnPort(pid, cdpPort);
+}
+
+/**
+ * Whether this PID is a Chrome launched for exactly this profile and port.
+ *
+ * Identity from the process itself, not inferred from what it happens to hold:
+ * holding a port proves only that something is listening, and a port freed by
+ * an exited Chrome can be taken over by anything. Required before anything
+ * destructive — the command line must carry both our --user-data-dir and our
+ * --remote-debugging-port. Returns false wherever the command line cannot be
+ * read, so callers fail safe rather than fail destructive.
+ */
+export function pidIsManagedChromeForProfile(params: {
+ pid: number;
+ cdpPort: number;
+ userDataDir: string;
+}): boolean {
+ if (!processExists(params.pid)) return false;
+ const command = readManagedProcessCommandLine(params.pid);
+ if (!command) return false;
+ return (
+ managedCommandHasExactArg(command, \`--remote-debugging-port=\${params.cdpPort}\`) &&
+ managedCommandHasExactArg(command, \`--user-data-dir=\${params.userDataDir}\`)
+ );
+}
+
+/**
+ * Exact-argument match for a process command line.
+ *
+ * NOT processCommandHasArg: that falls back to \`text.includes\` when argv is
+ * unavailable, which it always is on Darwin (ps yields a flat string). A
+ * substring test accepts \`--user-data-dir=<dir>-backup\` for \`<dir>\`, and this
+ * result gates SIGTERM/SIGKILL — so an unrelated Chrome could be killed. Where
+ * argv exists the element comparison is already exact; otherwise require a
+ * whitespace or quote delimiter on both sides.
+ */
+function managedCommandHasExactArg(
+ command: { argv: string[] | null; text: string },
+ expected: string,
+): boolean {
+ if (command.argv) {
+ return command.argv.includes(expected);
+ }
+ let offset = command.text.indexOf(expected);
+ while (offset >= 0) {
+ const before = offset === 0 ? "" : command.text[offset - 1];
+ const after = command.text[offset + expected.length] ?? "";
+ if ((!before || /[\\s"']/.test(before)) && (!after || /[\\s"']/.test(after))) return true;
+ offset = command.text.indexOf(expected, offset + 1);
+ }
+ return false;
+}
+
+function clearChromeSingletonArtifacts(userDataDir: string) {`,
+ },
+ {
+ desc: 'decorate Chrome chip with host displayName so Cindy-real stays disk-only',
+ find: ` fs.mkdirSync(userDataDir, { recursive: true });
+ await ensureOutputDirectory(DEFAULT_DOWNLOAD_DIR);
+
+ const needsDecorate = !isProfileDecorated(
+ userDataDir,
+ profile.name,
+ (profile.color ?? DEFAULT_OPENCLAW_BROWSER_COLOR).toUpperCase(),
+ DEFAULT_DOWNLOAD_DIR,
+ );`,
+ replace: ` fs.mkdirSync(userDataDir, { recursive: true });
+ await ensureOutputDirectory(DEFAULT_DOWNLOAD_DIR);
+
+ // LOCAL PATCH (Cindy, via sync.mjs): Chrome chip follows host displayName
+ // when set so the disk key (Cindy-real) never leaks into the profile button.
+ const chipName =
+ normalizeOptionalString(resolved.profiles[profile.name]?.displayName) ?? profile.name;
+
+ const needsDecorate = !isProfileDecorated(
+ userDataDir,
+ chipName,
+ (profile.color ?? DEFAULT_OPENCLAW_BROWSER_COLOR).toUpperCase(),
+ DEFAULT_DOWNLOAD_DIR,
+ );`,
+ },
+ {
+ desc: 'pass chipName into decorateOpenClawProfile instead of the disk key',
+ find: ` decorateOpenClawProfile(userDataDir, {
+ name: profile.name,
+ color: profile.color,
+ downloadDir: DEFAULT_DOWNLOAD_DIR,
+ });`,
+ replace: ` decorateOpenClawProfile(userDataDir, {
+ name: chipName,
+ color: profile.color,
+ downloadDir: DEFAULT_DOWNLOAD_DIR,
+ });`,
+ },
+ ],
'extension/src/browser/chrome.executables.ts': [
{
desc: 'detect macOS Google Chrome Beta after stable Chromium-family browsers',
@@ -435,49 +1817,23 @@ const LOCAL_PATCHES = {
' );',
},
],
- 'extension/src/browser/chrome.ts': [
- {
- desc: 'decorate Chrome chip with host displayName so Cindy-real stays disk-only',
- find: ` fs.mkdirSync(userDataDir, { recursive: true });
- await ensureOutputDirectory(DEFAULT_DOWNLOAD_DIR);
-
- const needsDecorate = !isProfileDecorated(
- userDataDir,
- profile.name,
- (profile.color ?? DEFAULT_OPENCLAW_BROWSER_COLOR).toUpperCase(),
- DEFAULT_DOWNLOAD_DIR,
- );`,
- replace: ` fs.mkdirSync(userDataDir, { recursive: true });
- await ensureOutputDirectory(DEFAULT_DOWNLOAD_DIR);
-
- // LOCAL PATCH (Cindy, via sync.mjs): Chrome chip follows host displayName
- // when set so the disk key (Cindy-real) never leaks into the profile button.
- const chipName =
- normalizeOptionalString(resolved.profiles[profile.name]?.displayName) ?? profile.name;
-
- const needsDecorate = !isProfileDecorated(
- userDataDir,
- chipName,
- (profile.color ?? DEFAULT_OPENCLAW_BROWSER_COLOR).toUpperCase(),
- DEFAULT_DOWNLOAD_DIR,
- );`,
- },
- {
- desc: 'pass chipName into decorateOpenClawProfile instead of the disk key',
- find: ` decorateOpenClawProfile(userDataDir, {
- name: profile.name,
- color: profile.color,
- downloadDir: DEFAULT_DOWNLOAD_DIR,
- });`,
- replace: ` decorateOpenClawProfile(userDataDir, {
- name: chipName,
- color: profile.color,
- downloadDir: DEFAULT_DOWNLOAD_DIR,
- });`,
- },
- ],
};
+function applyExactReplacements(source, replacements) {
+ let patched = source;
+ for (const [find, replace, expectedCount = 1] of replacements) {
+ const actualCount = patched.split(find).length - 1;
+ if (actualCount !== expectedCount) {
+ throw new Error(
+ `LOCAL_PATCH exact replacement count mismatch (expected ${expectedCount}, found ${actualCount}). ` +
+ 'Upstream likely refactored the patched region — update LOCAL_PATCHES in sync.mjs.',
+ );
+ }
+ patched = expectedCount === 1 ? patched.replace(find, replace) : patched.split(find).join(replace);
+ }
+ return patched;
+}
+
/**
* Apply any LOCAL_PATCHES registered for `relDest` to upstream `raw`. Throws if a
* patch anchor is gone (upstream drift). Returns the patched source + the applied
@@ -488,7 +1844,12 @@ function applyLocalPatches(relDest, raw) {
if (!patches) return { patched: raw, applied: [] };
let patched = raw;
const applied = [];
- for (const { desc, find, replace } of patches) {
+ for (const { desc, find, replace, transform } of patches) {
+ if (transform) {
+ patched = transform(patched);
+ applied.push({ file: relDest, desc });
+ continue;
+ }
if (!patched.includes(find)) {
throw new Error(
`LOCAL_PATCH anchor not found in ${relDest}: "${desc}". ` +