xploitscan-shared-rules 2.4.1 → 2.4.3

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
@@ -1248,6 +1248,16 @@ interface AIFilterResult {
1248
1248
  */
1249
1249
  unreviewedCount: number;
1250
1250
  }
1251
+ /** Exported for unit tests — keep prompt packing honest under hostile line lengths. */
1252
+ declare function buildReviewPrompt(findings: Finding[], fileContent: string): string;
1253
+ /**
1254
+ * Pack file findings into Haiku batches: at most MAX_FINDINGS_PER_BATCH and
1255
+ * at most MAX_BATCH_PROMPT_CHARS of prompt text. Severity order is preserved
1256
+ * (caller already sorted). A single finding that still exceeds the char cap
1257
+ * after truncation is emitted alone — better one oversized call than dropping
1258
+ * the finding with no review attempt.
1259
+ */
1260
+ declare function packReviewBatches(fileFindings: Finding[], content: string): Finding[][];
1251
1261
  /**
1252
1262
  * Filter false positives from findings using Claude Haiku.
1253
1263
  *
@@ -1630,4 +1640,4 @@ input: {
1630
1640
  content: string;
1631
1641
  }[] | QualityContext, rules?: QualityRule[]): Finding[];
1632
1642
 
1633
- 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, isLive, isMethodCall, isPrivateAddress, isSbomPath, isServerSideFile, isServerTarget, isTestFile, isTestPath, isUngradedFinding, 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 };
1643
+ 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, buildReviewPrompt, 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, isLive, isMethodCall, isPrivateAddress, isSbomPath, isServerSideFile, isServerTarget, isTestFile, isTestPath, isUngradedFinding, isVendoredFinding, isVendoredPath, lineNumberAt, lineTextAt, maskComments, maskOutboundAuthNoise, missingAuthMiddleware, missingCSP, missingErrorBoundary, missingHTTPS, missingLockFile, nextPublicSecret, noRateLimiting, normalizeScanPath, packReviewBatches, 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
@@ -1248,6 +1248,16 @@ interface AIFilterResult {
1248
1248
  */
1249
1249
  unreviewedCount: number;
1250
1250
  }
1251
+ /** Exported for unit tests — keep prompt packing honest under hostile line lengths. */
1252
+ declare function buildReviewPrompt(findings: Finding[], fileContent: string): string;
1253
+ /**
1254
+ * Pack file findings into Haiku batches: at most MAX_FINDINGS_PER_BATCH and
1255
+ * at most MAX_BATCH_PROMPT_CHARS of prompt text. Severity order is preserved
1256
+ * (caller already sorted). A single finding that still exceeds the char cap
1257
+ * after truncation is emitted alone — better one oversized call than dropping
1258
+ * the finding with no review attempt.
1259
+ */
1260
+ declare function packReviewBatches(fileFindings: Finding[], content: string): Finding[][];
1251
1261
  /**
1252
1262
  * Filter false positives from findings using Claude Haiku.
1253
1263
  *
@@ -1630,4 +1640,4 @@ input: {
1630
1640
  content: string;
1631
1641
  }[] | QualityContext, rules?: QualityRule[]): Finding[];
1632
1642
 
1633
- 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, isLive, isMethodCall, isPrivateAddress, isSbomPath, isServerSideFile, isServerTarget, isTestFile, isTestPath, isUngradedFinding, 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 };
1643
+ 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, buildReviewPrompt, 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, isLive, isMethodCall, isPrivateAddress, isSbomPath, isServerSideFile, isServerTarget, isTestFile, isTestPath, isUngradedFinding, isVendoredFinding, isVendoredPath, lineNumberAt, lineTextAt, maskComments, maskOutboundAuthNoise, missingAuthMiddleware, missingCSP, missingErrorBoundary, missingHTTPS, missingLockFile, nextPublicSecret, noRateLimiting, normalizeScanPath, packReviewBatches, 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
@@ -2676,7 +2676,7 @@ var stripeWebhookUnprotected = {
2676
2676
  if (!/stripe/i.test(code) && !pathSaysStripeWebhook) return [];
2677
2677
  const hasStripeWebhookHandler = pathSaysStripeWebhook || /(?:stripe.{0,200}webhook|webhook.{0,200}stripe)/i.test(code) || /(?:checkout\.session\.completed|invoice\.paid|payment_intent|customer\.subscription)/i.test(code);
2678
2678
  if (!hasStripeWebhookHandler) return [];
2679
- if (/constructEvent|verifyHeader|stripe[_-]?signature|webhook[_-]?secret|STRIPE_WEBHOOK_SECRET/i.test(code) || /\b\w*verif\w*\s*\(/i.test(code) && /\bverif\w*(?:stripe|webhook|signature|sig)\w*\s*\(/i.test(code)) return [];
2679
+ if (/constructEvent|verifyHeader|stripe[_-]?signature|webhook[_-]?secret|STRIPE_WEBHOOK_SECRET/i.test(code) || /\b\w{0,40}verif\w{0,40}\s*\(/i.test(code) && /\bverif\w{0,40}(?:stripe|webhook|signature|sig)\w{0,40}\s*\(/i.test(code)) return [];
2680
2680
  const handlerPatterns = [
2681
2681
  // POST handler that processes Stripe events
2682
2682
  /export\s+(?:async\s+)?function\s+POST\s*\(/g,
@@ -2684,7 +2684,10 @@ var stripeWebhookUnprotected = {
2684
2684
  // export const POST = async (req) => { … }
2685
2685
  // Added alongside the same shape in VC003 (#648); without it an App
2686
2686
  // Router webhook written in the arrow style was invisible.
2687
- /export\s+const\s+POST\s*(?::[^=]+)?=\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>/g,
2687
+ // Bound the optional TypeScript type annotation: `(?::[^=]+)?` walks an
2688
+ // entire 500KB line of non-`=` characters on every near-miss. Real
2689
+ // annotations (`: NextRequest`, `: RouteHandler`) sit well under 200.
2690
+ /export\s+const\s+POST\s*(?::[^=\n]{0,200})?=\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>/g,
2688
2691
  // Express-style Stripe webhook route
2689
2692
  /\.(post|all)\s*\(\s*["'`][^"'`]*(?:stripe|webhook)[^"'`]*["'`]/gi,
2690
2693
  // Event type checking without prior verification
@@ -4514,6 +4517,9 @@ For each finding, respond ONLY with a JSON array. No other text.
4514
4517
  Each element: {"index": <number>, "verdict": "real" or "fp", "reason": "<1 sentence>"}`;
4515
4518
  var MAX_FINDINGS_PER_BATCH = 15;
4516
4519
  var MAX_CONTEXT_LINES = 10;
4520
+ var MAX_CONTEXT_LINE_CHARS = 300;
4521
+ var MAX_BATCH_PROMPT_CHARS = 2e4;
4522
+ var MAX_FIELD_CHARS = 500;
4517
4523
  var DEFAULT_MAX_TOTAL_FINDINGS = 200;
4518
4524
  var MAX_TOTAL_FINDINGS = (() => {
4519
4525
  const raw = process.env.XPLOITSCAN_AI_FILTER_MAX;
@@ -4551,6 +4557,11 @@ var SEVERITY_PRIORITY = {
4551
4557
  low: 3,
4552
4558
  info: 4
4553
4559
  };
4560
+ function truncateChars(text, max) {
4561
+ if (text.length <= max) return text;
4562
+ if (max <= 1) return "\u2026";
4563
+ return `${text.slice(0, max - 1)}\u2026`;
4564
+ }
4554
4565
  function getExpandedContext(content, line, contextLines = MAX_CONTEXT_LINES) {
4555
4566
  const lines = content.split("\n");
4556
4567
  const start = Math.max(0, line - 1 - contextLines);
@@ -4558,7 +4569,7 @@ function getExpandedContext(content, line, contextLines = MAX_CONTEXT_LINES) {
4558
4569
  return lines.slice(start, end).map((l, i) => {
4559
4570
  const lineNum = start + i + 1;
4560
4571
  const marker = lineNum === line ? ">>>" : " ";
4561
- return `${marker} ${lineNum} | ${l}`;
4572
+ return `${marker} ${lineNum} | ${truncateChars(l, MAX_CONTEXT_LINE_CHARS)}`;
4562
4573
  }).join("\n");
4563
4574
  }
4564
4575
  function buildReviewPrompt(findings, fileContent) {
@@ -4571,8 +4582,8 @@ Rule: ${f.rule} (${f.title})
4571
4582
  Severity: ${f.severity}
4572
4583
  File: ${f.file}
4573
4584
  Line: ${f.line}
4574
- Description: ${f.description}
4575
- Suggested fix: ${f.fix || "N/A"}
4585
+ Description: ${truncateChars(f.description || "", MAX_FIELD_CHARS)}
4586
+ Suggested fix: ${truncateChars(f.fix || "N/A", MAX_FIELD_CHARS)}
4576
4587
 
4577
4588
  Code context:
4578
4589
  ${context}
@@ -4582,6 +4593,23 @@ ${context}
4582
4593
 
4583
4594
  ${parts.join("\n")}`;
4584
4595
  }
4596
+ function packReviewBatches(fileFindings, content) {
4597
+ const batches = [];
4598
+ let current = [];
4599
+ for (const f of fileFindings) {
4600
+ const candidate = [...current, f];
4601
+ const overCount = candidate.length > MAX_FINDINGS_PER_BATCH;
4602
+ const overChars = current.length > 0 && buildReviewPrompt(candidate, content).length > MAX_BATCH_PROMPT_CHARS;
4603
+ if (overCount || overChars) {
4604
+ if (current.length > 0) batches.push(current);
4605
+ current = [f];
4606
+ continue;
4607
+ }
4608
+ current = candidate;
4609
+ }
4610
+ if (current.length > 0) batches.push(current);
4611
+ return batches;
4612
+ }
4585
4613
  function parseReviewResponse(text) {
4586
4614
  try {
4587
4615
  const cleaned = text.replace(/```json\n?/g, "").replace(/```\n?/g, "").trim();
@@ -4635,8 +4663,8 @@ async function filterFalsePositives(findings, fileContents, budgetMs = AI_FILTER
4635
4663
  for (const [file, fileFindings] of byFile) {
4636
4664
  const content = fileContents.get(file);
4637
4665
  if (!content) continue;
4638
- for (let i = 0; i < fileFindings.length; i += MAX_FINDINGS_PER_BATCH) {
4639
- tasks.push({ batch: fileFindings.slice(i, i + MAX_FINDINGS_PER_BATCH), content });
4666
+ for (const batch of packReviewBatches(fileFindings, content)) {
4667
+ tasks.push({ batch, content });
4640
4668
  }
4641
4669
  }
4642
4670
  const reviewBatch = async (task) => {
@@ -4649,6 +4677,14 @@ async function filterFalsePositives(findings, fileContents, budgetMs = AI_FILTER
4649
4677
  try {
4650
4678
  const remaining = Math.max(1, deadlineMs - Date.now());
4651
4679
  const prompt = buildReviewPrompt(batch, content);
4680
+ console.info(
4681
+ `[ai-fp-filter] batch prompt ${prompt.length} chars (~${Math.ceil(prompt.length / 4)} tokens), ${batch.length} finding(s)`
4682
+ );
4683
+ if (prompt.length > MAX_BATCH_PROMPT_CHARS) {
4684
+ console.warn(
4685
+ `[ai-fp-filter] batch prompt ${prompt.length} chars exceeds ${MAX_BATCH_PROMPT_CHARS} cap (single oversized finding after truncation)`
4686
+ );
4687
+ }
4652
4688
  const response = await client.messages.create(
4653
4689
  {
4654
4690
  model: MODEL_TRIAGE,
@@ -9461,6 +9497,7 @@ export {
9461
9497
  astMatch,
9462
9498
  buildProjectContext,
9463
9499
  buildQualityContext,
9500
+ buildReviewPrompt,
9464
9501
  buildTaintMap,
9465
9502
  calculateGrade,
9466
9503
  callSpreads,
@@ -9533,6 +9570,7 @@ export {
9533
9570
  nextPublicSecret,
9534
9571
  noRateLimiting,
9535
9572
  normalizeScanPath,
9573
+ packReviewBatches,
9536
9574
  parseFile,
9537
9575
  parseScanTarget,
9538
9576
  parseSupabaseConfig,