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.d.cts CHANGED
@@ -1078,6 +1078,28 @@ interface GradeOptions {
1078
1078
  */
1079
1079
  gradeVendored?: boolean;
1080
1080
  }
1081
+ /**
1082
+ * How many findings of one rule count toward point deductions and toward the
1083
+ * severity caps. The 4th and later stay in the report and deduct nothing more,
1084
+ * so one noisy rule cannot floor the score at 0.
1085
+ *
1086
+ * Three is the existing "≥3 high → max D" threshold: a rule that really does
1087
+ * have three highs still caps the letter at D, and further copies of that
1088
+ * same rule do not also zero the numeric score.
1089
+ */
1090
+ declare const GRADE_FINDINGS_PER_RULE = 3;
1091
+ /**
1092
+ * Rule family for the per-rule grade cap.
1093
+ *
1094
+ * Findings group by `rule` (`VC001`), not by the per-line id
1095
+ * (`VC001-src/app.ts:12`). ENTROPY's id is `ENTROPY-<file>:<line>` and its
1096
+ * rule is `ENTROPY`; both collapse to one family so a noisy entropy pass
1097
+ * cannot deduct once per line.
1098
+ */
1099
+ declare function gradeRuleFamily(finding: {
1100
+ rule?: string;
1101
+ id?: string;
1102
+ }): string;
1081
1103
  declare function calculateGrade(findings: Finding[], _totalFiles: number, options?: GradeOptions): GradeResult;
1082
1104
  declare const complianceMap: Record<string, {
1083
1105
  owasp: string;
@@ -1157,8 +1179,11 @@ interface AIFilterResult {
1157
1179
  *
1158
1180
  * Returns filtered findings, the removed findings with AI reasons,
1159
1181
  * and metadata about what the AI did.
1182
+ *
1183
+ * @param budgetMs - Overall deadline (milliseconds). When expired, return
1184
+ * unreviewed findings with aiReviewed: false. Defaults to AI_FILTER_BUDGET_MS.
1160
1185
  */
1161
- declare function filterFalsePositives(findings: Finding[], fileContents: Map<string, string>): Promise<AIFilterResult>;
1186
+ declare function filterFalsePositives(findings: Finding[], fileContents: Map<string, string>, budgetMs?: number): Promise<AIFilterResult>;
1162
1187
 
1163
1188
  /**
1164
1189
  * Shannon-entropy based secret detection.
@@ -1531,4 +1556,4 @@ input: {
1531
1556
  content: string;
1532
1557
  }[] | QualityContext, rules?: QualityRule[]): Finding[];
1533
1558
 
1534
- export { type AIFilterResult, type AppRoute, type BuilderFingerprint, CHECKABLE_CLAIMS, type Confidence, type CustomRule, DOTENV_ASSIGN_RE, type DetectedFramework, type ExposedConfig, type Exposure, FREE_RULE_COUNT, type FilteredFinding, type Finding, type GradeOptions, type GradeResult, type HeaderFinding, INTENT_EXPECTATIONS, type IntentExpectation, type IntentMismatch, type IntentOrigin, type IntentReport, type IntentStatement, MODEL_ANALYSIS, MODEL_POLICY_REVIEWED, MODEL_REVIEW_INTERVAL_DAYS, MODEL_TEMPERATURE, MODEL_TRIAGE, NON_APP_PATH_PATTERNS, PRO_RULE_COUNT, PUBLIC_ENV_PREFIX_RE, type ParsedFile, type ProjectContext, QUALITY_EXAMPLES, type QualityContext, type QualityExample, type QualityFile, type QualityHit, type QualityRule, RULE_IMPACTS, type RouteFramework, type RouteTable, type RuleMatch, type SecurityGrade, type Severity, TEST_FILE_PATTERN, TOTAL_RULE_COUNT, type TaintMap, type TargetCheck, type VibePlatform, allRules, assessHeaders, astMatch, buildProjectContext, buildQualityContext, buildTaintMap, calculateGrade, callSpreads, checkIntent, classifyExposure, classifyPublicEnvVar, classifyStatement, clientSideAuth, complianceMap, consoleLogProduction, corsWildcard, dangerousInnerHTML, detectBuilder, detectExposedConfig, detectFramework, detectPlatform, disabledTLSVerification, dotenvValue, emptyCatchBlock, enclosingHandler, envNotGitignored, evalUsage, exposedAuthSecret, exposedDebugMode, exposedEnvFile, exposedStackTraces, extractRoutes, extractScriptUrls, filterFalsePositives, filterSilenced, findMatches, findMatchesAt, findSourceMapRefs, freeRules, getObjectProperty, getSnippet, hardcodedJWTSecret, hardcodedSecrets, harvestIntent, insecureCookies, insecureRandomness, isCalleeNamed, isClientTarget, isCommentLine, isDotenvPath, isInlineSilenced, isInsideFixMessage, isLineSilenced, isMethodCall, isPrivateAddress, isServerSideFile, isServerTarget, isTestFile, isVendoredFinding, isVendoredPath, lineNumberAt, lineTextAt, maskComments, maskOutboundAuthNoise, missingAuthMiddleware, missingCSP, missingErrorBoundary, missingHTTPS, missingLockFile, nextPublicSecret, noRateLimiting, normalizeScanPath, parseFile, parseScanTarget, parseSupabaseConfig, qualityRules, replaceBlockComments, routeForFile, runCustomRules, scanConfigs, scanDependencies, scanEntropy, scanMultiFile, scanQuality, sqlInjection, stripeWebhookUnprotected, supabaseFunctionName, supabaseNoRLS, todoLeftInCode, tryParse, unmeasuredQualityRules, unvalidatedRedirect, vendoredReason, visitBinary, visitCalls, weakHashing, xssVulnerability };
1559
+ export { type AIFilterResult, type AppRoute, type BuilderFingerprint, CHECKABLE_CLAIMS, type Confidence, type CustomRule, DOTENV_ASSIGN_RE, type DetectedFramework, type ExposedConfig, type Exposure, FREE_RULE_COUNT, type FilteredFinding, type Finding, GRADE_FINDINGS_PER_RULE, type GradeOptions, type GradeResult, type HeaderFinding, INTENT_EXPECTATIONS, type IntentExpectation, type IntentMismatch, type IntentOrigin, type IntentReport, type IntentStatement, MODEL_ANALYSIS, MODEL_POLICY_REVIEWED, MODEL_REVIEW_INTERVAL_DAYS, MODEL_TEMPERATURE, MODEL_TRIAGE, NON_APP_PATH_PATTERNS, PRO_RULE_COUNT, PUBLIC_ENV_PREFIX_RE, type ParsedFile, type ProjectContext, QUALITY_EXAMPLES, type QualityContext, type QualityExample, type QualityFile, type QualityHit, type QualityRule, RULE_IMPACTS, type RouteFramework, type RouteTable, type RuleMatch, type SecurityGrade, type Severity, TEST_FILE_PATTERN, TOTAL_RULE_COUNT, type TaintMap, type TargetCheck, type VibePlatform, allRules, assessHeaders, astMatch, buildProjectContext, buildQualityContext, buildTaintMap, calculateGrade, callSpreads, checkIntent, classifyExposure, classifyPublicEnvVar, classifyStatement, clientSideAuth, complianceMap, consoleLogProduction, corsWildcard, dangerousInnerHTML, detectBuilder, detectExposedConfig, detectFramework, detectPlatform, disabledTLSVerification, dotenvValue, emptyCatchBlock, enclosingHandler, envNotGitignored, evalUsage, exposedAuthSecret, exposedDebugMode, exposedEnvFile, exposedStackTraces, extractRoutes, extractScriptUrls, filterFalsePositives, filterSilenced, findMatches, findMatchesAt, findSourceMapRefs, freeRules, getObjectProperty, getSnippet, gradeRuleFamily, hardcodedJWTSecret, hardcodedSecrets, harvestIntent, insecureCookies, insecureRandomness, isCalleeNamed, isClientTarget, isCommentLine, isDotenvPath, isInlineSilenced, isInsideFixMessage, isLineSilenced, isMethodCall, isPrivateAddress, isServerSideFile, isServerTarget, isTestFile, isVendoredFinding, isVendoredPath, lineNumberAt, lineTextAt, maskComments, maskOutboundAuthNoise, missingAuthMiddleware, missingCSP, missingErrorBoundary, missingHTTPS, missingLockFile, nextPublicSecret, noRateLimiting, normalizeScanPath, parseFile, parseScanTarget, parseSupabaseConfig, qualityRules, replaceBlockComments, routeForFile, runCustomRules, scanConfigs, scanDependencies, scanEntropy, scanMultiFile, scanQuality, sqlInjection, stripeWebhookUnprotected, supabaseFunctionName, supabaseNoRLS, todoLeftInCode, tryParse, unmeasuredQualityRules, unvalidatedRedirect, vendoredReason, visitBinary, visitCalls, weakHashing, xssVulnerability };
package/dist/index.d.ts CHANGED
@@ -1078,6 +1078,28 @@ interface GradeOptions {
1078
1078
  */
1079
1079
  gradeVendored?: boolean;
1080
1080
  }
1081
+ /**
1082
+ * How many findings of one rule count toward point deductions and toward the
1083
+ * severity caps. The 4th and later stay in the report and deduct nothing more,
1084
+ * so one noisy rule cannot floor the score at 0.
1085
+ *
1086
+ * Three is the existing "≥3 high → max D" threshold: a rule that really does
1087
+ * have three highs still caps the letter at D, and further copies of that
1088
+ * same rule do not also zero the numeric score.
1089
+ */
1090
+ declare const GRADE_FINDINGS_PER_RULE = 3;
1091
+ /**
1092
+ * Rule family for the per-rule grade cap.
1093
+ *
1094
+ * Findings group by `rule` (`VC001`), not by the per-line id
1095
+ * (`VC001-src/app.ts:12`). ENTROPY's id is `ENTROPY-<file>:<line>` and its
1096
+ * rule is `ENTROPY`; both collapse to one family so a noisy entropy pass
1097
+ * cannot deduct once per line.
1098
+ */
1099
+ declare function gradeRuleFamily(finding: {
1100
+ rule?: string;
1101
+ id?: string;
1102
+ }): string;
1081
1103
  declare function calculateGrade(findings: Finding[], _totalFiles: number, options?: GradeOptions): GradeResult;
1082
1104
  declare const complianceMap: Record<string, {
1083
1105
  owasp: string;
@@ -1157,8 +1179,11 @@ interface AIFilterResult {
1157
1179
  *
1158
1180
  * Returns filtered findings, the removed findings with AI reasons,
1159
1181
  * and metadata about what the AI did.
1182
+ *
1183
+ * @param budgetMs - Overall deadline (milliseconds). When expired, return
1184
+ * unreviewed findings with aiReviewed: false. Defaults to AI_FILTER_BUDGET_MS.
1160
1185
  */
1161
- declare function filterFalsePositives(findings: Finding[], fileContents: Map<string, string>): Promise<AIFilterResult>;
1186
+ declare function filterFalsePositives(findings: Finding[], fileContents: Map<string, string>, budgetMs?: number): Promise<AIFilterResult>;
1162
1187
 
1163
1188
  /**
1164
1189
  * Shannon-entropy based secret detection.
@@ -1531,4 +1556,4 @@ input: {
1531
1556
  content: string;
1532
1557
  }[] | QualityContext, rules?: QualityRule[]): Finding[];
1533
1558
 
1534
- export { type AIFilterResult, type AppRoute, type BuilderFingerprint, CHECKABLE_CLAIMS, type Confidence, type CustomRule, DOTENV_ASSIGN_RE, type DetectedFramework, type ExposedConfig, type Exposure, FREE_RULE_COUNT, type FilteredFinding, type Finding, type GradeOptions, type GradeResult, type HeaderFinding, INTENT_EXPECTATIONS, type IntentExpectation, type IntentMismatch, type IntentOrigin, type IntentReport, type IntentStatement, MODEL_ANALYSIS, MODEL_POLICY_REVIEWED, MODEL_REVIEW_INTERVAL_DAYS, MODEL_TEMPERATURE, MODEL_TRIAGE, NON_APP_PATH_PATTERNS, PRO_RULE_COUNT, PUBLIC_ENV_PREFIX_RE, type ParsedFile, type ProjectContext, QUALITY_EXAMPLES, type QualityContext, type QualityExample, type QualityFile, type QualityHit, type QualityRule, RULE_IMPACTS, type RouteFramework, type RouteTable, type RuleMatch, type SecurityGrade, type Severity, TEST_FILE_PATTERN, TOTAL_RULE_COUNT, type TaintMap, type TargetCheck, type VibePlatform, allRules, assessHeaders, astMatch, buildProjectContext, buildQualityContext, buildTaintMap, calculateGrade, callSpreads, checkIntent, classifyExposure, classifyPublicEnvVar, classifyStatement, clientSideAuth, complianceMap, consoleLogProduction, corsWildcard, dangerousInnerHTML, detectBuilder, detectExposedConfig, detectFramework, detectPlatform, disabledTLSVerification, dotenvValue, emptyCatchBlock, enclosingHandler, envNotGitignored, evalUsage, exposedAuthSecret, exposedDebugMode, exposedEnvFile, exposedStackTraces, extractRoutes, extractScriptUrls, filterFalsePositives, filterSilenced, findMatches, findMatchesAt, findSourceMapRefs, freeRules, getObjectProperty, getSnippet, hardcodedJWTSecret, hardcodedSecrets, harvestIntent, insecureCookies, insecureRandomness, isCalleeNamed, isClientTarget, isCommentLine, isDotenvPath, isInlineSilenced, isInsideFixMessage, isLineSilenced, isMethodCall, isPrivateAddress, isServerSideFile, isServerTarget, isTestFile, isVendoredFinding, isVendoredPath, lineNumberAt, lineTextAt, maskComments, maskOutboundAuthNoise, missingAuthMiddleware, missingCSP, missingErrorBoundary, missingHTTPS, missingLockFile, nextPublicSecret, noRateLimiting, normalizeScanPath, parseFile, parseScanTarget, parseSupabaseConfig, qualityRules, replaceBlockComments, routeForFile, runCustomRules, scanConfigs, scanDependencies, scanEntropy, scanMultiFile, scanQuality, sqlInjection, stripeWebhookUnprotected, supabaseFunctionName, supabaseNoRLS, todoLeftInCode, tryParse, unmeasuredQualityRules, unvalidatedRedirect, vendoredReason, visitBinary, visitCalls, weakHashing, xssVulnerability };
1559
+ export { type AIFilterResult, type AppRoute, type BuilderFingerprint, CHECKABLE_CLAIMS, type Confidence, type CustomRule, DOTENV_ASSIGN_RE, type DetectedFramework, type ExposedConfig, type Exposure, FREE_RULE_COUNT, type FilteredFinding, type Finding, GRADE_FINDINGS_PER_RULE, type GradeOptions, type GradeResult, type HeaderFinding, INTENT_EXPECTATIONS, type IntentExpectation, type IntentMismatch, type IntentOrigin, type IntentReport, type IntentStatement, MODEL_ANALYSIS, MODEL_POLICY_REVIEWED, MODEL_REVIEW_INTERVAL_DAYS, MODEL_TEMPERATURE, MODEL_TRIAGE, NON_APP_PATH_PATTERNS, PRO_RULE_COUNT, PUBLIC_ENV_PREFIX_RE, type ParsedFile, type ProjectContext, QUALITY_EXAMPLES, type QualityContext, type QualityExample, type QualityFile, type QualityHit, type QualityRule, RULE_IMPACTS, type RouteFramework, type RouteTable, type RuleMatch, type SecurityGrade, type Severity, TEST_FILE_PATTERN, TOTAL_RULE_COUNT, type TaintMap, type TargetCheck, type VibePlatform, allRules, assessHeaders, astMatch, buildProjectContext, buildQualityContext, buildTaintMap, calculateGrade, callSpreads, checkIntent, classifyExposure, classifyPublicEnvVar, classifyStatement, clientSideAuth, complianceMap, consoleLogProduction, corsWildcard, dangerousInnerHTML, detectBuilder, detectExposedConfig, detectFramework, detectPlatform, disabledTLSVerification, dotenvValue, emptyCatchBlock, enclosingHandler, envNotGitignored, evalUsage, exposedAuthSecret, exposedDebugMode, exposedEnvFile, exposedStackTraces, extractRoutes, extractScriptUrls, filterFalsePositives, filterSilenced, findMatches, findMatchesAt, findSourceMapRefs, freeRules, getObjectProperty, getSnippet, gradeRuleFamily, hardcodedJWTSecret, hardcodedSecrets, harvestIntent, insecureCookies, insecureRandomness, isCalleeNamed, isClientTarget, isCommentLine, isDotenvPath, isInlineSilenced, isInsideFixMessage, isLineSilenced, isMethodCall, isPrivateAddress, isServerSideFile, isServerTarget, isTestFile, isVendoredFinding, isVendoredPath, lineNumberAt, lineTextAt, maskComments, maskOutboundAuthNoise, missingAuthMiddleware, missingCSP, missingErrorBoundary, missingHTTPS, missingLockFile, nextPublicSecret, noRateLimiting, normalizeScanPath, parseFile, parseScanTarget, parseSupabaseConfig, qualityRules, replaceBlockComments, routeForFile, runCustomRules, scanConfigs, scanDependencies, scanEntropy, scanMultiFile, scanQuality, sqlInjection, stripeWebhookUnprotected, supabaseFunctionName, supabaseNoRLS, todoLeftInCode, tryParse, unmeasuredQualityRules, unvalidatedRedirect, vendoredReason, visitBinary, visitCalls, weakHashing, xssVulnerability };
package/dist/index.js CHANGED
@@ -390,6 +390,15 @@ var NON_APP_PATH_PATTERNS = [
390
390
  "**/vendor/**",
391
391
  "**/vendored/**",
392
392
  "**/third_party/**",
393
+ // Hyphen, closed, and plural spellings. `third_party` alone left
394
+ // `third-party/licenses/*.spdx.json` in the grade.
395
+ "**/third-party/**",
396
+ "**/thirdparty/**",
397
+ "**/third_parties/**",
398
+ "**/third-parties/**",
399
+ "**/3rd_party/**",
400
+ "**/3rd-party/**",
401
+ "**/3rdparty/**",
393
402
  "**/generated/**",
394
403
  "**/__generated__/**"
395
404
  ];
@@ -3706,6 +3715,44 @@ function detectPlatform(files) {
3706
3715
  }
3707
3716
  return [...platforms];
3708
3717
  }
3718
+ var GRADE_FINDINGS_PER_RULE = 3;
3719
+ var GRADE_SEVERITY_RANK = {
3720
+ critical: 4,
3721
+ high: 3,
3722
+ medium: 2,
3723
+ low: 1,
3724
+ info: 0
3725
+ };
3726
+ function gradeRuleFamily(finding) {
3727
+ const rule = (finding.rule ?? "").trim();
3728
+ if (rule === "ENTROPY" || rule.startsWith("ENTROPY-")) return "ENTROPY";
3729
+ if (rule) return rule;
3730
+ const id = finding.id ?? "";
3731
+ if (id === "ENTROPY" || id.startsWith("ENTROPY-")) return "ENTROPY";
3732
+ return id || "unknown";
3733
+ }
3734
+ function isDeductingSeverity(severity) {
3735
+ return severity === "critical" || severity === "high" || severity === "medium" || severity === "low";
3736
+ }
3737
+ function findingsCountedTowardGrade(findings) {
3738
+ const groups = /* @__PURE__ */ new Map();
3739
+ findings.forEach((item, index) => {
3740
+ const key = gradeRuleFamily(item);
3741
+ const bucket = groups.get(key);
3742
+ const entry = { item, index };
3743
+ if (bucket) bucket.push(entry);
3744
+ else groups.set(key, [entry]);
3745
+ });
3746
+ const counted = [];
3747
+ for (const bucket of groups.values()) {
3748
+ const ranked = bucket.length <= GRADE_FINDINGS_PER_RULE ? bucket : [...bucket].sort((a, b) => {
3749
+ const bySeverity = (GRADE_SEVERITY_RANK[b.item.severity ?? ""] ?? 0) - (GRADE_SEVERITY_RANK[a.item.severity ?? ""] ?? 0);
3750
+ return bySeverity !== 0 ? bySeverity : a.index - b.index;
3751
+ }).slice(0, GRADE_FINDINGS_PER_RULE);
3752
+ for (const entry of ranked) counted.push(entry.item);
3753
+ }
3754
+ return counted;
3755
+ }
3709
3756
  function calculateGrade(findings, _totalFiles, options = {}) {
3710
3757
  const scored = options.gradeVendored ? findings : findings.filter((f) => !isVendoredFinding(f));
3711
3758
  const ungraded = findings.length - scored.length;
@@ -3718,13 +3765,22 @@ function calculateGrade(findings, _totalFiles, options = {}) {
3718
3765
  ungraded
3719
3766
  };
3720
3767
  }
3768
+ const counted = findingsCountedTowardGrade(scored);
3721
3769
  let critical = 0, high = 0, medium = 0, low = 0;
3722
- for (const f of scored) {
3770
+ for (const f of counted) {
3723
3771
  if (f.severity === "critical") critical++;
3724
3772
  else if (f.severity === "high") high++;
3725
3773
  else if (f.severity === "medium") medium++;
3726
3774
  else if (f.severity === "low") low++;
3727
3775
  }
3776
+ let rawCritical = 0, rawHigh = 0, rawMedium = 0, rawLow = 0;
3777
+ for (const f of scored) {
3778
+ if (f.severity === "critical") rawCritical++;
3779
+ else if (f.severity === "high") rawHigh++;
3780
+ else if (f.severity === "medium") rawMedium++;
3781
+ else if (f.severity === "low") rawLow++;
3782
+ }
3783
+ const omitted = scored.filter((f) => isDeductingSeverity(f.severity)).length - counted.filter((f) => isDeductingSeverity(f.severity)).length;
3728
3784
  const deductions = critical * 15 + high * 7 + medium * 3 + low * 1;
3729
3785
  const rawScore = Math.max(0, 100 - deductions);
3730
3786
  let grade;
@@ -3744,22 +3800,23 @@ function calculateGrade(findings, _totalFiles, options = {}) {
3744
3800
  else if (medium >= 5) grade = capGrade("B");
3745
3801
  else if (medium >= 1) grade = capGrade("A");
3746
3802
  let summary;
3747
- if (critical > 0) {
3748
- summary = `${critical} critical ${critical === 1 ? "vulnerability requires" : "vulnerabilities require"} immediate attention.`;
3749
- } else if (high >= 3) {
3750
- summary = `${high} high-severity issues require urgent attention.`;
3751
- } else if (high > 0) {
3752
- summary = `${high} high-severity ${high === 1 ? "issue needs" : "issues need"} attention.`;
3753
- } else if (medium >= 5) {
3754
- summary = `${medium} medium-severity issues to address.`;
3755
- } else if (medium > 0) {
3756
- summary = `Clean of critical and high issues. ${medium} medium-severity ${medium === 1 ? "issue" : "issues"} to review.`;
3757
- } else if (low > 0) {
3758
- summary = `Clean of critical, high, and medium issues. ${low} low-severity best-practice ${low === 1 ? "note" : "notes"}.`;
3803
+ if (rawCritical > 0) {
3804
+ summary = `${rawCritical} critical ${rawCritical === 1 ? "vulnerability requires" : "vulnerabilities require"} immediate attention.`;
3805
+ } else if (rawHigh >= 3) {
3806
+ summary = `${rawHigh} high-severity issues require urgent attention.`;
3807
+ } else if (rawHigh > 0) {
3808
+ summary = `${rawHigh} high-severity ${rawHigh === 1 ? "issue needs" : "issues need"} attention.`;
3809
+ } else if (rawMedium >= 5) {
3810
+ summary = `${rawMedium} medium-severity issues to address.`;
3811
+ } else if (rawMedium > 0) {
3812
+ summary = `Clean of critical and high issues. ${rawMedium} medium-severity ${rawMedium === 1 ? "issue" : "issues"} to review.`;
3813
+ } else if (rawLow > 0) {
3814
+ summary = `Clean of critical, high, and medium issues. ${rawLow} low-severity best-practice ${rawLow === 1 ? "note" : "notes"}.`;
3759
3815
  } else {
3760
3816
  summary = "No security issues detected.";
3761
3817
  }
3762
- return { grade, score: rawScore, summary: summary + holdout, ungraded };
3818
+ const capNote = omitted > 0 ? ` ${omitted} more ${omitted === 1 ? "finding was" : "findings were"} not deducted (at most ${GRADE_FINDINGS_PER_RULE} findings per rule count toward the score and the severity caps).` : "";
3819
+ return { grade, score: rawScore, summary: summary + capNote + holdout, ungraded };
3763
3820
  }
3764
3821
  var complianceMap = {
3765
3822
  VC001: { owasp: "A07:2021", cwe: "CWE-798" },
@@ -4313,6 +4370,20 @@ var MAX_CONCURRENT = (() => {
4313
4370
  if (!Number.isFinite(n) || n < 1) return DEFAULT_MAX_CONCURRENT;
4314
4371
  return Math.min(n, 20);
4315
4372
  })();
4373
+ var DEFAULT_AI_FILTER_BUDGET_MS = 8e3;
4374
+ var AI_FILTER_BUDGET_MS = (() => {
4375
+ const raw = process.env.AI_FILTER_BUDGET_MS;
4376
+ if (!raw) return DEFAULT_AI_FILTER_BUDGET_MS;
4377
+ const n = parseInt(raw, 10);
4378
+ if (!Number.isFinite(n) || n < 1) return DEFAULT_AI_FILTER_BUDGET_MS;
4379
+ return Math.min(n, 6e4);
4380
+ })();
4381
+ var PER_CALL_TIMEOUT_MS = 8e3;
4382
+ function isAbortError(err) {
4383
+ if (!err || typeof err !== "object") return false;
4384
+ const name = "name" in err ? String(err.name) : "";
4385
+ return name === "AbortError" || name === "APIUserAbortError";
4386
+ }
4316
4387
  var SEVERITY_PRIORITY = {
4317
4388
  critical: 0,
4318
4389
  high: 1,
@@ -4363,10 +4434,18 @@ function parseReviewResponse(text) {
4363
4434
  return [];
4364
4435
  }
4365
4436
  }
4366
- async function filterFalsePositives(findings, fileContents) {
4437
+ async function filterFalsePositives(findings, fileContents, budgetMs = AI_FILTER_BUDGET_MS) {
4367
4438
  const empty = { findings, filteredFindings: [], aiReviewed: false, removedCount: 0, totalBefore: findings.length, unreviewedCount: 0 };
4368
4439
  if (!process.env.ANTHROPIC_API_KEY) return empty;
4369
4440
  if (findings.length === 0) return empty;
4441
+ const deadlineMs = Date.now() + Math.max(0, budgetMs);
4442
+ const abortController = new AbortController();
4443
+ let budgetExpired = budgetMs <= 0;
4444
+ if (budgetExpired) abortController.abort();
4445
+ const budgetTimer = budgetExpired ? void 0 : setTimeout(() => {
4446
+ budgetExpired = true;
4447
+ abortController.abort();
4448
+ }, budgetMs);
4370
4449
  const prioritized = [...findings].sort((a, b) => {
4371
4450
  const pa = SEVERITY_PRIORITY[(a.severity || "").toLowerCase()] ?? 5;
4372
4451
  const pb = SEVERITY_PRIORITY[(b.severity || "").toLowerCase()] ?? 5;
@@ -4402,7 +4481,13 @@ async function filterFalsePositives(findings, fileContents) {
4402
4481
  }
4403
4482
  const reviewBatch = async (task) => {
4404
4483
  const { batch, content } = task;
4484
+ if (abortController.signal.aborted || Date.now() >= deadlineMs) {
4485
+ budgetExpired = true;
4486
+ unreviewedCount += batch.length;
4487
+ return;
4488
+ }
4405
4489
  try {
4490
+ const remaining = Math.max(1, deadlineMs - Date.now());
4406
4491
  const prompt = buildReviewPrompt(batch, content);
4407
4492
  const response = await client.messages.create(
4408
4493
  {
@@ -4422,12 +4507,9 @@ async function filterFalsePositives(findings, fileContents) {
4422
4507
  system: REVIEW_SYSTEM_PROMPT,
4423
4508
  messages: [{ role: "user", content: prompt }]
4424
4509
  },
4425
- // Cap a single call well under any serverless function timeout — the
4426
- // SDK default is 10 minutes, long enough for one hung connection to
4427
- // hold a worker until the platform SIGKILLs the whole scan request
4428
- // (which would skip the graceful-degradation fallback). A timeout
4429
- // turns a stuck batch into an unreviewed batch, handled below.
4430
- { timeout: 2e4 }
4510
+ // Shared AbortController plus a per-call timeout capped at remaining
4511
+ // budget. Previously 20s with no overall deadline.
4512
+ { timeout: Math.min(PER_CALL_TIMEOUT_MS, remaining), signal: abortController.signal }
4431
4513
  );
4432
4514
  const text = response.content.filter((b) => b.type === "text").map((b) => b.text).join("");
4433
4515
  const results = parseReviewResponse(text);
@@ -4441,20 +4523,33 @@ async function filterFalsePositives(findings, fileContents) {
4441
4523
  }
4442
4524
  }
4443
4525
  } catch (err) {
4444
- failedBatches++;
4445
4526
  unreviewedCount += batch.length;
4527
+ if (isAbortError(err) || abortController.signal.aborted) {
4528
+ budgetExpired = true;
4529
+ return;
4530
+ }
4531
+ failedBatches++;
4446
4532
  if (!firstError) firstError = err;
4447
4533
  }
4448
4534
  };
4449
- let next = 0;
4450
- const workerCount = Math.min(MAX_CONCURRENT, tasks.length);
4451
- const workers = Array.from({ length: workerCount }, async () => {
4452
- while (next < tasks.length) {
4453
- const cur = next++;
4454
- await reviewBatch(tasks[cur]);
4455
- }
4456
- });
4457
- await Promise.all(workers);
4535
+ try {
4536
+ let next = 0;
4537
+ const workerCount = Math.min(MAX_CONCURRENT, tasks.length);
4538
+ const workers = Array.from({ length: workerCount }, async () => {
4539
+ while (next < tasks.length) {
4540
+ const cur = next++;
4541
+ await reviewBatch(tasks[cur]);
4542
+ }
4543
+ });
4544
+ await Promise.all(workers);
4545
+ } finally {
4546
+ if (budgetTimer) clearTimeout(budgetTimer);
4547
+ }
4548
+ if (budgetExpired && unreviewedCount > 0) {
4549
+ console.warn(
4550
+ `[ai-fp-filter] budget expired (${budgetMs}ms) \u2014 ${unreviewedCount} finding(s) not reviewed; returning them unchanged`
4551
+ );
4552
+ }
4458
4553
  if (firstError) {
4459
4554
  const msg = firstError instanceof Error ? firstError.message : String(firstError);
4460
4555
  if (!reviewedAny) {
@@ -4594,10 +4689,31 @@ var SAFE_PATTERNS = [
4594
4689
  // HTTP security-header directive values (HSTS, etc.) — `max-age=63072000;
4595
4690
  // includeSubDomains; preload`. Config strings a security scanner actively
4596
4691
  // tells users to add; never secrets.
4597
- /^max-age=\d+/i
4692
+ /^max-age=\d+/i,
4693
+ // SPDX element ids, package URLs, and URNs. SBOM and license documents are
4694
+ // full of these (`SPDXRef-Package-…`, `pkg:golang/…`, `urn:uuid:…`) and they
4695
+ // are identifiers, not credentials. The filename skip below drops whole
4696
+ // SBOM files; this catches the same strings in a file we still scan.
4697
+ /^SPDXRef-/,
4698
+ /^pkg:[a-z0-9.+-]+\//,
4699
+ /^urn:/
4598
4700
  ];
4599
4701
  var SKIP_FILES = /\.(css|scss|less|svg|md|txt|html?|xml|yml|yaml|toml|lock|map|woff2?|ttf|eot|ico|png|jpg|gif|webp)$/i;
4600
4702
  var SKIP_FILENAMES = /(?:package-lock\.json|pnpm-lock\.yaml|yarn\.lock|composer\.lock|Gemfile\.lock|Cargo\.lock|poetry\.lock|Pipfile\.lock|shrinkwrap\.json)$/i;
4703
+ var SKIP_SBOM_FILES = /(?:^|\/)(?:[^/]*\.spdx(?:\.json)?|[^/]*\.cdx\.json|[^/]*\.cdx\.xml|bom\.json|sbom[^/]*\.json|[^/]*\.sbom\.json)$/i;
4704
+ function isEntropyTestPath(filePath) {
4705
+ const normalized = filePath.replace(/\\/g, "/");
4706
+ if (/(?:\.test\.|\.spec\.|__tests__|__mocks__|fixtures?\/)/i.test(normalized)) return true;
4707
+ if (/(?:^|\/)(?:tests|spec)\//i.test(normalized)) return true;
4708
+ if (/(?:^|\/)test\//i.test(normalized) && !/(?:^|\/)routes\/test\//i.test(normalized)) return true;
4709
+ if (/(?:^|\/)[^/]+\.Tests\//.test(normalized)) return true;
4710
+ const base = normalized.split("/").pop() ?? "";
4711
+ if (/^test_.*\.py$/i.test(base)) return true;
4712
+ if (/_test\.py$/i.test(base)) return true;
4713
+ if (/^Test[A-Z_]\w*\.py$/.test(base)) return true;
4714
+ if (/_test\.go$/.test(base)) return true;
4715
+ return false;
4716
+ }
4601
4717
  var SAFE_VAR_NAMES = /(?:description|message|text|label|title|content|template|html|svg|css|style|class(?:Name)?|query|mutation|schema|regex|pattern|format|placeholder|comment|url|path|route|endpoint|href|src|alt|name|type|version|encoding|charset|chars|alphabet|locale|translation|copy|prose|markdown|slug|handle)/i;
4602
4718
  var HASH_LIKE_VAR_NAMES = /(?:^|[^a-z])(?:hash|digest|checksum|fingerprint|etag|crc|md5|sha1|sha256|sha512|contenthash|buildid|revision|commit|sri|integrity|cacheKey|fileHash|assetId|versionId)(?:$|[^a-z])/i;
4603
4719
  var HASH_PREFIX_RE = /^(?:sha\d+|md5|crc32|base64|bcrypt|argon2|pbkdf2|blake2b?)[:_]/i;
@@ -4624,10 +4740,11 @@ function scanEntropy(files) {
4624
4740
  if (SKIP_FILENAMES.test(filePath)) continue;
4625
4741
  const basename = filePath.split("/").pop() || "";
4626
4742
  if (SKIP_FILENAMES.test(basename)) continue;
4743
+ if (SKIP_SBOM_FILES.test(filePath) || SKIP_SBOM_FILES.test(basename)) continue;
4627
4744
  if (filePath.includes("node_modules")) continue;
4628
4745
  if (filePath.includes(".min.")) continue;
4629
4746
  if (/pro-rules-bundle|\.bundle\.|\.chunk\./i.test(filePath)) continue;
4630
- if (/(?:\.test\.|\.spec\.|__tests__|__mocks__|fixtures?\/)/i.test(filePath)) continue;
4747
+ if (isEntropyTestPath(filePath)) continue;
4631
4748
  const vendored = isVendoredPath(filePath);
4632
4749
  const dotenv = isDotenvPath(filePath) && !DOTENV_EXAMPLE_RE.test(filePath);
4633
4750
  const lines = content.split("\n");
@@ -9176,6 +9293,7 @@ export {
9176
9293
  CHECKABLE_CLAIMS,
9177
9294
  DOTENV_ASSIGN_RE,
9178
9295
  FREE_RULE_COUNT,
9296
+ GRADE_FINDINGS_PER_RULE,
9179
9297
  INTENT_EXPECTATIONS,
9180
9298
  MODEL_ANALYSIS,
9181
9299
  MODEL_POLICY_REVIEWED,
@@ -9230,6 +9348,7 @@ export {
9230
9348
  freeRules,
9231
9349
  getObjectProperty,
9232
9350
  getSnippet,
9351
+ gradeRuleFamily,
9233
9352
  hardcodedJWTSecret,
9234
9353
  hardcodedSecrets,
9235
9354
  harvestIntent,