xploitscan-shared-rules 2.4.2 → 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
@@ -4517,6 +4517,9 @@ For each finding, respond ONLY with a JSON array. No other text.
4517
4517
  Each element: {"index": <number>, "verdict": "real" or "fp", "reason": "<1 sentence>"}`;
4518
4518
  var MAX_FINDINGS_PER_BATCH = 15;
4519
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;
4520
4523
  var DEFAULT_MAX_TOTAL_FINDINGS = 200;
4521
4524
  var MAX_TOTAL_FINDINGS = (() => {
4522
4525
  const raw = process.env.XPLOITSCAN_AI_FILTER_MAX;
@@ -4554,6 +4557,11 @@ var SEVERITY_PRIORITY = {
4554
4557
  low: 3,
4555
4558
  info: 4
4556
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
+ }
4557
4565
  function getExpandedContext(content, line, contextLines = MAX_CONTEXT_LINES) {
4558
4566
  const lines = content.split("\n");
4559
4567
  const start = Math.max(0, line - 1 - contextLines);
@@ -4561,7 +4569,7 @@ function getExpandedContext(content, line, contextLines = MAX_CONTEXT_LINES) {
4561
4569
  return lines.slice(start, end).map((l, i) => {
4562
4570
  const lineNum = start + i + 1;
4563
4571
  const marker = lineNum === line ? ">>>" : " ";
4564
- return `${marker} ${lineNum} | ${l}`;
4572
+ return `${marker} ${lineNum} | ${truncateChars(l, MAX_CONTEXT_LINE_CHARS)}`;
4565
4573
  }).join("\n");
4566
4574
  }
4567
4575
  function buildReviewPrompt(findings, fileContent) {
@@ -4574,8 +4582,8 @@ Rule: ${f.rule} (${f.title})
4574
4582
  Severity: ${f.severity}
4575
4583
  File: ${f.file}
4576
4584
  Line: ${f.line}
4577
- Description: ${f.description}
4578
- 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)}
4579
4587
 
4580
4588
  Code context:
4581
4589
  ${context}
@@ -4585,6 +4593,23 @@ ${context}
4585
4593
 
4586
4594
  ${parts.join("\n")}`;
4587
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
+ }
4588
4613
  function parseReviewResponse(text) {
4589
4614
  try {
4590
4615
  const cleaned = text.replace(/```json\n?/g, "").replace(/```\n?/g, "").trim();
@@ -4638,8 +4663,8 @@ async function filterFalsePositives(findings, fileContents, budgetMs = AI_FILTER
4638
4663
  for (const [file, fileFindings] of byFile) {
4639
4664
  const content = fileContents.get(file);
4640
4665
  if (!content) continue;
4641
- for (let i = 0; i < fileFindings.length; i += MAX_FINDINGS_PER_BATCH) {
4642
- 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 });
4643
4668
  }
4644
4669
  }
4645
4670
  const reviewBatch = async (task) => {
@@ -4652,6 +4677,14 @@ async function filterFalsePositives(findings, fileContents, budgetMs = AI_FILTER
4652
4677
  try {
4653
4678
  const remaining = Math.max(1, deadlineMs - Date.now());
4654
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
+ }
4655
4688
  const response = await client.messages.create(
4656
4689
  {
4657
4690
  model: MODEL_TRIAGE,
@@ -9464,6 +9497,7 @@ export {
9464
9497
  astMatch,
9465
9498
  buildProjectContext,
9466
9499
  buildQualityContext,
9500
+ buildReviewPrompt,
9467
9501
  buildTaintMap,
9468
9502
  calculateGrade,
9469
9503
  callSpreads,
@@ -9536,6 +9570,7 @@ export {
9536
9570
  nextPublicSecret,
9537
9571
  noRateLimiting,
9538
9572
  normalizeScanPath,
9573
+ packReviewBatches,
9539
9574
  parseFile,
9540
9575
  parseScanTarget,
9541
9576
  parseSupabaseConfig,