diff --git a/package-lock.json b/package-lock.json index 9943b6e6fb..484fa39545 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "claude-flow", - "version": "3.71.3", + "version": "3.71.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "claude-flow", - "version": "3.71.3", + "version": "3.71.4", "bundleDependencies": [ "@claude-flow/codex", "@claude-flow/mcp", diff --git a/package.json b/package.json index 424f65dd49..9aa147024c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "claude-flow", - "version": "3.71.3", + "version": "3.71.4", "workspaces": [ "v3/@claude-flow/codex", "v3/@claude-flow/mcp", diff --git a/ruflo/package.json b/ruflo/package.json index 550e9960d2..63a0209713 100644 --- a/ruflo/package.json +++ b/ruflo/package.json @@ -1,6 +1,6 @@ { "name": "ruflo", - "version": "3.71.3", + "version": "3.71.4", "description": "Ruflo - Enterprise AI agent orchestration platform. Deploy 60+ specialized agents in coordinated swarms with self-learning, fault-tolerant consensus, vector memory, and MCP integration", "main": "bin/ruflo.js", "type": "module", @@ -40,7 +40,7 @@ "package:rvf": "bash src/scripts/package-rvf.sh" }, "dependencies": { - "@claude-flow/cli": "3.71.3" + "@claude-flow/cli": "3.71.4" }, "optionalDependencies": {}, "overrides": { diff --git a/v3/@claude-flow/cli/__tests__/agentbbs-federation-origin-binding.test.ts b/v3/@claude-flow/cli/__tests__/agentbbs-federation-origin-binding.test.ts new file mode 100644 index 0000000000..8573051296 --- /dev/null +++ b/v3/@claude-flow/cli/__tests__/agentbbs-federation-origin-binding.test.ts @@ -0,0 +1,87 @@ +/** + * SECURITY: mergeEnvelopes checked the signature against the syncing peer's + * pinned key but never compared `origin` with that peer, so a pinned peer could + * sign envelopes that claimed any other node as their origin. The sync cursor + * also advanced past envelopes that failed verification. + */ +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { + canonicalEnvelopeBytes, + getNodeIdentity, + mergeEnvelopes, + readEnvelopes, + signEnvelope, + type SignedEnvelope, +} from '../src/mcp-tools/agentbbs-federation.js'; + +const ROOM = 'sales-dd6531eb'; +let dirA: string, dirB: string, dirC: string; + +function envelope(over: Partial = {}): SignedEnvelope { + return { + envelopeId: 'e-' + Math.random().toString(36).slice(2, 10), + roomId: ROOM, seq: 1, msgType: 'Note', payload: { hello: 'world' }, + timestamp: '2026-11-04T00:00:00.000Z', ...over, + }; +} + +/** Sign with `signerDir`'s key while naming `claimedOrigin` — what a hostile peer would send. */ +async function forge(signerDir: string, claimedOrigin: string, over: Partial = {}): Promise { + const id = await getNodeIdentity(signerDir); + const ed = await import('@noble/ed25519'); + const env = { ...envelope(over), origin: claimedOrigin, hops: 0 }; + const sig = await ((ed as any).signAsync ?? (ed as any).sign)(canonicalEnvelopeBytes(env), Buffer.from(id.privateKey, 'hex')); + return { ...env, signature: Buffer.from(sig).toString('hex') }; +} + +beforeEach(() => { + [dirA, dirB, dirC] = ['a', 'b', 'c'].map(n => mkdtempSync(join(tmpdir(), `abbs-origin-${n}-`))); +}); +afterEach(() => { for (const d of [dirA, dirB, dirC]) rmSync(d, { recursive: true, force: true }); }); + +describe('origin binding', () => { + it('refuses an envelope a peer signed while naming another node as origin', async () => { + const a = await getNodeIdentity(dirA); + const c = await getNodeIdentity(dirC); + const forged = await forge(dirA, c.nodeId); + const r = await mergeEnvelopes(dirB, ROOM, [forged], a.publicKey, { peerNodeId: a.nodeId, pinned: new Map([[a.nodeId, a.publicKey]]) }); + expect(r.merged).toBe(0); + expect(r.skippedForeignOrigin).toBe(1); + expect(readEnvelopes(dirB, ROOM)).toHaveLength(0); + }); + + it('refuses a forged origin even when that origin is pinned, because the key does not match', async () => { + const a = await getNodeIdentity(dirA); + const c = await getNodeIdentity(dirC); + const forged = await forge(dirA, c.nodeId); + const pinned = new Map([[a.nodeId, a.publicKey], [c.nodeId, c.publicKey]]); + const r = await mergeEnvelopes(dirB, ROOM, [forged], a.publicKey, { peerNodeId: a.nodeId, pinned }); + expect(r.merged).toBe(0); + expect(r.skippedUnverified).toBe(1); + }); + + it('accepts the peer\'s own envelopes and relays signed by another pinned node', async () => { + const a = await getNodeIdentity(dirA); + const c = await getNodeIdentity(dirC); + const own = await signEnvelope(dirA, envelope({ seq: 3 })); + const relayed = await signEnvelope(dirC, envelope({ seq: 5 })); + const pinned = new Map([[a.nodeId, a.publicKey], [c.nodeId, c.publicKey]]); + const r = await mergeEnvelopes(dirB, ROOM, [own, relayed], a.publicKey, { peerNodeId: a.nodeId, pinned }); + expect(r.merged).toBe(2); + expect(r.acceptedMaxSeq).toBe(5); + }); + + it('does not count unverified envelopes towards the sync cursor', async () => { + const a = await getNodeIdentity(dirA); + const c = await getNodeIdentity(dirC); + const good = await signEnvelope(dirA, envelope({ seq: 2 })); + const forged = await forge(dirA, c.nodeId, { seq: 999 }); + const tampered = { ...(await signEnvelope(dirA, envelope({ seq: 500 }))), payload: { evil: true } }; + const r = await mergeEnvelopes(dirB, ROOM, [good, forged, tampered], a.publicKey, { peerNodeId: a.nodeId, pinned: new Map([[a.nodeId, a.publicKey]]) }); + expect(r.merged).toBe(1); + expect(r.acceptedMaxSeq).toBe(2); + }); +}); diff --git a/v3/@claude-flow/cli/__tests__/browser-launch-args-allowlist.test.ts b/v3/@claude-flow/cli/__tests__/browser-launch-args-allowlist.test.ts new file mode 100644 index 0000000000..bf33654a44 --- /dev/null +++ b/v3/@claude-flow/cli/__tests__/browser-launch-args-allowlist.test.ts @@ -0,0 +1,77 @@ +/** + * SECURITY: browser_open forwarded caller-supplied Chromium launch flags, and + * agent-browser reads its own options anywhere in argv, so caller text such as + * a selector could add an option too. Launch flags are now limited to a fixed + * list of plain switches, and no caller value may add an option. + */ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const exec = vi.hoisted(() => ({ execFileSync: vi.fn(() => '{"success":true,"data":{}}') })); +vi.mock('child_process', () => ({ execFileSync: exec.execFileSync })); +vi.mock('node:child_process', () => ({ execFileSync: exec.execFileSync })); + +import { browserTools } from '../src/mcp-tools/browser-tools.js'; +import { ALLOWED_LAUNCH_ARGS, commandArgvError, launchArgsError } from '../src/mcp-tools/browser-argv.js'; + +const call = (name: string, input: Record) => + browserTools.find(t => t.name === name)!.handler(input) as Promise<{ isError?: boolean; content: Array<{ text: string }> }>; +const errorOf = (r: { content: Array<{ text: string }> }) => JSON.parse(r.content[0].text).error as string; + +beforeEach(() => exec.execFileSync.mockClear()); + +describe('launchArgsError', () => { + it('accepts only exact allowlisted switches', () => { + expect(launchArgsError(undefined)).toBeNull(); + expect(launchArgsError([...ALLOWED_LAUNCH_ARGS])).toBeNull(); + for (const bad of ['--gpu-launcher=/tmp/x', '--renderer-cmd-prefix=sh', '--disable-gpu=1', '--disable-gpu,--x', 'disable-gpu', '']) { + expect(launchArgsError([bad]), bad).toMatch(/not allowed/); + } + expect(launchArgsError('--disable-gpu')).toMatch(/array/); + expect(launchArgsError([1])).toMatch(/array/); + }); +}); + +describe('commandArgvError', () => { + it('lets ordinary values and the tools\' own options through', () => { + expect(commandArgvError(['open', 'https://example.com', '--wait-until', 'load'])).toBeNull(); + expect(commandArgvError(['fill', '@e1', '-5'])).toBeNull(); + expect(commandArgvError(['snapshot', '-i', '-c', '-d', '3', '-s', '#main'])).toBeNull(); + }); + it('refuses values that would add an agent-browser option', () => { + expect(commandArgvError(['click', '--executable-path', '/tmp/x'])).toMatch(/must not start with "--"/); + expect(commandArgvError(['type', '#q', '--args=--gpu-launcher=x'])).toMatch(/must not start with "--"/); + expect(commandArgvError(['press', '-p'])).toMatch(/must not be an option/); + }); +}); + +describe('browser tool handlers', () => { + it('refuses a launch flag outside the allowlist without spawning anything', async () => { + const r = await call('browser_open', { url: 'https://example.com', args: ['--gpu-launcher=/tmp/marker.sh'] }); + expect(r.isError).toBe(true); + expect(errorOf(r)).toMatch(/not allowed/); + expect(exec.execFileSync).not.toHaveBeenCalled(); + }); + + it('refuses caller text that names an agent-browser option', async () => { + for (const [name, input] of [ + ['browser_click', { target: '--executable-path' }], + ['browser_type', { target: '#q', text: '--extension=/tmp/x' }], + ['browser_open', { url: '--profile' }], + ['browser_eval', { script: '--state=/tmp/x' }], + ] as const) { + const r = await call(name, input); + expect(r.isError, name).toBe(true); + } + expect(exec.execFileSync).not.toHaveBeenCalled(); + }); + + it('passes allowlisted switches as a single --args value', async () => { + await call('browser_open', { url: 'https://example.com', args: ['--disable-gpu', '--mute-audio'] }); + expect(exec.execFileSync).toHaveBeenCalledTimes(1); + const argv = exec.execFileSync.mock.calls[0][1] as string[]; + const at = argv.indexOf('--args'); + expect(argv[at + 1].split(',')).toEqual(expect.arrayContaining(['--disable-gpu', '--mute-audio'])); + expect(at).toBeGreaterThan(-1); + expect(argv.filter(a => a === '--args')).toHaveLength(1); + }); +}); diff --git a/v3/@claude-flow/cli/__tests__/daa-workflow-claims-prototype-safety.test.ts b/v3/@claude-flow/cli/__tests__/daa-workflow-claims-prototype-safety.test.ts index 0bb57f5e4a..22b89be26b 100644 --- a/v3/@claude-flow/cli/__tests__/daa-workflow-claims-prototype-safety.test.ts +++ b/v3/@claude-flow/cli/__tests__/daa-workflow-claims-prototype-safety.test.ts @@ -39,7 +39,9 @@ describe('daa_workflow_execute', () => { const { daaTools } = await import('../src/mcp-tools/daa-tools.js'); const exec = daaTools.find((t) => t.name === 'daa_workflow_execute')!; const result = (await exec.handler({ workflowId: id })) as Record; - expect(result).toMatchObject({ success: false, error: 'Workflow not found' }); + // Reserved names are refused by validateIdentifier; other built-ins are unknown ids. + expect(result.success).toBe(false); + expect(String(result.error)).toMatch(/Workflow not found|reserved name/); clean(); }); @@ -58,7 +60,7 @@ describe('workflow_cancel / workflow_stop', () => { const tool = workflowTools.find((t) => t.name === name)!; for (const id of ['__proto__', 'constructor']) { const result = (await tool.handler({ workflowId: id, reason: 'x' })) as Record; - expect(result.error).toBe('Workflow not found'); + expect(String(result.error)).toMatch(/Workflow not found|reserved name/); } clean(); }); @@ -68,9 +70,10 @@ describe('claims_steal', () => { it('refuses a reserved-name claim that was never marked stealable', async () => { const { claimsTools } = await import('../src/mcp-tools/claims-tools.js'); const tool = (n: string) => claimsTools.find((t) => t.name === n)!; - const claimed = (await tool('claims_claim').handler({ issueId: 'constructor', claimant: 'agent:a1:coder' })) as Record; - expect(claimed.success).toBe(true); + // validateIdentifier now refuses the reserved name outright; either way it must not be stealable. + await tool('claims_claim').handler({ issueId: 'constructor', claimant: 'agent:a1:coder' }); const stolen = (await tool('claims_steal').handler({ issueId: 'constructor', stealer: 'agent:a2:coder' })) as Record; - expect(stolen).toMatchObject({ success: false, error: 'Issue is not stealable' }); + expect(stolen.success).toBe(false); + expect(String(stolen.error)).toMatch(/not stealable|reserved name/); }); }); diff --git a/v3/@claude-flow/cli/__tests__/memory-export-both-stores-4148.test.ts b/v3/@claude-flow/cli/__tests__/memory-export-both-stores-4148.test.ts index 563af5ab46..a02089ff7a 100644 --- a/v3/@claude-flow/cli/__tests__/memory-export-both-stores-4148.test.ts +++ b/v3/@claude-flow/cli/__tests__/memory-export-both-stores-4148.test.ts @@ -23,6 +23,7 @@ vi.mock('../src/memory/memory-initializer.js', () => ({ let dir: string; beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'ruflo-export-4148-')); + process.env.CLAUDE_FLOW_CWD = dir; // MCP export paths are contained to the project state.cliStore = join(dir, 'memory.db'); writeFileSync(state.cliStore, 'x'); // the CLI store exists on disk state.stores = {}; diff --git a/v3/@claude-flow/cli/__tests__/memory-export-completeness.test.ts b/v3/@claude-flow/cli/__tests__/memory-export-completeness.test.ts index 9d68dce276..bf64e7801b 100644 --- a/v3/@claude-flow/cli/__tests__/memory-export-completeness.test.ts +++ b/v3/@claude-flow/cli/__tests__/memory-export-completeness.test.ts @@ -13,6 +13,7 @@ let dir: string; let outputPath: string; beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'ruflo-export-pages-')); + process.env.CLAUDE_FLOW_CWD = dir; // MCP export paths are contained to the project outputPath = join(dir, 'backup.json'); writeFileSync(outputPath, 'existing complete backup'); layer.listEntries.mockReset(); diff --git a/v3/@claude-flow/cli/__tests__/memory-export-import-path-containment.test.ts b/v3/@claude-flow/cli/__tests__/memory-export-import-path-containment.test.ts new file mode 100644 index 0000000000..42bd972fde --- /dev/null +++ b/v3/@claude-flow/cli/__tests__/memory-export-import-path-containment.test.ts @@ -0,0 +1,135 @@ +/** + * SECURITY: memory_export wrote to any outputPath and memory_import read any + * inputPath (echoing parser errors that quote the file), so an MCP caller could + * overwrite or probe files anywhere the server can reach. MCP callers are now + * contained to the project; the local CLI keeps operator-chosen paths. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +const layer = vi.hoisted(() => ({ storeEntry: vi.fn(), listEntries: vi.fn() })); +vi.mock('../src/memory/memory-initializer.js', () => ({ + storeEntry: layer.storeEntry, + listEntries: layer.listEntries, + searchEntries: vi.fn(), getEntry: vi.fn(), deleteEntry: vi.fn(), + initializeMemoryDatabase: vi.fn(), + checkMemoryInitialization: vi.fn(async () => ({ initialized: true })), +})); +const { memoryTools } = await import('../src/mcp-tools/memory-tools.js'); +const { localCliContext, dbPathError, containedWritePath } = await import('../src/mcp-tools/path-containment.js'); +const tool = (name: string) => memoryTools.find(t => t.name === name)!; + +const originalCwd = process.env.CLAUDE_FLOW_CWD; +let project: string; +let outside: string; + +beforeEach(() => { + project = mkdtempSync(join(tmpdir(), 'ruflo-mem-contain-')); + outside = mkdtempSync(join(tmpdir(), 'ruflo-mem-outside-')); + process.env.CLAUDE_FLOW_CWD = project; + layer.storeEntry.mockReset().mockResolvedValue({ success: true, id: 'saved' }); + layer.listEntries.mockReset().mockResolvedValue({ success: true, entries: [{ key: 'k', namespace: 'default', content: 'v', tags: [] }], total: 1 }); +}); +afterEach(() => { + if (originalCwd === undefined) delete process.env.CLAUDE_FLOW_CWD; + else process.env.CLAUDE_FLOW_CWD = originalCwd; + rmSync(project, { recursive: true, force: true }); + rmSync(outside, { recursive: true, force: true }); +}); + +const exportTo = (outputPath: string, context?: Record) => + tool('memory_export').handler({ outputPath }, context) as Promise>; + +describe('memory_export outputPath', () => { + it('writes a .json file inside the project', async () => { + const r = await exportTo('backup.json'); + expect(r.error).toBeUndefined(); + expect(JSON.parse(readFileSync(join(project, 'backup.json'), 'utf8')).schema).toMatch(/ruflo-memory-export/); + }); + + it('refuses paths outside the project, non-.json targets, symlinks, .git and executables', async () => { + const victim = join(outside, 'victim.json'); + writeFileSync(victim, 'original'); + symlinkSync(victim, join(project, 'link.json')); + mkdirSync(join(project, '.git', 'hooks'), { recursive: true }); + writeFileSync(join(project, 'run.json'), '#!/bin/sh\n'); + chmodSync(join(project, 'run.json'), 0o755); + for (const p of [victim, '../escape.json', 'link.json', 'notes.sh', '.git/hooks/pre-commit.json', 'run.json']) { + const r = await exportTo(p); + expect(r.error, p).toMatch(/inside the project/); + } + expect(readFileSync(victim, 'utf8')).toBe('original'); + expect(readFileSync(join(project, 'run.json'), 'utf8')).toBe('#!/bin/sh\n'); + }); + + it('refuses everything when the project root is the home directory', () => { + process.env.CLAUDE_FLOW_CWD = '/'; + vi.spyOn(process, 'cwd').mockReturnValue(process.env.HOME ?? '/'); + try { + expect(containedWritePath('backup.json', ['.json'])).toBeNull(); + } finally { + vi.restoreAllMocks(); + } + }); + + it('lets the local CLI write where the operator asked', async () => { + const target = join(outside, 'cli-backup.json'); + const r = await exportTo(target, localCliContext()); + expect(r.error).toBeUndefined(); + expect(existsSync(target)).toBe(true); + }); +}); + +describe('memory_import inputPath', () => { + it('refuses a file outside the project and does not echo its contents', async () => { + const secret = join(outside, 'secret.txt'); + writeFileSync(secret, 'root:x:0:0:topsecret'); + const r = await tool('memory_import').handler({ inputPath: secret }) as Record; + expect(r.error).toMatch(/inside the project/); + expect(JSON.stringify(r)).not.toContain('topsecret'); + }); + + it('returns a generic error for a non-JSON file inside the project', async () => { + writeFileSync(join(project, 'notes.txt'), 'topsecret line'); + const r = await tool('memory_import').handler({ inputPath: 'notes.txt' }) as Record; + expect(r.error).toMatch(/not a valid memory export/); + expect(JSON.stringify(r)).not.toContain('topsecret'); + expect(layer.storeEntry).not.toHaveBeenCalled(); + }); + + it('imports a file inside the project, and the CLI may import from elsewhere', async () => { + const doc = JSON.stringify({ entries: [{ key: 'a', namespace: 'notes', value: 'x' }] }); + writeFileSync(join(project, 'in.json'), doc); + expect((await tool('memory_import').handler({ inputPath: 'in.json' }) as any).error).toBeUndefined(); + writeFileSync(join(outside, 'in.json'), doc); + expect((await tool('memory_import').handler({ inputPath: join(outside, 'in.json') }, localCliContext()) as any).error).toBeUndefined(); + }); +}); + +describe('dbPath', () => { + it('accepts a new or existing SQLite file and refuses anything else', () => { + expect(dbPathError(join(outside, 'new.db'))).toBeNull(); + writeFileSync(join(outside, 'real.db'), Buffer.concat([Buffer.from('SQLite format 3\0', 'latin1'), Buffer.alloc(84)])); + expect(dbPathError(join(outside, 'real.db'))).toBeNull(); + writeFileSync(join(outside, 'fake.db'), 'export PATH=evil'); + expect(dbPathError(join(outside, 'fake.db'))).toMatch(/not a SQLite database/); + expect(dbPathError(join(outside, '.bashrc'))).toMatch(/must end in/); + symlinkSync(join(outside, 'real.db'), join(outside, 'link.db')); + expect(dbPathError(join(outside, 'link.db'))).toMatch(/symlink/); + }); + + it('is enforced on the MCP memory tools', async () => { + writeFileSync(join(outside, 'fake.db'), 'not a database'); + await expect(tool('memory_store').handler({ key: 'k', value: 'v', dbPath: join(outside, 'fake.db') })).rejects.toThrow(/not a SQLite database/); + expect(readFileSync(join(outside, 'fake.db'), 'utf8')).toBe('not a database'); + }); +}); + +describe('dbPath with encryption at rest', () => { + it('accepts an RFE1-encrypted database file', () => { + writeFileSync(join(outside, 'enc.db'), Buffer.concat([Buffer.from('RFE1'), Buffer.alloc(64)])); + expect(dbPathError(join(outside, 'enc.db'))).toBeNull(); + }); +}); diff --git a/v3/@claude-flow/cli/__tests__/memory-export-native-pages.test.ts b/v3/@claude-flow/cli/__tests__/memory-export-native-pages.test.ts index 3199111a35..6ddc63b4ac 100644 --- a/v3/@claude-flow/cli/__tests__/memory-export-native-pages.test.ts +++ b/v3/@claude-flow/cli/__tests__/memory-export-native-pages.test.ts @@ -14,6 +14,7 @@ vi.mock('../src/memory/memory-initializer.js', () => ({ }, })); const dir = mkdtempSync(join(tmpdir(), 'ruflo-export-native-')); +process.env.CLAUDE_FLOW_CWD = dir; // MCP export paths are contained to the project state.dbPath = join(dir, 'memory.db'); const db = new Database(state.dbPath); afterAll(() => { db.close(); rmSync(dir, { recursive: true, force: true }); }); diff --git a/v3/@claude-flow/cli/__tests__/memory-export-path-3196.test.ts b/v3/@claude-flow/cli/__tests__/memory-export-path-3196.test.ts index daeda676da..f710dce9c5 100644 --- a/v3/@claude-flow/cli/__tests__/memory-export-path-3196.test.ts +++ b/v3/@claude-flow/cli/__tests__/memory-export-path-3196.test.ts @@ -52,6 +52,7 @@ describe('memory export explicit dbPath (#3196)', () => { beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'memory-export-path-')); + process.env.CLAUDE_FLOW_CWD = dir; // MCP export paths are contained to the project prevMemoryPath = process.env.CLAUDE_FLOW_MEMORY_PATH; prevBridge = process.env.CLAUDE_FLOW_DISABLE_BRIDGE; process.env.CLAUDE_FLOW_MEMORY_PATH = join(dir, 'default-memory-root'); diff --git a/v3/@claude-flow/cli/__tests__/memory-import-db-path-3196.test.ts b/v3/@claude-flow/cli/__tests__/memory-import-db-path-3196.test.ts index 299b198c8c..de42f32340 100644 --- a/v3/@claude-flow/cli/__tests__/memory-import-db-path-3196.test.ts +++ b/v3/@claude-flow/cli/__tests__/memory-import-db-path-3196.test.ts @@ -33,6 +33,7 @@ import { memoryTools } from '../src/mcp-tools/memory-tools.js'; const importCommand = memoryCommand.subcommands!.find(command => command.name === 'import')!; const importTool = memoryTools.find(tool => tool.name === 'memory_import')!; const tempDir = mkdtempSync(join(tmpdir(), 'ruflo-import-3196-')); +process.env.CLAUDE_FLOW_CWD = tempDir; // MCP import paths are contained to the project const importPath = join(tempDir, 'export.json'); writeFileSync(importPath, JSON.stringify({ entries: [{ key: 'remember-me', namespace: 'project', value: 'persisted' }], @@ -62,7 +63,7 @@ describe('memory import database selection', () => { } as any); expect(mocks.callMCPTool).toHaveBeenCalledWith('memory_import', expect.objectContaining({ dbPath: '/project/custom.db', - })); + }), expect.anything()); }); it('uses the same default database as CLI store when --path is omitted', async () => { @@ -72,7 +73,7 @@ describe('memory import database selection', () => { } as any); expect(mocks.callMCPTool).toHaveBeenCalledWith('memory_import', expect.objectContaining({ dbPath: '/project/.swarm/memory.db', - })); + }), expect.anything()); }); it('initializes and writes the selected file rather than the bridge fallback', async () => { diff --git a/v3/@claude-flow/cli/__tests__/memory-import-write-results.test.ts b/v3/@claude-flow/cli/__tests__/memory-import-write-results.test.ts index 2197b75f4b..0cc0500dc0 100644 --- a/v3/@claude-flow/cli/__tests__/memory-import-write-results.test.ts +++ b/v3/@claude-flow/cli/__tests__/memory-import-write-results.test.ts @@ -14,6 +14,7 @@ const importer = memoryTools.find(t => t.name === 'memory_import')!; let dir: string; beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'ruflo-import-result-')); + process.env.CLAUDE_FLOW_CWD = dir; // MCP import paths are contained to the project layer.storeEntry.mockReset().mockResolvedValue({ success: true, id: 'saved' }); }); afterEach(() => rmSync(dir, { recursive: true, force: true })); diff --git a/v3/@claude-flow/cli/__tests__/memory-sibling-disclosure-partial-3566.test.ts b/v3/@claude-flow/cli/__tests__/memory-sibling-disclosure-partial-3566.test.ts index 0b9bf18200..95db7c186e 100644 --- a/v3/@claude-flow/cli/__tests__/memory-sibling-disclosure-partial-3566.test.ts +++ b/v3/@claude-flow/cli/__tests__/memory-sibling-disclosure-partial-3566.test.ts @@ -46,6 +46,7 @@ const run = (cmd: typeof search, flags: Record) => const siblingWarnings = () => mocks.warning.mock.calls.map(c => String(c[0])).filter(m => m.includes(SIBLING.path)); const dir = mkdtempSync(join(tmpdir(), 'mem-3566-')); +process.env.CLAUDE_FLOW_CWD = dir; // MCP import paths are contained to the project afterAll(() => rmSync(dir, { recursive: true, force: true })); beforeEach(() => { diff --git a/v3/@claude-flow/cli/__tests__/memory-stats-selected-store.test.ts b/v3/@claude-flow/cli/__tests__/memory-stats-selected-store.test.ts index c713f6a957..3b9ba5be78 100644 --- a/v3/@claude-flow/cli/__tests__/memory-stats-selected-store.test.ts +++ b/v3/@claude-flow/cli/__tests__/memory-stats-selected-store.test.ts @@ -39,7 +39,8 @@ beforeEach(() => { vi.clearAllMocks(); dir = mkdtempSync(join(tmpdir(), 'stats-selected-')); selected = join(dir, 'selected.db'); - writeFileSync(selected, 'store'); + // MCP callers may only name a real SQLite file, so the fixture carries the header. + writeFileSync(selected, Buffer.concat([Buffer.from('SQLite format 3\0', 'latin1'), Buffer.from('store')])); writeFileSync(selected + '-wal', 'wal'); vi.stubEnv('CLAUDE_FLOW_DB_PATH', ''); mocks.labels.mockResolvedValue({ initialized: true, version: 'selected-version' }); @@ -58,7 +59,7 @@ describe('stats describes the selected store', () => { expect(mocks.labels).toHaveBeenCalledWith(selected); expect(mocks.init).not.toHaveBeenCalled(); expect(result.location).toBe(selected); - expect(result.totalSize).toBe('8 B'); + expect(result.totalSize).toBe('24 B'); expect(result.oldestEntry).toBe('2026-01-01T00:00:00.000Z'); expect(result.newestEntry).toBe('2026-03-01T00:00:00.000Z'); }); @@ -69,7 +70,7 @@ describe('stats describes the selected store', () => { const result = await run({ path: selected }) as any; expect(result.success).toBe(true); expect(result.data.entries.total).toBe(2); - expect(result.data.storage).toEqual({ total: '8 B', location: selected }); + expect(result.data.storage).toEqual({ total: '24 B', location: selected }); expect(result.data.unreadStore.rows).toBe(9); expect(mocks.sibling).toHaveBeenCalledWith(selected); }); diff --git a/v3/@claude-flow/cli/__tests__/memory-store-import-namespace-3570.test.ts b/v3/@claude-flow/cli/__tests__/memory-store-import-namespace-3570.test.ts index a6527b4559..53a48a636b 100644 --- a/v3/@claude-flow/cli/__tests__/memory-store-import-namespace-3570.test.ts +++ b/v3/@claude-flow/cli/__tests__/memory-store-import-namespace-3570.test.ts @@ -34,6 +34,7 @@ const importTool = memoryTools.find(t => t.name === 'memory_import')!; const exportTool = memoryTools.find(t => t.name === 'memory_export')!; const tempDir = mkdtempSync(join(tmpdir(), 'ruflo-ns-3570-')); +process.env.CLAUDE_FLOW_CWD = tempDir; // MCP export/import paths are contained to the project const writeImport = (name: string, entries: unknown[]) => { const p = join(tempDir, name); writeFileSync(p, JSON.stringify({ entries })); diff --git a/v3/@claude-flow/cli/__tests__/store-reserved-id-prototype-safety.test.ts b/v3/@claude-flow/cli/__tests__/store-reserved-id-prototype-safety.test.ts new file mode 100644 index 0000000000..890d334f58 --- /dev/null +++ b/v3/@claude-flow/cli/__tests__/store-reserved-id-prototype-safety.test.ts @@ -0,0 +1,72 @@ +/** + * SECURITY: the agent, task and terminal stores are plain JSON objects keyed by + * ids from MCP tool input, and validateIdentifier accepted `__proto__`, so + * `agent_update {agentId: "__proto__"}` wrote onto Object.prototype for the + * life of the MCP server. Reserved names are now refused and every record map + * loads with a null prototype. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { validateIdentifier } from '../src/mcp-tools/validate-input.js'; +import { readRecordStore } from '../src/mcp-tools/record-store.js'; + +vi.mock('../src/memory/memory-bridge.js', () => ({ bridgeStoreEntry: vi.fn(async () => undefined) })); + +const originalCwd = process.env.CLAUDE_FLOW_CWD; +let dir: string; +const polluted = () => ['status', 'config', 'error', 'output'].filter(k => k in ({} as object)); + +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'ruflo-reserved-id-')); + process.env.CLAUDE_FLOW_CWD = dir; + vi.spyOn(process, 'cwd').mockReturnValue(dir); +}); +afterEach(() => { + vi.restoreAllMocks(); + if (originalCwd === undefined) delete process.env.CLAUDE_FLOW_CWD; + else process.env.CLAUDE_FLOW_CWD = originalCwd; + for (const k of ['status', 'config', 'error', 'output', 'health', 'completedAt']) delete (Object.prototype as Record)[k]; + rmSync(dir, { recursive: true, force: true }); +}); + +describe('validateIdentifier', () => { + it('refuses names that resolve to Object.prototype or a built-in', () => { + for (const id of ['__proto__', 'constructor', 'prototype']) { + expect(validateIdentifier(id, 'agentId').valid, id).toBe(false); + } + expect(validateIdentifier('agent-1', 'agentId').valid).toBe(true); + expect(validateIdentifier('proto', 'agentId').valid).toBe(true); + }); +}); + +describe('record stores', () => { + it('load records with a null prototype, even from a store written with a __proto__ key', () => { + const path = join(dir, 'store.json'); + writeFileSync(path, '{"agents":{"__proto__":{"status":"x"},"a1":{"status":"idle"}}}'); + const store = readRecordStore<{ agents: Record }>(path, 'agents', () => ({ agents: {} })); + expect(Object.getPrototypeOf(store.agents)).toBeNull(); + expect(store.agents.constructor).toBeUndefined(); + const empty = readRecordStore<{ agents: Record }>(join(dir, 'missing.json'), 'agents', () => ({ agents: {} })); + expect(Object.getPrototypeOf(empty.agents)).toBeNull(); + }); + + it('agent, task and terminal handlers refuse reserved ids without touching Object.prototype', async () => { + const { agentTools } = await import('../src/mcp-tools/agent-tools.js'); + const { taskTools } = await import('../src/mcp-tools/task-tools.js'); + const { terminalTools } = await import('../src/mcp-tools/terminal-tools.js'); + mkdirSync(join(dir, '.claude-flow'), { recursive: true }); + const run = (tools: Array<{ name: string; handler: (i: Record) => Promise }>, name: string, input: Record) => + tools.find(t => t.name === name)!.handler(input).catch((e: Error) => ({ error: e.message })); + for (const id of ['__proto__', 'constructor']) { + await run(agentTools as any, 'agent_update', { agentId: id, status: 'pwned', config: { a: 1 } }); + await run(agentTools as any, 'agent_terminate', { agentId: id }); + await run(taskTools as any, 'task_complete', { taskId: id, result: { output: 'x' } }); + await run(taskTools as any, 'task_update', { taskId: id, status: 'pwned' }); + await run(taskTools as any, 'task_cancel', { taskId: id }); + await run(terminalTools as any, 'terminal_close', { sessionId: id }); + } + expect(polluted()).toEqual([]); + }); +}); diff --git a/v3/@claude-flow/cli/package.json b/v3/@claude-flow/cli/package.json index b40f5823b7..b033ac13f8 100644 --- a/v3/@claude-flow/cli/package.json +++ b/v3/@claude-flow/cli/package.json @@ -1,6 +1,6 @@ { "name": "@claude-flow/cli", - "version": "3.71.3", + "version": "3.71.4", "type": "module", "description": "Ruflo CLI - Enterprise AI agent orchestration with 60+ specialized agents, swarm coordination, MCP server, self-learning hooks, and vector memory for Claude Code", "main": "dist/src/index.js", diff --git a/v3/@claude-flow/cli/src/commands/memory.ts b/v3/@claude-flow/cli/src/commands/memory.ts index de02eb7c4f..863b25b101 100644 --- a/v3/@claude-flow/cli/src/commands/memory.ts +++ b/v3/@claude-flow/cli/src/commands/memory.ts @@ -9,6 +9,7 @@ import type { Command, CommandContext, CommandResult } from '../types.js'; import { output } from '../output.js'; import { select, confirm, input } from '../prompt.js'; import { callMCPTool, MCPClientError } from '../mcp-client.js'; +import { localCliContext } from '../mcp-tools/path-containment.js'; import { distillCommand } from './memory-distill.js'; import { backupCommand } from './memory-backup.js'; import { countSiblingStoreRows } from '../memory/sibling-store.js'; @@ -1155,7 +1156,7 @@ const statsCommand: Command = { // Call MCP memory/stats tool for real statistics try { const dbPath = resolveDbPath(ctx.flags.path as string | undefined); - const statsResult = await callMCPTool('memory_stats', { dbPath }) as { + const statsResult = await callMCPTool('memory_stats', { dbPath }, localCliContext()) as { available?: boolean; error?: string; truncated?: boolean; @@ -1825,7 +1826,7 @@ const exportCommand: Command = { namespace: ctx.flags.namespace, includeVectors: ctx.flags.includeVectors ?? true, dbPath: resolveDbPath(ctx.flags.path as string | undefined), - }); + }, localCliContext()); // memory_export reports failure as { error } rather than throwing; without // this check the command printed "Exported to undefined" and then crashed @@ -1914,7 +1915,7 @@ const importCommand: Command = { merge: ctx.flags.merge ?? true, namespace: ctx.flags.namespace, dbPath: resolveDbPath(ctx.flags.path as string | undefined), - }); + }, localCliContext()); // memory_import reports a bad file as { error } rather than throwing, and // a partial write as { success: false, error, imported }. Without this the diff --git a/v3/@claude-flow/cli/src/mcp-tools/agent-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/agent-tools.ts index 972c5c1133..9cb5790ef7 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/agent-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/agent-tools.ts @@ -7,7 +7,7 @@ import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'; import { join } from 'node:path'; -import { readRecordStore } from './record-store.js'; +import { nullPrototypeRecords, readRecordStore } from './record-store.js'; import { type MCPTool, getProjectCwd } from './types.js'; import { validateIdentifier, validateText, validateAgentSpawn } from './validate-input.js'; import { executeAgentTask } from './agent-execute-core.js'; @@ -98,13 +98,13 @@ function loadHiveAgents(): Record { if (existsSync(path)) { const data = JSON.parse(readFileSync(path, 'utf-8')); if (data && typeof data.agents === 'object' && data.agents) { - return data.agents as Record; + return nullPrototypeRecords(data.agents as Record); } } } catch { // Ignore — hive store is optional/best-effort. } - return {}; + return nullPrototypeRecords>(undefined); } /** @@ -113,7 +113,7 @@ function loadHiveAgents(): Record { * wins (it carries model-routing + lastResult that the hive store omits). */ function loadAllAgents(): Record { - return { ...loadHiveAgents(), ...loadAgentStore().agents }; + return Object.assign(nullPrototypeRecords>(undefined), loadHiveAgents(), loadAgentStore().agents); } // Default model mappings for agent types (can be overridden) diff --git a/v3/@claude-flow/cli/src/mcp-tools/agentbbs-federation.ts b/v3/@claude-flow/cli/src/mcp-tools/agentbbs-federation.ts index 74e92b84a9..84505e5e25 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/agentbbs-federation.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/agentbbs-federation.ts @@ -341,6 +341,21 @@ export interface MergeResult { skippedUnverified: number; skippedOversize: number; skippedHopLimit: number; + /** Envelopes whose `origin` names a node the signature does not belong to. */ + skippedForeignOrigin: number; + /** Highest `seq` among envelopes merged or already held; the next sync starts after it. */ + acceptedMaxSeq: number; +} + +/** + * Who may have signed an envelope. `origin` is inside the signature, but a + * signature only proves which key signed, not which node the envelope names. + * An envelope is accepted only when its origin is the syncing peer itself or + * another pinned peer, and it verifies against that origin's pinned key. + */ +export interface OriginKeys { + peerNodeId: string; + pinned: ReadonlyMap; } /** @@ -349,22 +364,27 @@ export interface MergeResult { * Idempotent: `envelopeId` is the merge key, so replaying the same batch is a * no-op. Anything that fails verification is dropped and counted rather than * quarantined — a receiver has no use for an envelope it cannot attribute. + * + * `hops` is not signed (relays change it), so it only limits propagation and + * is never trusted for anything else. */ export async function mergeEnvelopes( basePath: string, roomId: string, incoming: SignedEnvelope[], peerPublicKey: string, + origins?: OriginKeys, ): Promise { validateRoomId(roomId); ensureDir(basePath); const result: MergeResult = { merged: 0, skippedDuplicate: 0, skippedUnverified: 0, skippedOversize: 0, skippedHopLimit: 0, + skippedForeignOrigin: 0, acceptedMaxSeq: 0, }; const existing = readEnvelopes(basePath, roomId); - const seen = new Set(existing.map(e => e.envelopeId)); + const seen = new Map(existing.map(e => [e.envelopeId, Number(e.seq) || 0] as const)); const logPath = roomLogPath(basePath, roomId); const batch = incoming.slice(0, MAX_ENVELOPES_PER_SYNC); @@ -373,13 +393,24 @@ export async function mergeEnvelopes( result.skippedUnverified++; continue; } if (env.roomId !== roomId) { result.skippedUnverified++; continue; } - if (seen.has(env.envelopeId)) { result.skippedDuplicate++; continue; } + if (seen.has(env.envelopeId)) { + result.skippedDuplicate++; + result.acceptedMaxSeq = Math.max(result.acceptedMaxSeq, seen.get(env.envelopeId) ?? 0); + continue; + } if (JSON.stringify(env).length > MAX_ENVELOPE_BYTES) { result.skippedOversize++; continue; } if ((env.hops ?? 0) >= MAX_HOPS) { result.skippedHopLimit++; continue; } - if (!(await verifyEnvelope(env, peerPublicKey))) { result.skippedUnverified++; continue; } + let signerKey = peerPublicKey; + if (origins) { + const key = env.origin === origins.peerNodeId ? peerPublicKey : typeof env.origin === 'string' ? origins.pinned.get(env.origin) : undefined; + if (!key) { result.skippedForeignOrigin++; continue; } + signerKey = key; + } + if (!(await verifyEnvelope(env, signerKey))) { result.skippedUnverified++; continue; } appendFileSync(logPath, JSON.stringify({ ...env, hops: (env.hops ?? 0) + 1 }) + '\n'); - seen.add(env.envelopeId); + seen.set(env.envelopeId, Number(env.seq) || 0); + result.acceptedMaxSeq = Math.max(result.acceptedMaxSeq, Number(env.seq) || 0); result.merged++; } return result; @@ -410,15 +441,16 @@ export async function syncRoomFromPeer( } const envelopes: SignedEnvelope[] = Array.isArray(body?.envelopes) ? body.envelopes : []; - const merged = await mergeEnvelopes(basePath, roomId, envelopes, peer.publicKey); - const peers = readPeers(basePath); + const pinned = new Map(peers.filter(p => typeof p.publicKey === 'string').map(p => [p.nodeId, p.publicKey] as const)); + const merged = await mergeEnvelopes(basePath, roomId, envelopes, peer.publicKey, { peerNodeId: peer.nodeId, pinned }); + const rec = peers.find(p => p.nodeId === peer.nodeId); if (rec) { rec.lastSyncedAt = new Date().toISOString(); rec.lastSeq = rec.lastSeq ?? {}; - const maxSeq = envelopes.reduce((m, e) => Math.max(m, Number(e.seq) || 0), since); - rec.lastSeq[roomId] = maxSeq; + // Advance only past envelopes that verified; an unverifiable batch must not skip the cursor forward. + rec.lastSeq[roomId] = Math.max(since, merged.acceptedMaxSeq); writePeers(basePath, peers); } return { ...merged, peerNodeId: peer.nodeId, roomId }; diff --git a/v3/@claude-flow/cli/src/mcp-tools/browser-argv.ts b/v3/@claude-flow/cli/src/mcp-tools/browser-argv.ts new file mode 100644 index 0000000000..5fc16f8987 --- /dev/null +++ b/v3/@claude-flow/cli/src/mcp-tools/browser-argv.ts @@ -0,0 +1,56 @@ +/** + * Argument checks for the agent-browser bridge. + * + * agent-browser reads its own options anywhere in argv, and forwards `--args` + * to the Chromium it launches. Both are reachable from MCP tool input, so + * caller text must never be able to add an option, and launch flags are + * limited to a fixed list of plain switches. + */ + +/** Chromium launch switches a caller may request. Exact matches only; none takes a value. */ +export const ALLOWED_LAUNCH_ARGS: ReadonlySet = new Set([ + '--no-sandbox', + '--disable-setuid-sandbox', + '--disable-gpu', + '--disable-dev-shm-usage', + '--disable-extensions', + '--mute-audio', + '--hide-scrollbars', + '--incognito', +]); + +/** The agent-browser options the browser tools themselves emit after a subcommand. */ +const COMMAND_FLAGS: ReadonlySet = new Set([ + '--wait-until', '--full', '--button', '--count', '--delay', '--text', '--url', + '-i', '-c', '-d', '-s', +]); + +/** Returns an error when a launch-flag list contains anything outside the allowlist. */ +export function launchArgsError(value: unknown): string | null { + if (value === undefined || value === null) return null; + if (!Array.isArray(value)) return 'args must be an array of strings'; + for (const arg of value) { + if (typeof arg !== 'string') return 'args must be an array of strings'; + if (!ALLOWED_LAUNCH_ARGS.has(arg)) { + return `launch arg not allowed: ${JSON.stringify(arg.slice(0, 80))} (allowed: ${[...ALLOWED_LAUNCH_ARGS].join(', ')})`; + } + } + return null; +} + +/** + * Returns an error when argv contains an option the tools did not mean to + * pass — for example a selector or typed text of "--executable-path". + */ +export function commandArgvError(args: readonly string[]): 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; +} diff --git a/v3/@claude-flow/cli/src/mcp-tools/browser-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/browser-tools.ts index 1589d066d6..08a3b927da 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/browser-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/browser-tools.ts @@ -9,6 +9,7 @@ import { readFileSync, existsSync } from 'node:fs'; import type { MCPTool, MCPToolResult } from './types.js'; import { validateIdentifier, validateText } from './validate-input.js'; import { resolveAgentBrowserLaunch, resolveNpxLaunch } from '../runtime/browser-command.js'; +import { commandArgvError, launchArgsError } from './browser-argv.js'; // Session registry for multi-session support const browserSessions = new Map { +export async function execBrowserCommand( + args: string[], + session = 'default', + launchArgs: readonly string[] = [], +): Promise { + const argvError = commandArgvError(args) ?? launchArgsError(launchArgs); + if (argvError) return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: argvError }) }], isError: true }; const { execFileSync } = await import('child_process'); const fullArgs = ['--session', session, '--json', ...args]; + if (launchArgs.length > 0) fullArgs.push('--args', launchArgs.join(',')); // ADR-401: fullArgs carries tool-supplied text (fill values, eval scripts, // selectors), so no spawn here may use a shell. On Windows the npm shims are @@ -156,7 +164,7 @@ export const browserTools: MCPTool[] = [ args: { type: 'array', items: { type: 'string' }, - description: 'Additional Chrome launch args (e.g., ["--no-sandbox", "--disable-dev-shm-usage"])', + description: 'Additional Chrome launch switches. Only these are accepted: --no-sandbox, --disable-setuid-sandbox, --disable-gpu, --disable-dev-shm-usage, --disable-extensions, --mute-audio, --hide-scrollbars, --incognito', }, }, required: ['url'], @@ -170,13 +178,14 @@ export const browserTools: MCPTool[] = [ session?: string; waitUntil?: string; }; - const launchArgs = (input.args as string[] | undefined) || []; + const vArgs = launchArgsError(input.args); + if (vArgs) return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: vArgs }) }], isError: true }; + const launchArgs = [...((input.args as string[] | undefined) || [])]; if (needsNoSandbox() && !launchArgs.includes('--no-sandbox')) { launchArgs.push('--no-sandbox'); } const args = ['open', url]; if (waitUntil) args.push('--wait-until', waitUntil); - if (launchArgs.length > 0) args.push('--args', launchArgs.join(',')); // Create session if new const sessionId = session || 'default'; @@ -188,7 +197,7 @@ export const browserTools: MCPTool[] = [ }); } - return execBrowserCommand(args, sessionId); + return execBrowserCommand(args, sessionId, launchArgs); }, }, { diff --git a/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts index bf7247c61f..636f48cba9 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/memory-tools.ts @@ -13,6 +13,7 @@ import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, unlinkSync, writeFileSync } from 'fs'; import { homedir } from 'os'; import { basename, dirname, join, resolve } from 'path'; +import { containedReadPath, containedWritePath, dbPathError, isLocalCliCall } from './path-containment.js'; import { execFileSync } from 'node:child_process'; import { createHash } from 'crypto'; import { getProjectCwd, type MCPTool } from './types.js'; @@ -45,10 +46,19 @@ const LEGACY_MEMORY_DIR = '.claude-flow/memory'; * deliberately not an implicit `CLAUDE_FLOW_DB_PATH` override because the * native/encrypted CLI store and the AgentDB sibling are separate backends. */ -function resolveDbPathOption(inputDbPath: unknown): string | undefined { - return typeof inputDbPath === 'string' && inputDbPath.trim().length > 0 - ? resolve(inputDbPath) - : undefined; +/** + * Resolve an explicit `dbPath`. MCP callers may only name a SQLite database + * file, so the memory tools cannot be aimed at and overwrite an unrelated file; + * the local CLI (`--path`) keeps operator-chosen paths as-is. + */ +function resolveDbPathOption(inputDbPath: unknown, context?: unknown): string | undefined { + if (typeof inputDbPath !== 'string' || inputDbPath.trim().length === 0) return undefined; + const dbPath = resolve(inputDbPath); + if (!isLocalCliCall(context)) { + const error = dbPathError(dbPath); + if (error) throw new Error(error); + } + return dbPath; } const MIGRATION_MARKER = '.migrated-to-sqlite'; @@ -534,13 +544,13 @@ export const memoryTools: MCPTool[] = [ }, required: ['key', 'value'], }, - handler: async (input) => { + handler: async (input, context) => { const missingKey = missingRequiredString(input, 'key', 'memory_store'); if (missingKey) { return { success: false, key: input.key, stored: false, hasEmbedding: false, ...missingKey }; } - const dbPath = resolveDbPathOption(input.dbPath); + const dbPath = resolveDbPathOption(input.dbPath, context); if (!dbPath) await ensureInitialized(); const { storeEntry } = await getMemoryFunctions(); @@ -626,13 +636,13 @@ export const memoryTools: MCPTool[] = [ }, required: ['key'], }, - handler: async (input) => { + handler: async (input, context) => { const missingKey = missingRequiredString(input, 'key', 'memory_retrieve'); if (missingKey) { return { key: input.key, namespace: input.namespace, value: null, found: false, ...missingKey }; } - const dbPath = resolveDbPathOption(input.dbPath); + const dbPath = resolveDbPathOption(input.dbPath, context); if (!dbPath) await ensureInitialized(); const { getEntry } = await getMemoryFunctions(); @@ -705,13 +715,13 @@ export const memoryTools: MCPTool[] = [ }, required: ['query'], }, - handler: async (input) => { + handler: async (input, context) => { const missingQuery = missingRequiredString(input, 'query', 'memory_search'); if (missingQuery) { return { query: input.query, results: [], total: 0, ...missingQuery }; } - const dbPath = resolveDbPathOption(input.dbPath); + const dbPath = resolveDbPathOption(input.dbPath, context); if (!dbPath) await ensureInitialized(); const { searchEntries } = await getMemoryFunctions(); @@ -903,13 +913,13 @@ export const memoryTools: MCPTool[] = [ }, required: ['key'], }, - handler: async (input) => { + handler: async (input, context) => { const missingKey = missingRequiredString(input, 'key', 'memory_delete'); if (missingKey) { return { success: false, key: input.key, namespace: input.namespace, deleted: false, ...missingKey }; } - const dbPath = resolveDbPathOption(input.dbPath); + const dbPath = resolveDbPathOption(input.dbPath, context); if (!dbPath) await ensureInitialized(); const { deleteEntry } = await getMemoryFunctions(); @@ -958,8 +968,8 @@ export const memoryTools: MCPTool[] = [ dbPath: { type: 'string', description: 'Explicit SQLite store to read/write; omit to use the MCP default (the native/AgentDB sibling).' }, }, }, - handler: async (input) => { - const dbPath = resolveDbPathOption(input.dbPath); + handler: async (input, context) => { + const dbPath = resolveDbPathOption(input.dbPath, context); if (!dbPath) await ensureInitialized(); const { listEntries } = await getMemoryFunctions(); @@ -1035,11 +1045,11 @@ export const memoryTools: MCPTool[] = [ dbPath: { type: 'string', description: 'Explicit SQLite store to read/write; omit to use the MCP default (the native/AgentDB sibling).' }, }, }, - handler: async (input) => { + handler: async (input, context) => { if (input.dbPath !== undefined && (typeof input.dbPath !== 'string' || !input.dbPath.trim())) { return memoryStatsUnavailable('dbPath must be a non-empty string'); } - const dbPath = resolveDbPathOption(input.dbPath); + const dbPath = resolveDbPathOption(input.dbPath, context); // An explicit read must not initialize or migrate the unrelated default store. if (!dbPath) await ensureInitialized(); const { listEntries } = await getMemoryFunctions(); @@ -1715,16 +1725,16 @@ export const memoryTools: MCPTool[] = [ }, required: ['outputPath'], }, - handler: async (input) => { - const requestedDbPath = typeof input.dbPath === 'string' && input.dbPath.trim() - ? resolve(input.dbPath) - : undefined; + handler: async (input, context) => { + const requestedOutput = String(input.outputPath ?? ''); + if (!requestedOutput) return { error: 'outputPath is required' }; + const outputPath = isLocalCliCall(context) ? resolve(requestedOutput) : containedWritePath(requestedOutput, ['.json']); + if (!outputPath) return { error: 'outputPath must be a .json file inside the project directory (not a symlink, not in .git)' }; + const requestedDbPath = resolveDbPathOption(input.dbPath, context); // An explicit file selection is a single-store read. Do not initialize or // migrate the unrelated default store just to export a snapshot. if (!requestedDbPath) await ensureInitialized(); const { listEntries } = await getMemoryFunctions(); - const outputPath = String(input.outputPath ?? ''); - if (!outputPath) return { error: 'outputPath is required' }; const namespace = input.namespace ? String(input.namespace) : undefined; if (namespace) { const v = validateIdentifier(namespace, 'namespace'); if (!v.valid) throw new Error(v.error); } // #2073: pass includeContent so the value field carries the actual @@ -1830,21 +1840,26 @@ export const memoryTools: MCPTool[] = [ }, required: ['inputPath'], }, - handler: async (input) => { - const dbPath = typeof input.dbPath === 'string' && input.dbPath.trim() - ? resolve(input.dbPath) - : undefined; + handler: async (input, context) => { + const dbPath = resolveDbPathOption(input.dbPath, context); await ensureInitialized(dbPath); const { storeEntry } = await getMemoryFunctions(); const t0 = Date.now(); // Values are re-embedded on import; count the vectors actually written // rather than reporting a constant 0 next to entries that show a vector. let vectors = 0; - const inputPath = String(input.inputPath ?? ''); - if (!inputPath || !existsSync(inputPath)) return { error: `File not found: ${inputPath || '(empty)'}` }; + const requestedInput = String(input.inputPath ?? ''); + const inputPath = !requestedInput ? null + : isLocalCliCall(context) ? (existsSync(requestedInput) ? resolve(requestedInput) : null) + : containedReadPath(requestedInput); + if (!inputPath) { + return { error: isLocalCliCall(context) || !requestedInput + ? `File not found: ${requestedInput || '(empty)'}` + : 'inputPath must be an existing regular file inside the project directory (not a symlink)' }; + } let doc: { entries?: Array<{ key: string; namespace?: string; value?: unknown; tags?: string[] | string }> }; try { doc = JSON.parse(readFileSync(inputPath, 'utf-8')); } - catch (e) { return { error: `Invalid export JSON: ${(e as Error).message}` }; } + catch { return { error: 'inputPath is not a valid memory export (JSON parse failed)' }; } const entries = Array.isArray(doc.entries) ? doc.entries : []; const nsOverride = input.namespace ? String(input.namespace) : undefined; if (nsOverride) { const v = validateIdentifier(nsOverride, 'namespace'); if (!v.valid) throw new Error(v.error); } diff --git a/v3/@claude-flow/cli/src/mcp-tools/neural-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/neural-tools.ts index c2eba57797..4ae1f13035 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/neural-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/neural-tools.ts @@ -13,6 +13,7 @@ */ import { type MCPTool, getProjectCwd } from './types.js'; +import { nullPrototypeRecords } from './record-store.js'; import { validateIdentifier, validateText } from './validate-input.js'; import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'; import { join } from 'node:path'; @@ -265,12 +266,17 @@ function loadNeuralStore(): NeuralStore { try { const path = getNeuralPath(); if (existsSync(path)) { - return JSON.parse(readFileSync(path, 'utf-8')); + const parsed = JSON.parse(readFileSync(path, 'utf-8')); + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) { + parsed.models = nullPrototypeRecords(parsed.models); + parsed.patterns = nullPrototypeRecords(parsed.patterns); + return parsed; + } } } catch { // Return empty store } - return { models: {}, patterns: {}, version: '3.0.0' }; + return { models: nullPrototypeRecords(undefined), patterns: nullPrototypeRecords(undefined), version: '3.0.0' }; } /** diff --git a/v3/@claude-flow/cli/src/mcp-tools/path-containment.ts b/v3/@claude-flow/cli/src/mcp-tools/path-containment.ts new file mode 100644 index 0000000000..9228b58bba --- /dev/null +++ b/v3/@claude-flow/cli/src/mcp-tools/path-containment.ts @@ -0,0 +1,119 @@ +/** + * Path checks for MCP tools that read or write a caller-named file. + * + * Paths in tool input come from whoever drives the MCP server, including a + * model following injected instructions. A tool that writes or reads such a + * path must keep it inside the project directory, and must not follow a + * symlink out of it. + */ + +import { closeSync, lstatSync, openSync, readSync, realpathSync } from 'node:fs'; +import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path'; +import { isNonProjectDir } from '@claude-flow/cli-core/mcp-tools/types'; +import { getProjectCwd } from './types.js'; +import { existingFileIsEncrypted } from '../fs-secure.js'; + +function lstatOrNull(p: string) { + try { return lstatSync(p); } catch { return null; } +} + +function projectRoot(): string | null { + const root = realpathSync(getProjectCwd()); + // A server started in a home or filesystem root has no project to contain + // writes to; "inside the root" would mean the whole home directory. + return isNonProjectDir(root) ? null : root; +} + +function insideRoot(root: string, target: string): boolean { + const rel = relative(root, target); + if (!rel || rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) return false; + return !rel.split(sep).includes('.git'); +} + +/** + * Resolve a caller-named output file inside the project. The real parent + * directory must be inside the real project root and outside `.git`, and an + * existing target must be a regular, non-executable file — not a symlink. + * `extensions`, when given, lists the allowed lower-case file extensions. + */ +export function containedWritePath(p: string, extensions?: readonly string[]): string | null { + if (!p || p.includes('\0')) return null; + try { + const root = projectRoot(); + if (!root) return null; + const abs = resolve(root, p); + if (extensions && !extensions.includes(extname(abs).toLowerCase())) return null; + const target = join(realpathSync(dirname(abs)), basename(abs)); + if (!insideRoot(root, target)) return null; + const existing = lstatOrNull(target); + if (existing && (existing.isSymbolicLink() || !existing.isFile() || (existing.mode & 0o111) !== 0)) return null; + return target; + } catch { + return null; + } +} + +/** Resolve a caller-named input file inside the project: a regular file, not a symlink. */ +export function containedReadPath(p: string): string | null { + if (!p || p.includes('\0')) return null; + try { + const root = projectRoot(); + if (!root) return null; + const abs = resolve(root, p); + const existing = lstatOrNull(abs); + if (!existing || existing.isSymbolicLink() || !existing.isFile()) return null; + const target = realpathSync(abs); + return insideRoot(root, target) ? target : null; + } catch { + return null; + } +} + +const DB_EXTENSIONS = ['.db', '.sqlite', '.sqlite3']; +const SQLITE_HEADER = 'SQLite format 3\0'; + +/** + * Check a caller-named memory database path. It may live outside the project + * (the CLI's `--path` flag passes one), so this does not contain it; instead + * it refuses anything that is not plainly a SQLite database (plaintext, or + * encrypted at rest per ADR-096), so the memory tools cannot be pointed at and + * overwrite an unrelated file. + */ +export function dbPathError(p: string): string | null { + if (p.includes('\0')) return 'dbPath contains a null byte'; + if (!DB_EXTENSIONS.includes(extname(p).toLowerCase())) { + return `dbPath must end in ${DB_EXTENSIONS.join(', ')}`; + } + const existing = lstatOrNull(p); + if (!existing) return null; + if (existing.isSymbolicLink()) return 'dbPath must not be a symlink'; + if (!existing.isFile()) return 'dbPath must be a regular file'; + if (existing.size === 0 || existingFileIsEncrypted(p) === true) return null; + const header = Buffer.alloc(SQLITE_HEADER.length); + let fd: number | undefined; + try { + fd = openSync(p, 'r'); + readSync(fd, header, 0, header.length, 0); + } catch { + return 'dbPath could not be read'; + } finally { + if (fd !== undefined) closeSync(fd); + } + return header.toString('latin1') === SQLITE_HEADER ? null : 'dbPath is not a SQLite database'; +} + +/** + * Marks a tool call made by the local CLI on the operator's behalf (for + * example `ruflo memory export --output ~/backup.json`). MCP requests arrive + * as JSON and cannot carry a symbol key, so this cannot be forged remotely. + */ +export const LOCAL_CLI_CALL: unique symbol = Symbol('ruflo.localCliCall'); + +export function localCliContext(): Record { + return { [LOCAL_CLI_CALL]: true } as unknown as Record; +} + +export function isLocalCliCall(context: unknown): boolean { + return !!context && typeof context === 'object' + && (context as Record)[LOCAL_CLI_CALL] === true; +} diff --git a/v3/@claude-flow/cli/src/mcp-tools/record-store.ts b/v3/@claude-flow/cli/src/mcp-tools/record-store.ts index a25c756e35..e309a374ff 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/record-store.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/record-store.ts @@ -1,12 +1,30 @@ import { readFileSync } from 'node:fs'; +/** + * Give a record map a null prototype. Record keys come from MCP tool input; on + * a plain object `__proto__` or `constructor` resolve to Object.prototype or a + * built-in, which a handler would then write into. A null-prototype map only + * ever returns its own records. + */ +export function nullPrototypeRecords(map: M | undefined | null): M { + if (map && typeof map === 'object' && !Array.isArray(map)) { + Object.setPrototypeOf(map, null); + return map; + } + return Object.create(null) as M; +} + /** Only an absent store is empty. Failed reads must never authorize replacement. */ export function readRecordStore(path: string, collection: string, empty: () => T): T { let text: string; try { text = readFileSync(path, 'utf-8'); } catch (error) { - if ((error as NodeJS.ErrnoException).code === 'ENOENT') return empty(); + if ((error as NodeJS.ErrnoException).code === 'ENOENT') { + const store = empty() as Record; + store[collection] = nullPrototypeRecords(store[collection] as object | undefined); + return store as T; + } throw error; } const store = JSON.parse(text); @@ -15,5 +33,6 @@ export function readRecordStore(path: string, collection: string, empty: () = || !records || typeof records !== 'object' || Array.isArray(records)) { throw new Error(`Invalid ${collection} store at ${path}; existing data was preserved`); } + nullPrototypeRecords(records); return store as T; } diff --git a/v3/@claude-flow/cli/src/mcp-tools/session-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/session-tools.ts index 95a683a2c2..bac822f7ea 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/session-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/session-tools.ts @@ -4,11 +4,12 @@ * Tool definitions for session management with file persistence. */ -import { existsSync, lstatSync, readFileSync, readdirSync, realpathSync, unlinkSync, statSync, writeFileSync } from 'node:fs'; +import { existsSync, readFileSync, readdirSync, unlinkSync, statSync, writeFileSync } from 'node:fs'; import { randomUUID } from 'node:crypto'; import { gunzipSync } from 'node:zlib'; -import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'; +import { join } from 'node:path'; import { type MCPTool, getProjectCwd } from './types.js'; +import { containedWritePath } from './path-containment.js'; import { mkdirRestricted, readFileMaybeEncrypted, @@ -406,34 +407,6 @@ function isSessionRecordLike(value: unknown): value is Partial { return 'data' in v || 'stats' in v || 'sessionId' in v || 'savedAt' in v; } -/** - * SECURITY: `outputPath` comes from MCP tool input. Resolve it against the - * project root and require the real (symlink-resolved) parent directory to stay - * inside the real project root, and refuse an existing symlink as the target, - * so session_export cannot write files elsewhere on the host. The CLI's - * `session export` writes its own file and does not pass outputPath. - */ -function containedExportPath(outputPath: string): string | null { - if (!outputPath || outputPath.includes('\0')) return null; - try { - const root = realpathSync(getProjectCwd()); - const abs = resolve(root, outputPath); - const parent = realpathSync(dirname(abs)); - const target = join(parent, basename(abs)); - const rel = relative(root, target); - if (!rel || rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel)) return null; - const existing = lstatOrNull(target); - if (existing && (existing.isSymbolicLink() || !existing.isFile())) return null; - return target; - } catch { - return null; - } -} - -function lstatOrNull(p: string) { - try { return lstatSync(p); } catch { return null; } -} - export const sessionTools: MCPTool[] = [ { name: 'session_save', @@ -806,7 +779,7 @@ export const sessionTools: MCPTool[] = [ let path: string | null = null; const outputPath = input.outputPath ? String(input.outputPath) : null; if (outputPath) { - const target = containedExportPath(outputPath); + const target = containedWritePath(outputPath); if (!target) return { sessionId, error: 'outputPath must be a file inside the project directory (no symlinks)' }; try { writeFileSync(target, JSON.stringify(session, null, 2), 'utf-8'); path = target; } catch (e) { return { sessionId, error: `Could not write ${outputPath}: ${(e as Error).message}` }; } diff --git a/v3/@claude-flow/cli/src/mcp-tools/swarm-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/swarm-tools.ts index ea7d5cd506..02afc94d41 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/swarm-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/swarm-tools.ts @@ -17,6 +17,7 @@ import { writeFileSync, } from 'node:fs'; import { join } from 'node:path'; +import { nullPrototypeRecords } from './record-store.js'; import { type MCPTool, getProjectCwd } from './types.js'; import { validateIdentifier } from './validate-input.js'; import { @@ -141,6 +142,8 @@ export function loadSwarmStore(): SwarmStore { store = JSON.parse(readFileSync(path, 'utf-8')); } } catch { /* fall through with default */ } + if (!store || typeof store !== 'object' || Array.isArray(store)) store = { swarms: {}, version: '3.0.0' }; + store.swarms = nullPrototypeRecords(store.swarms); // #1799 — reconcile orphans on every load and persist if anything changed. // Cheap (process.kill(pid, 0) is sub-millisecond) and means diff --git a/v3/@claude-flow/cli/src/mcp-tools/terminal-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/terminal-tools.ts index c997e87feb..995d930953 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/terminal-tools.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/terminal-tools.ts @@ -5,6 +5,7 @@ */ import { type MCPTool, getProjectCwd } from './types.js'; +import { nullPrototypeRecords } from './record-store.js'; import { existsSync } from 'node:fs'; import { mkdirRestricted, @@ -59,12 +60,16 @@ function loadTerminalStore(): TerminalStore { // ADR-096 Phase 3: readFileMaybeEncrypted handles both legacy // plaintext stores and post-migration encrypted ones via the RFE1 // magic-byte sniff. - return JSON.parse(readFileMaybeEncrypted(path, 'utf-8')); + const parsed = JSON.parse(readFileMaybeEncrypted(path, 'utf-8')); + if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) { + parsed.sessions = nullPrototypeRecords(parsed.sessions); + return parsed; + } } } catch { // Return empty store } - return { sessions: {}, version: '3.0.0' }; + return { sessions: nullPrototypeRecords(undefined), version: '3.0.0' }; } function saveTerminalStore(store: TerminalStore): void { diff --git a/v3/@claude-flow/cli/src/mcp-tools/validate-input.ts b/v3/@claude-flow/cli/src/mcp-tools/validate-input.ts index 3db293d2ca..8370728158 100644 --- a/v3/@claude-flow/cli/src/mcp-tools/validate-input.ts +++ b/v3/@claude-flow/cli/src/mcp-tools/validate-input.ts @@ -6,4 +6,24 @@ * when available, with lightweight fallback otherwise. */ +import { + validateIdentifier as coreValidateIdentifier, + type ValidationResult, +} from '@claude-flow/cli-core/mcp-tools/validate-input'; + export * from '@claude-flow/cli-core/mcp-tools/validate-input'; + +/** + * Names that resolve to Object.prototype or a built-in when used as a key on a + * plain object. Identifiers key the JSON record stores, so they are refused. + * Move this check into cli-core on its next release. + */ +const RESERVED_KEYS: ReadonlySet = new Set(['__proto__', 'constructor', 'prototype']); + +export function validateIdentifier(value: unknown, label: string): ValidationResult { + const result = coreValidateIdentifier(value, label); + if (result.valid && RESERVED_KEYS.has(result.sanitized)) { + return { valid: false, sanitized: '', error: `${label} must not be a reserved name (${result.sanitized})` }; + } + return result; +}