@yagyeshvyas/vibeguard 1.13.0 → 1.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +18 -2
  3. package/bin/cli.js +2753 -2753
  4. package/ci/vibeguard.yml +42 -42
  5. package/package.json +1 -1
  6. package/scripts/counts.js +93 -93
  7. package/scripts/postinstall.js +26 -26
  8. package/src/auto.js +427 -427
  9. package/src/daemon.js +343 -343
  10. package/src/dashboard.js +278 -278
  11. package/src/engine.js +297 -297
  12. package/src/hook.js +151 -151
  13. package/src/install.js +298 -298
  14. package/src/integrity.json +1 -1
  15. package/src/plugin.js +182 -182
  16. package/src/privacy-audit.js +272 -272
  17. package/src/repl.js +150 -150
  18. package/src/report.js +331 -331
  19. package/src/rules-pack.js +3068 -3068
  20. package/src/rules.js +1822 -1822
  21. package/src/sbom.js +193 -193
  22. package/src/scanner.js +1032 -1032
  23. package/src/shell-guard.js +302 -302
  24. package/src/slopsquat.js +144 -144
  25. package/src/trace.js +220 -220
  26. package/src/.vibeguard/cache/file-hashes.json +0 -60
  27. package/src/.vibeguard/latest-snapshot.json +0 -36
  28. package/src/.vibeguard/mcp-pins.json +0 -1
  29. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/auto.js +0 -428
  30. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/daemon.js +0 -344
  31. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/dashboard.js +0 -279
  32. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/engine.js +0 -297
  33. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/hook.js +0 -151
  34. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/install.js +0 -299
  35. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/manifest.json +0 -65
  36. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/mcp-server.js +0 -2051
  37. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/plugin.js +0 -168
  38. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/pre-deploy.js +0 -362
  39. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/repl.js +0 -150
  40. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/rules.js +0 -1611
  41. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/sbom.js +0 -164
  42. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/shell-guard.js +0 -292
  43. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/slopsquat.js +0 -144
  44. package/src/.vibeguard/snapshots/2026-08-05T16-23-50-635Z/trace.js +0 -220
  45. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/auto.js +0 -428
  46. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/daemon.js +0 -344
  47. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/engine.js +0 -297
  48. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/install.js +0 -299
  49. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/manifest.json +0 -37
  50. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/mcp-server.js +0 -2055
  51. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/plugin.js +0 -168
  52. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/pre-deploy.js +0 -362
  53. package/src/.vibeguard/snapshots/2026-08-05T16-26-26-074Z/trace.js +0 -220
  54. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/auto.js +0 -428
  55. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/daemon.js +0 -344
  56. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/dashboard.js +0 -279
  57. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/engine.js +0 -297
  58. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/hook.js +0 -151
  59. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/install.js +0 -299
  60. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/manifest.json +0 -65
  61. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/mcp-server.js +0 -2055
  62. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/plugin.js +0 -168
  63. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/pre-deploy.js +0 -362
  64. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/repl.js +0 -150
  65. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/rules.js +0 -1611
  66. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/sbom.js +0 -164
  67. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/shell-guard.js +0 -292
  68. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/slopsquat.js +0 -144
  69. package/src/.vibeguard/snapshots/2026-08-05T16-35-06-272Z/trace.js +0 -220
  70. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/auto.js +0 -428
  71. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/daemon.js +0 -344
  72. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/dashboard.js +0 -279
  73. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/engine.js +0 -297
  74. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/hook.js +0 -151
  75. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/install.js +0 -299
  76. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/manifest.json +0 -65
  77. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/mcp-server.js +0 -2054
  78. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/plugin.js +0 -168
  79. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/pre-deploy.js +0 -362
  80. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/repl.js +0 -150
  81. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/rules.js +0 -1611
  82. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/sbom.js +0 -164
  83. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/shell-guard.js +0 -292
  84. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/slopsquat.js +0 -144
  85. package/src/.vibeguard/snapshots/2026-08-05T18-08-40-613Z/trace.js +0 -220
  86. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/auto.js +0 -428
  87. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/daemon.js +0 -344
  88. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/engine.js +0 -297
  89. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/install.js +0 -299
  90. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/manifest.json +0 -37
  91. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/mcp-server.js +0 -2055
  92. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/plugin.js +0 -168
  93. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/pre-deploy.js +0 -362
  94. package/src/.vibeguard/snapshots/2026-08-05T18-11-32-644Z/trace.js +0 -220
  95. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/auto.js +0 -428
  96. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/daemon.js +0 -344
  97. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/engine.js +0 -297
  98. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/manifest.json +0 -33
  99. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/mcp-server.js +0 -2055
  100. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/rules.js +0 -1611
  101. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/shell-guard.js +0 -292
  102. package/src/.vibeguard/snapshots/2026-08-05T18-16-47-635Z/trace.js +0 -220
  103. package/src/.vibeguard-baseline.json +0 -5226
package/src/scanner.js CHANGED
@@ -1,1032 +1,1032 @@
1
- 'use strict';
2
-
3
- const fs = require('fs');
4
- const path = require('path');
5
- const crypto = require('crypto');
6
-
7
- // Stable fingerprint: survives line moves (no line number), used for SARIF
8
- // partialFingerprints and the scan --new-only baseline diff.
9
- function fingerprintOf(f) {
10
- return crypto
11
- .createHash('sha1')
12
- .update(`${f.ruleId} ${f.file} ${(f.snippet || '').trim()}`)
13
- .digest('hex')
14
- .slice(0, 16);
15
- }
16
- const rules = require('./rules');
17
- const {
18
- SEVERITY_ORDER,
19
- lineRules,
20
- fileRules,
21
- crossFileRules,
22
- makeFinding,
23
- matchAll,
24
- requiredLiteral,
25
- isCommentLine,
26
- } = rules;
27
-
28
- // Load optional project config (.vibeguardrc.json / vibeguard.config.json).
29
- // Currently supports { "shapingFunctions": ["toDTO", ...] } to extend the
30
- // redaction allowlist. Best-effort: bad/missing config = defaults.
31
- function loadConfig(root) {
32
- for (const name of ['.vibeguardrc.json', 'vibeguard.config.json']) {
33
- try {
34
- const p = path.join(root, name);
35
- if (fs.existsSync(p)) return JSON.parse(fs.readFileSync(p, 'utf8'));
36
- } catch {
37
- /* ignore malformed config */
38
- }
39
- }
40
- return {};
41
- }
42
-
43
- // Directories we never walk into.
44
- const SKIP_DIRS = new Set([
45
- 'node_modules',
46
- '.git',
47
- '.vibeguard', // our own cache/baseline artifacts — never scan them
48
- 'dist',
49
- 'build',
50
- '.next',
51
- 'out',
52
- 'coverage',
53
- '.cache',
54
- 'vendor',
55
- '.venv',
56
- 'venv',
57
- '__pycache__',
58
- ]);
59
-
60
- // Only text-ish source/config files. Everything else is skipped as binary/noise.
61
- const SCAN_EXT = new Set([
62
- '.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs',
63
- '.py', '.rb', '.php', '.go', '.java', '.cs', '.rs',
64
- '.sh', '.bash', '.sql',
65
- '.json', '.yml', '.yaml', '.toml', '.ini', '.xml',
66
- '.env', '.html', '.vue', '.svelte',
67
- '.txt', '.md', '.pem', '.key',
68
- '.tf', '.hcl', '.dockerfile', '.rules',
69
- ]);
70
-
71
- // Files without a "normal" extension we still want to read (dotfiles etc.).
72
- const SCAN_BASENAMES = new Set([
73
- '.env', '.env.local', '.env.development', '.env.production',
74
- '.npmrc', 'Dockerfile', '.dockerenv',
75
- ]);
76
-
77
- const MAX_FILE_BYTES = 2 * 1024 * 1024; // 2MB — skip anything huge.
78
-
79
- function shouldScanFile(filePath) {
80
- const base = path.basename(filePath);
81
- if (base === '.vibeguard-baseline.json') return false; // our own artifact
82
- if (SCAN_BASENAMES.has(base)) return true;
83
- if (base.startsWith('.env')) return true;
84
- const ext = path.extname(filePath).toLowerCase();
85
- return SCAN_EXT.has(ext);
86
- }
87
-
88
- // Files staged for commit (git diff --cached), as a Set of absolute paths.
89
- // Returns null when not a git repo / git unavailable, so the caller can decide.
90
- function getStagedFiles(root) {
91
- try {
92
- const { execFileSync } = require('child_process');
93
- const out = execFileSync('git', ['diff', '--cached', '--name-only', '--diff-filter=ACM'], {
94
- cwd: root,
95
- encoding: 'utf8',
96
- stdio: ['ignore', 'pipe', 'ignore'],
97
- });
98
- const set = new Set();
99
- for (const rel of out.split(/\r?\n/)) {
100
- const t = rel.trim();
101
- if (t) set.add(path.resolve(root, t));
102
- }
103
- return set;
104
- } catch {
105
- return null; // not a git repo, or git not installed
106
- }
107
- }
108
-
109
- // Recursively collect scannable files.
110
- function walk(dir, out, rootStat) {
111
- let entries;
112
- try {
113
- entries = fs.readdirSync(dir, { withFileTypes: true });
114
- } catch {
115
- return out;
116
- }
117
- for (const entry of entries) {
118
- const full = path.join(dir, entry.name);
119
- if (entry.isDirectory()) {
120
- if (SKIP_DIRS.has(entry.name)) continue;
121
- walk(full, out, rootStat);
122
- } else if (entry.isFile()) {
123
- if (!shouldScanFile(full)) continue;
124
- try {
125
- const st = fs.statSync(full);
126
- if (st.size > MAX_FILE_BYTES) continue;
127
- } catch {
128
- continue;
129
- }
130
- out.push(full);
131
- }
132
- }
133
- return out;
134
- }
135
-
136
- // Naive check: is character offset `idx` inside a quoted string literal on this
137
- // line? Tracks ' " ` state left-to-right. Used to suppress code-pattern matches
138
- // that are actually text (e.g. the word eval() inside a message string).
139
- function isInsideString(line, idx) {
140
- let quote = null;
141
- for (let i = 0; i < idx && i < line.length; i++) {
142
- const c = line[i];
143
- if (quote) {
144
- if (c === '\\') i++; // skip escaped char
145
- else if (c === quote) quote = null;
146
- } else if (c === '"' || c === "'" || c === '`') {
147
- quote = c;
148
- }
149
- }
150
- return quote !== null;
151
- }
152
-
153
- // Cheap binary sniff: NUL byte in the first chunk.
154
- function looksBinary(buf) {
155
- const n = Math.min(buf.length, 8000);
156
- for (let i = 0; i < n; i++) if (buf[i] === 0) return true;
157
- return false;
158
- }
159
-
160
- // `diag` (optional): a collector { degraded: [] } into which each analysis pass
161
- // records a failure instead of swallowing it silently. A security scanner that
162
- // fails open MUST surface that it did so — a quietly-skipped pass is a coverage
163
- // hole the user never sees. Backward compatible: omit diag and behavior is old.
164
- function scanFileContent(absPath, relPath, content, tree, diag) {
165
- const noteDegraded = (pass, err) => {
166
- if (diag && Array.isArray(diag.degraded)) {
167
- diag.degraded.push({ file: relPath, pass, error: String((err && err.message) || err || 'unknown') });
168
- }
169
- };
170
- let findings = [];
171
- const lines = content.split(/\r?\n/);
172
-
173
- // fileFilter depends only on the path, not the line — compute the applicable
174
- // rule set ONCE per file instead of re-testing (and recompiling) a fileFilter
175
- // regex on every line. Compiled fileFilters are cached on the rule object.
176
- const activeRules = [];
177
- for (const rule of lineRules) {
178
- if (!rule.re) continue; // match()-based line rules (no regex) — inert until a line-level match hook exists
179
- if (rule.fileFilter) {
180
- let ff = rule._ffRe;
181
- if (!ff) {
182
- ff = typeof rule.fileFilter === 'string' ? new RegExp(rule.fileFilter) : rule.fileFilter;
183
- rule._ffRe = ff;
184
- }
185
- if (!ff.test(relPath)) continue;
186
- }
187
- // Precompute a mandatory literal once per rule (cached). '' = none extractable.
188
- if (rule._lit === undefined) rule._lit = requiredLiteral(rule.re.source) || '';
189
- activeRules.push(rule);
190
- }
191
-
192
- for (let i = 0; i < lines.length; i++) {
193
- const line = lines[i];
194
- if (line.length > 4000) continue; // minified blob line — skip.
195
- const commented = isCommentLine(line);
196
- const lineLower = line.toLowerCase();
197
- for (const rule of activeRules) {
198
- if (rule.skipComments && commented) continue;
199
- // Cheap literal prefilter: if the rule's mandatory literal isn't on this
200
- // line, the regex cannot match — skip it without running the regex.
201
- if (rule._lit && !lineLower.includes(rule._lit)) continue;
202
- for (const hit of matchAll(rule.re, line)) {
203
- if (rule.skipInString && isInsideString(line, hit.index)) continue;
204
- if (rule.filter && !rule.filter(line, hit, lines)) continue;
205
- findings.push(
206
- makeFinding(rule, {
207
- file: relPath,
208
- line: i + 1,
209
- column: hit.index + 1,
210
- snippet: redactSnippet(line.trim(), hit.match),
211
- })
212
- );
213
- }
214
- }
215
- }
216
-
217
- // Dataflow/taint analysis: follows user input across lines to a dangerous sink.
218
- try {
219
- const { analyzeTaint } = require('./taint');
220
- // A crash inside the AST pass falls back to regex taint rather than losing
221
- // the file entirely — but it is recorded, because every dataflow-confirmed
222
- // finding disappears when that happens and the grade would otherwise look
223
- // clean. `--strict` turns this into a hard failure.
224
- const onDegrade = (err) => noteDegraded('taint-ast', err);
225
- for (const t of analyzeTaint(content, lines, relPath, tree, onDegrade)) findings.push(t);
226
- } catch (err) {
227
- noteDegraded('taint', err);
228
- }
229
-
230
- // Python taint analysis for .py files (advanced multi-pass engine)
231
- if (relPath && relPath.endsWith('.py')) {
232
- try {
233
- const { analyzePythonTaintAdvanced } = require('./taint-py');
234
- for (const t of analyzePythonTaintAdvanced(content, lines, relPath)) findings.push(t);
235
- } catch (err) {
236
- // Fallback to legacy engine
237
- try {
238
- const { analyzePythonTaint } = require('./engine');
239
- for (const t of analyzePythonTaint(content, lines, relPath)) findings.push(t);
240
- } catch (e) {
241
- noteDegraded('python-taint', e);
242
- }
243
- }
244
- }
245
-
246
- // Optional AST pass (acorn) — precise eval/exec/Function/mass-assignment/nosql.
247
- try {
248
- const { analyzeAst, AST_SUPERSEDES } = require('./ast');
249
- const ast = analyzeAst(content, relPath, tree); // tree cached by the caller
250
- if (ast.parsed) {
251
- // AST is precise for these categories — drop the regex heuristics for this
252
- // file so we don't double-report or carry their false positives.
253
- findings = findings.filter((f) => !AST_SUPERSEDES.has(f.ruleId));
254
- }
255
- for (const a of ast.findings) findings.push(a);
256
- } catch (err) {
257
- noteDegraded('ast', err);
258
- }
259
-
260
- // Obfuscation / backdoor analysis: decodes encoded payloads and correlates
261
- // capabilities (exec + net + env) that no honest source file needs. Runs on
262
- // every text file; the analyzer itself skips minified bundles/lockfiles.
263
- try {
264
- const { analyzeObfuscation } = require('./obfuscation');
265
- for (const o of analyzeObfuscation(content, relPath)) findings.push(o);
266
- } catch (err) {
267
- noteDegraded('obfuscation', err);
268
- }
269
-
270
- // File-level rules (need whole-file context). Pass prior findings so rules
271
- // can suppress noise that a line-level rule already reported (e.g. the
272
- // high-entropy hint shouldn't double-fire on a line a specific secret rule
273
- // already flagged). Backward compatible: rules that ignore the arg are fine.
274
- for (const rule of fileRules) {
275
- let hits = [];
276
- try {
277
- if (typeof rule.match === 'function') {
278
- // Function-based rule (no regex): match(content, ctx) -> [{ index, match }].
279
- const raw = rule.match(content, { lines, relPath, findings }) || [];
280
- hits = raw.map((h) => {
281
- const before = content.slice(0, h.index);
282
- const ln = before.split('\n').length - 1;
283
- return {
284
- line: ln + 1,
285
- column: before.length - before.lastIndexOf('\n'),
286
- snippet: redactSnippet((lines[ln] || '').trim(), h.match),
287
- };
288
- });
289
- } else {
290
- hits = rule.run(content, lines, relPath, findings) || [];
291
- }
292
- } catch (err) {
293
- noteDegraded(`file-rule:${rule.id || 'unknown'}`, err);
294
- hits = [];
295
- }
296
- for (const h of hits) {
297
- findings.push(
298
- makeFinding(rule, {
299
- file: relPath,
300
- line: h.line,
301
- column: h.column || 1,
302
- snippet: h.snippet,
303
- message: h.message,
304
- fix: h.fix,
305
- severity: h.severity, // per-hit overrides (makeFinding falls back to rule)
306
- confidence: h.confidence,
307
- ruleId: h.ruleId,
308
- title: h.title,
309
- })
310
- );
311
- }
312
- }
313
-
314
- // Plugin file-level rules (v2 plugin system).
315
- try {
316
- const { getPluginFileRules } = require('./plugin');
317
- const pFileRules = getPluginFileRules();
318
- for (const rule of pFileRules) {
319
- let hits = [];
320
- try {
321
- hits = rule.run(content, lines, relPath) || [];
322
- } catch (err) {
323
- noteDegraded(`plugin-file-rule:${rule.id || 'unknown'}`, err);
324
- hits = [];
325
- }
326
- for (const h of hits) {
327
- findings.push(
328
- makeFinding(rule, {
329
- file: relPath,
330
- line: h.line,
331
- column: h.column || 1,
332
- snippet: h.snippet,
333
- message: h.message,
334
- fix: h.fix,
335
- severity: h.severity,
336
- confidence: h.confidence,
337
- ruleId: h.ruleId,
338
- title: h.title,
339
- })
340
- );
341
- }
342
- }
343
- } catch { /* plugin file rules are best-effort */ }
344
-
345
- return findings;
346
- }
347
-
348
- // Never echo a full secret back into a report/log. Show a masked snippet.
349
- function redactSnippet(line, match) {
350
- if (!match || match.length < 8) return truncate(line);
351
- const masked = match.slice(0, 4) + '****' + match.slice(-2);
352
- return truncate(line.split(match).join(masked));
353
- }
354
-
355
- function truncate(s) {
356
- return s.length > 160 ? s.slice(0, 157) + '...' : s;
357
- }
358
-
359
- // ---------------------------------------------------------------------------
360
- // Project-level rules
361
- // ---------------------------------------------------------------------------
362
-
363
- function projectScan(root) {
364
- const findings = [];
365
- const gitignorePath = path.join(root, '.gitignore');
366
- let gitignore = '';
367
- try {
368
- gitignore = fs.readFileSync(gitignorePath, 'utf8');
369
- } catch {
370
- gitignore = '';
371
- }
372
- const ignoreLines = gitignore
373
- .split(/\r?\n/)
374
- .map((l) => l.trim())
375
- .filter(Boolean);
376
-
377
- const envIsIgnored = ignoreLines.some((l) =>
378
- /^\.env($|\.|\/|\*)/.test(l) || l === '.env*' || l === '*.env'
379
- );
380
-
381
- // .env present but not gitignored -> critical.
382
- const envFiles = ['.env', '.env.local', '.env.production', '.env.development'];
383
- for (const name of envFiles) {
384
- const p = path.join(root, name);
385
- if (fs.existsSync(p)) {
386
- if (!envIsIgnored) {
387
- findings.push({
388
- ruleId: 'project.env-not-ignored',
389
- severity: 'critical',
390
- title: '.env not in .gitignore',
391
- message: `${name} exists but is not covered by .gitignore — secrets can be committed and pushed.`,
392
- fix: `Add ".env" (and ".env.*") to .gitignore, then remove it from git history if already committed (git rm --cached ${name}).`,
393
- file: name,
394
- line: 1,
395
- column: 1,
396
- snippet: `${name} present, .gitignore does not cover it`,
397
- });
398
- }
399
- }
400
- }
401
-
402
- // A committed .git folder inside a subpath, or a tracked .env that is world-exposed
403
- // via a public dir — flag .env living under a web/public/static dir.
404
- const exposedDirs = ['public', 'static', 'dist', 'www'];
405
- for (const d of exposedDirs) {
406
- for (const name of ['.env', '.env.local']) {
407
- const p = path.join(root, d, name);
408
- if (fs.existsSync(p)) {
409
- findings.push({
410
- ruleId: 'project.env-exposed',
411
- severity: 'critical',
412
- title: '.env inside a public directory',
413
- message: `${d}/${name} sits in a publicly served directory and may be downloadable.`,
414
- fix: `Move ${name} out of ${d}/ and load config from environment variables.`,
415
- file: `${d}/${name}`,
416
- line: 1,
417
- column: 1,
418
- snippet: `${d}/${name} is web-served`,
419
- });
420
- }
421
- }
422
- }
423
-
424
- // package.json present but no lockfile -> non-reproducible installs.
425
- if (fs.existsSync(path.join(root, 'package.json'))) {
426
- const lockfiles = ['package-lock.json', 'yarn.lock', 'pnpm-lock.yaml', 'npm-shrinkwrap.json'];
427
- if (!lockfiles.some((l) => fs.existsSync(path.join(root, l)))) {
428
- findings.push({
429
- ruleId: 'package.no-lockfile',
430
- severity: 'low',
431
- confidence: 'high',
432
- title: 'No dependency lockfile',
433
- message: 'package.json exists but no lockfile is committed — installs are not reproducible and pull the newest matching versions (supply-chain drift).',
434
- fix: 'Commit a lockfile (package-lock.json / yarn.lock / pnpm-lock.yaml).',
435
- file: 'package.json',
436
- line: 1,
437
- column: 1,
438
- snippet: 'no lockfile found',
439
- });
440
- }
441
- }
442
-
443
- return findings;
444
- }
445
-
446
- // ---------------------------------------------------------------------------
447
- // Grading
448
- // ---------------------------------------------------------------------------
449
-
450
- const TIER = ['critical', 'high', 'medium', 'low'];
451
-
452
- // Grade off EFFECTIVE severity: low-confidence findings are heuristics ("review
453
- // this"), so they count one tier lower and low-confidence 'low' is ignored for
454
- // the grade. This keeps a single heuristic hint from tanking an otherwise clean
455
- // project, while confirmed issues still drive the grade hard.
456
- function effectiveSeverity(f) {
457
- let sev = f.severity;
458
- if (f.confidence === 'low') {
459
- const i = TIER.indexOf(sev);
460
- sev = TIER[i + 1] || null; // low-confidence 'low' -> null (ignored)
461
- }
462
- // Optional reachability weighting: dead-code findings grade one tier lower.
463
- // A critical sink in code no route imports still lands at 'high' — visible,
464
- // just not grade-destroying.
465
- if (f._reachDemote && sev) {
466
- const idx = TIER.indexOf(sev);
467
- if (idx >= 0 && idx < TIER.length - 1) sev = TIER[idx + 1];
468
- }
469
- return sev;
470
- }
471
-
472
- // Minimal glob -> RegExp: supports *, **, and gitignore-style "**/" (zero+ dirs).
473
- function globToRe(glob) {
474
- const esc = glob.replace(/[.+^${}()|[\]\\]/g, '\\$&');
475
- const body = esc.replace(/\*\*\/|\*\*|\*/g, (m) =>
476
- m === '**/' ? '(?:.*/)?' : m === '**' ? '.*' : '[^/]*'
477
- );
478
- return new RegExp('^' + body + '$');
479
- }
480
-
481
- // Inline suppression comments:
482
- // // vibeguard-ignore-line [rule1, rule2] -> suppress on this line
483
- // // vibeguard-ignore-next-line [rule1, ...] -> suppress on the next line
484
- // No rule list = suppress everything on the target line. Works with //, #, /* */.
485
- function buildIgnoreMap(lines) {
486
- const map = new Map(); // targetLine(1-based) -> Set(ruleIds) | '*'
487
- const re = /(?:\/\/|#|\/\*|\*)\s*vibeguard-ignore(-next)?-line\b([^*\n]*)/i;
488
- for (let i = 0; i < lines.length; i++) {
489
- const m = re.exec(lines[i]);
490
- if (!m) continue;
491
- const target = m[1] ? i + 2 : i + 1; // next-line -> i+2 (1-based)
492
- const rulesPart = (m[2] || '').replace(/\*\/.*/, '').trim();
493
- const rules = rulesPart
494
- ? rulesPart.split(/[\s,]+/).filter(Boolean)
495
- : '*';
496
- const existing = map.get(target);
497
- if (existing === '*' || rules === '*') map.set(target, '*');
498
- else map.set(target, new Set([...(existing || []), ...rules]));
499
- }
500
- return map;
501
- }
502
-
503
- function applyInlineSuppressions(findings, contents) {
504
- const byFile = new Map();
505
- for (const c of contents) byFile.set(c.rel, buildIgnoreMap(c.lines));
506
- return findings.filter((f) => {
507
- const map = byFile.get(f.file);
508
- if (!map) return true;
509
- const entry = map.get(f.line);
510
- if (!entry) return true;
511
- if (entry === '*') return false;
512
- return !entry.has(f.ruleId);
513
- });
514
- }
515
-
516
- // Apply project config: drop ignored rules/paths, remap severities.
517
- // config = { ignoreRules:[ruleId], ignorePaths:[glob], ignore:[{rule,path}],
518
- // severityOverrides:{ruleId: 'low'} }
519
- function applyConfigFilters(findings, config) {
520
- if (!config || typeof config !== 'object') return findings;
521
- const ignoreRules = new Set(Array.isArray(config.ignoreRules) ? config.ignoreRules : []);
522
- const ignorePathRes = (Array.isArray(config.ignorePaths) ? config.ignorePaths : []).map(globToRe);
523
- const pairIgnores = (Array.isArray(config.ignore) ? config.ignore : []).filter(
524
- (x) => x && typeof x === 'object'
525
- );
526
- const sevOverride = config.severityOverrides && typeof config.severityOverrides === 'object'
527
- ? config.severityOverrides
528
- : {};
529
- const validSev = new Set(['critical', 'high', 'medium', 'low']);
530
-
531
- return findings
532
- .filter((f) => {
533
- if (ignoreRules.has(f.ruleId)) return false;
534
- if (ignorePathRes.some((re) => re.test(f.file))) return false;
535
- for (const pair of pairIgnores) {
536
- const ruleMatch = !pair.rule || pair.rule === f.ruleId;
537
- const pathMatch = !pair.path || globToRe(pair.path).test(f.file) || f.file.includes(pair.path);
538
- if (ruleMatch && pathMatch) return false;
539
- }
540
- return true;
541
- })
542
- .map((f) => {
543
- const ov = sevOverride[f.ruleId];
544
- if (ov && validSev.has(ov)) return { ...f, severity: ov };
545
- return f;
546
- });
547
- }
548
-
549
- function computeGrade(findings) {
550
- // Reported counts are the real severities (what the user sees).
551
- const counts = { critical: 0, high: 0, medium: 0, low: 0 };
552
- for (const f of findings) counts[f.severity] = (counts[f.severity] || 0) + 1;
553
-
554
- // Grade counts use effective severity.
555
- const g = { critical: 0, high: 0, medium: 0, low: 0 };
556
- for (const f of findings) {
557
- const s = effectiveSeverity(f);
558
- if (s) g[s] += 1;
559
- }
560
-
561
- let grade;
562
- if (g.critical > 0) grade = 'F';
563
- else if (g.high > 0) grade = g.high >= 3 ? 'D' : 'C';
564
- else if (g.medium > 0) grade = g.medium >= 3 ? 'C' : 'B';
565
- else if (g.low > 0) grade = 'B';
566
- else grade = 'A';
567
-
568
- return { grade, counts };
569
- }
570
-
571
- // Collapse noise: on a single file:line, a specific rule supersedes the generic
572
- // credential catch-all (e.g. a weak session secret shouldn't also report as a
573
- // bare "hardcoded credential"). Also drop exact duplicate (ruleId+file+line).
574
- //
575
- // Additionally: when a dataflow-confirmed taint.* finding and a structural ast.*
576
- // finding land on the same file:line and describe the same vulnerability category,
577
- // keep only the taint finding (higher confidence) and drop the ast.* duplicate.
578
- // Map: taint.command-injection ↔ ast.command-injection, etc.
579
- /*
580
- * Which lower-fidelity findings a stronger finding supersedes on the same
581
- * file:line.
582
- *
583
- * Two rules that describe the same vulnerability on the same line are one
584
- * finding reported twice. The higher-fidelity rule wins and the rest are
585
- * dropped: a taint.* finding proves the path from source to sink, whereas a
586
- * regex rule only pattern-matched the text; and among overlapping regex rules
587
- * the higher-confidence, more specific one wins.
588
- *
589
- * Keys are the superseding rule; values are every rule it can shadow.
590
- */
591
- const TAINT_SUPERSEDES = {
592
- 'taint.command-injection': ['ast.command-injection'],
593
- 'taint.sql-injection': [
594
- 'ast.sql-injection',
595
- 'code.sql-injection',
596
- 'db.sql-template-literal',
597
- 'injection.orm-raw-user',
598
- ],
599
- 'taint.code-injection': ['ast.eval-dynamic'],
600
- 'taint.path-traversal': ['ast.path-traversal', 'upload.filename-path-traversal'],
601
- 'taint.ssrf': ['ast.ssrf'],
602
- // Go: three rules match the same `db.Query(fmt.Sprintf(...))` line. Only the
603
- // high-confidence one is shown by default, so the other two were pure noise
604
- // for anyone running --all.
605
- 'go.sql-injection': ['go.sql-format', 'go.sql-fmt-sprintf'],
606
- };
607
-
608
- function dedupeFindings(findings) {
609
- const linesWithSpecific = new Set();
610
- for (const f of findings) {
611
- if (f.ruleId !== 'secret.generic-credential') {
612
- linesWithSpecific.add(`${f.file}:${f.line}`);
613
- }
614
- }
615
-
616
- // Every (file:line:ruleId) that a dataflow-confirmed finding supersedes.
617
- const supersededKeys = new Set();
618
- for (const f of findings) {
619
- for (const shadowed of TAINT_SUPERSEDES[f.ruleId] || []) {
620
- supersededKeys.add(`${f.file}:${f.line}:${shadowed}`);
621
- }
622
- }
623
-
624
- const seen = new Set();
625
- const out = [];
626
- for (const f of findings) {
627
- if (
628
- f.ruleId === 'secret.generic-credential' &&
629
- linesWithSpecific.has(`${f.file}:${f.line}`)
630
- ) {
631
- continue; // superseded by a more specific rule
632
- }
633
- // Drop a pattern-match when a dataflow-confirmed finding covers the line.
634
- if (supersededKeys.has(`${f.file}:${f.line}:${f.ruleId}`)) continue;
635
- const key = `${f.ruleId}:${f.file}:${f.line}:${f.column}`;
636
- if (seen.has(key)) continue;
637
- seen.add(key);
638
- out.push(f);
639
- }
640
- return out;
641
- }
642
-
643
- function sortFindings(findings) {
644
- const reachRank = (f) => (f.surface && f.surface.reach === 'dead' ? 1 : 0);
645
- return findings.slice().sort((a, b) => {
646
- const s = SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity];
647
- if (s !== 0) return s;
648
- // Live code first: a high finding an entrypoint can reach outranks a high
649
- // finding in a test fixture or build script at the same severity.
650
- const r = reachRank(a) - reachRank(b);
651
- if (r !== 0) return r;
652
- if (a.file !== b.file) return a.file < b.file ? -1 : 1;
653
- return a.line - b.line;
654
- });
655
- }
656
-
657
- /**
658
- * Scan a directory. Returns a structured result object.
659
- * @param {string} dir
660
- * @param {object} [opts]
661
- */
662
- function scan(dir, opts = {}) {
663
- const root = path.resolve(dir);
664
- // Apply project config (extends the redaction allowlist). Reset each scan so
665
- // config never leaks between runs (important for tests / MCP long sessions).
666
- const config = loadConfig(root);
667
- rules.configure(config);
668
-
669
- // Reset and load plugins early — before the file scan loop — so that
670
- // plugin fileRules and crossFileRules are available in scanFileContent.
671
- try {
672
- const { loadPlugins, resetPlugins } = require('./plugin');
673
- resetPlugins();
674
- loadPlugins(root, config, { trustPlugins: opts.trustPlugins === true });
675
- } catch { /* plugins are best-effort */ }
676
-
677
- const allFiles = walk(root, [], null);
678
-
679
- // Incremental mode: only scan files whose content changed since the last scan
680
- // (SHA-256 hash cache under .vibeguard/cache). First run has an empty cache so
681
- // everything is "changed" (full scan, populates cache); later runs are near
682
- // instant. Cross-file analysis needs ALL files, so it is skipped here — this
683
- // mode is per-file (line/AST/taint), intended for pre-commit / watch loops.
684
- let files = allFiles;
685
- let incremental = null;
686
- let staged = null;
687
- if (opts.staged) {
688
- // Git-aware: scan only files staged for the current commit. Perfect for a
689
- // pre-commit hook — fast and scoped to exactly what's being committed.
690
- const stagedSet = getStagedFiles(root);
691
- if (stagedSet) {
692
- files = allFiles.filter((abs) => stagedSet.has(path.resolve(abs)));
693
- staged = { total: allFiles.length, scanned: files.length };
694
- }
695
- } else if (opts.changed) {
696
- const { getChangedFiles } = require('./engine');
697
- const res = getChangedFiles(root, allFiles);
698
- files = res.changed;
699
- incremental = { total: res.total, scanned: res.changed.length, cached: res.cached };
700
- }
701
- // Both modes scan a partial file set → cross-file analysis (which needs the
702
- // whole project) must be skipped and reported as such.
703
- const partialScan = !!incremental || !!staged;
704
-
705
- let findings = [];
706
- const contents = []; // {rel, content, lines} for cross-file analysis
707
- const trees = new Map(); // rel -> parsed AST (one parse per file, shared)
708
- const astMod = require('./ast');
709
-
710
- // Engine mode + coverage diagnostics. `astAvailable` is false when the acorn
711
- // optional deps aren't installed → precise eval/exec/taint/mass-assignment
712
- // passes silently downgrade to regex. We surface that instead of hiding it.
713
- const astAvailable = astMod.isAvailable();
714
- const diag = { degraded: [] };
715
- const parseFailed = []; // JS/TS files acorn IS installed for but couldn't parse
716
- // Config-ignored paths (rule databases, fixtures, demo code) are not part of
717
- // the product surface: their findings are filtered anyway, so a parse failure
718
- // there is not a coverage gap and must not be reported as one.
719
- const configIgnoreRes = (Array.isArray(config.ignorePaths) ? config.ignorePaths : []).map(globToRe);
720
- const isConfigIgnored = (rel) => configIgnoreRes.some((re) => re.test(rel));
721
-
722
- for (const abs of files) {
723
- let buf;
724
- try {
725
- buf = fs.readFileSync(abs);
726
- } catch {
727
- continue;
728
- }
729
- if (looksBinary(buf)) continue;
730
- const rel = path.relative(root, abs).split(path.sep).join('/');
731
- const content = buf.toString('utf8');
732
- // Parse JS/TS once here; the AST pass, interprocedural, and cross-file all reuse it.
733
- let tree = null;
734
- if (/\.(?:js|jsx|ts|tsx|mjs|cjs)$/.test(rel)) {
735
- try {
736
- tree = astMod.parseSource(content, rel);
737
- } catch {
738
- tree = null;
739
- }
740
- if (tree) trees.set(rel, tree);
741
- // acorn installed but this file didn't parse → AST rules skipped for it.
742
- // (When acorn is absent entirely that's engine-mode, reported separately.)
743
- else if (astAvailable && !isConfigIgnored(rel)) parseFailed.push(rel);
744
- }
745
- findings = findings.concat(scanFileContent(abs, rel, content, tree, diag));
746
- contents.push({ rel, content, lines: content.split(/\r?\n/) });
747
- }
748
-
749
- // Cross-file passes need the WHOLE project in `contents`. In a partial scan
750
- // (--changed / --staged) we only loaded a subset, so skip them (they would
751
- // produce wrong results from a partial view) — the documented tradeoff.
752
- if (!partialScan) {
753
- // Cross-file taint: request data flowing across module boundaries into a sink.
754
- try {
755
- const { analyzeCrossFile } = require('./crosstaint');
756
- for (const cf of analyzeCrossFile(contents, trees)) findings.push(cf);
757
- } catch {
758
- /* cross-file taint is optional (needs acorn) */
759
- }
760
-
761
- // Cross-file rules see every file at once (e.g. Supabase RLS across migrations).
762
- for (const rule of crossFileRules) {
763
- let hits = [];
764
- try {
765
- hits = rule.run(contents) || [];
766
- } catch {
767
- hits = [];
768
- }
769
- for (const h of hits) {
770
- findings.push(
771
- makeFinding(rule, {
772
- file: h.file,
773
- line: h.line,
774
- column: h.column || 1,
775
- snippet: h.snippet,
776
- message: h.message,
777
- fix: h.fix,
778
- })
779
- );
780
- }
781
- }
782
-
783
- // Plugin cross-file rules (v2 plugin system).
784
- try {
785
- const { getPluginCrossFileRules } = require('./plugin');
786
- const pCrossRules = getPluginCrossFileRules();
787
- for (const rule of pCrossRules) {
788
- let hits = [];
789
- try {
790
- hits = rule.run(contents) || [];
791
- } catch {
792
- hits = [];
793
- }
794
- for (const h of hits) {
795
- findings.push(
796
- makeFinding(rule, {
797
- file: h.file,
798
- line: h.line,
799
- column: h.column || 1,
800
- snippet: h.snippet,
801
- message: h.message,
802
- fix: h.fix,
803
- })
804
- );
805
- }
806
- }
807
- } catch { /* plugin cross-file rules are best-effort */ }
808
- // Agentic/MCP posture: configs and tool definitions in the repo (not the
809
- // developer's laptop). Catches unpinned/remote MCP servers, secrets in config
810
- // env, tool-description poisoning, destructive tools without confirmation and
811
- // agent loops without caps.
812
- try {
813
- const { analyzeAgentic } = require('./agentic');
814
- for (const a of analyzeAgentic({ root, files: contents })) findings.push(a);
815
- } catch (err) {
816
- diag.degraded.push({ file: '<project>', pass: 'agentic', error: String((err && err.message) || err) });
817
- }
818
- } // end !incremental cross-file block
819
-
820
- findings = findings.concat(projectScan(root));
821
-
822
- // Dependency vulnerabilities (opt-in; the CLI enables it by default, unit
823
- // tests leave it off so they stay offline and deterministic).
824
- let depsInfo = null;
825
- if (opts.deps) {
826
- try {
827
- const { scanDependencies } = require('./deps');
828
- const dep = scanDependencies(root);
829
- findings = findings.concat(dep.findings);
830
- depsInfo = { ran: dep.ran, notes: dep.notes };
831
- } catch (err) {
832
- depsInfo = { ran: { npm: false, pip: false }, notes: [String(err && err.message)] };
833
- }
834
- }
835
-
836
- // Deep mode: fold in external best-in-class scanners if present (opt-in).
837
- let externalInfo = null;
838
- if (opts.deep) {
839
- try {
840
- const { runExternal } = require('./external');
841
- const ext = runExternal(root);
842
- findings = findings.concat(ext.findings);
843
- externalInfo = { ran: ext.ran, notes: ext.notes };
844
- } catch (err) {
845
- externalInfo = { ran: {}, notes: [String(err && err.message)] };
846
- }
847
- }
848
-
849
- // --no-suppress (opts.noSuppress): report everything, ignoring inline
850
- // `vibeguard-ignore` comments and the heuristic FP filter. Config policy
851
- // (ignoreRules/ignorePaths) is deliberate, versioned, and kept. This gives CI
852
- // a trust mode that a careless/hostile inline comment in a PR cannot silence.
853
- let suppressedFindings = [];
854
- if (!opts.noSuppress) {
855
- findings = applyInlineSuppressions(findings, contents);
856
- const { applyInlineSuppressionsWithCount } = require('./suppress');
857
- const supResult = applyInlineSuppressionsWithCount(findings, contents);
858
- findings = supResult.kept;
859
- suppressedFindings = supResult.suppressed;
860
- }
861
- findings = applyConfigFilters(findings, config);
862
-
863
- // Optional baseline filter: attack-surface and `--new-only` consumers want the
864
- // same "known findings are accepted" view the default scan shows.
865
- if (opts.baseline) {
866
- try {
867
- const { readBaseline } = require('./verify');
868
- const base = readBaseline(root);
869
- if (base && Array.isArray(base.findings) && base.findings.length > 0) {
870
- const seen = new Set(
871
- base.findings.map((f) => f.fingerprint || `${f.ruleId} ${f.file} ${(f.snippet || '').trim()}`)
872
- );
873
- findings = findings.filter((f) => !seen.has(f.fingerprint));
874
- }
875
- } catch {
876
- /* baseline is optional */
877
- }
878
- }
879
-
880
- // Merge plugin line rules (file/cross-file rules already applied above)
881
- try {
882
- const { getPluginRules } = require('./plugin');
883
- const pluginRules = getPluginRules();
884
- if (pluginRules.length > 0) {
885
- const { matchAll, makeFinding } = require('./rules');
886
- for (const [rel, content] of Object.entries(contents)) {
887
- const lines = content.split(/\r?\n/);
888
- for (let i = 0; i < lines.length; i++) {
889
- const line = lines[i];
890
- const commented = /^\s*(\/\/|#|--|\/\*)/.test(line);
891
- for (const rule of pluginRules) {
892
- if (rule.skipComments && commented) continue;
893
- for (const hit of matchAll(rule.re, line)) {
894
- findings.push(
895
- makeFinding(rule, {
896
- file: rel,
897
- line: i + 1,
898
- column: hit.index + 1,
899
- snippet: line.trim().slice(0, 200),
900
- })
901
- );
902
- }
903
- }
904
- }
905
- }
906
- }
907
- } catch {
908
- /* plugins are best-effort */
909
- }
910
-
911
- findings = dedupeFindings(findings);
912
-
913
- // Context-aware false positive suppression (skipped under --no-suppress).
914
- if (!opts.noSuppress) {
915
- try {
916
- const { suppressFindings } = require('./suppress');
917
- findings = findings.filter((f) => {
918
- const matching = contents.find((c) => c.rel === f.file);
919
- if (matching) {
920
- return suppressFindings([f], matching.content, f.file).length > 0;
921
- }
922
- return true;
923
- });
924
- } catch { /* suppression is best-effort */ }
925
- }
926
-
927
- // Optional confidence floor (the CLI's default view excludes low-confidence
928
- // heuristics). Applied before the surface merge so the entrypoint risks and the
929
- // printed grade describe the same finding set the user sees.
930
- if (opts.minConfidence) {
931
- const order = { low: 0, medium: 1, high: 2 };
932
- const floor = order[String(opts.minConfidence).toLowerCase()] ?? 0;
933
- findings = findings.filter((f) => (order[f.confidence] ?? 0) >= floor);
934
- }
935
-
936
- // Attack-surface merge: joins entrypoints, reachability and the final finding
937
- // set. Every finding is annotated with `surface.reach` (direct / imported /
938
- // dead), which drives `--live`, reachability-first ordering and the optional
939
- // grade demotion for dead code. Cheap enough to run by default (≈0.2 s per
940
- // 1000 files); `surface: false` disables it for snippet scanners/tests.
941
- let surface = null;
942
- if (opts.surface !== false) {
943
- try {
944
- const { buildSurface } = require('./surface');
945
- // Only files the project actually ships: config-ignored paths (fixtures,
946
- // rule databases, demo code) must not become "entrypoints".
947
- const filesForSurface = contents.filter((c) => !isConfigIgnored(c.rel));
948
- surface = buildSurface({ files: filesForSurface, findings });
949
- } catch (err) {
950
- noteDegraded('surface', err);
951
- }
952
- }
953
-
954
- // --live: report only findings an entrypoint can actually reach. Dead tooling
955
- // and example code stay out of the response entirely (they were never attack
956
- // surface), and the grade is computed on the live set. If the project exposes
957
- // no entrypoints at all, reachability says nothing — leave the scan untouched.
958
- if (opts.liveOnly && surface && surface.stats.entrypoints > 0) {
959
- findings = findings.filter((f) => !f.surface || f.surface.reach !== 'dead');
960
- }
961
-
962
- // Optional reachability-weighted grading: a finding in code no entrypoint
963
- // imports cannot be exploited through the app, so it counts one tier lower.
964
- // Off by default because "dead" is a static approximation (dynamic imports,
965
- // framework conventions) and a project with no entrypoints has no reachability.
966
- if (opts.reachabilityGrade && surface && surface.stats.entrypoints > 0) {
967
- for (const f of findings) {
968
- f._reachDemote = f.surface && f.surface.reach === 'dead';
969
- }
970
- }
971
-
972
- const reach = surface
973
- ? {
974
- direct: findings.filter((f) => f.surface && f.surface.reach === 'direct').length,
975
- imported: findings.filter((f) => f.surface && f.surface.reach === 'imported').length,
976
- dead: findings.filter((f) => f.surface && f.surface.reach === 'dead').length,
977
- unanalyzed: findings.filter((f) => !f.surface).length,
978
- }
979
- : null;
980
-
981
- findings = sortFindings(findings);
982
- for (const f of findings) f.fingerprint = fingerprintOf(f);
983
-
984
- const { grade, counts } = computeGrade(findings);
985
-
986
- // Coverage transparency: engine mode + every pass that failed open. Callers
987
- // (CLI, MCP, CI) can warn the user that a scan ran degraded rather than let a
988
- // silent parse/taint failure masquerade as a clean result.
989
- const engine = {
990
- astAvailable,
991
- mode: astAvailable ? 'ast' : 'regex-only',
992
- };
993
- const diagnostics = {
994
- degradedPasses: diag.degraded,
995
- parseFailedFiles: parseFailed,
996
- degradedFileCount: new Set([...diag.degraded.map((d) => d.file), ...parseFailed]).size,
997
- };
998
-
999
- return {
1000
- root,
1001
- scannedFiles: files.length,
1002
- findings,
1003
- suppressedFindings,
1004
- suppressedCount: suppressedFindings.length,
1005
- grade,
1006
- counts,
1007
- depsInfo,
1008
- externalInfo,
1009
- engine,
1010
- diagnostics,
1011
- surface,
1012
- reach,
1013
- incremental, // null on a full scan; {total, scanned, cached} with --changed
1014
- staged, // null unless --staged; {total, scanned}
1015
- generatedAt: new Date().toISOString(),
1016
- };
1017
- }
1018
-
1019
- module.exports = {
1020
- scan,
1021
- scanFileContent,
1022
- computeGrade,
1023
- sortFindings,
1024
- walk,
1025
- shouldScanFile,
1026
- SKIP_DIRS,
1027
- // Exported so the benchmark scorer measures exactly what a user sees: the
1028
- // same supersession relation and the same de-duplication the scan pipeline
1029
- // applies, rather than a second hand-maintained copy that drifts.
1030
- TAINT_SUPERSEDES,
1031
- dedupeFindings,
1032
- };
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const crypto = require('crypto');
6
+
7
+ // Stable fingerprint: survives line moves (no line number), used for SARIF
8
+ // partialFingerprints and the scan --new-only baseline diff.
9
+ function fingerprintOf(f) {
10
+ return crypto
11
+ .createHash('sha1')
12
+ .update(`${f.ruleId} ${f.file} ${(f.snippet || '').trim()}`)
13
+ .digest('hex')
14
+ .slice(0, 16);
15
+ }
16
+ const rules = require('./rules');
17
+ const {
18
+ SEVERITY_ORDER,
19
+ lineRules,
20
+ fileRules,
21
+ crossFileRules,
22
+ makeFinding,
23
+ matchAll,
24
+ requiredLiteral,
25
+ isCommentLine,
26
+ } = rules;
27
+
28
+ // Load optional project config (.vibeguardrc.json / vibeguard.config.json).
29
+ // Currently supports { "shapingFunctions": ["toDTO", ...] } to extend the
30
+ // redaction allowlist. Best-effort: bad/missing config = defaults.
31
+ function loadConfig(root) {
32
+ for (const name of ['.vibeguardrc.json', 'vibeguard.config.json']) {
33
+ try {
34
+ const p = path.join(root, name);
35
+ if (fs.existsSync(p)) return JSON.parse(fs.readFileSync(p, 'utf8'));
36
+ } catch {
37
+ /* ignore malformed config */
38
+ }
39
+ }
40
+ return {};
41
+ }
42
+
43
+ // Directories we never walk into.
44
+ const SKIP_DIRS = new Set([
45
+ 'node_modules',
46
+ '.git',
47
+ '.vibeguard', // our own cache/baseline artifacts — never scan them
48
+ 'dist',
49
+ 'build',
50
+ '.next',
51
+ 'out',
52
+ 'coverage',
53
+ '.cache',
54
+ 'vendor',
55
+ '.venv',
56
+ 'venv',
57
+ '__pycache__',
58
+ ]);
59
+
60
+ // Only text-ish source/config files. Everything else is skipped as binary/noise.
61
+ const SCAN_EXT = new Set([
62
+ '.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs',
63
+ '.py', '.rb', '.php', '.go', '.java', '.cs', '.rs',
64
+ '.sh', '.bash', '.sql',
65
+ '.json', '.yml', '.yaml', '.toml', '.ini', '.xml',
66
+ '.env', '.html', '.vue', '.svelte',
67
+ '.txt', '.md', '.pem', '.key',
68
+ '.tf', '.hcl', '.dockerfile', '.rules',
69
+ ]);
70
+
71
+ // Files without a "normal" extension we still want to read (dotfiles etc.).
72
+ const SCAN_BASENAMES = new Set([
73
+ '.env', '.env.local', '.env.development', '.env.production',
74
+ '.npmrc', 'Dockerfile', '.dockerenv',
75
+ ]);
76
+
77
+ const MAX_FILE_BYTES = 2 * 1024 * 1024; // 2MB — skip anything huge.
78
+
79
+ function shouldScanFile(filePath) {
80
+ const base = path.basename(filePath);
81
+ if (base === '.vibeguard-baseline.json') return false; // our own artifact
82
+ if (SCAN_BASENAMES.has(base)) return true;
83
+ if (base.startsWith('.env')) return true;
84
+ const ext = path.extname(filePath).toLowerCase();
85
+ return SCAN_EXT.has(ext);
86
+ }
87
+
88
+ // Files staged for commit (git diff --cached), as a Set of absolute paths.
89
+ // Returns null when not a git repo / git unavailable, so the caller can decide.
90
+ function getStagedFiles(root) {
91
+ try {
92
+ const { execFileSync } = require('child_process');
93
+ const out = execFileSync('git', ['diff', '--cached', '--name-only', '--diff-filter=ACM'], {
94
+ cwd: root,
95
+ encoding: 'utf8',
96
+ stdio: ['ignore', 'pipe', 'ignore'],
97
+ });
98
+ const set = new Set();
99
+ for (const rel of out.split(/\r?\n/)) {
100
+ const t = rel.trim();
101
+ if (t) set.add(path.resolve(root, t));
102
+ }
103
+ return set;
104
+ } catch {
105
+ return null; // not a git repo, or git not installed
106
+ }
107
+ }
108
+
109
+ // Recursively collect scannable files.
110
+ function walk(dir, out, rootStat) {
111
+ let entries;
112
+ try {
113
+ entries = fs.readdirSync(dir, { withFileTypes: true });
114
+ } catch {
115
+ return out;
116
+ }
117
+ for (const entry of entries) {
118
+ const full = path.join(dir, entry.name);
119
+ if (entry.isDirectory()) {
120
+ if (SKIP_DIRS.has(entry.name)) continue;
121
+ walk(full, out, rootStat);
122
+ } else if (entry.isFile()) {
123
+ if (!shouldScanFile(full)) continue;
124
+ try {
125
+ const st = fs.statSync(full);
126
+ if (st.size > MAX_FILE_BYTES) continue;
127
+ } catch {
128
+ continue;
129
+ }
130
+ out.push(full);
131
+ }
132
+ }
133
+ return out;
134
+ }
135
+
136
+ // Naive check: is character offset `idx` inside a quoted string literal on this
137
+ // line? Tracks ' " ` state left-to-right. Used to suppress code-pattern matches
138
+ // that are actually text (e.g. the word eval() inside a message string).
139
+ function isInsideString(line, idx) {
140
+ let quote = null;
141
+ for (let i = 0; i < idx && i < line.length; i++) {
142
+ const c = line[i];
143
+ if (quote) {
144
+ if (c === '\\') i++; // skip escaped char
145
+ else if (c === quote) quote = null;
146
+ } else if (c === '"' || c === "'" || c === '`') {
147
+ quote = c;
148
+ }
149
+ }
150
+ return quote !== null;
151
+ }
152
+
153
+ // Cheap binary sniff: NUL byte in the first chunk.
154
+ function looksBinary(buf) {
155
+ const n = Math.min(buf.length, 8000);
156
+ for (let i = 0; i < n; i++) if (buf[i] === 0) return true;
157
+ return false;
158
+ }
159
+
160
+ // `diag` (optional): a collector { degraded: [] } into which each analysis pass
161
+ // records a failure instead of swallowing it silently. A security scanner that
162
+ // fails open MUST surface that it did so — a quietly-skipped pass is a coverage
163
+ // hole the user never sees. Backward compatible: omit diag and behavior is old.
164
+ function scanFileContent(absPath, relPath, content, tree, diag) {
165
+ const noteDegraded = (pass, err) => {
166
+ if (diag && Array.isArray(diag.degraded)) {
167
+ diag.degraded.push({ file: relPath, pass, error: String((err && err.message) || err || 'unknown') });
168
+ }
169
+ };
170
+ let findings = [];
171
+ const lines = content.split(/\r?\n/);
172
+
173
+ // fileFilter depends only on the path, not the line — compute the applicable
174
+ // rule set ONCE per file instead of re-testing (and recompiling) a fileFilter
175
+ // regex on every line. Compiled fileFilters are cached on the rule object.
176
+ const activeRules = [];
177
+ for (const rule of lineRules) {
178
+ if (!rule.re) continue; // match()-based line rules (no regex) — inert until a line-level match hook exists
179
+ if (rule.fileFilter) {
180
+ let ff = rule._ffRe;
181
+ if (!ff) {
182
+ ff = typeof rule.fileFilter === 'string' ? new RegExp(rule.fileFilter) : rule.fileFilter;
183
+ rule._ffRe = ff;
184
+ }
185
+ if (!ff.test(relPath)) continue;
186
+ }
187
+ // Precompute a mandatory literal once per rule (cached). '' = none extractable.
188
+ if (rule._lit === undefined) rule._lit = requiredLiteral(rule.re.source) || '';
189
+ activeRules.push(rule);
190
+ }
191
+
192
+ for (let i = 0; i < lines.length; i++) {
193
+ const line = lines[i];
194
+ if (line.length > 4000) continue; // minified blob line — skip.
195
+ const commented = isCommentLine(line);
196
+ const lineLower = line.toLowerCase();
197
+ for (const rule of activeRules) {
198
+ if (rule.skipComments && commented) continue;
199
+ // Cheap literal prefilter: if the rule's mandatory literal isn't on this
200
+ // line, the regex cannot match — skip it without running the regex.
201
+ if (rule._lit && !lineLower.includes(rule._lit)) continue;
202
+ for (const hit of matchAll(rule.re, line)) {
203
+ if (rule.skipInString && isInsideString(line, hit.index)) continue;
204
+ if (rule.filter && !rule.filter(line, hit, lines)) continue;
205
+ findings.push(
206
+ makeFinding(rule, {
207
+ file: relPath,
208
+ line: i + 1,
209
+ column: hit.index + 1,
210
+ snippet: redactSnippet(line.trim(), hit.match),
211
+ })
212
+ );
213
+ }
214
+ }
215
+ }
216
+
217
+ // Dataflow/taint analysis: follows user input across lines to a dangerous sink.
218
+ try {
219
+ const { analyzeTaint } = require('./taint');
220
+ // A crash inside the AST pass falls back to regex taint rather than losing
221
+ // the file entirely — but it is recorded, because every dataflow-confirmed
222
+ // finding disappears when that happens and the grade would otherwise look
223
+ // clean. `--strict` turns this into a hard failure.
224
+ const onDegrade = (err) => noteDegraded('taint-ast', err);
225
+ for (const t of analyzeTaint(content, lines, relPath, tree, onDegrade)) findings.push(t);
226
+ } catch (err) {
227
+ noteDegraded('taint', err);
228
+ }
229
+
230
+ // Python taint analysis for .py files (advanced multi-pass engine)
231
+ if (relPath && relPath.endsWith('.py')) {
232
+ try {
233
+ const { analyzePythonTaintAdvanced } = require('./taint-py');
234
+ for (const t of analyzePythonTaintAdvanced(content, lines, relPath)) findings.push(t);
235
+ } catch (err) {
236
+ // Fallback to legacy engine
237
+ try {
238
+ const { analyzePythonTaint } = require('./engine');
239
+ for (const t of analyzePythonTaint(content, lines, relPath)) findings.push(t);
240
+ } catch (e) {
241
+ noteDegraded('python-taint', e);
242
+ }
243
+ }
244
+ }
245
+
246
+ // Optional AST pass (acorn) — precise eval/exec/Function/mass-assignment/nosql.
247
+ try {
248
+ const { analyzeAst, AST_SUPERSEDES } = require('./ast');
249
+ const ast = analyzeAst(content, relPath, tree); // tree cached by the caller
250
+ if (ast.parsed) {
251
+ // AST is precise for these categories — drop the regex heuristics for this
252
+ // file so we don't double-report or carry their false positives.
253
+ findings = findings.filter((f) => !AST_SUPERSEDES.has(f.ruleId));
254
+ }
255
+ for (const a of ast.findings) findings.push(a);
256
+ } catch (err) {
257
+ noteDegraded('ast', err);
258
+ }
259
+
260
+ // Obfuscation / backdoor analysis: decodes encoded payloads and correlates
261
+ // capabilities (exec + net + env) that no honest source file needs. Runs on
262
+ // every text file; the analyzer itself skips minified bundles/lockfiles.
263
+ try {
264
+ const { analyzeObfuscation } = require('./obfuscation');
265
+ for (const o of analyzeObfuscation(content, relPath)) findings.push(o);
266
+ } catch (err) {
267
+ noteDegraded('obfuscation', err);
268
+ }
269
+
270
+ // File-level rules (need whole-file context). Pass prior findings so rules
271
+ // can suppress noise that a line-level rule already reported (e.g. the
272
+ // high-entropy hint shouldn't double-fire on a line a specific secret rule
273
+ // already flagged). Backward compatible: rules that ignore the arg are fine.
274
+ for (const rule of fileRules) {
275
+ let hits = [];
276
+ try {
277
+ if (typeof rule.match === 'function') {
278
+ // Function-based rule (no regex): match(content, ctx) -> [{ index, match }].
279
+ const raw = rule.match(content, { lines, relPath, findings }) || [];
280
+ hits = raw.map((h) => {
281
+ const before = content.slice(0, h.index);
282
+ const ln = before.split('\n').length - 1;
283
+ return {
284
+ line: ln + 1,
285
+ column: before.length - before.lastIndexOf('\n'),
286
+ snippet: redactSnippet((lines[ln] || '').trim(), h.match),
287
+ };
288
+ });
289
+ } else {
290
+ hits = rule.run(content, lines, relPath, findings) || [];
291
+ }
292
+ } catch (err) {
293
+ noteDegraded(`file-rule:${rule.id || 'unknown'}`, err);
294
+ hits = [];
295
+ }
296
+ for (const h of hits) {
297
+ findings.push(
298
+ makeFinding(rule, {
299
+ file: relPath,
300
+ line: h.line,
301
+ column: h.column || 1,
302
+ snippet: h.snippet,
303
+ message: h.message,
304
+ fix: h.fix,
305
+ severity: h.severity, // per-hit overrides (makeFinding falls back to rule)
306
+ confidence: h.confidence,
307
+ ruleId: h.ruleId,
308
+ title: h.title,
309
+ })
310
+ );
311
+ }
312
+ }
313
+
314
+ // Plugin file-level rules (v2 plugin system).
315
+ try {
316
+ const { getPluginFileRules } = require('./plugin');
317
+ const pFileRules = getPluginFileRules();
318
+ for (const rule of pFileRules) {
319
+ let hits = [];
320
+ try {
321
+ hits = rule.run(content, lines, relPath) || [];
322
+ } catch (err) {
323
+ noteDegraded(`plugin-file-rule:${rule.id || 'unknown'}`, err);
324
+ hits = [];
325
+ }
326
+ for (const h of hits) {
327
+ findings.push(
328
+ makeFinding(rule, {
329
+ file: relPath,
330
+ line: h.line,
331
+ column: h.column || 1,
332
+ snippet: h.snippet,
333
+ message: h.message,
334
+ fix: h.fix,
335
+ severity: h.severity,
336
+ confidence: h.confidence,
337
+ ruleId: h.ruleId,
338
+ title: h.title,
339
+ })
340
+ );
341
+ }
342
+ }
343
+ } catch { /* plugin file rules are best-effort */ }
344
+
345
+ return findings;
346
+ }
347
+
348
+ // Never echo a full secret back into a report/log. Show a masked snippet.
349
+ function redactSnippet(line, match) {
350
+ if (!match || match.length < 8) return truncate(line);
351
+ const masked = match.slice(0, 4) + '****' + match.slice(-2);
352
+ return truncate(line.split(match).join(masked));
353
+ }
354
+
355
+ function truncate(s) {
356
+ return s.length > 160 ? s.slice(0, 157) + '...' : s;
357
+ }
358
+
359
+ // ---------------------------------------------------------------------------
360
+ // Project-level rules
361
+ // ---------------------------------------------------------------------------
362
+
363
+ function projectScan(root) {
364
+ const findings = [];
365
+ const gitignorePath = path.join(root, '.gitignore');
366
+ let gitignore = '';
367
+ try {
368
+ gitignore = fs.readFileSync(gitignorePath, 'utf8');
369
+ } catch {
370
+ gitignore = '';
371
+ }
372
+ const ignoreLines = gitignore
373
+ .split(/\r?\n/)
374
+ .map((l) => l.trim())
375
+ .filter(Boolean);
376
+
377
+ const envIsIgnored = ignoreLines.some((l) =>
378
+ /^\.env($|\.|\/|\*)/.test(l) || l === '.env*' || l === '*.env'
379
+ );
380
+
381
+ // .env present but not gitignored -> critical.
382
+ const envFiles = ['.env', '.env.local', '.env.production', '.env.development'];
383
+ for (const name of envFiles) {
384
+ const p = path.join(root, name);
385
+ if (fs.existsSync(p)) {
386
+ if (!envIsIgnored) {
387
+ findings.push({
388
+ ruleId: 'project.env-not-ignored',
389
+ severity: 'critical',
390
+ title: '.env not in .gitignore',
391
+ message: `${name} exists but is not covered by .gitignore — secrets can be committed and pushed.`,
392
+ fix: `Add ".env" (and ".env.*") to .gitignore, then remove it from git history if already committed (git rm --cached ${name}).`,
393
+ file: name,
394
+ line: 1,
395
+ column: 1,
396
+ snippet: `${name} present, .gitignore does not cover it`,
397
+ });
398
+ }
399
+ }
400
+ }
401
+
402
+ // A committed .git folder inside a subpath, or a tracked .env that is world-exposed
403
+ // via a public dir — flag .env living under a web/public/static dir.
404
+ const exposedDirs = ['public', 'static', 'dist', 'www'];
405
+ for (const d of exposedDirs) {
406
+ for (const name of ['.env', '.env.local']) {
407
+ const p = path.join(root, d, name);
408
+ if (fs.existsSync(p)) {
409
+ findings.push({
410
+ ruleId: 'project.env-exposed',
411
+ severity: 'critical',
412
+ title: '.env inside a public directory',
413
+ message: `${d}/${name} sits in a publicly served directory and may be downloadable.`,
414
+ fix: `Move ${name} out of ${d}/ and load config from environment variables.`,
415
+ file: `${d}/${name}`,
416
+ line: 1,
417
+ column: 1,
418
+ snippet: `${d}/${name} is web-served`,
419
+ });
420
+ }
421
+ }
422
+ }
423
+
424
+ // package.json present but no lockfile -> non-reproducible installs.
425
+ if (fs.existsSync(path.join(root, 'package.json'))) {
426
+ const lockfiles = ['package-lock.json', 'yarn.lock', 'pnpm-lock.yaml', 'npm-shrinkwrap.json'];
427
+ if (!lockfiles.some((l) => fs.existsSync(path.join(root, l)))) {
428
+ findings.push({
429
+ ruleId: 'package.no-lockfile',
430
+ severity: 'low',
431
+ confidence: 'high',
432
+ title: 'No dependency lockfile',
433
+ message: 'package.json exists but no lockfile is committed — installs are not reproducible and pull the newest matching versions (supply-chain drift).',
434
+ fix: 'Commit a lockfile (package-lock.json / yarn.lock / pnpm-lock.yaml).',
435
+ file: 'package.json',
436
+ line: 1,
437
+ column: 1,
438
+ snippet: 'no lockfile found',
439
+ });
440
+ }
441
+ }
442
+
443
+ return findings;
444
+ }
445
+
446
+ // ---------------------------------------------------------------------------
447
+ // Grading
448
+ // ---------------------------------------------------------------------------
449
+
450
+ const TIER = ['critical', 'high', 'medium', 'low'];
451
+
452
+ // Grade off EFFECTIVE severity: low-confidence findings are heuristics ("review
453
+ // this"), so they count one tier lower and low-confidence 'low' is ignored for
454
+ // the grade. This keeps a single heuristic hint from tanking an otherwise clean
455
+ // project, while confirmed issues still drive the grade hard.
456
+ function effectiveSeverity(f) {
457
+ let sev = f.severity;
458
+ if (f.confidence === 'low') {
459
+ const i = TIER.indexOf(sev);
460
+ sev = TIER[i + 1] || null; // low-confidence 'low' -> null (ignored)
461
+ }
462
+ // Optional reachability weighting: dead-code findings grade one tier lower.
463
+ // A critical sink in code no route imports still lands at 'high' — visible,
464
+ // just not grade-destroying.
465
+ if (f._reachDemote && sev) {
466
+ const idx = TIER.indexOf(sev);
467
+ if (idx >= 0 && idx < TIER.length - 1) sev = TIER[idx + 1];
468
+ }
469
+ return sev;
470
+ }
471
+
472
+ // Minimal glob -> RegExp: supports *, **, and gitignore-style "**/" (zero+ dirs).
473
+ function globToRe(glob) {
474
+ const esc = glob.replace(/[.+^${}()|[\]\\]/g, '\\$&');
475
+ const body = esc.replace(/\*\*\/|\*\*|\*/g, (m) =>
476
+ m === '**/' ? '(?:.*/)?' : m === '**' ? '.*' : '[^/]*'
477
+ );
478
+ return new RegExp('^' + body + '$');
479
+ }
480
+
481
+ // Inline suppression comments:
482
+ // // vibeguard-ignore-line [rule1, rule2] -> suppress on this line
483
+ // // vibeguard-ignore-next-line [rule1, ...] -> suppress on the next line
484
+ // No rule list = suppress everything on the target line. Works with //, #, /* */.
485
+ function buildIgnoreMap(lines) {
486
+ const map = new Map(); // targetLine(1-based) -> Set(ruleIds) | '*'
487
+ const re = /(?:\/\/|#|\/\*|\*)\s*vibeguard-ignore(-next)?-line\b([^*\n]*)/i;
488
+ for (let i = 0; i < lines.length; i++) {
489
+ const m = re.exec(lines[i]);
490
+ if (!m) continue;
491
+ const target = m[1] ? i + 2 : i + 1; // next-line -> i+2 (1-based)
492
+ const rulesPart = (m[2] || '').replace(/\*\/.*/, '').trim();
493
+ const rules = rulesPart
494
+ ? rulesPart.split(/[\s,]+/).filter(Boolean)
495
+ : '*';
496
+ const existing = map.get(target);
497
+ if (existing === '*' || rules === '*') map.set(target, '*');
498
+ else map.set(target, new Set([...(existing || []), ...rules]));
499
+ }
500
+ return map;
501
+ }
502
+
503
+ function applyInlineSuppressions(findings, contents) {
504
+ const byFile = new Map();
505
+ for (const c of contents) byFile.set(c.rel, buildIgnoreMap(c.lines));
506
+ return findings.filter((f) => {
507
+ const map = byFile.get(f.file);
508
+ if (!map) return true;
509
+ const entry = map.get(f.line);
510
+ if (!entry) return true;
511
+ if (entry === '*') return false;
512
+ return !entry.has(f.ruleId);
513
+ });
514
+ }
515
+
516
+ // Apply project config: drop ignored rules/paths, remap severities.
517
+ // config = { ignoreRules:[ruleId], ignorePaths:[glob], ignore:[{rule,path}],
518
+ // severityOverrides:{ruleId: 'low'} }
519
+ function applyConfigFilters(findings, config) {
520
+ if (!config || typeof config !== 'object') return findings;
521
+ const ignoreRules = new Set(Array.isArray(config.ignoreRules) ? config.ignoreRules : []);
522
+ const ignorePathRes = (Array.isArray(config.ignorePaths) ? config.ignorePaths : []).map(globToRe);
523
+ const pairIgnores = (Array.isArray(config.ignore) ? config.ignore : []).filter(
524
+ (x) => x && typeof x === 'object'
525
+ );
526
+ const sevOverride = config.severityOverrides && typeof config.severityOverrides === 'object'
527
+ ? config.severityOverrides
528
+ : {};
529
+ const validSev = new Set(['critical', 'high', 'medium', 'low']);
530
+
531
+ return findings
532
+ .filter((f) => {
533
+ if (ignoreRules.has(f.ruleId)) return false;
534
+ if (ignorePathRes.some((re) => re.test(f.file))) return false;
535
+ for (const pair of pairIgnores) {
536
+ const ruleMatch = !pair.rule || pair.rule === f.ruleId;
537
+ const pathMatch = !pair.path || globToRe(pair.path).test(f.file) || f.file.includes(pair.path);
538
+ if (ruleMatch && pathMatch) return false;
539
+ }
540
+ return true;
541
+ })
542
+ .map((f) => {
543
+ const ov = sevOverride[f.ruleId];
544
+ if (ov && validSev.has(ov)) return { ...f, severity: ov };
545
+ return f;
546
+ });
547
+ }
548
+
549
+ function computeGrade(findings) {
550
+ // Reported counts are the real severities (what the user sees).
551
+ const counts = { critical: 0, high: 0, medium: 0, low: 0 };
552
+ for (const f of findings) counts[f.severity] = (counts[f.severity] || 0) + 1;
553
+
554
+ // Grade counts use effective severity.
555
+ const g = { critical: 0, high: 0, medium: 0, low: 0 };
556
+ for (const f of findings) {
557
+ const s = effectiveSeverity(f);
558
+ if (s) g[s] += 1;
559
+ }
560
+
561
+ let grade;
562
+ if (g.critical > 0) grade = 'F';
563
+ else if (g.high > 0) grade = g.high >= 3 ? 'D' : 'C';
564
+ else if (g.medium > 0) grade = g.medium >= 3 ? 'C' : 'B';
565
+ else if (g.low > 0) grade = 'B';
566
+ else grade = 'A';
567
+
568
+ return { grade, counts };
569
+ }
570
+
571
+ // Collapse noise: on a single file:line, a specific rule supersedes the generic
572
+ // credential catch-all (e.g. a weak session secret shouldn't also report as a
573
+ // bare "hardcoded credential"). Also drop exact duplicate (ruleId+file+line).
574
+ //
575
+ // Additionally: when a dataflow-confirmed taint.* finding and a structural ast.*
576
+ // finding land on the same file:line and describe the same vulnerability category,
577
+ // keep only the taint finding (higher confidence) and drop the ast.* duplicate.
578
+ // Map: taint.command-injection ↔ ast.command-injection, etc.
579
+ /*
580
+ * Which lower-fidelity findings a stronger finding supersedes on the same
581
+ * file:line.
582
+ *
583
+ * Two rules that describe the same vulnerability on the same line are one
584
+ * finding reported twice. The higher-fidelity rule wins and the rest are
585
+ * dropped: a taint.* finding proves the path from source to sink, whereas a
586
+ * regex rule only pattern-matched the text; and among overlapping regex rules
587
+ * the higher-confidence, more specific one wins.
588
+ *
589
+ * Keys are the superseding rule; values are every rule it can shadow.
590
+ */
591
+ const TAINT_SUPERSEDES = {
592
+ 'taint.command-injection': ['ast.command-injection'],
593
+ 'taint.sql-injection': [
594
+ 'ast.sql-injection',
595
+ 'code.sql-injection',
596
+ 'db.sql-template-literal',
597
+ 'injection.orm-raw-user',
598
+ ],
599
+ 'taint.code-injection': ['ast.eval-dynamic'],
600
+ 'taint.path-traversal': ['ast.path-traversal', 'upload.filename-path-traversal'],
601
+ 'taint.ssrf': ['ast.ssrf'],
602
+ // Go: three rules match the same `db.Query(fmt.Sprintf(...))` line. Only the
603
+ // high-confidence one is shown by default, so the other two were pure noise
604
+ // for anyone running --all.
605
+ 'go.sql-injection': ['go.sql-format', 'go.sql-fmt-sprintf'],
606
+ };
607
+
608
+ function dedupeFindings(findings) {
609
+ const linesWithSpecific = new Set();
610
+ for (const f of findings) {
611
+ if (f.ruleId !== 'secret.generic-credential') {
612
+ linesWithSpecific.add(`${f.file}:${f.line}`);
613
+ }
614
+ }
615
+
616
+ // Every (file:line:ruleId) that a dataflow-confirmed finding supersedes.
617
+ const supersededKeys = new Set();
618
+ for (const f of findings) {
619
+ for (const shadowed of TAINT_SUPERSEDES[f.ruleId] || []) {
620
+ supersededKeys.add(`${f.file}:${f.line}:${shadowed}`);
621
+ }
622
+ }
623
+
624
+ const seen = new Set();
625
+ const out = [];
626
+ for (const f of findings) {
627
+ if (
628
+ f.ruleId === 'secret.generic-credential' &&
629
+ linesWithSpecific.has(`${f.file}:${f.line}`)
630
+ ) {
631
+ continue; // superseded by a more specific rule
632
+ }
633
+ // Drop a pattern-match when a dataflow-confirmed finding covers the line.
634
+ if (supersededKeys.has(`${f.file}:${f.line}:${f.ruleId}`)) continue;
635
+ const key = `${f.ruleId}:${f.file}:${f.line}:${f.column}`;
636
+ if (seen.has(key)) continue;
637
+ seen.add(key);
638
+ out.push(f);
639
+ }
640
+ return out;
641
+ }
642
+
643
+ function sortFindings(findings) {
644
+ const reachRank = (f) => (f.surface && f.surface.reach === 'dead' ? 1 : 0);
645
+ return findings.slice().sort((a, b) => {
646
+ const s = SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity];
647
+ if (s !== 0) return s;
648
+ // Live code first: a high finding an entrypoint can reach outranks a high
649
+ // finding in a test fixture or build script at the same severity.
650
+ const r = reachRank(a) - reachRank(b);
651
+ if (r !== 0) return r;
652
+ if (a.file !== b.file) return a.file < b.file ? -1 : 1;
653
+ return a.line - b.line;
654
+ });
655
+ }
656
+
657
+ /**
658
+ * Scan a directory. Returns a structured result object.
659
+ * @param {string} dir
660
+ * @param {object} [opts]
661
+ */
662
+ function scan(dir, opts = {}) {
663
+ const root = path.resolve(dir);
664
+ // Apply project config (extends the redaction allowlist). Reset each scan so
665
+ // config never leaks between runs (important for tests / MCP long sessions).
666
+ const config = loadConfig(root);
667
+ rules.configure(config);
668
+
669
+ // Reset and load plugins early — before the file scan loop — so that
670
+ // plugin fileRules and crossFileRules are available in scanFileContent.
671
+ try {
672
+ const { loadPlugins, resetPlugins } = require('./plugin');
673
+ resetPlugins();
674
+ loadPlugins(root, config, { trustPlugins: opts.trustPlugins === true });
675
+ } catch { /* plugins are best-effort */ }
676
+
677
+ const allFiles = walk(root, [], null);
678
+
679
+ // Incremental mode: only scan files whose content changed since the last scan
680
+ // (SHA-256 hash cache under .vibeguard/cache). First run has an empty cache so
681
+ // everything is "changed" (full scan, populates cache); later runs are near
682
+ // instant. Cross-file analysis needs ALL files, so it is skipped here — this
683
+ // mode is per-file (line/AST/taint), intended for pre-commit / watch loops.
684
+ let files = allFiles;
685
+ let incremental = null;
686
+ let staged = null;
687
+ if (opts.staged) {
688
+ // Git-aware: scan only files staged for the current commit. Perfect for a
689
+ // pre-commit hook — fast and scoped to exactly what's being committed.
690
+ const stagedSet = getStagedFiles(root);
691
+ if (stagedSet) {
692
+ files = allFiles.filter((abs) => stagedSet.has(path.resolve(abs)));
693
+ staged = { total: allFiles.length, scanned: files.length };
694
+ }
695
+ } else if (opts.changed) {
696
+ const { getChangedFiles } = require('./engine');
697
+ const res = getChangedFiles(root, allFiles);
698
+ files = res.changed;
699
+ incremental = { total: res.total, scanned: res.changed.length, cached: res.cached };
700
+ }
701
+ // Both modes scan a partial file set → cross-file analysis (which needs the
702
+ // whole project) must be skipped and reported as such.
703
+ const partialScan = !!incremental || !!staged;
704
+
705
+ let findings = [];
706
+ const contents = []; // {rel, content, lines} for cross-file analysis
707
+ const trees = new Map(); // rel -> parsed AST (one parse per file, shared)
708
+ const astMod = require('./ast');
709
+
710
+ // Engine mode + coverage diagnostics. `astAvailable` is false when the acorn
711
+ // optional deps aren't installed → precise eval/exec/taint/mass-assignment
712
+ // passes silently downgrade to regex. We surface that instead of hiding it.
713
+ const astAvailable = astMod.isAvailable();
714
+ const diag = { degraded: [] };
715
+ const parseFailed = []; // JS/TS files acorn IS installed for but couldn't parse
716
+ // Config-ignored paths (rule databases, fixtures, demo code) are not part of
717
+ // the product surface: their findings are filtered anyway, so a parse failure
718
+ // there is not a coverage gap and must not be reported as one.
719
+ const configIgnoreRes = (Array.isArray(config.ignorePaths) ? config.ignorePaths : []).map(globToRe);
720
+ const isConfigIgnored = (rel) => configIgnoreRes.some((re) => re.test(rel));
721
+
722
+ for (const abs of files) {
723
+ let buf;
724
+ try {
725
+ buf = fs.readFileSync(abs);
726
+ } catch {
727
+ continue;
728
+ }
729
+ if (looksBinary(buf)) continue;
730
+ const rel = path.relative(root, abs).split(path.sep).join('/');
731
+ const content = buf.toString('utf8');
732
+ // Parse JS/TS once here; the AST pass, interprocedural, and cross-file all reuse it.
733
+ let tree = null;
734
+ if (/\.(?:js|jsx|ts|tsx|mjs|cjs)$/.test(rel)) {
735
+ try {
736
+ tree = astMod.parseSource(content, rel);
737
+ } catch {
738
+ tree = null;
739
+ }
740
+ if (tree) trees.set(rel, tree);
741
+ // acorn installed but this file didn't parse → AST rules skipped for it.
742
+ // (When acorn is absent entirely that's engine-mode, reported separately.)
743
+ else if (astAvailable && !isConfigIgnored(rel)) parseFailed.push(rel);
744
+ }
745
+ findings = findings.concat(scanFileContent(abs, rel, content, tree, diag));
746
+ contents.push({ rel, content, lines: content.split(/\r?\n/) });
747
+ }
748
+
749
+ // Cross-file passes need the WHOLE project in `contents`. In a partial scan
750
+ // (--changed / --staged) we only loaded a subset, so skip them (they would
751
+ // produce wrong results from a partial view) — the documented tradeoff.
752
+ if (!partialScan) {
753
+ // Cross-file taint: request data flowing across module boundaries into a sink.
754
+ try {
755
+ const { analyzeCrossFile } = require('./crosstaint');
756
+ for (const cf of analyzeCrossFile(contents, trees)) findings.push(cf);
757
+ } catch {
758
+ /* cross-file taint is optional (needs acorn) */
759
+ }
760
+
761
+ // Cross-file rules see every file at once (e.g. Supabase RLS across migrations).
762
+ for (const rule of crossFileRules) {
763
+ let hits = [];
764
+ try {
765
+ hits = rule.run(contents) || [];
766
+ } catch {
767
+ hits = [];
768
+ }
769
+ for (const h of hits) {
770
+ findings.push(
771
+ makeFinding(rule, {
772
+ file: h.file,
773
+ line: h.line,
774
+ column: h.column || 1,
775
+ snippet: h.snippet,
776
+ message: h.message,
777
+ fix: h.fix,
778
+ })
779
+ );
780
+ }
781
+ }
782
+
783
+ // Plugin cross-file rules (v2 plugin system).
784
+ try {
785
+ const { getPluginCrossFileRules } = require('./plugin');
786
+ const pCrossRules = getPluginCrossFileRules();
787
+ for (const rule of pCrossRules) {
788
+ let hits = [];
789
+ try {
790
+ hits = rule.run(contents) || [];
791
+ } catch {
792
+ hits = [];
793
+ }
794
+ for (const h of hits) {
795
+ findings.push(
796
+ makeFinding(rule, {
797
+ file: h.file,
798
+ line: h.line,
799
+ column: h.column || 1,
800
+ snippet: h.snippet,
801
+ message: h.message,
802
+ fix: h.fix,
803
+ })
804
+ );
805
+ }
806
+ }
807
+ } catch { /* plugin cross-file rules are best-effort */ }
808
+ // Agentic/MCP posture: configs and tool definitions in the repo (not the
809
+ // developer's laptop). Catches unpinned/remote MCP servers, secrets in config
810
+ // env, tool-description poisoning, destructive tools without confirmation and
811
+ // agent loops without caps.
812
+ try {
813
+ const { analyzeAgentic } = require('./agentic');
814
+ for (const a of analyzeAgentic({ root, files: contents })) findings.push(a);
815
+ } catch (err) {
816
+ diag.degraded.push({ file: '<project>', pass: 'agentic', error: String((err && err.message) || err) });
817
+ }
818
+ } // end !incremental cross-file block
819
+
820
+ findings = findings.concat(projectScan(root));
821
+
822
+ // Dependency vulnerabilities (opt-in; the CLI enables it by default, unit
823
+ // tests leave it off so they stay offline and deterministic).
824
+ let depsInfo = null;
825
+ if (opts.deps) {
826
+ try {
827
+ const { scanDependencies } = require('./deps');
828
+ const dep = scanDependencies(root);
829
+ findings = findings.concat(dep.findings);
830
+ depsInfo = { ran: dep.ran, notes: dep.notes };
831
+ } catch (err) {
832
+ depsInfo = { ran: { npm: false, pip: false }, notes: [String(err && err.message)] };
833
+ }
834
+ }
835
+
836
+ // Deep mode: fold in external best-in-class scanners if present (opt-in).
837
+ let externalInfo = null;
838
+ if (opts.deep) {
839
+ try {
840
+ const { runExternal } = require('./external');
841
+ const ext = runExternal(root);
842
+ findings = findings.concat(ext.findings);
843
+ externalInfo = { ran: ext.ran, notes: ext.notes };
844
+ } catch (err) {
845
+ externalInfo = { ran: {}, notes: [String(err && err.message)] };
846
+ }
847
+ }
848
+
849
+ // --no-suppress (opts.noSuppress): report everything, ignoring inline
850
+ // `vibeguard-ignore` comments and the heuristic FP filter. Config policy
851
+ // (ignoreRules/ignorePaths) is deliberate, versioned, and kept. This gives CI
852
+ // a trust mode that a careless/hostile inline comment in a PR cannot silence.
853
+ let suppressedFindings = [];
854
+ if (!opts.noSuppress) {
855
+ findings = applyInlineSuppressions(findings, contents);
856
+ const { applyInlineSuppressionsWithCount } = require('./suppress');
857
+ const supResult = applyInlineSuppressionsWithCount(findings, contents);
858
+ findings = supResult.kept;
859
+ suppressedFindings = supResult.suppressed;
860
+ }
861
+ findings = applyConfigFilters(findings, config);
862
+
863
+ // Optional baseline filter: attack-surface and `--new-only` consumers want the
864
+ // same "known findings are accepted" view the default scan shows.
865
+ if (opts.baseline) {
866
+ try {
867
+ const { readBaseline } = require('./verify');
868
+ const base = readBaseline(root);
869
+ if (base && Array.isArray(base.findings) && base.findings.length > 0) {
870
+ const seen = new Set(
871
+ base.findings.map((f) => f.fingerprint || `${f.ruleId} ${f.file} ${(f.snippet || '').trim()}`)
872
+ );
873
+ findings = findings.filter((f) => !seen.has(f.fingerprint));
874
+ }
875
+ } catch {
876
+ /* baseline is optional */
877
+ }
878
+ }
879
+
880
+ // Merge plugin line rules (file/cross-file rules already applied above)
881
+ try {
882
+ const { getPluginRules } = require('./plugin');
883
+ const pluginRules = getPluginRules();
884
+ if (pluginRules.length > 0) {
885
+ const { matchAll, makeFinding } = require('./rules');
886
+ for (const [rel, content] of Object.entries(contents)) {
887
+ const lines = content.split(/\r?\n/);
888
+ for (let i = 0; i < lines.length; i++) {
889
+ const line = lines[i];
890
+ const commented = /^\s*(\/\/|#|--|\/\*)/.test(line);
891
+ for (const rule of pluginRules) {
892
+ if (rule.skipComments && commented) continue;
893
+ for (const hit of matchAll(rule.re, line)) {
894
+ findings.push(
895
+ makeFinding(rule, {
896
+ file: rel,
897
+ line: i + 1,
898
+ column: hit.index + 1,
899
+ snippet: line.trim().slice(0, 200),
900
+ })
901
+ );
902
+ }
903
+ }
904
+ }
905
+ }
906
+ }
907
+ } catch {
908
+ /* plugins are best-effort */
909
+ }
910
+
911
+ findings = dedupeFindings(findings);
912
+
913
+ // Context-aware false positive suppression (skipped under --no-suppress).
914
+ if (!opts.noSuppress) {
915
+ try {
916
+ const { suppressFindings } = require('./suppress');
917
+ findings = findings.filter((f) => {
918
+ const matching = contents.find((c) => c.rel === f.file);
919
+ if (matching) {
920
+ return suppressFindings([f], matching.content, f.file).length > 0;
921
+ }
922
+ return true;
923
+ });
924
+ } catch { /* suppression is best-effort */ }
925
+ }
926
+
927
+ // Optional confidence floor (the CLI's default view excludes low-confidence
928
+ // heuristics). Applied before the surface merge so the entrypoint risks and the
929
+ // printed grade describe the same finding set the user sees.
930
+ if (opts.minConfidence) {
931
+ const order = { low: 0, medium: 1, high: 2 };
932
+ const floor = order[String(opts.minConfidence).toLowerCase()] ?? 0;
933
+ findings = findings.filter((f) => (order[f.confidence] ?? 0) >= floor);
934
+ }
935
+
936
+ // Attack-surface merge: joins entrypoints, reachability and the final finding
937
+ // set. Every finding is annotated with `surface.reach` (direct / imported /
938
+ // dead), which drives `--live`, reachability-first ordering and the optional
939
+ // grade demotion for dead code. Cheap enough to run by default (≈0.2 s per
940
+ // 1000 files); `surface: false` disables it for snippet scanners/tests.
941
+ let surface = null;
942
+ if (opts.surface !== false) {
943
+ try {
944
+ const { buildSurface } = require('./surface');
945
+ // Only files the project actually ships: config-ignored paths (fixtures,
946
+ // rule databases, demo code) must not become "entrypoints".
947
+ const filesForSurface = contents.filter((c) => !isConfigIgnored(c.rel));
948
+ surface = buildSurface({ files: filesForSurface, findings });
949
+ } catch (err) {
950
+ noteDegraded('surface', err);
951
+ }
952
+ }
953
+
954
+ // --live: report only findings an entrypoint can actually reach. Dead tooling
955
+ // and example code stay out of the response entirely (they were never attack
956
+ // surface), and the grade is computed on the live set. If the project exposes
957
+ // no entrypoints at all, reachability says nothing — leave the scan untouched.
958
+ if (opts.liveOnly && surface && surface.stats.entrypoints > 0) {
959
+ findings = findings.filter((f) => !f.surface || f.surface.reach !== 'dead');
960
+ }
961
+
962
+ // Optional reachability-weighted grading: a finding in code no entrypoint
963
+ // imports cannot be exploited through the app, so it counts one tier lower.
964
+ // Off by default because "dead" is a static approximation (dynamic imports,
965
+ // framework conventions) and a project with no entrypoints has no reachability.
966
+ if (opts.reachabilityGrade && surface && surface.stats.entrypoints > 0) {
967
+ for (const f of findings) {
968
+ f._reachDemote = f.surface && f.surface.reach === 'dead';
969
+ }
970
+ }
971
+
972
+ const reach = surface
973
+ ? {
974
+ direct: findings.filter((f) => f.surface && f.surface.reach === 'direct').length,
975
+ imported: findings.filter((f) => f.surface && f.surface.reach === 'imported').length,
976
+ dead: findings.filter((f) => f.surface && f.surface.reach === 'dead').length,
977
+ unanalyzed: findings.filter((f) => !f.surface).length,
978
+ }
979
+ : null;
980
+
981
+ findings = sortFindings(findings);
982
+ for (const f of findings) f.fingerprint = fingerprintOf(f);
983
+
984
+ const { grade, counts } = computeGrade(findings);
985
+
986
+ // Coverage transparency: engine mode + every pass that failed open. Callers
987
+ // (CLI, MCP, CI) can warn the user that a scan ran degraded rather than let a
988
+ // silent parse/taint failure masquerade as a clean result.
989
+ const engine = {
990
+ astAvailable,
991
+ mode: astAvailable ? 'ast' : 'regex-only',
992
+ };
993
+ const diagnostics = {
994
+ degradedPasses: diag.degraded,
995
+ parseFailedFiles: parseFailed,
996
+ degradedFileCount: new Set([...diag.degraded.map((d) => d.file), ...parseFailed]).size,
997
+ };
998
+
999
+ return {
1000
+ root,
1001
+ scannedFiles: files.length,
1002
+ findings,
1003
+ suppressedFindings,
1004
+ suppressedCount: suppressedFindings.length,
1005
+ grade,
1006
+ counts,
1007
+ depsInfo,
1008
+ externalInfo,
1009
+ engine,
1010
+ diagnostics,
1011
+ surface,
1012
+ reach,
1013
+ incremental, // null on a full scan; {total, scanned, cached} with --changed
1014
+ staged, // null unless --staged; {total, scanned}
1015
+ generatedAt: new Date().toISOString(),
1016
+ };
1017
+ }
1018
+
1019
+ module.exports = {
1020
+ scan,
1021
+ scanFileContent,
1022
+ computeGrade,
1023
+ sortFindings,
1024
+ walk,
1025
+ shouldScanFile,
1026
+ SKIP_DIRS,
1027
+ // Exported so the benchmark scorer measures exactly what a user sees: the
1028
+ // same supersession relation and the same de-duplication the scan pipeline
1029
+ // applies, rather than a second hand-maintained copy that drifts.
1030
+ TAINT_SUPERSEDES,
1031
+ dedupeFindings,
1032
+ };