@yagyeshvyas/vibeguard 0.1.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.
Files changed (52) hide show
  1. package/README.md +600 -0
  2. package/bin/cli.js +1640 -0
  3. package/ci/vibeguard.yml +41 -0
  4. package/ci-templates/Jenkinsfile +26 -0
  5. package/ci-templates/azure-pipelines.yml +29 -0
  6. package/ci-templates/circleci.yml +24 -0
  7. package/ci-templates/gitlab.yml +19 -0
  8. package/hooks/pre-commit +31 -0
  9. package/package.json +94 -0
  10. package/src/ai-guard.js +205 -0
  11. package/src/ast.js +319 -0
  12. package/src/audit-trail.js +154 -0
  13. package/src/autofix.js +524 -0
  14. package/src/badge.js +42 -0
  15. package/src/behavior.js +205 -0
  16. package/src/compliance.js +151 -0
  17. package/src/crosstaint.js +324 -0
  18. package/src/cve-intel.js +136 -0
  19. package/src/dashboard.js +279 -0
  20. package/src/deps.js +159 -0
  21. package/src/doctor.js +111 -0
  22. package/src/engine.js +234 -0
  23. package/src/external.js +160 -0
  24. package/src/firewall.js +517 -0
  25. package/src/history.js +87 -0
  26. package/src/hook.js +151 -0
  27. package/src/install.js +248 -0
  28. package/src/interceptor.js +476 -0
  29. package/src/mcp-server.js +1804 -0
  30. package/src/net-audit.js +208 -0
  31. package/src/pii.js +212 -0
  32. package/src/plugin.js +80 -0
  33. package/src/policy-gen.js +288 -0
  34. package/src/pre-deploy.js +282 -0
  35. package/src/presets.js +113 -0
  36. package/src/privacy-audit.js +273 -0
  37. package/src/repl.js +150 -0
  38. package/src/report.js +312 -0
  39. package/src/rules-pack.js +2753 -0
  40. package/src/rules.js +1446 -0
  41. package/src/sandbox.js +139 -0
  42. package/src/scanner.js +651 -0
  43. package/src/secure-prompt.js +140 -0
  44. package/src/slopsquat.js +144 -0
  45. package/src/supply-firewall.js +243 -0
  46. package/src/suppress.js +89 -0
  47. package/src/taint.js +168 -0
  48. package/src/trace.js +220 -0
  49. package/src/urlscan.js +142 -0
  50. package/src/vault.js +145 -0
  51. package/src/verify.js +98 -0
  52. package/src/verifykeys.js +87 -0
package/src/scanner.js ADDED
@@ -0,0 +1,651 @@
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)) 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)) 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
+ function dedupeFindings(findings) {
444
+ const linesWithSpecific = new Set();
445
+ for (const f of findings) {
446
+ if (f.ruleId !== 'secret.generic-credential') {
447
+ linesWithSpecific.add(`${f.file}:${f.line}`);
448
+ }
449
+ }
450
+ const seen = new Set();
451
+ const out = [];
452
+ for (const f of findings) {
453
+ if (
454
+ f.ruleId === 'secret.generic-credential' &&
455
+ linesWithSpecific.has(`${f.file}:${f.line}`)
456
+ ) {
457
+ continue; // superseded by a more specific rule
458
+ }
459
+ const key = `${f.ruleId}:${f.file}:${f.line}:${f.column}`;
460
+ if (seen.has(key)) continue;
461
+ seen.add(key);
462
+ out.push(f);
463
+ }
464
+ return out;
465
+ }
466
+
467
+ function sortFindings(findings) {
468
+ return findings.slice().sort((a, b) => {
469
+ const s = SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity];
470
+ if (s !== 0) return s;
471
+ if (a.file !== b.file) return a.file < b.file ? -1 : 1;
472
+ return a.line - b.line;
473
+ });
474
+ }
475
+
476
+ /**
477
+ * Scan a directory. Returns a structured result object.
478
+ * @param {string} dir
479
+ * @param {object} [opts]
480
+ */
481
+ function scan(dir, opts = {}) {
482
+ const root = path.resolve(dir);
483
+ // Apply project config (extends the redaction allowlist). Reset each scan so
484
+ // config never leaks between runs (important for tests / MCP long sessions).
485
+ const config = loadConfig(root);
486
+ rules.configure(config);
487
+
488
+ const files = walk(root, [], null);
489
+ let findings = [];
490
+ const contents = []; // {rel, content, lines} for cross-file analysis
491
+ const trees = new Map(); // rel -> parsed AST (one parse per file, shared)
492
+ const astMod = require('./ast');
493
+
494
+ for (const abs of files) {
495
+ let buf;
496
+ try {
497
+ buf = fs.readFileSync(abs);
498
+ } catch {
499
+ continue;
500
+ }
501
+ if (looksBinary(buf)) continue;
502
+ const rel = path.relative(root, abs).split(path.sep).join('/');
503
+ const content = buf.toString('utf8');
504
+ // Parse JS/TS once here; the AST pass, interprocedural, and cross-file all reuse it.
505
+ let tree = null;
506
+ if (/\.(?:js|jsx|ts|tsx|mjs|cjs)$/.test(rel)) {
507
+ try {
508
+ tree = astMod.parseSource(content, rel);
509
+ } catch {
510
+ tree = null;
511
+ }
512
+ if (tree) trees.set(rel, tree);
513
+ }
514
+ findings = findings.concat(scanFileContent(abs, rel, content, tree));
515
+ contents.push({ rel, content, lines: content.split(/\r?\n/) });
516
+ }
517
+
518
+ // Cross-file taint: request data flowing across module boundaries into a sink.
519
+ try {
520
+ const { analyzeCrossFile } = require('./crosstaint');
521
+ for (const cf of analyzeCrossFile(contents, trees)) findings.push(cf);
522
+ } catch {
523
+ /* cross-file taint is optional (needs acorn) */
524
+ }
525
+
526
+ // Cross-file rules see every file at once (e.g. Supabase RLS across migrations).
527
+ for (const rule of crossFileRules) {
528
+ let hits = [];
529
+ try {
530
+ hits = rule.run(contents) || [];
531
+ } catch {
532
+ hits = [];
533
+ }
534
+ for (const h of hits) {
535
+ findings.push(
536
+ makeFinding(rule, {
537
+ file: h.file,
538
+ line: h.line,
539
+ column: h.column || 1,
540
+ snippet: h.snippet,
541
+ message: h.message,
542
+ fix: h.fix,
543
+ })
544
+ );
545
+ }
546
+ }
547
+
548
+ findings = findings.concat(projectScan(root));
549
+
550
+ // Dependency vulnerabilities (opt-in; the CLI enables it by default, unit
551
+ // tests leave it off so they stay offline and deterministic).
552
+ let depsInfo = null;
553
+ if (opts.deps) {
554
+ try {
555
+ const { scanDependencies } = require('./deps');
556
+ const dep = scanDependencies(root);
557
+ findings = findings.concat(dep.findings);
558
+ depsInfo = { ran: dep.ran, notes: dep.notes };
559
+ } catch (err) {
560
+ depsInfo = { ran: { npm: false, pip: false }, notes: [String(err && err.message)] };
561
+ }
562
+ }
563
+
564
+ // Deep mode: fold in external best-in-class scanners if present (opt-in).
565
+ let externalInfo = null;
566
+ if (opts.deep) {
567
+ try {
568
+ const { runExternal } = require('./external');
569
+ const ext = runExternal(root);
570
+ findings = findings.concat(ext.findings);
571
+ externalInfo = { ran: ext.ran, notes: ext.notes };
572
+ } catch (err) {
573
+ externalInfo = { ran: {}, notes: [String(err && err.message)] };
574
+ }
575
+ }
576
+
577
+ findings = applyInlineSuppressions(findings, contents);
578
+ findings = applyConfigFilters(findings, config);
579
+
580
+ // Merge plugin rules
581
+ try {
582
+ const { loadPlugins, getPluginRules } = require('./plugin');
583
+ loadPlugins(root, config);
584
+ const pluginRules = getPluginRules();
585
+ if (pluginRules.length > 0) {
586
+ const { matchAll, makeFinding } = require('./rules');
587
+ for (const [rel, content] of Object.entries(contents)) {
588
+ const lines = content.split(/\r?\n/);
589
+ for (let i = 0; i < lines.length; i++) {
590
+ const line = lines[i];
591
+ const commented = /^\s*(\/\/|#|--|\/\*)/.test(line);
592
+ for (const rule of pluginRules) {
593
+ if (rule.skipComments && commented) continue;
594
+ for (const hit of matchAll(rule.re, line)) {
595
+ findings.push(
596
+ makeFinding(rule, {
597
+ file: rel,
598
+ line: i + 1,
599
+ column: hit.index + 1,
600
+ snippet: line.trim().slice(0, 200),
601
+ })
602
+ );
603
+ }
604
+ }
605
+ }
606
+ }
607
+ }
608
+ } catch {
609
+ /* plugins are best-effort */
610
+ }
611
+
612
+ findings = dedupeFindings(findings);
613
+
614
+ // Context-aware false positive suppression
615
+ try {
616
+ const { suppressFindings } = require('./suppress');
617
+ findings = findings.filter((f) => {
618
+ const matching = contents.find((c) => c.rel === f.file);
619
+ if (matching) {
620
+ return suppressFindings([f], matching.content, f.file).length > 0;
621
+ }
622
+ return true;
623
+ });
624
+ } catch { /* suppression is best-effort */ }
625
+
626
+ findings = sortFindings(findings);
627
+ for (const f of findings) f.fingerprint = fingerprintOf(f);
628
+
629
+ const { grade, counts } = computeGrade(findings);
630
+
631
+ return {
632
+ root,
633
+ scannedFiles: files.length,
634
+ findings,
635
+ grade,
636
+ counts,
637
+ depsInfo,
638
+ externalInfo,
639
+ generatedAt: new Date().toISOString(),
640
+ };
641
+ }
642
+
643
+ module.exports = {
644
+ scan,
645
+ scanFileContent,
646
+ computeGrade,
647
+ sortFindings,
648
+ walk,
649
+ shouldScanFile,
650
+ SKIP_DIRS,
651
+ };