🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
fix(security): scan code patterns without the false positives seen on a real tree
Dragan Spiridonov3b4b91fcd5f3
diff --git a/v3/@claude-flow/cli/__tests__/security-scan-code-patterns.test.ts b/v3/@claude-flow/cli/__tests__/security-scan-code-patterns.test.tsnew file mode 100644index 0000000000..3f497f8548--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/security-scan-code-patterns.test.ts@@ -0,0 +1,202 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import type { CommandContext } from '../src/types.js';++vi.mock('../src/output.js', () => ({+ output: {+ writeln: () => {}, printJson: () => {}, printTable: () => {}, printBox: () => {}, printError: () => {}, printWarning: () => {},+ bold: (v: string) => v, dim: (v: string) => v, success: (v: string) => v, error: (v: string) => v, warning: (v: string) => v, info: (v: string) => v,+ createSpinner: () => ({ start: () => {}, setText: () => {}, succeed: () => {}, fail: () => {} }),+ },+}));++import { securityCommand } from '../src/commands/security.js';++const scan = securityCommand.subcommands!.find(command => command.name === 'scan')!;+let target: string;++type Finding = { severity: string; type: string; location: string };++async function findings(files: Record<string, string>): Promise<Finding[]> {+ for (const [name, body] of Object.entries(files)) {+ mkdirSync(join(target, name, '..'), { recursive: true });+ writeFileSync(join(target, name), body);+ }+ const ctx: CommandContext = { args: [], flags: { _: [], target, depth: 'standard', type: 'code', output: 'json' }, cwd: target, interactive: false };+ await scan.action!(ctx);+ return JSON.parse(readFileSync(join(target, '.claude/security-scans/scan-code-standard.json'), 'utf8')).findings;+}++const types = (rows: Finding[]) => rows.map(row => `${row.type} ${row.location}`).sort();++beforeEach(() => { target = mkdtempSync(join(tmpdir(), 'ruflo-scan-patterns-')); });+afterEach(() => { rmSync(target, { recursive: true, force: true }); });++describe('security scan code patterns: false positives seen on a real tree', () => {+ it('does not report eval inside a longer word such as "retrieval ("', async () => {+ expect(await findings({ 'copy.ts': 'export const label = "Memory + retrieval (vector) and private inference";\n' })).toEqual([]);+ });++ it('does not report execFile, or child_process named in comments and messages, as command injection', async () => {+ expect(await findings({+ 'discovery.ts': [+ '// TailscaleDiscovery only needs Node built-ins (`child_process.execFile`),',+ '/**',+ ' * No new dependency: shells out via `node:child_process.execFile`,',+ ' */',+ "const { execFile } = require('child_process'); execFile('tailscale', ['status', '--json']);",+ 'throw new Error("child_process.exec must never be called by a blocked stub");',+ ].join('\n'),+ })).toEqual([]);+ });++ it('does not report a numbered SQL placeholder ($${n}) as SQL injection', async () => {+ expect(await findings({+ 'store.js': [+ ' sql += ` AND t.category_id = $${paramCount}`;',+ ' sql += ` ORDER BY text_score DESC LIMIT $${paramCount + 1}`;',+ ].join('\n'),+ })).toEqual([]);+ });++ it('skips generated coverage and Playwright report bundles, known by their marker files', async () => {+ expect(await findings({+ 'coverage/coverage-final.json': '{}',+ 'coverage/prettify.js': 'el.innerHTML = html;\n',+ 'e2e/playwright-report/index.html': '<html></html>',+ 'e2e/playwright-report/trace/assets/view.js': 'node.innerHTML = s; eval(x);\n',+ })).toEqual([]);+ });++ it('does not report a URL or a pattern inside a string as a comment boundary', async () => {+ expect(await findings({ 'u.ts': "const u = 'http://x/*'; const v = 1;\n" })).toEqual([]);+ });+});++describe('security scan code patterns: real findings still reported', () => {+ it('reports eval calls, including window.eval', async () => {+ expect(types(await findings({ 'a.ts': 'eval(userInput);\nwindow.eval(bundle);\n' }))).toEqual(['Eval Usage a.ts:1', 'Eval Usage a.ts:2']);+ });++ it('reports exec and execSync called through child_process', async () => {+ expect(types(await findings({+ 'b.ts': "require('child_process').exec(`ls ${dir}`);\nchild_process.execSync(cmd);\n",+ }))).toEqual(['Command Injection b.ts:1', 'Command Injection b.ts:2']);+ });++ it('reports an interpolated value in SQL, also next to a placeholder', async () => {+ expect(types(await findings({+ 'c.ts': 'const sql = `SELECT * FROM users WHERE id = ${id}`;\nsql += ` AND a = $${n} AND b = ${name}`;\n',+ }))).toEqual(['SQL Injection c.ts:1', 'SQL Injection c.ts:2']);+ });++ it('reports innerHTML and dangerouslySetInnerHTML in source', async () => {+ expect(types(await findings({ 'src/d.tsx': 'el.innerHTML = html;\n<div dangerouslySetInnerHTML={{ __html: body }} />\n' })))+ .toEqual(['React XSS src/d.tsx:2', 'innerHTML src/d.tsx:1']);+ });+});++describe('security scan code patterns: shapes the narrowing must not hide', () => {+ it('scans code that shares a line with a comment, a generator method and JSX continuation lines', async () => {+ expect(types(await findings({+ 'e.tsx': [+ '/* route */ eval(userInput);',+ '/* start',+ ' end */ eval(userInput);',+ 'class A { * run() { eval(userInput); } }',+ ' * <span dangerouslySetInnerHTML={{ __html: userInput }} />',+ 'const x = 1 // eval(commented)',+ ].join('\n'),+ }))).toEqual(['Eval Usage e.tsx:1', 'Eval Usage e.tsx:3', 'Eval Usage e.tsx:4', 'React XSS e.tsx:5']);+ });++ it('reports execFile handed a shell, and exec through call/apply', async () => {+ expect(types(await findings({+ 'f.ts': [+ "require('child_process').execFile('sh', ['-c', userInput]);",+ "require('child_process').execFile('echo', [userInput], { shell: true });",+ "require('child_process').exec.call(null, userInput);",+ "require('child_process').exec/*why*/(userInput);",+ "require('child_process').execFile('git', ['status'], { shell: false });",+ "require('child_process').execFile('/bin/sh', ['-c', input]);",+ "require('child_process').execFile.call(null, 'sh', ['-c', input]);",+ "require('child_process').execFile('echo', [input], {'shell': true});",+ "require('child_process').exec?.(input);",+ "require('child_process')['exec'](input);",+ "const cp = require('child_process'); cp.exec(input); cp.execFile('git', ['status']);",+ ].join('\n'),+ }))).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].map(n => `Command Injection f.ts:${n}`).sort());+ });++ it('keeps a /* inside a regex or JSX text from hiding the lines after it', async () => {+ expect(types(await findings({+ 'h.tsx': "const r = /[/*]/;\neval(input);\nconst v = <p>don't</p>; const s = '/*';\neval(input);\n",+ }))).toEqual(['Eval Usage h.tsx:2', 'Eval Usage h.tsx:4']);+ });++ it('reports a $${value} that is quoted or not counter-shaped, as SQL injection', async () => {+ expect(types(await findings({+ 'g.ts': [+ "const sql = `SELECT * FROM users WHERE name = '$${userInput}'`;",+ 'const sql2 = `SELECT * FROM t WHERE id = $${userInput}`;',+ "const sql3 = `SELECT * FROM users WHERE name = 'prefix $${discount} suffix'`;",+ 'const sql4 = `SELECT * FROM t WHERE id = $${amount}`;',+ ].join('\n'),+ }))).toEqual(['SQL Injection g.ts:1', 'SQL Injection g.ts:2', 'SQL Injection g.ts:3', 'SQL Injection g.ts:4']);+ });++ it('still scans source in a folder named coverage, with or without report markers', async () => {+ expect(types(await findings({+ 'src/coverage/handler.ts': 'eval(userInput);\n',+ 'coverage/lcov.info': '',+ 'coverage/handler.ts': 'eval(userInput);\n',+ 'playwright-report/index.html': '',+ 'playwright-report/handler.ts': 'eval(userInput);\n',+ }))).toEqual(['Eval Usage coverage/handler.ts:1', 'Eval Usage playwright-report/handler.ts:1', 'Eval Usage src/coverage/handler.ts:1']);+ });++ it('scans a folder named constructor or __proto__', async () => {+ expect(types(await findings({ 'constructor/a.ts': 'eval(input);\n', '__proto__/b.ts': 'eval(input);\n' })))+ .toEqual(['Eval Usage __proto__/b.ts:1', 'Eval Usage constructor/a.ts:1']);+ });++ it('keeps a line-start /* in JSX text, never closed, from hiding the lines after it', async () => {+ expect(types(await findings({+ 'j.tsx': "const view = <p>\n/*\n</p>;\neval(input);\nrequire('child_process').exec(input);\n",+ }))).toEqual(['Command Injection j.tsx:5', 'Eval Usage j.tsx:4']);+ });++ it('reports a counter placeholder inside SQL quotes, wherever the quote count lands', async () => {+ expect(types(await findings({+ 'k.ts': [+ 'const label = "\'"; const sql = `SELECT \'$${paramCount}\'`;',+ 'const sql = `SELECT "$${paramCount}" FROM t`;',+ "const sql = `SELECT * FROM t WHERE name = 'prefix = $${paramCount} suffix'`;",+ ].join('\n'),+ }))).toEqual(['SQL Injection k.ts:1', 'SQL Injection k.ts:2', 'SQL Injection k.ts:3']);+ });++ it('reports execFile given an options variable, a chained argv, or exec passed around as a value', async () => {+ expect(types(await findings({+ 'm.ts': [+ "require('child_process').execFile('echo', [input], options);",+ "require('child_process').execFile('git', ['status'].concat(input));",+ "module.exports = require('child_process').exec;",+ "require('child_process').execFile('git', ['status'], (err, out) => done(out));",+ "require('child_process').execFile('git', ['status'], (options));",+ "require('child_process').execFile('git', ['status'], { ...options });",+ "const run = require('child_process').exec || fallback;",+ "const cp = require('child_process'); const run = cp.exec; cp.execFile('git', ['status']);",+ ].join('\n'),+ }))).toEqual([1, 2, 3, 5, 6, 7, 8].map(n => `Command Injection m.ts:${n}`));+ });++ it('scans a long minified line in linear time', async () => {+ const started = Date.now();+ await findings({ 'min.js': `const s = "${'$$" + "{'.repeat(32_000)}"; const sql = 1;\n` });+ expect(Date.now() - started).toBeLessThan(1_000);+ });+});+diff --git a/v3/@claude-flow/cli/src/commands/security-code-patterns.ts b/v3/@claude-flow/cli/src/commands/security-code-patterns.tsnew file mode 100644index 0000000000..4c1c529f2f--- /dev/null+++ b/v3/@claude-flow/cli/src/commands/security-code-patterns.ts@@ -0,0 +1,150 @@+/**+ * Line patterns for `security scan` phase 3, and what each line is tested on.+ *+ * The patterns are a heuristic, so each one is narrowed only where a false positive was seen on a real tree, and only+ * by a shape that is safe on its face:+ * - eval needs a word start: "retrieval (" in prose is not a call; `window.eval(` still is.+ * - command injection is any exec, execSync or execFile use (a call, `?.(`, `.call`/`.apply`/`.bind`, `['exec']`),+ * except execFile of a literal non-shell program with a literal argv array and no `shell` key on the line. The old+ * `exec[^S]` matched every execFile and the word in comments, and skipped execSync.+ * - a pg placeholder `$${paramCount + 1}` is a parameter number, not a value in the SQL text. Exempt only when the+ * expression is a number, a loop letter, an `.length`, or a name ending in Count/Index/Idx/Num/Pos, and the+ * placeholder is not inside a quoted SQL string; `'$${name}'`, `$${userInput}` and `'x $${discount} y'` are reported.+ * - comment text is removed before matching, not whole lines: code after a closing `*` + `/`, a generator method+ * `* run()` and JSX continuation lines are still scanned.+ */++export type CodePattern = {+ /** Tested on one comment-stripped line. */+ match: (line: string) => boolean+ type: string+ severity: 'high' | 'medium'+ desc: string+}++/** No `g` flag, so `test` keeps no lastIndex between lines. */+const re = (pattern: RegExp) => (line: string) => pattern.test(line)++const SHELL_PROGRAM = /^(?:.*[\\/])?(?:sh|bash|zsh|dash|ksh|fish|cmd(?:\.exe)?|powershell(?:\.exe)?|pwsh)$/i+// Every use of an exec function on a line, as a call or a value; `{ execFile }` in a destructure is a name, not a use.+const EXEC_ANY = /\bexec\w*\b(?!\s*[A-Za-z_$}:,])|\[\s*['"`]exec/g+const EXEC_USE = /child_process.*(?:\bexec(?:Sync|File|FileSync)?\b\s*(?:\(|\?\.\s*\(|\.(?:call|apply|bind)\b)|\[\s*['"`]exec\w*['"`]\s*\]|\.exec(?:Sync|File|FileSync)?\b(?!\s*[A-Za-z_$]))/+// A literal program, a literal argv array (nothing chained on it), then the end of the call, an options object literal+// with no computed key, or a callback. An options variable could carry `shell: true`, so it is not plain.+const PLAIN_EXEC_FILE = /\bexecFile(?:Sync)?\s*\(\s*(['"`])([^'"`$]+)\1\s*,\s*\[[^\][]*\]\s*(?:\)|,\s*\{(?:(?!\.\.\.)[^{}[\]])*\}\s*[,)]|,\s*(?:\((?:\s*[A-Za-z_$][\w$]*\s*,?)*\)\s*=>|function\b|async\b|[A-Za-z_$][\w$]*\s*=>))/++/** execFile of a literal, non-shell program with a literal argv array, and no `shell` anywhere on the line. */+const isPlainExecFile = (line: string): boolean => {+ const call = PLAIN_EXEC_FILE.exec(line)+ if (call === null || /shell/i.test(line) || SHELL_PROGRAM.test(call[2])) return false+ // Every exec use on the line must be that one call: `exec(x); execFile('git', [...])` is still reported.+ return (line.match(EXEC_ANY) ?? []).length === 1+}++const commandInjection = (line: string): boolean => EXEC_USE.test(line) && !isPlainExecFile(line)++const COUNTER = /^\s*(?:\d+|[ijkn]|[\w$.]+\.length|(?:[A-Za-z_$][\w$]*[a-z0-9])?(?:Count|Index|Idx|Num|Pos)|count|index|idx|num|pos)\s*(?:[+-]\s*\d+\s*)?$/+// Where a pg parameter stands in SQL: after a comparison, a list or call opener, or a clause keyword.+const PARAM_BEFORE = /(?:[=<>(,]|\b(?:LIMIT|OFFSET|IN|VALUES|BETWEEN|AND|OR|LIKE|ILIKE|SET|BY|THEN|ELSE|WHEN|IS))\s*$/i+const PARAM_AFTER = /^(?:\s|[,);]|::|$|`)/++/**+ * `$${paramCount}` / `LIMIT $${params.length + 1}`: the pg parameter number where SQL takes a value, not interpolated+ * SQL text. `'$${n}'`, `"$${n}"`, `$${userInput}` and `x $${discount}` keep their interpolation.+ */+export const withoutPlaceholders = (line: string): string =>+ line.replace(/\$\$\{([^}]*)\}/g, (match, expr: string, at: number) =>+ COUNTER.test(expr) && PARAM_BEFORE.test(line.slice(Math.max(0, at - 16), at)) && PARAM_AFTER.test(line.slice(at + match.length)) && !inSqlQuote(line, at) ? '' : match)++/** An odd count of `'` between the template literal's opening backtick and `at`: inside a quoted SQL string. */+const inSqlQuote = (line: string, at: number): boolean =>+ (line.slice(line.lastIndexOf('`', at) + 1, at).match(/'/g) ?? []).length % 2 === 1++/** The old `/\$\{.*\}.*sql|sql.*\$\{/i`, in linear time: a long minified line made the regex quadratic. */+const sqlInterpolation = (line: string): boolean => {+ const lower = line.toLowerCase()+ const open = line.indexOf('${')+ const close = open < 0 ? -1 : line.indexOf('}', open + 2)+ if (close >= 0 && lower.indexOf('sql', close + 1) >= 0) return true+ const sql = lower.indexOf('sql')+ return sql >= 0 && line.indexOf('${', sql + 3) >= 0+}++export const CODE_PATTERNS: readonly CodePattern[] = [+ { match: re(/(?<![\w$])eval\s*\(/), type: 'Eval Usage', severity: 'medium', desc: 'eval() can execute arbitrary code' },+ { match: re(/innerHTML\s*=/), type: 'innerHTML', severity: 'medium', desc: 'XSS risk with innerHTML' },+ { match: re(/dangerouslySetInnerHTML/), type: 'React XSS', severity: 'medium', desc: 'React XSS risk' },+ { match: commandInjection, type: 'Command Injection', severity: 'high', desc: 'Possible command injection' },+ { match: line => sqlInterpolation(line) && sqlInterpolation(withoutPlaceholders(line)), type: 'SQL Injection', severity: 'high', desc: 'Possible SQL injection' },+]++/**+ * The file's lines with comment text blanked (line count kept, so locations stay right). Strings are respected, so+ * `'http://x'` is not a comment; a template literal may span lines. Regex literals and JSX text are not parsed, so a+ * `//` or `/*` inside one is taken as a comment. That can only hide the rest of that one line: a block comment carries+ * to the next lines only when its `/*` starts the line, which a regex or JSX text never does.+ */+export function codeLinesOf(content: string): string[] {+ const out: string[] = []+ let inBlock = false+ let inTemplate = false++ let offset = 0++ for (const line of content.split('\n')) {+ let code = ''+ let quote: string | null = inTemplate ? '`' : null+ let carries = inBlock++ for (let i = 0; i < line.length; i++) {+ const ch = line[i]+ const next = line[i + 1]++ if (inBlock) {+ if (ch === '*' && next === '/') { inBlock = false; i++; code += ' ' }+ continue+ }+ if (ch === '\\') { code += ch + (next ?? ''); i++; continue }+ if (quote !== null) {+ if (ch === quote) quote = null+ code += ch+ continue+ }+ if (ch === '/' && next === '/') break+ if (ch === '/' && next === '*') {+ inBlock = true+ // Carried past this line only from a line-start opener that is closed later in the file: JSX text or a regex+ // never starts a line with an unclosed comment, so neither can blank the lines after it.+ carries = code.trim() === '' && content.indexOf('*/', offset + i + 2) >= 0+ i+++ code += ' '+ continue+ }+ if (ch === '"' || ch === "'" || ch === '`') quote = ch+ code += ch+ }++ if (inBlock && !carries) inBlock = false+ inTemplate = quote === '`'+ out.push(code)+ offset += line.length + 1+ }++ return out+}++/**+ * Generated report assets, named by what the report writes, inside a folder its marker file identifies. Only those+ * entries are skipped: other files in a folder that merely shares the name are still scanned.+ */+const REPORT_ASSETS = new Map<string, { markers: readonly string[]; assets: ReadonlySet<string> }>([+ ['coverage', { markers: ['coverage-final.json', 'lcov.info', 'clover.xml'], assets: new Set(['prettify.js', 'sorter.js', 'block-navigation.js', 'lcov-report']) }],+ ['playwright-report', { markers: ['index.html'], assets: new Set(['trace', 'data']) }],+])++/** True for an istanbul or Playwright asset, given its parent folder's name and what the parent folder holds. */+export function isGeneratedReportAsset(parentName: string, entryName: string, parentHas: (name: string) => boolean): boolean {+ // A Map, so a folder named `constructor` or `__proto__` is not looked up on Object.prototype.+ const report = REPORT_ASSETS.get(parentName)+ return report !== undefined && report.assets.has(entryName) && report.markers.some(parentHas)+}diff --git a/v3/@claude-flow/cli/src/commands/security.ts b/v3/@claude-flow/cli/src/commands/security.tsindex 70bb75162a..c765e3f19e 100644--- a/v3/@claude-flow/cli/src/commands/security.ts+++ b/v3/@claude-flow/cli/src/commands/security.ts@@ -11,6 +11,7 @@ import { execSync } from 'node:child_process';import { existsSync, statSync } from 'node:fs';import { resolve as resolvePath } from 'node:path';import { createBuiltinAIDefence, type DefenceEngine } from '../security/builtin-aidefence.js';+import { CODE_PATTERNS, codeLinesOf, isGeneratedReportAsset } from './security-code-patterns.js';// Accepted values for `security scan`'s enum flags — the single source of truth// for both validation and the traversal-depth maps below.@@ -292,14 +293,7 @@ const scanCommand: Command = {// Phase 3: Check for common security issues in codeif ((scanType === 'all' || scanType === 'code') && depth !== 'quick') {spinner.setText('Analyzing code patterns...');- const codePatterns = [- { pattern: /eval\s*\(/g, type: 'Eval Usage', severity: 'medium', desc: 'eval() can execute arbitrary code' },- { pattern: /innerHTML\s*=/g, type: 'innerHTML', severity: 'medium', desc: 'XSS risk with innerHTML' },- { pattern: /dangerouslySetInnerHTML/g, type: 'React XSS', severity: 'medium', desc: 'React XSS risk' },- { pattern: /child_process.*exec[^S]/g, type: 'Command Injection', severity: 'high', desc: 'Possible command injection' },- { pattern: /\$\{.*\}.*sql|sql.*\$\{/gi, type: 'SQL Injection', severity: 'high', desc: 'Possible SQL injection' },- ];-+ // The patterns, and the comment stripping they are tested after, live in security-code-patterns.ts.const scanCodeDir = (dir: string, depthLimit: number) => {// Positive-test rather than `<= 0`: undefined and NaN both fail this,// so a bad budget stops the recursion instead of disabling the limiter.@@ -309,15 +303,17 @@ const scanCommand: Command = {for (const entry of entries) {if (entry.name.startsWith('.') || entry.name === 'node_modules' || entry.name === 'dist') continue;const fullPath = path.join(dir, entry.name);+ // Coverage and Playwright report assets bundle third-party code (prettify, CodeMirror, React), not the project's.+ if (isGeneratedReportAsset(path.basename(dir), entry.name, name => fs.existsSync(path.join(dir, name)))) continue;if (entry.isDirectory()) {scanCodeDir(fullPath, depthLimit - 1);} else if (entry.isFile() && /\.(ts|js|tsx|jsx)$/.test(entry.name) && !entry.name.endsWith('.d.ts')) {try {const content = fs.readFileSync(fullPath, 'utf-8');- const lines = content.split('\n');+ const lines = codeLinesOf(content);for (let i = 0; i < lines.length; i++) {- for (const { pattern, type, severity, desc } of codePatterns) {- if (pattern.test(lines[i])) {+ for (const { match, type, severity, desc } of CODE_PATTERNS) {+ if (match(lines[i])) {if (severity === 'high') highCount++;else mediumCount++;findings.push({@@ -326,7 +322,6 @@ const scanCommand: Command = {location: `${path.relative(target, fullPath)}:${i + 1}`,description: desc,});- pattern.lastIndex = 0;}}}