mirror of
https://github.com/ruvnet/ruflo.git
synced 2026-11-23 21:59:14 +09:00
Merge pull request #3999 from proffesor-for-testing/fix/security-scan-false-positives
fix(security): scan code patterns without the false positives seen on a real tree
This commit is contained in:
3 files changed
+459
-12
No files matched your search
@@ -0,0 +1,275 @@
|
||||
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 child_process.execFile named in comments 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`,',
|
||||
' */',
|
||||
].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}`;',
|
||||
' const q = `SELECT * FROM t WHERE id IN ($${params.length}, $${values.length + 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 every exec use the old rule reported, execFile included, as command injection', async () => {
|
||||
const lines = [
|
||||
"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('/usr/bin/env', ['sh', '-c', userCmd]);",
|
||||
"require('child_process').execFile('node', ['-e', userCode]);",
|
||||
"require('child_process').execFileSync('bash.exe', ['-c', userCmd]);",
|
||||
"require('child_process').exec?.(input);",
|
||||
"require('child_process')['exec'](input);",
|
||||
"module.exports = require('child_process').exec;",
|
||||
"(require('child_process').exec as any)(cmd);",
|
||||
"const { exec } = require('child_process'); const run = promisify(exec);",
|
||||
"const { exec, execFile } = require('child_process'); register(exec, 1); execFile('git', ['status']);",
|
||||
"const {exec} = require('child_process'); Reflect.apply(exec, null, [input]);",
|
||||
"require('child_process').execFile('git', ['status'], (a = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx') => a);",
|
||||
];
|
||||
expect(types(await findings({ 'f.ts': lines.join('\n') })))
|
||||
.toEqual(lines.map((_, i) => `Command Injection f.ts:${i + 1}`).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('keeps a backtick misread in a regex or JSX from hiding later lines through a template /*', async () => {
|
||||
expect(types(await findings({
|
||||
'n.tsx': [
|
||||
'const Q = /[`]/;',
|
||||
'const t = `',
|
||||
'/* text',
|
||||
'`;',
|
||||
'eval(userInput);',
|
||||
"require('child_process').exec(userCmd);",
|
||||
"const glob = '**/*.ts';",
|
||||
'fetch(`https://api.example.com/${id}`); eval(userInput);',
|
||||
].join('\n'),
|
||||
}))).toEqual(['Command Injection n.tsx:6', 'Eval Usage n.tsx:5', 'Eval Usage n.tsx:8']);
|
||||
});
|
||||
|
||||
it('reports a counter placeholder that is not where SQL takes a value, or not param-named', async () => {
|
||||
expect(types(await findings({
|
||||
'p.ts': [
|
||||
'const sql = `SELECT x$${paramCount} FROM t`;',
|
||||
'const sql = `SELECT * FROM t WHERE id = $${paramCount}abc`;',
|
||||
'const sql = `SELECT * FROM t OFFSET $${pageNum}`;',
|
||||
'const sql = `SELECT * FROM t WHERE id = $${userIdx}`;',
|
||||
'const sql = `UPDATE t SET a = $${req.body.length}`;',
|
||||
].join('\n'),
|
||||
}))).toEqual([1, 2, 3, 4, 5].map(n => `SQL Injection p.ts:${n}`));
|
||||
});
|
||||
|
||||
it('scans report-named assets when their marker file is absent', async () => {
|
||||
expect(types(await findings({
|
||||
'coverage/prettify.js': 'el.innerHTML = html;\n',
|
||||
'playwright-report/trace/view.js': 'eval(x);\n',
|
||||
}))).toEqual(['Eval Usage playwright-report/trace/view.js:1', 'innerHTML coverage/prettify.js:1']);
|
||||
});
|
||||
|
||||
it('reads a regex literal as code, so a // or /* or backtick inside it hides nothing', async () => {
|
||||
expect(types(await findings({
|
||||
'r.ts': [
|
||||
'const r = /[//]/; eval(input);',
|
||||
'const s = /[/*]/; eval(input);',
|
||||
'const Q = /[`]/;',
|
||||
'const t = `',
|
||||
'/*',
|
||||
'* ${eval(input)}',
|
||||
'`;',
|
||||
'const half = a / b; eval(input); // eval(commented)',
|
||||
].join('\n'),
|
||||
}))).toEqual(['Eval Usage r.ts:1', 'Eval Usage r.ts:2', 'Eval Usage r.ts:6', 'Eval Usage r.ts:8']);
|
||||
});
|
||||
|
||||
it('keeps a URL after a backtick misread in JSX text from blanking the rest of its line', async () => {
|
||||
expect(types(await findings({
|
||||
'k.tsx': 'const v = <kbd>`</kbd>;\nfetch(`https://api.example.com/${id}`); eval(input);\n',
|
||||
}))).toEqual(['Eval Usage k.tsx:2']);
|
||||
});
|
||||
|
||||
it('reports a counter placeholder inside double-quoted SQL text, or after an escaped backtick in quotes', async () => {
|
||||
expect(types(await findings({
|
||||
'q.ts': [
|
||||
'const sql = `SELECT "x = $${paramCount} y" FROM t`;',
|
||||
"const sql = `SELECT 'x \\` = $${paramCount} y' FROM t`;",
|
||||
'const sql = `SELECT * FROM t WHERE id = $${userargs.length}`;',
|
||||
].join('\n'),
|
||||
}))).toEqual(['SQL Injection q.ts:1', 'SQL Injection q.ts:2', 'SQL Injection q.ts:3']);
|
||||
});
|
||||
|
||||
it('stays linear on lines of comment openers, placeholders and regex starts', async () => {
|
||||
const started = Date.now();
|
||||
await findings({
|
||||
'long.js': [
|
||||
'x; /* */'.repeat(16_000),
|
||||
'const sql = `SELECT ' + Array(8_000).fill('$${paramCount}').join(', ') + '`;',
|
||||
'(/'.repeat(16_000),
|
||||
'[/'.repeat(16_000),
|
||||
'x / '.repeat(64_000) + 'z',
|
||||
].join('\n'),
|
||||
});
|
||||
expect(Date.now() - started).toBeLessThan(1_000);
|
||||
});
|
||||
|
||||
it('scans many unclosed line-start comment openers in linear time', async () => {
|
||||
const started = Date.now();
|
||||
await findings({ 'open.js': '/* x\n'.repeat(40_000) + 'eval(input);\n' });
|
||||
expect(Date.now() - started).toBeLessThan(1_000);
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
/**
|
||||
* Line patterns for `security scan` phase 3, and what each line is tested on.
|
||||
*
|
||||
* The patterns are a heuristic. Each is narrowed only where a false positive was seen on a real tree, and only by a
|
||||
* shape that cannot carry the risk the rule looks for:
|
||||
* - every rule is tested after comment text is blanked, so a comment naming `child_process.execFile` or `eval(` is
|
||||
* not a finding;
|
||||
* - eval needs a word start: "retrieval (" in prose is not a call; `eval(` and `window.eval(` still are;
|
||||
* - command injection keeps the old rule's reach (any `exec` after `child_process` on the line), and no longer skips
|
||||
* execSync as `exec[^S]` did;
|
||||
* - a pg placeholder such as `$${paramCount + 1}` is a parameter number, not a value in the SQL text. It is exempt only
|
||||
* when its expression is a number, a loop letter, `params.length`-style, or a name containing `param` or `placeholder`, it
|
||||
* stands where SQL takes a value, and it is not inside a quoted SQL string.
|
||||
*/
|
||||
|
||||
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)
|
||||
|
||||
// A `.length` counts only on a param-, value- or arg-named array: `req.body.length` is whatever the client sent.
|
||||
const COUNTER = /^\s*(?:\d+|[ijkn]|(?:[A-Za-z_$][\w$]*(?:Params?|Placeholders?|Values?|Args?)|params?|placeholders?|values?|args?)\.length|[A-Za-z_$]*(?:[Pp]aram|[Pp]laceholder)[\w$]*)\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. One left-to-right
|
||||
* pass: quotes are counted since the last backtick, so a placeholder inside a quoted SQL string keeps its finding.
|
||||
*/
|
||||
export const withoutPlaceholders = (line: string): string => {
|
||||
const token = /\\[\s\S]|\$\$\{([^}]{0,80})\}|[`'"]/g
|
||||
let single = 0
|
||||
let double = 0
|
||||
let out = ''
|
||||
let kept = 0
|
||||
|
||||
for (let m = token.exec(line); m !== null; m = token.exec(line)) {
|
||||
if (m[0][0] === '\\') continue
|
||||
if (m[0] === '`') { single = 0; double = 0; continue }
|
||||
if (m[0] === "'") { single++; continue }
|
||||
if (m[0] === '"') { double++; continue }
|
||||
const end = m.index + m[0].length
|
||||
const isParam = single % 2 === 0 && double % 2 === 0 && COUNTER.test(m[1])
|
||||
&& PARAM_BEFORE.test(line.slice(Math.max(0, m.index - 16), m.index)) && PARAM_AFTER.test(line.slice(end, end + 2))
|
||||
if (isParam) { out += line.slice(kept, m.index); kept = end }
|
||||
}
|
||||
|
||||
return out + line.slice(kept)
|
||||
}
|
||||
|
||||
/** 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: re(/child_process.*exec/), 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 backtick inside one can be misread. The damage is bounded to one line: a block comment carries to the
|
||||
* next line only from a `/*` that starts its line, and only through lines that look like comment lines (they start
|
||||
* with `*` or contain the closing `*` + `/`). Any other line ends the carried comment and is scanned as code. One pass,
|
||||
* linear in the file size.
|
||||
*/
|
||||
export function codeLinesOf(content: string): string[] {
|
||||
const out: string[] = []
|
||||
let inBlock = false
|
||||
let inTemplate = false
|
||||
|
||||
for (const line of content.split('\n')) {
|
||||
if (inBlock && !/^\s*\*|\*\//.test(line)) inBlock = false
|
||||
const parts: string[] = []
|
||||
let tail = ''
|
||||
let hasCode = false
|
||||
let quote: string | null = inTemplate ? '`' : null
|
||||
let carries = inBlock
|
||||
// Parts plus a 12-character tail, not one growing string: slicing a concatenated string flattens it each time.
|
||||
const emit = (text: string) => {
|
||||
parts.push(text)
|
||||
tail = (tail + text).slice(-12)
|
||||
if (/\S/.test(text)) hasCode = true
|
||||
}
|
||||
|
||||
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++; emit(' ') }
|
||||
continue
|
||||
}
|
||||
if (ch === '\\') { emit(ch + (next ?? '')); i++; continue }
|
||||
if (quote !== null) {
|
||||
if (ch === quote) quote = null
|
||||
emit(ch)
|
||||
continue
|
||||
}
|
||||
// `://` is a URL scheme, not a comment.
|
||||
if (ch === '/' && next === '/' && line[i - 1] !== ':') break
|
||||
if (ch === '/' && next === '*') {
|
||||
inBlock = true
|
||||
carries = !hasCode
|
||||
i++
|
||||
emit(' ')
|
||||
continue
|
||||
}
|
||||
if (ch === '/' && REGEX_MAY_START.test(tail)) {
|
||||
const end = regexEnd(line, i)
|
||||
if (end > i) { emit(line.slice(i, end + 1)); i = end; continue }
|
||||
}
|
||||
if (ch === '"' || ch === "'" || ch === '`') quote = ch
|
||||
emit(ch)
|
||||
}
|
||||
|
||||
if (inBlock && !carries) inBlock = false
|
||||
inTemplate = quote === '`'
|
||||
out.push(parts.join(''))
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
/** Code so far ends where an expression starts, so a `/` there opens a regex literal, not a division. */
|
||||
const REGEX_MAY_START = /(?:^|[(,=:[!&|?{};+\-*%<>~^]|\b(?:return|typeof|case|do|else|in|of|void|yield|await))\s*$/
|
||||
|
||||
/**
|
||||
* The index of the `/` closing a regex literal that opens at `start`, or -1 when the line has none (then it was a
|
||||
* division). Its text is kept as code, so misreading a regex can only keep comment text, never blank code.
|
||||
*/
|
||||
function regexEnd(line: string, start: number): number {
|
||||
let inClass = false
|
||||
// Bounded, so a line of `(/` cannot make the stripper quadratic; a longer regex is read as code, which is safe.
|
||||
for (let i = start + 1; i < Math.min(line.length, start + 200); i++) {
|
||||
const ch = line[i]
|
||||
if (ch === '\\') { i++; continue }
|
||||
if (ch === '[') inClass = true
|
||||
else if (ch === ']') inClass = false
|
||||
else if (ch === '/' && !inClass) return i
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
/**
|
||||
* 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)
|
||||
}
|
||||
@@ -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 code
|
||||
if ((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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user