xploitscan-shared-rules 2.2.0 → 2.4.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.cjs CHANGED
@@ -33,6 +33,7 @@ __export(index_exports, {
33
33
  CHECKABLE_CLAIMS: () => CHECKABLE_CLAIMS,
34
34
  DOTENV_ASSIGN_RE: () => DOTENV_ASSIGN_RE,
35
35
  FREE_RULE_COUNT: () => FREE_RULE_COUNT,
36
+ GRADE_FINDINGS_PER_RULE: () => GRADE_FINDINGS_PER_RULE,
36
37
  INTENT_EXPECTATIONS: () => INTENT_EXPECTATIONS,
37
38
  MODEL_ANALYSIS: () => MODEL_ANALYSIS,
38
39
  MODEL_POLICY_REVIEWED: () => MODEL_POLICY_REVIEWED,
@@ -87,6 +88,7 @@ __export(index_exports, {
87
88
  freeRules: () => freeRules,
88
89
  getObjectProperty: () => getObjectProperty,
89
90
  getSnippet: () => getSnippet,
91
+ gradeRuleFamily: () => gradeRuleFamily,
90
92
  hardcodedJWTSecret: () => hardcodedJWTSecret,
91
93
  hardcodedSecrets: () => hardcodedSecrets,
92
94
  harvestIntent: () => harvestIntent,
@@ -99,11 +101,15 @@ __export(index_exports, {
99
101
  isInlineSilenced: () => isInlineSilenced,
100
102
  isInsideFixMessage: () => isInsideFixMessage,
101
103
  isLineSilenced: () => isLineSilenced,
104
+ isLive: () => isLive,
102
105
  isMethodCall: () => isMethodCall,
103
106
  isPrivateAddress: () => isPrivateAddress,
107
+ isSbomPath: () => isSbomPath,
104
108
  isServerSideFile: () => isServerSideFile,
105
109
  isServerTarget: () => isServerTarget,
106
110
  isTestFile: () => isTestFile,
111
+ isTestPath: () => isTestPath,
112
+ isUngradedFinding: () => isUngradedFinding,
107
113
  isVendoredFinding: () => isVendoredFinding,
108
114
  isVendoredPath: () => isVendoredPath,
109
115
  lineNumberAt: () => lineNumberAt,
@@ -538,6 +544,15 @@ var NON_APP_PATH_PATTERNS = [
538
544
  "**/vendor/**",
539
545
  "**/vendored/**",
540
546
  "**/third_party/**",
547
+ // Hyphen, closed, and plural spellings. `third_party` alone left
548
+ // `third-party/licenses/*.spdx.json` in the grade.
549
+ "**/third-party/**",
550
+ "**/thirdparty/**",
551
+ "**/third_parties/**",
552
+ "**/third-parties/**",
553
+ "**/3rd_party/**",
554
+ "**/3rd-party/**",
555
+ "**/3rdparty/**",
541
556
  "**/generated/**",
542
557
  "**/__generated__/**"
543
558
  ];
@@ -601,6 +616,89 @@ function vendoredReason(filePath) {
601
616
  return null;
602
617
  }
603
618
 
619
+ // src/test-path.ts
620
+ function normalize(filePath) {
621
+ return filePath.replace(/\\/g, "/");
622
+ }
623
+ function baseName(normalized) {
624
+ const slash = normalized.lastIndexOf("/");
625
+ return slash === -1 ? normalized : normalized.slice(slash + 1);
626
+ }
627
+ function isTestPath(filePath) {
628
+ const normalized = normalize(filePath);
629
+ if (!normalized) return false;
630
+ const base = baseName(normalized);
631
+ if (/(?:\.test\.|\.spec\.|\.stories\.|\.story\.|\.mock\.|\.cy\.|\.e2e\.)/i.test(base)) return true;
632
+ if (/^test_.*\.py$/i.test(base) || /_test\.py$/i.test(base)) return true;
633
+ if (/^Test[A-Z_]\w*\.py$/.test(base)) return true;
634
+ if (/^conftest\.py$/i.test(base)) return true;
635
+ if (/_test\.go$/.test(base)) return true;
636
+ if (/(?:^|\/)routes\/test\//i.test(normalized)) return false;
637
+ if (/(?:^|\/)(?:tests|testdata|spec|__tests__|__mocks__|fixtures?|mocks?)(?:\/|$)/i.test(normalized)) return true;
638
+ if (/(?:^|\/)test\//i.test(normalized)) return true;
639
+ if (/(?:^|\/)[^/]*\.(?:UnitTests|IntegrationTests|Tests)\//i.test(normalized)) return true;
640
+ if (/test-utils/i.test(normalized)) return true;
641
+ if (/(?:^|\/)testing(?:\/|$)/i.test(normalized)) return true;
642
+ return false;
643
+ }
644
+ var SBOM_FILE_RE = /(?:^|\/)(?:[^/]*\.spdx(?:\.json)?|[^/]*\.cdx\.json|[^/]*\.cdx\.xml|bom\.json|sbom[^/]*\.json|[^/]*\.sbom\.json|[^/]*cyclonedx[^/]*\.(?:json|xml))$/i;
645
+ function isSbomPath(filePath) {
646
+ return SBOM_FILE_RE.test(normalize(filePath));
647
+ }
648
+ function isPlaceholderToken(token) {
649
+ if (!token) return true;
650
+ if (/(.)\1{7,}/.test(token)) return true;
651
+ if (new Set(token).size < 8) return true;
652
+ return /example|placeholder|redacted|your_?(?:api_?)?(?:key|token)|insert_?your|replace_?me|\b(?:test|fake|dummy|sample|your)\b/i.test(token);
653
+ }
654
+ var LIVE_TOKEN_SOURCES = [
655
+ String.raw`(?:sk|rk)_live_[A-Za-z0-9]+`,
656
+ // OpenAI (`T3BlbkFJ` sits in every sk-proj- / sk-svcacct- / sk-admin- / legacy
657
+ // sk- key) and OpenRouter. A bare `sk-` is not a provider format.
658
+ String.raw`sk-(?:(?:proj|svcacct|admin)-[A-Za-z0-9_-]{20,80}|[A-Za-z0-9]{20,80})T3BlbkFJ[A-Za-z0-9_-]{20,80}`,
659
+ String.raw`sk-or-v1-[a-f0-9]{64}`,
660
+ String.raw`sk-ant-api03-[A-Za-z0-9_-]{80,}`,
661
+ String.raw`ghp_[A-Za-z0-9]{36}`,
662
+ String.raw`github_pat_[A-Za-z0-9_]{22,}`,
663
+ String.raw`xox[a-z]-[0-9A-Za-z-]{10,}`,
664
+ String.raw`AIza[A-Za-z0-9_-]{35}`,
665
+ String.raw`SG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}`,
666
+ String.raw`\bhf_[A-Za-z]{34}\b`,
667
+ String.raw`(?:AKIA|ABIA|ACCA|ASIA)[A-Z0-9]{16}`
668
+ ];
669
+ function providerTokens(text) {
670
+ if (!text) return [];
671
+ const out = [];
672
+ for (const source of LIVE_TOKEN_SOURCES) {
673
+ const found = text.match(new RegExp(source, "g"));
674
+ if (found) out.push(...found);
675
+ }
676
+ return out;
677
+ }
678
+ function tokenIsLive(token) {
679
+ if (isPlaceholderToken(token)) return false;
680
+ if (/^(?:AKIA|ABIA|ACCA|ASIA)/.test(token) && /EXAMPLE$/i.test(token)) return false;
681
+ return true;
682
+ }
683
+ function isLive(finding) {
684
+ const rule = finding?.rule ?? "";
685
+ if (rule === "ENTROPY" || rule.startsWith("ENTROPY-")) return false;
686
+ if (rule === "VC002" || rule === "VC014") return false;
687
+ if (rule === "VC001") return finding?.live === true;
688
+ if (finding?.live === true) return true;
689
+ const snippet = finding?.snippet ?? "";
690
+ if (providerTokens(snippet).length > 0 && !textHasLiveCredential(snippet)) return false;
691
+ return finding?.category === "Secrets";
692
+ }
693
+ function textHasLiveCredential(text) {
694
+ return providerTokens(text).some(tokenIsLive);
695
+ }
696
+ function isUngradedFinding(finding, options = {}) {
697
+ if (isTestPath(finding?.file ?? "")) return !isLive(finding);
698
+ if (options.gradeVendored) return false;
699
+ return isVendoredFinding(finding);
700
+ }
701
+
604
702
  // src/routes.ts
605
703
  var API_RE = /^\/api(\/|$)|^\/_|\.(json|js|xml|txt|ico)$/;
606
704
  var DYNAMIC_RE = /:[A-Za-z_]|\[[^\]]+\]|<[^>]+>|\$[A-Za-z_]|\*/;
@@ -616,7 +714,7 @@ function hasDep(files, name) {
616
714
  return false;
617
715
  }
618
716
  }
619
- function normalize(p) {
717
+ function normalize2(p) {
620
718
  if (!p.startsWith("/")) return "";
621
719
  if (p.length > 1 && p.endsWith("/")) return p.replace(/\/+$/, "");
622
720
  return p;
@@ -625,7 +723,7 @@ function extractRoutes(files) {
625
723
  const routes = /* @__PURE__ */ new Map();
626
724
  const frameworks = /* @__PURE__ */ new Set();
627
725
  const add = (raw, framework, source, kindOverride) => {
628
- const path = normalize(raw);
726
+ const path = normalize2(raw);
629
727
  if (!path || routes.has(path)) return;
630
728
  routes.set(path, {
631
729
  path,
@@ -1637,7 +1735,7 @@ function callSpreads(call, matcher) {
1637
1735
  // src/rules.ts
1638
1736
  var TEST_FILE_PATTERN = /(?:\.test\.|\.spec\.|__tests__|__mocks__|\.stories\.|\.story\.|\/test\/|\/tests\/|\/fixtures?\/|\/mocks?\/|\.mock\.|test-utils|testing|\.cy\.|\.e2e\.)/i;
1639
1737
  function isTestFile(filePath) {
1640
- return TEST_FILE_PATTERN.test(filePath);
1738
+ return isTestPath(filePath);
1641
1739
  }
1642
1740
  var HANDLER_HEADER_RE = /(?:\b(?:async\s+)?function\b|=>\s*$|=>\s*\{?\s*$|\.(?:get|post|put|patch|delete|use|all)\s*\(|\bexport\s+(?:async\s+)?(?:function|const)\s+(?:GET|POST|PUT|PATCH|DELETE)\b|\b(?:Deno\.)?serve\s*\()/i;
1643
1741
  function maskComments(content) {
@@ -1852,11 +1950,6 @@ function isNamespacedSlotKey(name, value) {
1852
1950
  }
1853
1951
  var CREDENTIAL_NAME = /SECRET|SIGN|ENCRYPT|CRYPT|CIPHER|HMAC|JWT|PRIVATE|API|ACCESS|AUTH|MASTER|ADMIN|SESSION|PASS|TOKEN|CLIENT|SALT|PEPPER|LICEN[CS]E|WEBHOOK|STRIPE|AWS|SERVICE/;
1854
1952
  var CREDENTIAL_WORD = /secret|passw|token|private|signing|apikey|credential/i;
1855
- function isPlaceholderToken(token) {
1856
- if (/(.)\1{7,}/.test(token)) return true;
1857
- if (new Set(token).size < 8) return true;
1858
- return /example|placeholder|redacted|your_?(?:api_?)?(?:key|token)|insert_?your|replace_?me/i.test(token);
1859
- }
1860
1953
  var GEMINI_FILE_CONTEXT_RE = /generativelanguage\.googleapis\.com|@google\/generative-ai|@google\/genai|\bGoogleGenerativeAI\b|\bGoogleGenAI\b|\bgoogle\.generativeai\b|\bfrom\s+google\s+import\s+genai\b/;
1861
1954
  var GEMINI_NAME_RE = /gemini|generative/i;
1862
1955
  var PUBLIC_GOOGLE_KEY_NAME_RE = /firebase|maps?(?:\b|_)|places|recaptcha|youtube/i;
@@ -1873,6 +1966,39 @@ function isGeminiKeyContext(lines, line, fileIsGemini) {
1873
1966
  }
1874
1967
  return fileIsGemini || GEMINI_NAME_RE.test(before);
1875
1968
  }
1969
+ function dbUrlLacksRealCredential(url) {
1970
+ const rest = url.replace(/^[a-z0-9+]+:\/\//i, "");
1971
+ const at = rest.lastIndexOf("@");
1972
+ if (at < 0) return true;
1973
+ const userinfo = rest.slice(0, at);
1974
+ const colon = userinfo.indexOf(":");
1975
+ const user = colon < 0 ? userinfo : userinfo.slice(0, colon);
1976
+ const pass = colon < 0 ? "" : decodeURIComponentSafe(userinfo.slice(colon + 1));
1977
+ if (!pass) return true;
1978
+ if (isFormatPlaceholder(pass)) return true;
1979
+ if (isPlaceholderSecret(pass)) return true;
1980
+ if (/^(?:u|user|username)$/i.test(user) && /^(?:pass|password|passwd|pwd)$/i.test(pass)) return true;
1981
+ return false;
1982
+ }
1983
+ function decodeURIComponentSafe(value) {
1984
+ try {
1985
+ return decodeURIComponent(value);
1986
+ } catch {
1987
+ return value;
1988
+ }
1989
+ }
1990
+ var FORMAT_PLACEHOLDER_MAX = 256;
1991
+ function isFormatPlaceholder(value) {
1992
+ const v = value.trim();
1993
+ if (!v) return true;
1994
+ if (v.length > FORMAT_PLACEHOLDER_MAX) return false;
1995
+ if (/^(?:%(?:[%sdifvx]|\([^)]+\))|\{[0-9]*\}|\$\{[^}]*\}|<[^<>]*>|\*+)$/i.test(v)) return true;
1996
+ if (/%(?:[%sdifvx]|\([^)]+\))|\{[0-9]*\}|\$\{[^}]*\}|<[^<>]*>/.test(v)) return true;
1997
+ return false;
1998
+ }
1999
+ function isPlaceholderSecret(value) {
2000
+ return /^(?:password|passwd|pwd|changeme|change[-_]?me|your[-_]?password)$/i.test(value.trim());
2001
+ }
1876
2002
  var hardcodedSecrets = {
1877
2003
  id: "VC001",
1878
2004
  title: "Hardcoded API Key or Secret",
@@ -1881,7 +2007,6 @@ var hardcodedSecrets = {
1881
2007
  description: "API keys, tokens, or secrets hardcoded in source code can be extracted by anyone with access to the code.",
1882
2008
  check(content, filePath) {
1883
2009
  if (filePath.endsWith(".example") || filePath.endsWith(".template")) return [];
1884
- if (isTestFile(filePath)) return [];
1885
2010
  if (filePath.match(/\.(md|txt|rst|adoc)$/)) return [];
1886
2011
  const patterns = [
1887
2012
  // Generic API key patterns — require actual value assignment, not variable declarations
@@ -2015,13 +2140,17 @@ var hardcodedSecrets = {
2015
2140
  if (isPlaceholderToken(token)) continue;
2016
2141
  if (pi === GOOGLE_PI) {
2017
2142
  if (!isGeminiKeyContext(lines, rm.line, fileIsGemini)) continue;
2018
- matches.push({ ...rm, severity: "high" });
2143
+ matches.push(textHasLiveCredential(token) ? { ...rm, severity: "high", live: true } : { ...rm, severity: "high" });
2019
2144
  continue;
2020
2145
  }
2021
2146
  if (pi === STRIPE_RESTRICTED_PI && !token.startsWith("rk_live_")) {
2022
2147
  matches.push({ ...rm, severity: "high" });
2023
2148
  continue;
2024
2149
  }
2150
+ if (textHasLiveCredential(token)) {
2151
+ matches.push({ ...rm, live: true });
2152
+ continue;
2153
+ }
2025
2154
  }
2026
2155
  if (floor > 0) {
2027
2156
  const secretMatch = lineText.match(/[:=]\s*["'`]([^"'`]*)["'`]/);
@@ -2037,7 +2166,9 @@ var hardcodedSecrets = {
2037
2166
  if (isKeySuffix && isSlotIdentifier) continue;
2038
2167
  }
2039
2168
  }
2040
- matches.push(rm);
2169
+ if (pi === 10 && dbUrlLacksRealCredential(matchedText[ri] ?? "")) continue;
2170
+ const matched = matchedText[ri] ?? "";
2171
+ matches.push(textHasLiveCredential(matched) ? { ...rm, live: true } : rm);
2041
2172
  }
2042
2173
  }
2043
2174
  return matches;
@@ -3503,10 +3634,12 @@ var missingHTTPS = {
3503
3634
  category: "Configuration",
3504
3635
  description: "Hardcoded http:// URLs (other than localhost and private-network addresses) send data unencrypted, exposing it to man-in-the-middle attacks.",
3505
3636
  check(content, filePath) {
3506
- const baseName = filePath.slice(filePath.lastIndexOf("/") + 1);
3507
- 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);
3508
- if (filePath.endsWith(".example") || isTestPath || filePath.includes("README")) return [];
3509
- if (filePath.match(/\.(md|txt)$/)) return [];
3637
+ const baseName2 = filePath.slice(filePath.lastIndexOf("/") + 1);
3638
+ const vc032SkipsTests = /(?:^|\/)(?:__tests__|tests?|testdata|testing|test[-_]?(?:utils?|helpers?|support))\//i.test(filePath) || /^(?:tests?(?![a-z])|conftest\.py$|setupTests\.)|[._-]tests?\.\w+$|\.spec\.\w+$|_spec\.rb$/.test(baseName2);
3639
+ if (filePath.endsWith(".example") || vc032SkipsTests || filePath.includes("README")) return [];
3640
+ if (filePath.match(/\.(md|txt|rst)$/)) return [];
3641
+ if (/(?:^|\/)(?:doc|docs)\//i.test(filePath)) return [];
3642
+ if (/(?:^|\/)conf\.py$/i.test(filePath) && /intersphinx/i.test(content)) return [];
3510
3643
  const matches = [];
3511
3644
  const isScriptFile = /\.(?:[cm]?[jt]sx?|vue|svelte)$/i.test(filePath);
3512
3645
  if (!isScriptFile && /<!DOCTYPE|xmlns|\.dtd|\.xsd/i.test(content) && !/fetch|axios|request|http\.get/i.test(content)) return [];
@@ -3522,6 +3655,8 @@ var missingHTTPS = {
3522
3655
  for (const rm of rawMatches) {
3523
3656
  const matchText = lines[rm.line - 1] ?? "";
3524
3657
  if (/DTD|DOCTYPE|w3\.org|apple\.com\/DTDs|\bxmlns[\w:-]*\s*=/i.test(matchText)) continue;
3658
+ if (/["']\$schema["']\s*:|["']\$id["']\s*:/.test(matchText)) continue;
3659
+ if (/--\s*tsaurl\b|\btsaurl\b|timestamp\.(?:digicert|sectigo|comodoca|globalsign|entrust|geotrust|verisign|apple)\.|timestamp\.acs\.microsoft\.com|freetsa\.org/i.test(matchText)) continue;
3525
3660
  matches.push(rm);
3526
3661
  }
3527
3662
  return matches;
@@ -3854,10 +3989,68 @@ function detectPlatform(files) {
3854
3989
  }
3855
3990
  return [...platforms];
3856
3991
  }
3992
+ var GRADE_FINDINGS_PER_RULE = 3;
3993
+ var GRADE_SEVERITY_RANK = {
3994
+ critical: 4,
3995
+ high: 3,
3996
+ medium: 2,
3997
+ low: 1,
3998
+ info: 0
3999
+ };
4000
+ var ADVISORY_FAMILY_RE = /^(?:GHSA-|CVE-\d|OSV-|DEP\d)/i;
4001
+ function gradeRuleFamily(finding) {
4002
+ const rule = (finding.rule ?? "").trim();
4003
+ const id = finding.id ?? "";
4004
+ if (ADVISORY_FAMILY_RE.test(rule) || ADVISORY_FAMILY_RE.test(id)) return "ADVISORY";
4005
+ if (rule === "ENTROPY" || rule.startsWith("ENTROPY-")) return "ENTROPY";
4006
+ if (rule) return rule;
4007
+ if (id === "ENTROPY" || id.startsWith("ENTROPY-")) return "ENTROPY";
4008
+ return id || "unknown";
4009
+ }
4010
+ function isDeductingSeverity(severity) {
4011
+ return severity === "critical" || severity === "high" || severity === "medium" || severity === "low";
4012
+ }
4013
+ function findingsCountedTowardGrade(findings) {
4014
+ const groups = /* @__PURE__ */ new Map();
4015
+ findings.forEach((item, index) => {
4016
+ const key = gradeRuleFamily(item);
4017
+ const bucket = groups.get(key);
4018
+ const entry = { item, index };
4019
+ if (bucket) bucket.push(entry);
4020
+ else groups.set(key, [entry]);
4021
+ });
4022
+ const counted = [];
4023
+ for (const bucket of groups.values()) {
4024
+ const ranked = bucket.length <= GRADE_FINDINGS_PER_RULE ? bucket : [...bucket].sort((a, b) => {
4025
+ const bySeverity = (GRADE_SEVERITY_RANK[b.item.severity ?? ""] ?? 0) - (GRADE_SEVERITY_RANK[a.item.severity ?? ""] ?? 0);
4026
+ return bySeverity !== 0 ? bySeverity : a.index - b.index;
4027
+ }).slice(0, GRADE_FINDINGS_PER_RULE);
4028
+ for (const entry of ranked) counted.push(entry.item);
4029
+ }
4030
+ return counted;
4031
+ }
3857
4032
  function calculateGrade(findings, _totalFiles, options = {}) {
3858
- const scored = options.gradeVendored ? findings : findings.filter((f) => !isVendoredFinding(f));
4033
+ const scored = findings.filter((f) => !isUngradedFinding(f, options));
3859
4034
  const ungraded = findings.length - scored.length;
3860
- const holdout = ungraded > 0 ? ` ${ungraded} finding${ungraded === 1 ? "" : "s"} in vendored, generated, or documentation files ${ungraded === 1 ? "is" : "are"} reported but not graded.` : "";
4035
+ let testHeld = 0;
4036
+ let vendoredHeld = 0;
4037
+ for (const f of findings) {
4038
+ if (!isUngradedFinding(f, options)) continue;
4039
+ if (isTestPath(f.file ?? "")) testHeld++;
4040
+ else vendoredHeld++;
4041
+ }
4042
+ const holdoutParts = [];
4043
+ if (vendoredHeld > 0) {
4044
+ holdoutParts.push(
4045
+ `${vendoredHeld} finding${vendoredHeld === 1 ? "" : "s"} in vendored, generated, or documentation files ${vendoredHeld === 1 ? "is" : "are"} reported but not graded.`
4046
+ );
4047
+ }
4048
+ if (testHeld > 0) {
4049
+ holdoutParts.push(
4050
+ `${testHeld} finding${testHeld === 1 ? "" : "s"} in a test or fixture file, not counted toward the grade, ${testHeld === 1 ? "is" : "are"} reported but not graded.`
4051
+ );
4052
+ }
4053
+ const holdout = holdoutParts.length > 0 ? ` ${holdoutParts.join(" ")}` : "";
3861
4054
  if (scored.length === 0) {
3862
4055
  return {
3863
4056
  grade: "A+",
@@ -3866,13 +4059,22 @@ function calculateGrade(findings, _totalFiles, options = {}) {
3866
4059
  ungraded
3867
4060
  };
3868
4061
  }
4062
+ const counted = findingsCountedTowardGrade(scored);
3869
4063
  let critical = 0, high = 0, medium = 0, low = 0;
3870
- for (const f of scored) {
4064
+ for (const f of counted) {
3871
4065
  if (f.severity === "critical") critical++;
3872
4066
  else if (f.severity === "high") high++;
3873
4067
  else if (f.severity === "medium") medium++;
3874
4068
  else if (f.severity === "low") low++;
3875
4069
  }
4070
+ let rawCritical = 0, rawHigh = 0, rawMedium = 0, rawLow = 0;
4071
+ for (const f of scored) {
4072
+ if (f.severity === "critical") rawCritical++;
4073
+ else if (f.severity === "high") rawHigh++;
4074
+ else if (f.severity === "medium") rawMedium++;
4075
+ else if (f.severity === "low") rawLow++;
4076
+ }
4077
+ const omitted = scored.filter((f) => isDeductingSeverity(f.severity)).length - counted.filter((f) => isDeductingSeverity(f.severity)).length;
3876
4078
  const deductions = critical * 15 + high * 7 + medium * 3 + low * 1;
3877
4079
  const rawScore = Math.max(0, 100 - deductions);
3878
4080
  let grade;
@@ -3892,22 +4094,23 @@ function calculateGrade(findings, _totalFiles, options = {}) {
3892
4094
  else if (medium >= 5) grade = capGrade("B");
3893
4095
  else if (medium >= 1) grade = capGrade("A");
3894
4096
  let summary;
3895
- if (critical > 0) {
3896
- summary = `${critical} critical ${critical === 1 ? "vulnerability requires" : "vulnerabilities require"} immediate attention.`;
3897
- } else if (high >= 3) {
3898
- summary = `${high} high-severity issues require urgent attention.`;
3899
- } else if (high > 0) {
3900
- summary = `${high} high-severity ${high === 1 ? "issue needs" : "issues need"} attention.`;
3901
- } else if (medium >= 5) {
3902
- summary = `${medium} medium-severity issues to address.`;
3903
- } else if (medium > 0) {
3904
- summary = `Clean of critical and high issues. ${medium} medium-severity ${medium === 1 ? "issue" : "issues"} to review.`;
3905
- } else if (low > 0) {
3906
- summary = `Clean of critical, high, and medium issues. ${low} low-severity best-practice ${low === 1 ? "note" : "notes"}.`;
4097
+ if (rawCritical > 0) {
4098
+ summary = `${rawCritical} critical ${rawCritical === 1 ? "vulnerability requires" : "vulnerabilities require"} immediate attention.`;
4099
+ } else if (rawHigh >= 3) {
4100
+ summary = `${rawHigh} high-severity issues require urgent attention.`;
4101
+ } else if (rawHigh > 0) {
4102
+ summary = `${rawHigh} high-severity ${rawHigh === 1 ? "issue needs" : "issues need"} attention.`;
4103
+ } else if (rawMedium >= 5) {
4104
+ summary = `${rawMedium} medium-severity issues to address.`;
4105
+ } else if (rawMedium > 0) {
4106
+ summary = `Clean of critical and high issues. ${rawMedium} medium-severity ${rawMedium === 1 ? "issue" : "issues"} to review.`;
4107
+ } else if (rawLow > 0) {
4108
+ summary = `Clean of critical, high, and medium issues. ${rawLow} low-severity best-practice ${rawLow === 1 ? "note" : "notes"}.`;
3907
4109
  } else {
3908
4110
  summary = "No security issues detected.";
3909
4111
  }
3910
- return { grade, score: rawScore, summary: summary + holdout, ungraded };
4112
+ 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).` : "";
4113
+ return { grade, score: rawScore, summary: summary + capNote + holdout, ungraded };
3911
4114
  }
3912
4115
  var complianceMap = {
3913
4116
  VC001: { owasp: "A07:2021", cwe: "CWE-798" },
@@ -4383,6 +4586,7 @@ function runCustomRules(content, filePath, disabledRules = [], tier = "free", ex
4383
4586
  }
4384
4587
  if (maxLineLen > 5e4) return findings;
4385
4588
  if (/demo-data|example-vulnerable|code-sample/i.test(filePath)) return findings;
4589
+ if (isSbomPath(filePath)) return findings;
4386
4590
  const vendoredFile = isVendoredPath(filePath);
4387
4591
  const ruleset = tier === "pro" && extraRules.length > 0 ? [...freeRules, ...extraRules] : freeRules;
4388
4592
  const silenceableLines = /-OK\b/i.test(content) ? content.split("\n") : null;
@@ -4391,12 +4595,21 @@ function runCustomRules(content, filePath, disabledRules = [], tier = "free", ex
4391
4595
  const matches = rule.check(content, filePath, project);
4392
4596
  const compliance = complianceMap[rule.id];
4393
4597
  const vendored = vendoredFile && isVendoredFinding({ file: filePath, rule: rule.id, category: rule.category });
4598
+ const onTestPath = isTestPath(filePath);
4394
4599
  for (const match of matches) {
4395
4600
  if (silenceableLines && isLineSilenced(silenceableLines, match.line - 1, match.rule)) {
4396
4601
  continue;
4397
4602
  }
4603
+ const live = isLive({
4604
+ rule: match.rule,
4605
+ category: match.category,
4606
+ live: match.live,
4607
+ snippet: match.snippet
4608
+ });
4398
4609
  findings.push({
4399
4610
  ...vendored ? { vendored: true } : {},
4611
+ ...onTestPath && !live ? { testFile: true } : {},
4612
+ ...live ? { live: true } : {},
4400
4613
  id: `${match.rule}-${match.file}:${match.line}`,
4401
4614
  rule: match.rule,
4402
4615
  severity: match.severity,
@@ -4461,6 +4674,20 @@ var MAX_CONCURRENT = (() => {
4461
4674
  if (!Number.isFinite(n) || n < 1) return DEFAULT_MAX_CONCURRENT;
4462
4675
  return Math.min(n, 20);
4463
4676
  })();
4677
+ var DEFAULT_AI_FILTER_BUDGET_MS = 8e3;
4678
+ var AI_FILTER_BUDGET_MS = (() => {
4679
+ const raw = process.env.AI_FILTER_BUDGET_MS;
4680
+ if (!raw) return DEFAULT_AI_FILTER_BUDGET_MS;
4681
+ const n = parseInt(raw, 10);
4682
+ if (!Number.isFinite(n) || n < 1) return DEFAULT_AI_FILTER_BUDGET_MS;
4683
+ return Math.min(n, 6e4);
4684
+ })();
4685
+ var PER_CALL_TIMEOUT_MS = 8e3;
4686
+ function isAbortError(err) {
4687
+ if (!err || typeof err !== "object") return false;
4688
+ const name = "name" in err ? String(err.name) : "";
4689
+ return name === "AbortError" || name === "APIUserAbortError";
4690
+ }
4464
4691
  var SEVERITY_PRIORITY = {
4465
4692
  critical: 0,
4466
4693
  high: 1,
@@ -4511,10 +4738,18 @@ function parseReviewResponse(text) {
4511
4738
  return [];
4512
4739
  }
4513
4740
  }
4514
- async function filterFalsePositives(findings, fileContents) {
4741
+ async function filterFalsePositives(findings, fileContents, budgetMs = AI_FILTER_BUDGET_MS) {
4515
4742
  const empty = { findings, filteredFindings: [], aiReviewed: false, removedCount: 0, totalBefore: findings.length, unreviewedCount: 0 };
4516
4743
  if (!process.env.ANTHROPIC_API_KEY) return empty;
4517
4744
  if (findings.length === 0) return empty;
4745
+ const deadlineMs = Date.now() + Math.max(0, budgetMs);
4746
+ const abortController = new AbortController();
4747
+ let budgetExpired = budgetMs <= 0;
4748
+ if (budgetExpired) abortController.abort();
4749
+ const budgetTimer = budgetExpired ? void 0 : setTimeout(() => {
4750
+ budgetExpired = true;
4751
+ abortController.abort();
4752
+ }, budgetMs);
4518
4753
  const prioritized = [...findings].sort((a, b) => {
4519
4754
  const pa = SEVERITY_PRIORITY[(a.severity || "").toLowerCase()] ?? 5;
4520
4755
  const pb = SEVERITY_PRIORITY[(b.severity || "").toLowerCase()] ?? 5;
@@ -4550,7 +4785,13 @@ async function filterFalsePositives(findings, fileContents) {
4550
4785
  }
4551
4786
  const reviewBatch = async (task) => {
4552
4787
  const { batch, content } = task;
4788
+ if (abortController.signal.aborted || Date.now() >= deadlineMs) {
4789
+ budgetExpired = true;
4790
+ unreviewedCount += batch.length;
4791
+ return;
4792
+ }
4553
4793
  try {
4794
+ const remaining = Math.max(1, deadlineMs - Date.now());
4554
4795
  const prompt = buildReviewPrompt(batch, content);
4555
4796
  const response = await client.messages.create(
4556
4797
  {
@@ -4570,12 +4811,9 @@ async function filterFalsePositives(findings, fileContents) {
4570
4811
  system: REVIEW_SYSTEM_PROMPT,
4571
4812
  messages: [{ role: "user", content: prompt }]
4572
4813
  },
4573
- // Cap a single call well under any serverless function timeout — the
4574
- // SDK default is 10 minutes, long enough for one hung connection to
4575
- // hold a worker until the platform SIGKILLs the whole scan request
4576
- // (which would skip the graceful-degradation fallback). A timeout
4577
- // turns a stuck batch into an unreviewed batch, handled below.
4578
- { timeout: 2e4 }
4814
+ // Shared AbortController plus a per-call timeout capped at remaining
4815
+ // budget. Previously 20s with no overall deadline.
4816
+ { timeout: Math.min(PER_CALL_TIMEOUT_MS, remaining), signal: abortController.signal }
4579
4817
  );
4580
4818
  const text = response.content.filter((b) => b.type === "text").map((b) => b.text).join("");
4581
4819
  const results = parseReviewResponse(text);
@@ -4589,20 +4827,33 @@ async function filterFalsePositives(findings, fileContents) {
4589
4827
  }
4590
4828
  }
4591
4829
  } catch (err) {
4592
- failedBatches++;
4593
4830
  unreviewedCount += batch.length;
4831
+ if (isAbortError(err) || abortController.signal.aborted) {
4832
+ budgetExpired = true;
4833
+ return;
4834
+ }
4835
+ failedBatches++;
4594
4836
  if (!firstError) firstError = err;
4595
4837
  }
4596
4838
  };
4597
- let next = 0;
4598
- const workerCount = Math.min(MAX_CONCURRENT, tasks.length);
4599
- const workers = Array.from({ length: workerCount }, async () => {
4600
- while (next < tasks.length) {
4601
- const cur = next++;
4602
- await reviewBatch(tasks[cur]);
4603
- }
4604
- });
4605
- await Promise.all(workers);
4839
+ try {
4840
+ let next = 0;
4841
+ const workerCount = Math.min(MAX_CONCURRENT, tasks.length);
4842
+ const workers = Array.from({ length: workerCount }, async () => {
4843
+ while (next < tasks.length) {
4844
+ const cur = next++;
4845
+ await reviewBatch(tasks[cur]);
4846
+ }
4847
+ });
4848
+ await Promise.all(workers);
4849
+ } finally {
4850
+ if (budgetTimer) clearTimeout(budgetTimer);
4851
+ }
4852
+ if (budgetExpired && unreviewedCount > 0) {
4853
+ console.warn(
4854
+ `[ai-fp-filter] budget expired (${budgetMs}ms) \u2014 ${unreviewedCount} finding(s) not reviewed; returning them unchanged`
4855
+ );
4856
+ }
4606
4857
  if (firstError) {
4607
4858
  const msg = firstError instanceof Error ? firstError.message : String(firstError);
4608
4859
  if (!reviewedAny) {
@@ -4742,7 +4993,14 @@ var SAFE_PATTERNS = [
4742
4993
  // HTTP security-header directive values (HSTS, etc.) — `max-age=63072000;
4743
4994
  // includeSubDomains; preload`. Config strings a security scanner actively
4744
4995
  // tells users to add; never secrets.
4745
- /^max-age=\d+/i
4996
+ /^max-age=\d+/i,
4997
+ // SPDX element ids, package URLs, and URNs. SBOM and license documents are
4998
+ // full of these (`SPDXRef-Package-…`, `pkg:golang/…`, `urn:uuid:…`) and they
4999
+ // are identifiers, not credentials. The filename skip below drops whole
5000
+ // SBOM files; this catches the same strings in a file we still scan.
5001
+ /^SPDXRef-/,
5002
+ /^pkg:[a-z0-9.+-]+\//,
5003
+ /^urn:/
4746
5004
  ];
4747
5005
  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;
4748
5006
  var SKIP_FILENAMES = /(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock|composer\.lock|Gemfile\.lock|Cargo\.lock|poetry\.lock|Pipfile\.lock|shrinkwrap\.json)$/i;
@@ -4772,10 +5030,11 @@ function scanEntropy(files) {
4772
5030
  if (SKIP_FILENAMES.test(filePath)) continue;
4773
5031
  const basename = filePath.split("/").pop() || "";
4774
5032
  if (SKIP_FILENAMES.test(basename)) continue;
5033
+ if (isSbomPath(filePath) || isSbomPath(basename)) continue;
4775
5034
  if (filePath.includes("node_modules")) continue;
4776
5035
  if (filePath.includes(".min.")) continue;
4777
5036
  if (/pro-rules-bundle|\.bundle\.|\.chunk\./i.test(filePath)) continue;
4778
- if (/(?:\.test\.|\.spec\.|__tests__|__mocks__|fixtures?\/)/i.test(filePath)) continue;
5037
+ if (isTestPath(filePath)) continue;
4779
5038
  const vendored = isVendoredPath(filePath);
4780
5039
  const dotenv = isDotenvPath(filePath) && !DOTENV_EXAMPLE_RE.test(filePath);
4781
5040
  const lines = content.split("\n");
@@ -5080,6 +5339,7 @@ function getSnippet3(content, line) {
5080
5339
  function scanDependencies(files) {
5081
5340
  const findings = [];
5082
5341
  for (const { path: filePath, content } of files) {
5342
+ if (isSbomPath(filePath)) continue;
5083
5343
  if (filePath.endsWith("package.json") && !filePath.includes("node_modules")) {
5084
5344
  try {
5085
5345
  const pkg = JSON.parse(content);
@@ -5425,6 +5685,7 @@ var CONFIG_CHECKS = [
5425
5685
  function scanConfigs(files) {
5426
5686
  const findings = [];
5427
5687
  for (const { path: filePath, content } of files) {
5688
+ if (isSbomPath(filePath)) continue;
5428
5689
  for (const check of CONFIG_CHECKS) {
5429
5690
  if (!check.filePattern.test(filePath)) continue;
5430
5691
  const result = check.check(content, filePath);
@@ -5462,6 +5723,7 @@ function getSnippet5(content, line) {
5462
5723
  }).join("\n");
5463
5724
  }
5464
5725
  function scanMultiFile(files) {
5726
+ files = files.filter((f) => !isSbomPath(f.path));
5465
5727
  const findings = [];
5466
5728
  const fileMap = /* @__PURE__ */ new Map();
5467
5729
  for (const f of files) {
@@ -5812,7 +6074,7 @@ function extractScriptUrls(html, pageUrl, limit = 12) {
5812
6074
 
5813
6075
  // src/quality/context.ts
5814
6076
  function isExcludedPath(path) {
5815
- if (TEST_FILE_PATTERN.test(path)) return true;
6077
+ if (isTestPath(path)) return true;
5816
6078
  if (/(?:^|\/)[\w.-]*(?:fixtures?|mocks?|examples?|samples?)\//i.test(path)) return true;
5817
6079
  if (isVendoredPath(path)) return true;
5818
6080
  if (/(?:^|\/)(?:\.next|dist|build|out|coverage|node_modules)\//.test(path)) return true;
@@ -7625,8 +7887,8 @@ function hasOpenStateEarlyReturn(fn) {
7625
7887
  }
7626
7888
  return false;
7627
7889
  }
7628
- function isOpenGated(element, parents, baseName) {
7629
- if (MODAL_FILENAME.test(baseName)) return true;
7890
+ function isOpenGated(element, parents, baseName2) {
7891
+ if (MODAL_FILENAME.test(baseName2)) return true;
7630
7892
  let child = element;
7631
7893
  let parent = parents.get(child);
7632
7894
  for (let steps = 0; parent && steps < 256; steps++) {
@@ -7669,7 +7931,7 @@ var undeclaredModal = {
7669
7931
  if (DIALOG_PRIMITIVE.test(file.code)) continue;
7670
7932
  const program = parsed.ast.program;
7671
7933
  const parents = buildParents(program);
7672
- const baseName = baseNameWithoutExtension(file.path);
7934
+ const baseName2 = baseNameWithoutExtension(file.path);
7673
7935
  const elements = [];
7674
7936
  walkNodes2(program, (node) => {
7675
7937
  if (node.type === "JSXElement") elements.push(node);
@@ -7684,7 +7946,7 @@ var undeclaredModal = {
7684
7946
  if (!rendersElementChild(element)) continue;
7685
7947
  if (!hasFocusableDescendant(element)) continue;
7686
7948
  if (declaresSemantics(element)) continue;
7687
- if (!isOpenGated(element, parents, baseName)) continue;
7949
+ if (!isOpenGated(element, parents, baseName2)) continue;
7688
7950
  const line = opening.loc?.start.line ?? lineAt(file.content, opening.start ?? 0);
7689
7951
  hits.push({ file: file.path, line });
7690
7952
  break;
@@ -9325,6 +9587,7 @@ function scanQuality(input, rules = qualityRules) {
9325
9587
  CHECKABLE_CLAIMS,
9326
9588
  DOTENV_ASSIGN_RE,
9327
9589
  FREE_RULE_COUNT,
9590
+ GRADE_FINDINGS_PER_RULE,
9328
9591
  INTENT_EXPECTATIONS,
9329
9592
  MODEL_ANALYSIS,
9330
9593
  MODEL_POLICY_REVIEWED,
@@ -9379,6 +9642,7 @@ function scanQuality(input, rules = qualityRules) {
9379
9642
  freeRules,
9380
9643
  getObjectProperty,
9381
9644
  getSnippet,
9645
+ gradeRuleFamily,
9382
9646
  hardcodedJWTSecret,
9383
9647
  hardcodedSecrets,
9384
9648
  harvestIntent,
@@ -9391,11 +9655,15 @@ function scanQuality(input, rules = qualityRules) {
9391
9655
  isInlineSilenced,
9392
9656
  isInsideFixMessage,
9393
9657
  isLineSilenced,
9658
+ isLive,
9394
9659
  isMethodCall,
9395
9660
  isPrivateAddress,
9661
+ isSbomPath,
9396
9662
  isServerSideFile,
9397
9663
  isServerTarget,
9398
9664
  isTestFile,
9665
+ isTestPath,
9666
+ isUngradedFinding,
9399
9667
  isVendoredFinding,
9400
9668
  isVendoredPath,
9401
9669
  lineNumberAt,