xploitscan-shared-rules 2.2.0 → 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.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,
@@ -538,6 +540,15 @@ var NON_APP_PATH_PATTERNS = [
538
540
  "**/vendor/**",
539
541
  "**/vendored/**",
540
542
  "**/third_party/**",
543
+ // Hyphen, closed, and plural spellings. `third_party` alone left
544
+ // `third-party/licenses/*.spdx.json` in the grade.
545
+ "**/third-party/**",
546
+ "**/thirdparty/**",
547
+ "**/third_parties/**",
548
+ "**/third-parties/**",
549
+ "**/3rd_party/**",
550
+ "**/3rd-party/**",
551
+ "**/3rdparty/**",
541
552
  "**/generated/**",
542
553
  "**/__generated__/**"
543
554
  ];
@@ -3854,6 +3865,44 @@ function detectPlatform(files) {
3854
3865
  }
3855
3866
  return [...platforms];
3856
3867
  }
3868
+ var GRADE_FINDINGS_PER_RULE = 3;
3869
+ var GRADE_SEVERITY_RANK = {
3870
+ critical: 4,
3871
+ high: 3,
3872
+ medium: 2,
3873
+ low: 1,
3874
+ info: 0
3875
+ };
3876
+ function gradeRuleFamily(finding) {
3877
+ const rule = (finding.rule ?? "").trim();
3878
+ if (rule === "ENTROPY" || rule.startsWith("ENTROPY-")) return "ENTROPY";
3879
+ if (rule) return rule;
3880
+ const id = finding.id ?? "";
3881
+ if (id === "ENTROPY" || id.startsWith("ENTROPY-")) return "ENTROPY";
3882
+ return id || "unknown";
3883
+ }
3884
+ function isDeductingSeverity(severity) {
3885
+ return severity === "critical" || severity === "high" || severity === "medium" || severity === "low";
3886
+ }
3887
+ function findingsCountedTowardGrade(findings) {
3888
+ const groups = /* @__PURE__ */ new Map();
3889
+ findings.forEach((item, index) => {
3890
+ const key = gradeRuleFamily(item);
3891
+ const bucket = groups.get(key);
3892
+ const entry = { item, index };
3893
+ if (bucket) bucket.push(entry);
3894
+ else groups.set(key, [entry]);
3895
+ });
3896
+ const counted = [];
3897
+ for (const bucket of groups.values()) {
3898
+ const ranked = bucket.length <= GRADE_FINDINGS_PER_RULE ? bucket : [...bucket].sort((a, b) => {
3899
+ const bySeverity = (GRADE_SEVERITY_RANK[b.item.severity ?? ""] ?? 0) - (GRADE_SEVERITY_RANK[a.item.severity ?? ""] ?? 0);
3900
+ return bySeverity !== 0 ? bySeverity : a.index - b.index;
3901
+ }).slice(0, GRADE_FINDINGS_PER_RULE);
3902
+ for (const entry of ranked) counted.push(entry.item);
3903
+ }
3904
+ return counted;
3905
+ }
3857
3906
  function calculateGrade(findings, _totalFiles, options = {}) {
3858
3907
  const scored = options.gradeVendored ? findings : findings.filter((f) => !isVendoredFinding(f));
3859
3908
  const ungraded = findings.length - scored.length;
@@ -3866,13 +3915,22 @@ function calculateGrade(findings, _totalFiles, options = {}) {
3866
3915
  ungraded
3867
3916
  };
3868
3917
  }
3918
+ const counted = findingsCountedTowardGrade(scored);
3869
3919
  let critical = 0, high = 0, medium = 0, low = 0;
3870
- for (const f of scored) {
3920
+ for (const f of counted) {
3871
3921
  if (f.severity === "critical") critical++;
3872
3922
  else if (f.severity === "high") high++;
3873
3923
  else if (f.severity === "medium") medium++;
3874
3924
  else if (f.severity === "low") low++;
3875
3925
  }
3926
+ let rawCritical = 0, rawHigh = 0, rawMedium = 0, rawLow = 0;
3927
+ for (const f of scored) {
3928
+ if (f.severity === "critical") rawCritical++;
3929
+ else if (f.severity === "high") rawHigh++;
3930
+ else if (f.severity === "medium") rawMedium++;
3931
+ else if (f.severity === "low") rawLow++;
3932
+ }
3933
+ const omitted = scored.filter((f) => isDeductingSeverity(f.severity)).length - counted.filter((f) => isDeductingSeverity(f.severity)).length;
3876
3934
  const deductions = critical * 15 + high * 7 + medium * 3 + low * 1;
3877
3935
  const rawScore = Math.max(0, 100 - deductions);
3878
3936
  let grade;
@@ -3892,22 +3950,23 @@ function calculateGrade(findings, _totalFiles, options = {}) {
3892
3950
  else if (medium >= 5) grade = capGrade("B");
3893
3951
  else if (medium >= 1) grade = capGrade("A");
3894
3952
  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"}.`;
3953
+ if (rawCritical > 0) {
3954
+ summary = `${rawCritical} critical ${rawCritical === 1 ? "vulnerability requires" : "vulnerabilities require"} immediate attention.`;
3955
+ } else if (rawHigh >= 3) {
3956
+ summary = `${rawHigh} high-severity issues require urgent attention.`;
3957
+ } else if (rawHigh > 0) {
3958
+ summary = `${rawHigh} high-severity ${rawHigh === 1 ? "issue needs" : "issues need"} attention.`;
3959
+ } else if (rawMedium >= 5) {
3960
+ summary = `${rawMedium} medium-severity issues to address.`;
3961
+ } else if (rawMedium > 0) {
3962
+ summary = `Clean of critical and high issues. ${rawMedium} medium-severity ${rawMedium === 1 ? "issue" : "issues"} to review.`;
3963
+ } else if (rawLow > 0) {
3964
+ summary = `Clean of critical, high, and medium issues. ${rawLow} low-severity best-practice ${rawLow === 1 ? "note" : "notes"}.`;
3907
3965
  } else {
3908
3966
  summary = "No security issues detected.";
3909
3967
  }
3910
- return { grade, score: rawScore, summary: summary + holdout, ungraded };
3968
+ 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).` : "";
3969
+ return { grade, score: rawScore, summary: summary + capNote + holdout, ungraded };
3911
3970
  }
3912
3971
  var complianceMap = {
3913
3972
  VC001: { owasp: "A07:2021", cwe: "CWE-798" },
@@ -4461,6 +4520,20 @@ var MAX_CONCURRENT = (() => {
4461
4520
  if (!Number.isFinite(n) || n < 1) return DEFAULT_MAX_CONCURRENT;
4462
4521
  return Math.min(n, 20);
4463
4522
  })();
4523
+ var DEFAULT_AI_FILTER_BUDGET_MS = 8e3;
4524
+ var AI_FILTER_BUDGET_MS = (() => {
4525
+ const raw = process.env.AI_FILTER_BUDGET_MS;
4526
+ if (!raw) return DEFAULT_AI_FILTER_BUDGET_MS;
4527
+ const n = parseInt(raw, 10);
4528
+ if (!Number.isFinite(n) || n < 1) return DEFAULT_AI_FILTER_BUDGET_MS;
4529
+ return Math.min(n, 6e4);
4530
+ })();
4531
+ var PER_CALL_TIMEOUT_MS = 8e3;
4532
+ function isAbortError(err) {
4533
+ if (!err || typeof err !== "object") return false;
4534
+ const name = "name" in err ? String(err.name) : "";
4535
+ return name === "AbortError" || name === "APIUserAbortError";
4536
+ }
4464
4537
  var SEVERITY_PRIORITY = {
4465
4538
  critical: 0,
4466
4539
  high: 1,
@@ -4511,10 +4584,18 @@ function parseReviewResponse(text) {
4511
4584
  return [];
4512
4585
  }
4513
4586
  }
4514
- async function filterFalsePositives(findings, fileContents) {
4587
+ async function filterFalsePositives(findings, fileContents, budgetMs = AI_FILTER_BUDGET_MS) {
4515
4588
  const empty = { findings, filteredFindings: [], aiReviewed: false, removedCount: 0, totalBefore: findings.length, unreviewedCount: 0 };
4516
4589
  if (!process.env.ANTHROPIC_API_KEY) return empty;
4517
4590
  if (findings.length === 0) return empty;
4591
+ const deadlineMs = Date.now() + Math.max(0, budgetMs);
4592
+ const abortController = new AbortController();
4593
+ let budgetExpired = budgetMs <= 0;
4594
+ if (budgetExpired) abortController.abort();
4595
+ const budgetTimer = budgetExpired ? void 0 : setTimeout(() => {
4596
+ budgetExpired = true;
4597
+ abortController.abort();
4598
+ }, budgetMs);
4518
4599
  const prioritized = [...findings].sort((a, b) => {
4519
4600
  const pa = SEVERITY_PRIORITY[(a.severity || "").toLowerCase()] ?? 5;
4520
4601
  const pb = SEVERITY_PRIORITY[(b.severity || "").toLowerCase()] ?? 5;
@@ -4550,7 +4631,13 @@ async function filterFalsePositives(findings, fileContents) {
4550
4631
  }
4551
4632
  const reviewBatch = async (task) => {
4552
4633
  const { batch, content } = task;
4634
+ if (abortController.signal.aborted || Date.now() >= deadlineMs) {
4635
+ budgetExpired = true;
4636
+ unreviewedCount += batch.length;
4637
+ return;
4638
+ }
4553
4639
  try {
4640
+ const remaining = Math.max(1, deadlineMs - Date.now());
4554
4641
  const prompt = buildReviewPrompt(batch, content);
4555
4642
  const response = await client.messages.create(
4556
4643
  {
@@ -4570,12 +4657,9 @@ async function filterFalsePositives(findings, fileContents) {
4570
4657
  system: REVIEW_SYSTEM_PROMPT,
4571
4658
  messages: [{ role: "user", content: prompt }]
4572
4659
  },
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 }
4660
+ // Shared AbortController plus a per-call timeout capped at remaining
4661
+ // budget. Previously 20s with no overall deadline.
4662
+ { timeout: Math.min(PER_CALL_TIMEOUT_MS, remaining), signal: abortController.signal }
4579
4663
  );
4580
4664
  const text = response.content.filter((b) => b.type === "text").map((b) => b.text).join("");
4581
4665
  const results = parseReviewResponse(text);
@@ -4589,20 +4673,33 @@ async function filterFalsePositives(findings, fileContents) {
4589
4673
  }
4590
4674
  }
4591
4675
  } catch (err) {
4592
- failedBatches++;
4593
4676
  unreviewedCount += batch.length;
4677
+ if (isAbortError(err) || abortController.signal.aborted) {
4678
+ budgetExpired = true;
4679
+ return;
4680
+ }
4681
+ failedBatches++;
4594
4682
  if (!firstError) firstError = err;
4595
4683
  }
4596
4684
  };
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);
4685
+ try {
4686
+ let next = 0;
4687
+ const workerCount = Math.min(MAX_CONCURRENT, tasks.length);
4688
+ const workers = Array.from({ length: workerCount }, async () => {
4689
+ while (next < tasks.length) {
4690
+ const cur = next++;
4691
+ await reviewBatch(tasks[cur]);
4692
+ }
4693
+ });
4694
+ await Promise.all(workers);
4695
+ } finally {
4696
+ if (budgetTimer) clearTimeout(budgetTimer);
4697
+ }
4698
+ if (budgetExpired && unreviewedCount > 0) {
4699
+ console.warn(
4700
+ `[ai-fp-filter] budget expired (${budgetMs}ms) \u2014 ${unreviewedCount} finding(s) not reviewed; returning them unchanged`
4701
+ );
4702
+ }
4606
4703
  if (firstError) {
4607
4704
  const msg = firstError instanceof Error ? firstError.message : String(firstError);
4608
4705
  if (!reviewedAny) {
@@ -4742,10 +4839,31 @@ var SAFE_PATTERNS = [
4742
4839
  // HTTP security-header directive values (HSTS, etc.) — `max-age=63072000;
4743
4840
  // includeSubDomains; preload`. Config strings a security scanner actively
4744
4841
  // tells users to add; never secrets.
4745
- /^max-age=\d+/i
4842
+ /^max-age=\d+/i,
4843
+ // SPDX element ids, package URLs, and URNs. SBOM and license documents are
4844
+ // full of these (`SPDXRef-Package-…`, `pkg:golang/…`, `urn:uuid:…`) and they
4845
+ // are identifiers, not credentials. The filename skip below drops whole
4846
+ // SBOM files; this catches the same strings in a file we still scan.
4847
+ /^SPDXRef-/,
4848
+ /^pkg:[a-z0-9.+-]+\//,
4849
+ /^urn:/
4746
4850
  ];
4747
4851
  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
4852
  var SKIP_FILENAMES = /(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock|composer\.lock|Gemfile\.lock|Cargo\.lock|poetry\.lock|Pipfile\.lock|shrinkwrap\.json)$/i;
4853
+ var SKIP_SBOM_FILES = /(?:^|\/)(?:[^/]*\.spdx(?:\.json)?|[^/]*\.cdx\.json|[^/]*\.cdx\.xml|bom\.json|sbom[^/]*\.json|[^/]*\.sbom\.json)$/i;
4854
+ function isEntropyTestPath(filePath) {
4855
+ const normalized = filePath.replace(/\\/g, "/");
4856
+ if (/(?:\.test\.|\.spec\.|__tests__|__mocks__|fixtures?\/)/i.test(normalized)) return true;
4857
+ if (/(?:^|\/)(?:tests|spec)\//i.test(normalized)) return true;
4858
+ if (/(?:^|\/)test\//i.test(normalized) && !/(?:^|\/)routes\/test\//i.test(normalized)) return true;
4859
+ if (/(?:^|\/)[^/]+\.Tests\//.test(normalized)) return true;
4860
+ const base = normalized.split("/").pop() ?? "";
4861
+ if (/^test_.*\.py$/i.test(base)) return true;
4862
+ if (/_test\.py$/i.test(base)) return true;
4863
+ if (/^Test[A-Z_]\w*\.py$/.test(base)) return true;
4864
+ if (/_test\.go$/.test(base)) return true;
4865
+ return false;
4866
+ }
4749
4867
  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;
4750
4868
  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;
4751
4869
  var HASH_PREFIX_RE = /^(?:sha\d+|md5|crc32|base64|bcrypt|argon2|pbkdf2|blake2b?)[:_]/i;
@@ -4772,10 +4890,11 @@ function scanEntropy(files) {
4772
4890
  if (SKIP_FILENAMES.test(filePath)) continue;
4773
4891
  const basename = filePath.split("/").pop() || "";
4774
4892
  if (SKIP_FILENAMES.test(basename)) continue;
4893
+ if (SKIP_SBOM_FILES.test(filePath) || SKIP_SBOM_FILES.test(basename)) continue;
4775
4894
  if (filePath.includes("node_modules")) continue;
4776
4895
  if (filePath.includes(".min.")) continue;
4777
4896
  if (/pro-rules-bundle|\.bundle\.|\.chunk\./i.test(filePath)) continue;
4778
- if (/(?:\.test\.|\.spec\.|__tests__|__mocks__|fixtures?\/)/i.test(filePath)) continue;
4897
+ if (isEntropyTestPath(filePath)) continue;
4779
4898
  const vendored = isVendoredPath(filePath);
4780
4899
  const dotenv = isDotenvPath(filePath) && !DOTENV_EXAMPLE_RE.test(filePath);
4781
4900
  const lines = content.split("\n");
@@ -9325,6 +9444,7 @@ function scanQuality(input, rules = qualityRules) {
9325
9444
  CHECKABLE_CLAIMS,
9326
9445
  DOTENV_ASSIGN_RE,
9327
9446
  FREE_RULE_COUNT,
9447
+ GRADE_FINDINGS_PER_RULE,
9328
9448
  INTENT_EXPECTATIONS,
9329
9449
  MODEL_ANALYSIS,
9330
9450
  MODEL_POLICY_REVIEWED,
@@ -9379,6 +9499,7 @@ function scanQuality(input, rules = qualityRules) {
9379
9499
  freeRules,
9380
9500
  getObjectProperty,
9381
9501
  getSnippet,
9502
+ gradeRuleFamily,
9382
9503
  hardcodedJWTSecret,
9383
9504
  hardcodedSecrets,
9384
9505
  harvestIntent,