@yagyeshvyas/vibeguard 1.0.0 → 1.2.0

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.
package/src/scanner.js CHANGED
@@ -1,685 +1,805 @@
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
- isCommentLine,
25
- } = rules;
26
-
27
- // Load optional project config (.vibeguardrc.json / vibeguard.config.json).
28
- // Currently supports { "shapingFunctions": ["toDTO", ...] } to extend the
29
- // redaction allowlist. Best-effort: bad/missing config = defaults.
30
- function loadConfig(root) {
31
- for (const name of ['.vibeguardrc.json', 'vibeguard.config.json']) {
32
- try {
33
- const p = path.join(root, name);
34
- if (fs.existsSync(p)) return JSON.parse(fs.readFileSync(p, 'utf8'));
35
- } catch {
36
- /* ignore malformed config */
37
- }
38
- }
39
- return {};
40
- }
41
-
42
- // Directories we never walk into.
43
- const SKIP_DIRS = new Set([
44
- 'node_modules',
45
- '.git',
46
- 'dist',
47
- 'build',
48
- '.next',
49
- 'out',
50
- 'coverage',
51
- '.cache',
52
- 'vendor',
53
- '.venv',
54
- 'venv',
55
- '__pycache__',
56
- ]);
57
-
58
- // Only text-ish source/config files. Everything else is skipped as binary/noise.
59
- const SCAN_EXT = new Set([
60
- '.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs',
61
- '.py', '.rb', '.php', '.go', '.java', '.cs', '.rs',
62
- '.sh', '.bash', '.sql',
63
- '.json', '.yml', '.yaml', '.toml', '.ini', '.xml',
64
- '.env', '.html', '.vue', '.svelte',
65
- '.txt', '.md', '.pem', '.key',
66
- '.tf', '.hcl', '.dockerfile',
67
- ]);
68
-
69
- // Files without a "normal" extension we still want to read (dotfiles etc.).
70
- const SCAN_BASENAMES = new Set([
71
- '.env', '.env.local', '.env.development', '.env.production',
72
- '.npmrc', 'Dockerfile', '.dockerenv',
73
- ]);
74
-
75
- const MAX_FILE_BYTES = 2 * 1024 * 1024; // 2MB — skip anything huge.
76
-
77
- function shouldScanFile(filePath) {
78
- const base = path.basename(filePath);
79
- if (base === '.vibeguard-baseline.json') return false; // our own artifact
80
- if (SCAN_BASENAMES.has(base)) return true;
81
- if (base.startsWith('.env')) return true;
82
- const ext = path.extname(filePath).toLowerCase();
83
- return SCAN_EXT.has(ext);
84
- }
85
-
86
- // Recursively collect scannable files.
87
- function walk(dir, out, rootStat) {
88
- let entries;
89
- try {
90
- entries = fs.readdirSync(dir, { withFileTypes: true });
91
- } catch {
92
- return out;
93
- }
94
- for (const entry of entries) {
95
- const full = path.join(dir, entry.name);
96
- if (entry.isDirectory()) {
97
- if (SKIP_DIRS.has(entry.name)) continue;
98
- walk(full, out, rootStat);
99
- } else if (entry.isFile()) {
100
- if (!shouldScanFile(full)) continue;
101
- try {
102
- const st = fs.statSync(full);
103
- if (st.size > MAX_FILE_BYTES) continue;
104
- } catch {
105
- continue;
106
- }
107
- out.push(full);
108
- }
109
- }
110
- return out;
111
- }
112
-
113
- // Naive check: is character offset `idx` inside a quoted string literal on this
114
- // line? Tracks ' " ` state left-to-right. Used to suppress code-pattern matches
115
- // that are actually text (e.g. the word eval() inside a message string).
116
- function isInsideString(line, idx) {
117
- let quote = null;
118
- for (let i = 0; i < idx && i < line.length; i++) {
119
- const c = line[i];
120
- if (quote) {
121
- if (c === '\\') i++; // skip escaped char
122
- else if (c === quote) quote = null;
123
- } else if (c === '"' || c === "'" || c === '`') {
124
- quote = c;
125
- }
126
- }
127
- return quote !== null;
128
- }
129
-
130
- // Cheap binary sniff: NUL byte in the first chunk.
131
- function looksBinary(buf) {
132
- const n = Math.min(buf.length, 8000);
133
- for (let i = 0; i < n; i++) if (buf[i] === 0) return true;
134
- return false;
135
- }
136
-
137
- function scanFileContent(absPath, relPath, content, tree) {
138
- let findings = [];
139
- const lines = content.split(/\r?\n/);
140
- for (let i = 0; i < lines.length; i++) {
141
- const line = lines[i];
142
- if (line.length > 4000) continue; // minified blob line — skip.
143
- const commented = isCommentLine(line);
144
- for (const rule of lineRules) {
145
- if (rule.skipComments && commented) continue;
146
- if (rule.fileFilter) {
147
- const ff = typeof rule.fileFilter === 'string' ? new RegExp(rule.fileFilter) : rule.fileFilter;
148
- if (!ff.test(relPath)) continue;
149
- }
150
- for (const hit of matchAll(rule.re, line)) {
151
- if (rule.skipInString && isInsideString(line, hit.index)) continue;
152
- if (rule.filter && !rule.filter(line, hit, lines)) continue;
153
- findings.push(
154
- makeFinding(rule, {
155
- file: relPath,
156
- line: i + 1,
157
- column: hit.index + 1,
158
- snippet: redactSnippet(line.trim(), hit.match),
159
- })
160
- );
161
- }
162
- }
163
- }
164
-
165
- // Dataflow/taint analysis: follows user input across lines to a dangerous sink.
166
- try {
167
- const { analyzeTaint } = require('./taint');
168
- for (const t of analyzeTaint(content, lines, relPath, tree)) findings.push(t);
169
- } catch {
170
- /* taint is best-effort */
171
- }
172
-
173
- // Python taint analysis for .py files
174
- if (relPath && relPath.endsWith('.py')) {
175
- try {
176
- const { analyzePythonTaint } = require('./engine');
177
- for (const t of analyzePythonTaint(content, lines, relPath)) findings.push(t);
178
- } catch {
179
- /* Python taint is best-effort */
180
- }
181
- }
182
-
183
- // Optional AST pass (acorn) — precise eval/exec/Function/mass-assignment/nosql.
184
- try {
185
- const { analyzeAst, AST_SUPERSEDES } = require('./ast');
186
- const ast = analyzeAst(content, relPath, tree); // tree cached by the caller
187
- if (ast.parsed) {
188
- // AST is precise for these categories — drop the regex heuristics for this
189
- // file so we don't double-report or carry their false positives.
190
- findings = findings.filter((f) => !AST_SUPERSEDES.has(f.ruleId));
191
- }
192
- for (const a of ast.findings) findings.push(a);
193
- } catch {
194
- /* AST is optional */
195
- }
196
-
197
- // File-level rules (need whole-file context).
198
- for (const rule of fileRules) {
199
- let hits = [];
200
- try {
201
- hits = rule.run(content, lines, relPath) || [];
202
- } catch {
203
- hits = [];
204
- }
205
- for (const h of hits) {
206
- findings.push(
207
- makeFinding(rule, {
208
- file: relPath,
209
- line: h.line,
210
- column: h.column || 1,
211
- snippet: h.snippet,
212
- message: h.message,
213
- fix: h.fix,
214
- severity: h.severity, // per-hit overrides (makeFinding falls back to rule)
215
- confidence: h.confidence,
216
- ruleId: h.ruleId,
217
- title: h.title,
218
- })
219
- );
220
- }
221
- }
222
- return findings;
223
- }
224
-
225
- // Never echo a full secret back into a report/log. Show a masked snippet.
226
- function redactSnippet(line, match) {
227
- if (!match || match.length < 8) return truncate(line);
228
- const masked = match.slice(0, 4) + '****' + match.slice(-2);
229
- return truncate(line.split(match).join(masked));
230
- }
231
-
232
- function truncate(s) {
233
- return s.length > 160 ? s.slice(0, 157) + '...' : s;
234
- }
235
-
236
- // ---------------------------------------------------------------------------
237
- // Project-level rules
238
- // ---------------------------------------------------------------------------
239
-
240
- function projectScan(root) {
241
- const findings = [];
242
- const gitignorePath = path.join(root, '.gitignore');
243
- let gitignore = '';
244
- try {
245
- gitignore = fs.readFileSync(gitignorePath, 'utf8');
246
- } catch {
247
- gitignore = '';
248
- }
249
- const ignoreLines = gitignore
250
- .split(/\r?\n/)
251
- .map((l) => l.trim())
252
- .filter(Boolean);
253
-
254
- const envIsIgnored = ignoreLines.some((l) =>
255
- /^\.env($|\.|\/|\*)/.test(l) || l === '.env*' || l === '*.env'
256
- );
257
-
258
- // .env present but not gitignored -> critical.
259
- const envFiles = ['.env', '.env.local', '.env.production', '.env.development'];
260
- for (const name of envFiles) {
261
- const p = path.join(root, name);
262
- if (fs.existsSync(p)) {
263
- if (!envIsIgnored) {
264
- findings.push({
265
- ruleId: 'project.env-not-ignored',
266
- severity: 'critical',
267
- title: '.env not in .gitignore',
268
- message: `${name} exists but is not covered by .gitignore — secrets can be committed and pushed.`,
269
- fix: `Add ".env" (and ".env.*") to .gitignore, then remove it from git history if already committed (git rm --cached ${name}).`,
270
- file: name,
271
- line: 1,
272
- column: 1,
273
- snippet: `${name} present, .gitignore does not cover it`,
274
- });
275
- }
276
- }
277
- }
278
-
279
- // A committed .git folder inside a subpath, or a tracked .env that is world-exposed
280
- // via a public dir — flag .env living under a web/public/static dir.
281
- const exposedDirs = ['public', 'static', 'dist', 'www'];
282
- for (const d of exposedDirs) {
283
- for (const name of ['.env', '.env.local']) {
284
- const p = path.join(root, d, name);
285
- if (fs.existsSync(p)) {
286
- findings.push({
287
- ruleId: 'project.env-exposed',
288
- severity: 'critical',
289
- title: '.env inside a public directory',
290
- message: `${d}/${name} sits in a publicly served directory and may be downloadable.`,
291
- fix: `Move ${name} out of ${d}/ and load config from environment variables.`,
292
- file: `${d}/${name}`,
293
- line: 1,
294
- column: 1,
295
- snippet: `${d}/${name} is web-served`,
296
- });
297
- }
298
- }
299
- }
300
-
301
- // package.json present but no lockfile -> non-reproducible installs.
302
- if (fs.existsSync(path.join(root, 'package.json'))) {
303
- const lockfiles = ['package-lock.json', 'yarn.lock', 'pnpm-lock.yaml', 'npm-shrinkwrap.json'];
304
- if (!lockfiles.some((l) => fs.existsSync(path.join(root, l)))) {
305
- findings.push({
306
- ruleId: 'package.no-lockfile',
307
- severity: 'low',
308
- confidence: 'high',
309
- title: 'No dependency lockfile',
310
- message: 'package.json exists but no lockfile is committed — installs are not reproducible and pull the newest matching versions (supply-chain drift).',
311
- fix: 'Commit a lockfile (package-lock.json / yarn.lock / pnpm-lock.yaml).',
312
- file: 'package.json',
313
- line: 1,
314
- column: 1,
315
- snippet: 'no lockfile found',
316
- });
317
- }
318
- }
319
-
320
- return findings;
321
- }
322
-
323
- // ---------------------------------------------------------------------------
324
- // Grading
325
- // ---------------------------------------------------------------------------
326
-
327
- const TIER = ['critical', 'high', 'medium', 'low'];
328
-
329
- // Grade off EFFECTIVE severity: low-confidence findings are heuristics ("review
330
- // this"), so they count one tier lower and low-confidence 'low' is ignored for
331
- // the grade. This keeps a single heuristic hint from tanking an otherwise clean
332
- // project, while confirmed issues still drive the grade hard.
333
- function effectiveSeverity(f) {
334
- if (f.confidence === 'low') {
335
- const i = TIER.indexOf(f.severity);
336
- return TIER[i + 1] || null; // low-confidence 'low' -> null (ignored)
337
- }
338
- return f.severity;
339
- }
340
-
341
- // Minimal glob -> RegExp: supports *, **, and gitignore-style "**/" (zero+ dirs).
342
- function globToRe(glob) {
343
- const esc = glob.replace(/[.+^${}()|[\]\\]/g, '\\$&');
344
- const body = esc.replace(/\*\*\/|\*\*|\*/g, (m) =>
345
- m === '**/' ? '(?:.*/)?' : m === '**' ? '.*' : '[^/]*'
346
- );
347
- return new RegExp('^' + body + '$');
348
- }
349
-
350
- // Inline suppression comments:
351
- // // vibeguard-ignore-line [rule1, rule2] -> suppress on this line
352
- // // vibeguard-ignore-next-line [rule1, ...] -> suppress on the next line
353
- // No rule list = suppress everything on the target line. Works with //, #, /* */.
354
- function buildIgnoreMap(lines) {
355
- const map = new Map(); // targetLine(1-based) -> Set(ruleIds) | '*'
356
- const re = /(?:\/\/|#|\/\*|\*)\s*vibeguard-ignore(-next)?-line\b([^*\n]*)/i;
357
- for (let i = 0; i < lines.length; i++) {
358
- const m = re.exec(lines[i]);
359
- if (!m) continue;
360
- const target = m[1] ? i + 2 : i + 1; // next-line -> i+2 (1-based)
361
- const rulesPart = (m[2] || '').replace(/\*\/.*/, '').trim();
362
- const rules = rulesPart
363
- ? rulesPart.split(/[\s,]+/).filter(Boolean)
364
- : '*';
365
- const existing = map.get(target);
366
- if (existing === '*' || rules === '*') map.set(target, '*');
367
- else map.set(target, new Set([...(existing || []), ...rules]));
368
- }
369
- return map;
370
- }
371
-
372
- function applyInlineSuppressions(findings, contents) {
373
- const byFile = new Map();
374
- for (const c of contents) byFile.set(c.rel, buildIgnoreMap(c.lines));
375
- return findings.filter((f) => {
376
- const map = byFile.get(f.file);
377
- if (!map) return true;
378
- const entry = map.get(f.line);
379
- if (!entry) return true;
380
- if (entry === '*') return false;
381
- return !entry.has(f.ruleId);
382
- });
383
- }
384
-
385
- // Apply project config: drop ignored rules/paths, remap severities.
386
- // config = { ignoreRules:[ruleId], ignorePaths:[glob], ignore:[{rule,path}],
387
- // severityOverrides:{ruleId: 'low'} }
388
- function applyConfigFilters(findings, config) {
389
- if (!config || typeof config !== 'object') return findings;
390
- const ignoreRules = new Set(Array.isArray(config.ignoreRules) ? config.ignoreRules : []);
391
- const ignorePathRes = (Array.isArray(config.ignorePaths) ? config.ignorePaths : []).map(globToRe);
392
- const pairIgnores = (Array.isArray(config.ignore) ? config.ignore : []).filter(
393
- (x) => x && typeof x === 'object'
394
- );
395
- const sevOverride = config.severityOverrides && typeof config.severityOverrides === 'object'
396
- ? config.severityOverrides
397
- : {};
398
- const validSev = new Set(['critical', 'high', 'medium', 'low']);
399
-
400
- return findings
401
- .filter((f) => {
402
- if (ignoreRules.has(f.ruleId)) return false;
403
- if (ignorePathRes.some((re) => re.test(f.file))) return false;
404
- for (const pair of pairIgnores) {
405
- const ruleMatch = !pair.rule || pair.rule === f.ruleId;
406
- const pathMatch = !pair.path || globToRe(pair.path).test(f.file) || f.file.includes(pair.path);
407
- if (ruleMatch && pathMatch) return false;
408
- }
409
- return true;
410
- })
411
- .map((f) => {
412
- const ov = sevOverride[f.ruleId];
413
- if (ov && validSev.has(ov)) return { ...f, severity: ov };
414
- return f;
415
- });
416
- }
417
-
418
- function computeGrade(findings) {
419
- // Reported counts are the real severities (what the user sees).
420
- const counts = { critical: 0, high: 0, medium: 0, low: 0 };
421
- for (const f of findings) counts[f.severity] = (counts[f.severity] || 0) + 1;
422
-
423
- // Grade counts use effective severity.
424
- const g = { critical: 0, high: 0, medium: 0, low: 0 };
425
- for (const f of findings) {
426
- const s = effectiveSeverity(f);
427
- if (s) g[s] += 1;
428
- }
429
-
430
- let grade;
431
- if (g.critical > 0) grade = 'F';
432
- else if (g.high > 0) grade = g.high >= 3 ? 'D' : 'C';
433
- else if (g.medium > 0) grade = g.medium >= 3 ? 'C' : 'B';
434
- else if (g.low > 0) grade = 'B';
435
- else grade = 'A';
436
-
437
- return { grade, counts };
438
- }
439
-
440
- // Collapse noise: on a single file:line, a specific rule supersedes the generic
441
- // credential catch-all (e.g. a weak session secret shouldn't also report as a
442
- // bare "hardcoded credential"). Also drop exact duplicate (ruleId+file+line).
443
- //
444
- // Additionally: when a dataflow-confirmed taint.* finding and a structural ast.*
445
- // finding land on the same file:line and describe the same vulnerability category,
446
- // keep only the taint finding (higher confidence) and drop the ast.* duplicate.
447
- // Map: taint.command-injection ↔ ast.command-injection, etc.
448
- const TAINT_TO_AST = {
449
- 'taint.command-injection': 'ast.command-injection',
450
- 'taint.sql-injection': 'ast.sql-injection',
451
- 'taint.code-injection': 'ast.eval-dynamic',
452
- 'taint.path-traversal': 'ast.path-traversal',
453
- 'taint.ssrf': 'ast.ssrf',
454
- };
455
-
456
- function dedupeFindings(findings) {
457
- const linesWithSpecific = new Set();
458
- for (const f of findings) {
459
- if (f.ruleId !== 'secret.generic-credential') {
460
- linesWithSpecific.add(`${f.file}:${f.line}`);
461
- }
462
- }
463
-
464
- // Build a set of taint.* ruleIds that fired, keyed by file:line, so we can
465
- // drop the corresponding ast.* finding on the same file:line.
466
- const taintKeys = new Set();
467
- for (const f of findings) {
468
- if (TAINT_TO_AST[f.ruleId]) {
469
- taintKeys.add(`${f.file}:${f.line}:${TAINT_TO_AST[f.ruleId]}`);
470
- }
471
- }
472
-
473
- const seen = new Set();
474
- const out = [];
475
- for (const f of findings) {
476
- if (
477
- f.ruleId === 'secret.generic-credential' &&
478
- linesWithSpecific.has(`${f.file}:${f.line}`)
479
- ) {
480
- continue; // superseded by a more specific rule
481
- }
482
- // Drop ast.* finding when a taint.* finding already covers the same file:line.
483
- const astCounterpart = Object.entries(TAINT_TO_AST).find(([, ast]) => ast === f.ruleId);
484
- if (astCounterpart && taintKeys.has(`${f.file}:${f.line}:${f.ruleId}`)) {
485
- continue; // superseded by the dataflow-confirmed taint finding
486
- }
487
- const key = `${f.ruleId}:${f.file}:${f.line}:${f.column}`;
488
- if (seen.has(key)) continue;
489
- seen.add(key);
490
- out.push(f);
491
- }
492
- return out;
493
- }
494
-
495
- function sortFindings(findings) {
496
- return findings.slice().sort((a, b) => {
497
- const s = SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity];
498
- if (s !== 0) return s;
499
- if (a.file !== b.file) return a.file < b.file ? -1 : 1;
500
- return a.line - b.line;
501
- });
502
- }
503
-
504
- /**
505
- * Scan a directory. Returns a structured result object.
506
- * @param {string} dir
507
- * @param {object} [opts]
508
- */
509
- function scan(dir, opts = {}) {
510
- const root = path.resolve(dir);
511
- // Apply project config (extends the redaction allowlist). Reset each scan so
512
- // config never leaks between runs (important for tests / MCP long sessions).
513
- const config = loadConfig(root);
514
- rules.configure(config);
515
-
516
- const files = walk(root, [], null);
517
- let findings = [];
518
- const contents = []; // {rel, content, lines} for cross-file analysis
519
- const trees = new Map(); // rel -> parsed AST (one parse per file, shared)
520
- const astMod = require('./ast');
521
-
522
- for (const abs of files) {
523
- let buf;
524
- try {
525
- buf = fs.readFileSync(abs);
526
- } catch {
527
- continue;
528
- }
529
- if (looksBinary(buf)) continue;
530
- const rel = path.relative(root, abs).split(path.sep).join('/');
531
- const content = buf.toString('utf8');
532
- // Parse JS/TS once here; the AST pass, interprocedural, and cross-file all reuse it.
533
- let tree = null;
534
- if (/\.(?:js|jsx|ts|tsx|mjs|cjs)$/.test(rel)) {
535
- try {
536
- tree = astMod.parseSource(content, rel);
537
- } catch {
538
- tree = null;
539
- }
540
- if (tree) trees.set(rel, tree);
541
- }
542
- findings = findings.concat(scanFileContent(abs, rel, content, tree));
543
- contents.push({ rel, content, lines: content.split(/\r?\n/) });
544
- }
545
-
546
- // Cross-file taint: request data flowing across module boundaries into a sink.
547
- try {
548
- const { analyzeCrossFile } = require('./crosstaint');
549
- for (const cf of analyzeCrossFile(contents, trees)) findings.push(cf);
550
- } catch {
551
- /* cross-file taint is optional (needs acorn) */
552
- }
553
-
554
- // Cross-file rules see every file at once (e.g. Supabase RLS across migrations).
555
- for (const rule of crossFileRules) {
556
- let hits = [];
557
- try {
558
- hits = rule.run(contents) || [];
559
- } catch {
560
- hits = [];
561
- }
562
- for (const h of hits) {
563
- findings.push(
564
- makeFinding(rule, {
565
- file: h.file,
566
- line: h.line,
567
- column: h.column || 1,
568
- snippet: h.snippet,
569
- message: h.message,
570
- fix: h.fix,
571
- })
572
- );
573
- }
574
- }
575
-
576
- findings = findings.concat(projectScan(root));
577
-
578
- // Dependency vulnerabilities (opt-in; the CLI enables it by default, unit
579
- // tests leave it off so they stay offline and deterministic).
580
- let depsInfo = null;
581
- if (opts.deps) {
582
- try {
583
- const { scanDependencies } = require('./deps');
584
- const dep = scanDependencies(root);
585
- findings = findings.concat(dep.findings);
586
- depsInfo = { ran: dep.ran, notes: dep.notes };
587
- } catch (err) {
588
- depsInfo = { ran: { npm: false, pip: false }, notes: [String(err && err.message)] };
589
- }
590
- }
591
-
592
- // Deep mode: fold in external best-in-class scanners if present (opt-in).
593
- let externalInfo = null;
594
- if (opts.deep) {
595
- try {
596
- const { runExternal } = require('./external');
597
- const ext = runExternal(root);
598
- findings = findings.concat(ext.findings);
599
- externalInfo = { ran: ext.ran, notes: ext.notes };
600
- } catch (err) {
601
- externalInfo = { ran: {}, notes: [String(err && err.message)] };
602
- }
603
- }
604
-
605
- findings = applyInlineSuppressions(findings, contents);
606
- const { applyInlineSuppressionsWithCount } = require('./suppress');
607
- const supResult = applyInlineSuppressionsWithCount(findings, contents);
608
- findings = supResult.kept;
609
- const suppressedFindings = supResult.suppressed;
610
- findings = applyConfigFilters(findings, config);
611
-
612
- // Merge plugin rules
613
- try {
614
- const { loadPlugins, getPluginRules } = require('./plugin');
615
- loadPlugins(root, config);
616
- const pluginRules = getPluginRules();
617
- if (pluginRules.length > 0) {
618
- const { matchAll, makeFinding } = require('./rules');
619
- for (const [rel, content] of Object.entries(contents)) {
620
- const lines = content.split(/\r?\n/);
621
- for (let i = 0; i < lines.length; i++) {
622
- const line = lines[i];
623
- const commented = /^\s*(\/\/|#|--|\/\*)/.test(line);
624
- for (const rule of pluginRules) {
625
- if (rule.skipComments && commented) continue;
626
- for (const hit of matchAll(rule.re, line)) {
627
- findings.push(
628
- makeFinding(rule, {
629
- file: rel,
630
- line: i + 1,
631
- column: hit.index + 1,
632
- snippet: line.trim().slice(0, 200),
633
- })
634
- );
635
- }
636
- }
637
- }
638
- }
639
- }
640
- } catch {
641
- /* plugins are best-effort */
642
- }
643
-
644
- findings = dedupeFindings(findings);
645
-
646
- // Context-aware false positive suppression
647
- try {
648
- const { suppressFindings } = require('./suppress');
649
- findings = findings.filter((f) => {
650
- const matching = contents.find((c) => c.rel === f.file);
651
- if (matching) {
652
- return suppressFindings([f], matching.content, f.file).length > 0;
653
- }
654
- return true;
655
- });
656
- } catch { /* suppression is best-effort */ }
657
-
658
- findings = sortFindings(findings);
659
- for (const f of findings) f.fingerprint = fingerprintOf(f);
660
-
661
- const { grade, counts } = computeGrade(findings);
662
-
663
- return {
664
- root,
665
- scannedFiles: files.length,
666
- findings,
667
- suppressedFindings,
668
- suppressedCount: suppressedFindings.length,
669
- grade,
670
- counts,
671
- depsInfo,
672
- externalInfo,
673
- generatedAt: new Date().toISOString(),
674
- };
675
- }
676
-
677
- module.exports = {
678
- scan,
679
- scanFileContent,
680
- computeGrade,
681
- sortFindings,
682
- walk,
683
- shouldScanFile,
684
- SKIP_DIRS,
685
- };
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',
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.fileFilter) {
179
+ let ff = rule._ffRe;
180
+ if (!ff) {
181
+ ff = typeof rule.fileFilter === 'string' ? new RegExp(rule.fileFilter) : rule.fileFilter;
182
+ rule._ffRe = ff;
183
+ }
184
+ if (!ff.test(relPath)) continue;
185
+ }
186
+ // Precompute a mandatory literal once per rule (cached). '' = none extractable.
187
+ if (rule._lit === undefined) rule._lit = requiredLiteral(rule.re.source) || '';
188
+ activeRules.push(rule);
189
+ }
190
+
191
+ for (let i = 0; i < lines.length; i++) {
192
+ const line = lines[i];
193
+ if (line.length > 4000) continue; // minified blob line — skip.
194
+ const commented = isCommentLine(line);
195
+ const lineLower = line.toLowerCase();
196
+ for (const rule of activeRules) {
197
+ if (rule.skipComments && commented) continue;
198
+ // Cheap literal prefilter: if the rule's mandatory literal isn't on this
199
+ // line, the regex cannot match — skip it without running the regex.
200
+ if (rule._lit && !lineLower.includes(rule._lit)) continue;
201
+ for (const hit of matchAll(rule.re, line)) {
202
+ if (rule.skipInString && isInsideString(line, hit.index)) continue;
203
+ if (rule.filter && !rule.filter(line, hit, lines)) continue;
204
+ findings.push(
205
+ makeFinding(rule, {
206
+ file: relPath,
207
+ line: i + 1,
208
+ column: hit.index + 1,
209
+ snippet: redactSnippet(line.trim(), hit.match),
210
+ })
211
+ );
212
+ }
213
+ }
214
+ }
215
+
216
+ // Dataflow/taint analysis: follows user input across lines to a dangerous sink.
217
+ try {
218
+ const { analyzeTaint } = require('./taint');
219
+ for (const t of analyzeTaint(content, lines, relPath, tree)) findings.push(t);
220
+ } catch (err) {
221
+ noteDegraded('taint', err);
222
+ }
223
+
224
+ // Python taint analysis for .py files
225
+ if (relPath && relPath.endsWith('.py')) {
226
+ try {
227
+ const { analyzePythonTaint } = require('./engine');
228
+ for (const t of analyzePythonTaint(content, lines, relPath)) findings.push(t);
229
+ } catch (err) {
230
+ noteDegraded('python-taint', err);
231
+ }
232
+ }
233
+
234
+ // Optional AST pass (acorn) — precise eval/exec/Function/mass-assignment/nosql.
235
+ try {
236
+ const { analyzeAst, AST_SUPERSEDES } = require('./ast');
237
+ const ast = analyzeAst(content, relPath, tree); // tree cached by the caller
238
+ if (ast.parsed) {
239
+ // AST is precise for these categories — drop the regex heuristics for this
240
+ // file so we don't double-report or carry their false positives.
241
+ findings = findings.filter((f) => !AST_SUPERSEDES.has(f.ruleId));
242
+ }
243
+ for (const a of ast.findings) findings.push(a);
244
+ } catch (err) {
245
+ noteDegraded('ast', err);
246
+ }
247
+
248
+ // File-level rules (need whole-file context).
249
+ for (const rule of fileRules) {
250
+ let hits = [];
251
+ try {
252
+ hits = rule.run(content, lines, relPath) || [];
253
+ } catch (err) {
254
+ noteDegraded(`file-rule:${rule.id || 'unknown'}`, err);
255
+ hits = [];
256
+ }
257
+ for (const h of hits) {
258
+ findings.push(
259
+ makeFinding(rule, {
260
+ file: relPath,
261
+ line: h.line,
262
+ column: h.column || 1,
263
+ snippet: h.snippet,
264
+ message: h.message,
265
+ fix: h.fix,
266
+ severity: h.severity, // per-hit overrides (makeFinding falls back to rule)
267
+ confidence: h.confidence,
268
+ ruleId: h.ruleId,
269
+ title: h.title,
270
+ })
271
+ );
272
+ }
273
+ }
274
+ return findings;
275
+ }
276
+
277
+ // Never echo a full secret back into a report/log. Show a masked snippet.
278
+ function redactSnippet(line, match) {
279
+ if (!match || match.length < 8) return truncate(line);
280
+ const masked = match.slice(0, 4) + '****' + match.slice(-2);
281
+ return truncate(line.split(match).join(masked));
282
+ }
283
+
284
+ function truncate(s) {
285
+ return s.length > 160 ? s.slice(0, 157) + '...' : s;
286
+ }
287
+
288
+ // ---------------------------------------------------------------------------
289
+ // Project-level rules
290
+ // ---------------------------------------------------------------------------
291
+
292
+ function projectScan(root) {
293
+ const findings = [];
294
+ const gitignorePath = path.join(root, '.gitignore');
295
+ let gitignore = '';
296
+ try {
297
+ gitignore = fs.readFileSync(gitignorePath, 'utf8');
298
+ } catch {
299
+ gitignore = '';
300
+ }
301
+ const ignoreLines = gitignore
302
+ .split(/\r?\n/)
303
+ .map((l) => l.trim())
304
+ .filter(Boolean);
305
+
306
+ const envIsIgnored = ignoreLines.some((l) =>
307
+ /^\.env($|\.|\/|\*)/.test(l) || l === '.env*' || l === '*.env'
308
+ );
309
+
310
+ // .env present but not gitignored -> critical.
311
+ const envFiles = ['.env', '.env.local', '.env.production', '.env.development'];
312
+ for (const name of envFiles) {
313
+ const p = path.join(root, name);
314
+ if (fs.existsSync(p)) {
315
+ if (!envIsIgnored) {
316
+ findings.push({
317
+ ruleId: 'project.env-not-ignored',
318
+ severity: 'critical',
319
+ title: '.env not in .gitignore',
320
+ message: `${name} exists but is not covered by .gitignore — secrets can be committed and pushed.`,
321
+ fix: `Add ".env" (and ".env.*") to .gitignore, then remove it from git history if already committed (git rm --cached ${name}).`,
322
+ file: name,
323
+ line: 1,
324
+ column: 1,
325
+ snippet: `${name} present, .gitignore does not cover it`,
326
+ });
327
+ }
328
+ }
329
+ }
330
+
331
+ // A committed .git folder inside a subpath, or a tracked .env that is world-exposed
332
+ // via a public dir — flag .env living under a web/public/static dir.
333
+ const exposedDirs = ['public', 'static', 'dist', 'www'];
334
+ for (const d of exposedDirs) {
335
+ for (const name of ['.env', '.env.local']) {
336
+ const p = path.join(root, d, name);
337
+ if (fs.existsSync(p)) {
338
+ findings.push({
339
+ ruleId: 'project.env-exposed',
340
+ severity: 'critical',
341
+ title: '.env inside a public directory',
342
+ message: `${d}/${name} sits in a publicly served directory and may be downloadable.`,
343
+ fix: `Move ${name} out of ${d}/ and load config from environment variables.`,
344
+ file: `${d}/${name}`,
345
+ line: 1,
346
+ column: 1,
347
+ snippet: `${d}/${name} is web-served`,
348
+ });
349
+ }
350
+ }
351
+ }
352
+
353
+ // package.json present but no lockfile -> non-reproducible installs.
354
+ if (fs.existsSync(path.join(root, 'package.json'))) {
355
+ const lockfiles = ['package-lock.json', 'yarn.lock', 'pnpm-lock.yaml', 'npm-shrinkwrap.json'];
356
+ if (!lockfiles.some((l) => fs.existsSync(path.join(root, l)))) {
357
+ findings.push({
358
+ ruleId: 'package.no-lockfile',
359
+ severity: 'low',
360
+ confidence: 'high',
361
+ title: 'No dependency lockfile',
362
+ message: 'package.json exists but no lockfile is committed — installs are not reproducible and pull the newest matching versions (supply-chain drift).',
363
+ fix: 'Commit a lockfile (package-lock.json / yarn.lock / pnpm-lock.yaml).',
364
+ file: 'package.json',
365
+ line: 1,
366
+ column: 1,
367
+ snippet: 'no lockfile found',
368
+ });
369
+ }
370
+ }
371
+
372
+ return findings;
373
+ }
374
+
375
+ // ---------------------------------------------------------------------------
376
+ // Grading
377
+ // ---------------------------------------------------------------------------
378
+
379
+ const TIER = ['critical', 'high', 'medium', 'low'];
380
+
381
+ // Grade off EFFECTIVE severity: low-confidence findings are heuristics ("review
382
+ // this"), so they count one tier lower and low-confidence 'low' is ignored for
383
+ // the grade. This keeps a single heuristic hint from tanking an otherwise clean
384
+ // project, while confirmed issues still drive the grade hard.
385
+ function effectiveSeverity(f) {
386
+ if (f.confidence === 'low') {
387
+ const i = TIER.indexOf(f.severity);
388
+ return TIER[i + 1] || null; // low-confidence 'low' -> null (ignored)
389
+ }
390
+ return f.severity;
391
+ }
392
+
393
+ // Minimal glob -> RegExp: supports *, **, and gitignore-style "**/" (zero+ dirs).
394
+ function globToRe(glob) {
395
+ const esc = glob.replace(/[.+^${}()|[\]\\]/g, '\\$&');
396
+ const body = esc.replace(/\*\*\/|\*\*|\*/g, (m) =>
397
+ m === '**/' ? '(?:.*/)?' : m === '**' ? '.*' : '[^/]*'
398
+ );
399
+ return new RegExp('^' + body + '$');
400
+ }
401
+
402
+ // Inline suppression comments:
403
+ // // vibeguard-ignore-line [rule1, rule2] -> suppress on this line
404
+ // // vibeguard-ignore-next-line [rule1, ...] -> suppress on the next line
405
+ // No rule list = suppress everything on the target line. Works with //, #, /* */.
406
+ function buildIgnoreMap(lines) {
407
+ const map = new Map(); // targetLine(1-based) -> Set(ruleIds) | '*'
408
+ const re = /(?:\/\/|#|\/\*|\*)\s*vibeguard-ignore(-next)?-line\b([^*\n]*)/i;
409
+ for (let i = 0; i < lines.length; i++) {
410
+ const m = re.exec(lines[i]);
411
+ if (!m) continue;
412
+ const target = m[1] ? i + 2 : i + 1; // next-line -> i+2 (1-based)
413
+ const rulesPart = (m[2] || '').replace(/\*\/.*/, '').trim();
414
+ const rules = rulesPart
415
+ ? rulesPart.split(/[\s,]+/).filter(Boolean)
416
+ : '*';
417
+ const existing = map.get(target);
418
+ if (existing === '*' || rules === '*') map.set(target, '*');
419
+ else map.set(target, new Set([...(existing || []), ...rules]));
420
+ }
421
+ return map;
422
+ }
423
+
424
+ function applyInlineSuppressions(findings, contents) {
425
+ const byFile = new Map();
426
+ for (const c of contents) byFile.set(c.rel, buildIgnoreMap(c.lines));
427
+ return findings.filter((f) => {
428
+ const map = byFile.get(f.file);
429
+ if (!map) return true;
430
+ const entry = map.get(f.line);
431
+ if (!entry) return true;
432
+ if (entry === '*') return false;
433
+ return !entry.has(f.ruleId);
434
+ });
435
+ }
436
+
437
+ // Apply project config: drop ignored rules/paths, remap severities.
438
+ // config = { ignoreRules:[ruleId], ignorePaths:[glob], ignore:[{rule,path}],
439
+ // severityOverrides:{ruleId: 'low'} }
440
+ function applyConfigFilters(findings, config) {
441
+ if (!config || typeof config !== 'object') return findings;
442
+ const ignoreRules = new Set(Array.isArray(config.ignoreRules) ? config.ignoreRules : []);
443
+ const ignorePathRes = (Array.isArray(config.ignorePaths) ? config.ignorePaths : []).map(globToRe);
444
+ const pairIgnores = (Array.isArray(config.ignore) ? config.ignore : []).filter(
445
+ (x) => x && typeof x === 'object'
446
+ );
447
+ const sevOverride = config.severityOverrides && typeof config.severityOverrides === 'object'
448
+ ? config.severityOverrides
449
+ : {};
450
+ const validSev = new Set(['critical', 'high', 'medium', 'low']);
451
+
452
+ return findings
453
+ .filter((f) => {
454
+ if (ignoreRules.has(f.ruleId)) return false;
455
+ if (ignorePathRes.some((re) => re.test(f.file))) return false;
456
+ for (const pair of pairIgnores) {
457
+ const ruleMatch = !pair.rule || pair.rule === f.ruleId;
458
+ const pathMatch = !pair.path || globToRe(pair.path).test(f.file) || f.file.includes(pair.path);
459
+ if (ruleMatch && pathMatch) return false;
460
+ }
461
+ return true;
462
+ })
463
+ .map((f) => {
464
+ const ov = sevOverride[f.ruleId];
465
+ if (ov && validSev.has(ov)) return { ...f, severity: ov };
466
+ return f;
467
+ });
468
+ }
469
+
470
+ function computeGrade(findings) {
471
+ // Reported counts are the real severities (what the user sees).
472
+ const counts = { critical: 0, high: 0, medium: 0, low: 0 };
473
+ for (const f of findings) counts[f.severity] = (counts[f.severity] || 0) + 1;
474
+
475
+ // Grade counts use effective severity.
476
+ const g = { critical: 0, high: 0, medium: 0, low: 0 };
477
+ for (const f of findings) {
478
+ const s = effectiveSeverity(f);
479
+ if (s) g[s] += 1;
480
+ }
481
+
482
+ let grade;
483
+ if (g.critical > 0) grade = 'F';
484
+ else if (g.high > 0) grade = g.high >= 3 ? 'D' : 'C';
485
+ else if (g.medium > 0) grade = g.medium >= 3 ? 'C' : 'B';
486
+ else if (g.low > 0) grade = 'B';
487
+ else grade = 'A';
488
+
489
+ return { grade, counts };
490
+ }
491
+
492
+ // Collapse noise: on a single file:line, a specific rule supersedes the generic
493
+ // credential catch-all (e.g. a weak session secret shouldn't also report as a
494
+ // bare "hardcoded credential"). Also drop exact duplicate (ruleId+file+line).
495
+ //
496
+ // Additionally: when a dataflow-confirmed taint.* finding and a structural ast.*
497
+ // finding land on the same file:line and describe the same vulnerability category,
498
+ // keep only the taint finding (higher confidence) and drop the ast.* duplicate.
499
+ // Map: taint.command-injection ↔ ast.command-injection, etc.
500
+ const TAINT_TO_AST = {
501
+ 'taint.command-injection': 'ast.command-injection',
502
+ 'taint.sql-injection': 'ast.sql-injection',
503
+ 'taint.code-injection': 'ast.eval-dynamic',
504
+ 'taint.path-traversal': 'ast.path-traversal',
505
+ 'taint.ssrf': 'ast.ssrf',
506
+ };
507
+
508
+ function dedupeFindings(findings) {
509
+ const linesWithSpecific = new Set();
510
+ for (const f of findings) {
511
+ if (f.ruleId !== 'secret.generic-credential') {
512
+ linesWithSpecific.add(`${f.file}:${f.line}`);
513
+ }
514
+ }
515
+
516
+ // Build a set of taint.* ruleIds that fired, keyed by file:line, so we can
517
+ // drop the corresponding ast.* finding on the same file:line.
518
+ const taintKeys = new Set();
519
+ for (const f of findings) {
520
+ if (TAINT_TO_AST[f.ruleId]) {
521
+ taintKeys.add(`${f.file}:${f.line}:${TAINT_TO_AST[f.ruleId]}`);
522
+ }
523
+ }
524
+
525
+ const seen = new Set();
526
+ const out = [];
527
+ for (const f of findings) {
528
+ if (
529
+ f.ruleId === 'secret.generic-credential' &&
530
+ linesWithSpecific.has(`${f.file}:${f.line}`)
531
+ ) {
532
+ continue; // superseded by a more specific rule
533
+ }
534
+ // Drop ast.* finding when a taint.* finding already covers the same file:line.
535
+ const astCounterpart = Object.entries(TAINT_TO_AST).find(([, ast]) => ast === f.ruleId);
536
+ if (astCounterpart && taintKeys.has(`${f.file}:${f.line}:${f.ruleId}`)) {
537
+ continue; // superseded by the dataflow-confirmed taint finding
538
+ }
539
+ const key = `${f.ruleId}:${f.file}:${f.line}:${f.column}`;
540
+ if (seen.has(key)) continue;
541
+ seen.add(key);
542
+ out.push(f);
543
+ }
544
+ return out;
545
+ }
546
+
547
+ function sortFindings(findings) {
548
+ return findings.slice().sort((a, b) => {
549
+ const s = SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity];
550
+ if (s !== 0) return s;
551
+ if (a.file !== b.file) return a.file < b.file ? -1 : 1;
552
+ return a.line - b.line;
553
+ });
554
+ }
555
+
556
+ /**
557
+ * Scan a directory. Returns a structured result object.
558
+ * @param {string} dir
559
+ * @param {object} [opts]
560
+ */
561
+ function scan(dir, opts = {}) {
562
+ const root = path.resolve(dir);
563
+ // Apply project config (extends the redaction allowlist). Reset each scan so
564
+ // config never leaks between runs (important for tests / MCP long sessions).
565
+ const config = loadConfig(root);
566
+ rules.configure(config);
567
+
568
+ const allFiles = walk(root, [], null);
569
+
570
+ // Incremental mode: only scan files whose content changed since the last scan
571
+ // (SHA-256 hash cache under .vibeguard/cache). First run has an empty cache so
572
+ // everything is "changed" (full scan, populates cache); later runs are near
573
+ // instant. Cross-file analysis needs ALL files, so it is skipped here — this
574
+ // mode is per-file (line/AST/taint), intended for pre-commit / watch loops.
575
+ let files = allFiles;
576
+ let incremental = null;
577
+ let staged = null;
578
+ if (opts.staged) {
579
+ // Git-aware: scan only files staged for the current commit. Perfect for a
580
+ // pre-commit hook — fast and scoped to exactly what's being committed.
581
+ const stagedSet = getStagedFiles(root);
582
+ if (stagedSet) {
583
+ files = allFiles.filter((abs) => stagedSet.has(path.resolve(abs)));
584
+ staged = { total: allFiles.length, scanned: files.length };
585
+ }
586
+ } else if (opts.changed) {
587
+ const { getChangedFiles } = require('./engine');
588
+ const res = getChangedFiles(root, allFiles);
589
+ files = res.changed;
590
+ incremental = { total: res.total, scanned: res.changed.length, cached: res.cached };
591
+ }
592
+ // Both modes scan a partial file set → cross-file analysis (which needs the
593
+ // whole project) must be skipped and reported as such.
594
+ const partialScan = !!incremental || !!staged;
595
+
596
+ let findings = [];
597
+ const contents = []; // {rel, content, lines} for cross-file analysis
598
+ const trees = new Map(); // rel -> parsed AST (one parse per file, shared)
599
+ const astMod = require('./ast');
600
+
601
+ // Engine mode + coverage diagnostics. `astAvailable` is false when the acorn
602
+ // optional deps aren't installed → precise eval/exec/taint/mass-assignment
603
+ // passes silently downgrade to regex. We surface that instead of hiding it.
604
+ const astAvailable = astMod.isAvailable();
605
+ const diag = { degraded: [] };
606
+ const parseFailed = []; // JS/TS files acorn IS installed for but couldn't parse
607
+
608
+ for (const abs of files) {
609
+ let buf;
610
+ try {
611
+ buf = fs.readFileSync(abs);
612
+ } catch {
613
+ continue;
614
+ }
615
+ if (looksBinary(buf)) continue;
616
+ const rel = path.relative(root, abs).split(path.sep).join('/');
617
+ const content = buf.toString('utf8');
618
+ // Parse JS/TS once here; the AST pass, interprocedural, and cross-file all reuse it.
619
+ let tree = null;
620
+ if (/\.(?:js|jsx|ts|tsx|mjs|cjs)$/.test(rel)) {
621
+ try {
622
+ tree = astMod.parseSource(content, rel);
623
+ } catch {
624
+ tree = null;
625
+ }
626
+ if (tree) trees.set(rel, tree);
627
+ // acorn installed but this file didn't parse → AST rules skipped for it.
628
+ // (When acorn is absent entirely that's engine-mode, reported separately.)
629
+ else if (astAvailable) parseFailed.push(rel);
630
+ }
631
+ findings = findings.concat(scanFileContent(abs, rel, content, tree, diag));
632
+ contents.push({ rel, content, lines: content.split(/\r?\n/) });
633
+ }
634
+
635
+ // Cross-file passes need the WHOLE project in `contents`. In a partial scan
636
+ // (--changed / --staged) we only loaded a subset, so skip them (they would
637
+ // produce wrong results from a partial view) — the documented tradeoff.
638
+ if (!partialScan) {
639
+ // Cross-file taint: request data flowing across module boundaries into a sink.
640
+ try {
641
+ const { analyzeCrossFile } = require('./crosstaint');
642
+ for (const cf of analyzeCrossFile(contents, trees)) findings.push(cf);
643
+ } catch {
644
+ /* cross-file taint is optional (needs acorn) */
645
+ }
646
+
647
+ // Cross-file rules see every file at once (e.g. Supabase RLS across migrations).
648
+ for (const rule of crossFileRules) {
649
+ let hits = [];
650
+ try {
651
+ hits = rule.run(contents) || [];
652
+ } catch {
653
+ hits = [];
654
+ }
655
+ for (const h of hits) {
656
+ findings.push(
657
+ makeFinding(rule, {
658
+ file: h.file,
659
+ line: h.line,
660
+ column: h.column || 1,
661
+ snippet: h.snippet,
662
+ message: h.message,
663
+ fix: h.fix,
664
+ })
665
+ );
666
+ }
667
+ }
668
+ } // end !incremental cross-file block
669
+
670
+ findings = findings.concat(projectScan(root));
671
+
672
+ // Dependency vulnerabilities (opt-in; the CLI enables it by default, unit
673
+ // tests leave it off so they stay offline and deterministic).
674
+ let depsInfo = null;
675
+ if (opts.deps) {
676
+ try {
677
+ const { scanDependencies } = require('./deps');
678
+ const dep = scanDependencies(root);
679
+ findings = findings.concat(dep.findings);
680
+ depsInfo = { ran: dep.ran, notes: dep.notes };
681
+ } catch (err) {
682
+ depsInfo = { ran: { npm: false, pip: false }, notes: [String(err && err.message)] };
683
+ }
684
+ }
685
+
686
+ // Deep mode: fold in external best-in-class scanners if present (opt-in).
687
+ let externalInfo = null;
688
+ if (opts.deep) {
689
+ try {
690
+ const { runExternal } = require('./external');
691
+ const ext = runExternal(root);
692
+ findings = findings.concat(ext.findings);
693
+ externalInfo = { ran: ext.ran, notes: ext.notes };
694
+ } catch (err) {
695
+ externalInfo = { ran: {}, notes: [String(err && err.message)] };
696
+ }
697
+ }
698
+
699
+ // --no-suppress (opts.noSuppress): report everything, ignoring inline
700
+ // `vibeguard-ignore` comments and the heuristic FP filter. Config policy
701
+ // (ignoreRules/ignorePaths) is deliberate, versioned, and kept. This gives CI
702
+ // a trust mode that a careless/hostile inline comment in a PR cannot silence.
703
+ let suppressedFindings = [];
704
+ if (!opts.noSuppress) {
705
+ findings = applyInlineSuppressions(findings, contents);
706
+ const { applyInlineSuppressionsWithCount } = require('./suppress');
707
+ const supResult = applyInlineSuppressionsWithCount(findings, contents);
708
+ findings = supResult.kept;
709
+ suppressedFindings = supResult.suppressed;
710
+ }
711
+ findings = applyConfigFilters(findings, config);
712
+
713
+ // Merge plugin rules
714
+ try {
715
+ const { loadPlugins, getPluginRules } = require('./plugin');
716
+ loadPlugins(root, config);
717
+ const pluginRules = getPluginRules();
718
+ if (pluginRules.length > 0) {
719
+ const { matchAll, makeFinding } = require('./rules');
720
+ for (const [rel, content] of Object.entries(contents)) {
721
+ const lines = content.split(/\r?\n/);
722
+ for (let i = 0; i < lines.length; i++) {
723
+ const line = lines[i];
724
+ const commented = /^\s*(\/\/|#|--|\/\*)/.test(line);
725
+ for (const rule of pluginRules) {
726
+ if (rule.skipComments && commented) continue;
727
+ for (const hit of matchAll(rule.re, line)) {
728
+ findings.push(
729
+ makeFinding(rule, {
730
+ file: rel,
731
+ line: i + 1,
732
+ column: hit.index + 1,
733
+ snippet: line.trim().slice(0, 200),
734
+ })
735
+ );
736
+ }
737
+ }
738
+ }
739
+ }
740
+ }
741
+ } catch {
742
+ /* plugins are best-effort */
743
+ }
744
+
745
+ findings = dedupeFindings(findings);
746
+
747
+ // Context-aware false positive suppression (skipped under --no-suppress).
748
+ if (!opts.noSuppress) {
749
+ try {
750
+ const { suppressFindings } = require('./suppress');
751
+ findings = findings.filter((f) => {
752
+ const matching = contents.find((c) => c.rel === f.file);
753
+ if (matching) {
754
+ return suppressFindings([f], matching.content, f.file).length > 0;
755
+ }
756
+ return true;
757
+ });
758
+ } catch { /* suppression is best-effort */ }
759
+ }
760
+
761
+ findings = sortFindings(findings);
762
+ for (const f of findings) f.fingerprint = fingerprintOf(f);
763
+
764
+ const { grade, counts } = computeGrade(findings);
765
+
766
+ // Coverage transparency: engine mode + every pass that failed open. Callers
767
+ // (CLI, MCP, CI) can warn the user that a scan ran degraded rather than let a
768
+ // silent parse/taint failure masquerade as a clean result.
769
+ const engine = {
770
+ astAvailable,
771
+ mode: astAvailable ? 'ast' : 'regex-only',
772
+ };
773
+ const diagnostics = {
774
+ degradedPasses: diag.degraded,
775
+ parseFailedFiles: parseFailed,
776
+ degradedFileCount: new Set([...diag.degraded.map((d) => d.file), ...parseFailed]).size,
777
+ };
778
+
779
+ return {
780
+ root,
781
+ scannedFiles: files.length,
782
+ findings,
783
+ suppressedFindings,
784
+ suppressedCount: suppressedFindings.length,
785
+ grade,
786
+ counts,
787
+ depsInfo,
788
+ externalInfo,
789
+ engine,
790
+ diagnostics,
791
+ incremental, // null on a full scan; {total, scanned, cached} with --changed
792
+ staged, // null unless --staged; {total, scanned}
793
+ generatedAt: new Date().toISOString(),
794
+ };
795
+ }
796
+
797
+ module.exports = {
798
+ scan,
799
+ scanFileContent,
800
+ computeGrade,
801
+ sortFindings,
802
+ walk,
803
+ shouldScanFile,
804
+ SKIP_DIRS,
805
+ };