diff --git a/v3/@claude-flow/browser/src/infrastructure/agent-browser-adapter.ts b/v3/@claude-flow/browser/src/infrastructure/agent-browser-adapter.ts index 172447d7a5..c5fa288164 100644 --- a/v3/@claude-flow/browser/src/infrastructure/agent-browser-adapter.ts +++ b/v3/@claude-flow/browser/src/infrastructure/agent-browser-adapter.ts @@ -19,6 +19,7 @@ import type { BrowserSession, NetworkRouteInput, } from '../domain/types.js'; +import { browserUrlError, commandArgvError } from './argv-guard.js'; export interface AgentBrowserAdapterOptions { session?: string; @@ -55,6 +56,9 @@ export class AgentBrowserAdapter { private async exec(args: string[], jsonOutput = true): Promise> { const startTime = Date.now(); + // Caller values must not be parsed as agent-browser options. + const argvError = commandArgvError(args); + if (argvError) return { success: false, error: argvError, duration: 0 }; const fullArgs = [ '--session', this.session, ...(this.timeout ? ['--timeout', String(this.timeout)] : []), @@ -106,6 +110,8 @@ export class AgentBrowserAdapter { // =========================================================================== async open(input: OpenInput): Promise { + const urlError = browserUrlError(input.url); + if (urlError) return { success: false, error: urlError, duration: 0 }; const args = ['open', input.url]; if (input.waitUntil) args.push('--wait', input.waitUntil); if (input.headers) args.push('--headers', JSON.stringify(input.headers)); @@ -461,7 +467,11 @@ export class AgentBrowserAdapter { async newTab(url?: string): Promise { const args = ['tab', 'new']; - if (url) args.push(url); + if (url) { + const urlError = browserUrlError(url); + if (urlError) return { success: false, error: urlError, duration: 0 }; + args.push(url); + } return this.exec(args); } diff --git a/v3/@claude-flow/browser/src/infrastructure/argv-guard.ts b/v3/@claude-flow/browser/src/infrastructure/argv-guard.ts new file mode 100644 index 0000000000..cff9550d87 --- /dev/null +++ b/v3/@claude-flow/browser/src/infrastructure/argv-guard.ts @@ -0,0 +1,52 @@ +/** + * @claude-flow/browser - agent-browser argv guard + * + * agent-browser reads its own options anywhere in argv, so a caller value + * (selector, typed text, URL, path) that starts with "--" would be parsed + * as an option such as --executable-path. Values reach the adapter from MCP + * tool input, so command argv may only carry the options the adapter itself + * emits. Mirrors @claude-flow/cli's browser-argv.ts. + */ + +/** Options the adapter emits after a subcommand. Global options (--session, --executable-path, ...) are excluded. */ +const COMMAND_FLAGS: ReadonlySet = new Set([ + '--abort', '--body', '--button', '--clear', '--click-count', '--delay', + '--exact', '--filter', '--fn', '--force', '--full', '--headers', '--load', + '--name', '--status', '--text', '--url', '--wait', '--with-deps', + '-c', '-d', '-i', '-s', +]); + +/** Returns an error when command argv contains an option the adapter did not mean to pass. */ +export function commandArgvError(args: readonly unknown[]): string | null { + for (const arg of args) { + if (typeof arg !== 'string') return 'browser command arguments must be strings'; + if (arg.startsWith('--')) { + const name = arg.split('=', 1)[0]; + if (!COMMAND_FLAGS.has(name)) return `value must not start with "--": ${JSON.stringify(arg.slice(0, 80))}`; + } else if (/^-[A-Za-z]$/.test(arg) && !COMMAND_FLAGS.has(arg)) { + return `value must not be an option: ${JSON.stringify(arg)}`; + } + } + return null; +} + +/** + * Returns an error when a navigation target is not a web page. Page text is + * returned to the caller, so file:, view-source:, chrome:, data: and similar + * schemes would read local files or browser state. Accepts http(s), + * about:blank, and scheme-less targets such as example.com/path or + * localhost:3000. + */ +export function browserUrlError(value: unknown): string | null { + if (typeof value !== 'string' || !value.trim()) return 'url must be a non-empty string'; + // Chromium drops tabs/newlines anywhere and trims leading control chars and spaces. + const url = value.replace(/[\t\n\r]/g, '').replace(/^[\u0000- ]+/, ''); + const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(url); + if (!scheme) return null; + const name = scheme[1].toLowerCase(); + if (name === 'http' || name === 'https') return null; + if (url.toLowerCase() === 'about:blank') return null; + // host:port with no scheme; host must be localhost or contain a dot. + if ((name === 'localhost' || name.includes('.')) && /^[a-z0-9.-]+:\d{1,5}(?:[/?#]|$)/i.test(url)) return null; + return `url scheme not allowed: ${JSON.stringify(name.slice(0, 40))} (use http or https)`; +} diff --git a/v3/@claude-flow/browser/tests/agent-browser-adapter.test.ts b/v3/@claude-flow/browser/tests/agent-browser-adapter.test.ts index dc5b6e733a..ebec2c910d 100644 --- a/v3/@claude-flow/browser/tests/agent-browser-adapter.test.ts +++ b/v3/@claude-flow/browser/tests/agent-browser-adapter.test.ts @@ -46,6 +46,46 @@ describe('AgentBrowserAdapter', () => { }); }); + describe('argv and URL guards', () => { + it('refuses a caller value that would be parsed as an agent-browser option', async () => { + const result = await adapter.fill({ target: '--executable-path=/tmp/x', value: 'v' } as any); + expect(result.success).toBe(false); + expect(result.error).toMatch(/must not start with "--"/); + expect(mockExecSync).not.toHaveBeenCalled(); + }); + + it('refuses a single-letter option smuggled in as a value', async () => { + const result = await adapter.click({ target: '-x' } as any); + expect(result.success).toBe(false); + expect(mockExecSync).not.toHaveBeenCalled(); + }); + + it.each(['file:///etc/passwd', 'view-source:https://example.com', 'chrome://settings', 'data:text/html,hi', ' \tfile:///etc/hosts'])( + 'refuses to open non-web URL %s', + async (url) => { + expect((await adapter.open({ url })).success).toBe(false); + expect((await adapter.newTab(url)).success).toBe(false); + expect(mockExecSync).not.toHaveBeenCalled(); + }, + ); + + it.each(['https://example.com', 'http://localhost:3000/app', 'example.com/path', 'localhost:8080', 'about:blank'])( + 'still opens web URL %s', + async (url) => { + mockExecSync.mockReturnValue(JSON.stringify({ success: true })); + expect((await adapter.open({ url })).success).toBe(true); + expect(mockExecSync).toHaveBeenCalled(); + }, + ); + + it('still passes the adapter\'s own command flags', async () => { + mockExecSync.mockReturnValue(JSON.stringify({ success: true })); + const result = await adapter.open({ url: 'https://example.com', waitUntil: 'load' } as any); + expect(result.success).toBe(true); + expect(mockExecSync.mock.calls[0][1]).toContain('--wait'); + }); + }); + describe('navigation', () => { it('should open a URL', async () => { mockExecSync.mockReturnValue(JSON.stringify({ diff --git a/v3/@claude-flow/cli/__tests__/hooks-build-agents-4558.test.ts b/v3/@claude-flow/cli/__tests__/hooks-build-agents-4558.test.ts index 1e35a9e52b..844339955f 100644 --- a/v3/@claude-flow/cli/__tests__/hooks-build-agents-4558.test.ts +++ b/v3/@claude-flow/cli/__tests__/hooks-build-agents-4558.test.ts @@ -6,7 +6,7 @@ * - reported patternsApplied = agents * 3 although no pretrain data is read. */ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { existsSync, mkdtempSync, readdirSync } from 'node:fs'; +import { existsSync, mkdtempSync, readdirSync, symlinkSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; @@ -55,6 +55,25 @@ describe('hooks_build-agents (#4558)', () => { expect(r._note).toMatch(/templates/); }); + it('rejects an absolute outputDir outside the project without writing', async () => { + const r = await build({ outputDir: join(elsewhere, 'out') }); + expect(r).toMatchObject({ success: false, error: expect.stringMatching(/inside the project/) }); + expect(existsSync(join(elsewhere, 'out'))).toBe(false); + }); + + it('rejects an outputDir that escapes the project through a symlink', async () => { + symlinkSync(elsewhere, join(project, 'link')); + const r = await build({ outputDir: 'link/out' }); + expect(r).toMatchObject({ success: false, error: expect.stringMatching(/inside the project/) }); + expect(existsSync(join(elsewhere, 'out'))).toBe(false); + }); + + it('rejects a format other than yaml/json (it is spliced into file names)', async () => { + const r = await build({ format: 'json/../../x' }); + expect(r).toMatchObject({ success: false, error: expect.stringMatching(/format/) }); + expect(existsSync(join(project, 'agents'))).toBe(false); + }); + it('still honours an explicit absolute outputDir (control)', async () => { const out = join(project, 'custom'); const r = await build({ outputDir: out, format: 'json', focus: 'security' }); diff --git a/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts index aeb1b613f8..b3c823842f 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/hooks-tools.ts @@ -2436,8 +2436,19 @@ export const hooksBuildAgents: MCPTool = { if (!v.valid) return { success: false, error: v.error }; } const outputDir = resolve(getProjectCwd(), (params.outputDir as string) || './agents'); + // validatePath allows absolute paths, so keep the real output dir inside + // the real project root (CWE-22/59): configs are only ever project files. + let realProjectRoot: string; + try { realProjectRoot = nodeFs.realpathSync(getProjectCwd()); } catch { realProjectRoot = getProjectCwd(); } + if (!isInsideRealRoot(realProjectRoot, outputDir)) { + return { success: false, error: 'outputDir must be inside the project directory' }; + } const focus = (params.focus as string) || 'all'; - const format = (params.format as string) || 'yaml'; + // format is spliced into each file name; only the two supported formats. + const format = params.format === undefined ? 'yaml' : params.format; + if (format !== 'yaml' && format !== 'json') { + return { success: false, error: 'format must be "yaml" or "json"' }; + } const persist = params.persist !== false; // Default to true const agents = [