xploitscan-shared-rules 2.4.19 → 2.4.21

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
@@ -30,6 +30,10 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
+ AI_REASONS: () => AI_REASONS,
34
+ AI_STATUSES: () => AI_STATUSES,
35
+ AI_SURFACES: () => AI_SURFACES,
36
+ BILLING_WEBHOOK_UNMATCHED_KEYS: () => BILLING_WEBHOOK_UNMATCHED_KEYS,
33
37
  CHECKABLE_CLAIMS: () => CHECKABLE_CLAIMS,
34
38
  DOTENV_ASSIGN_RE: () => DOTENV_ASSIGN_RE,
35
39
  FREE_RULE_COUNT: () => FREE_RULE_COUNT,
@@ -41,17 +45,26 @@ __export(index_exports, {
41
45
  MODEL_TEMPERATURE: () => MODEL_TEMPERATURE,
42
46
  MODEL_TRIAGE: () => MODEL_TRIAGE,
43
47
  NON_APP_PATH_PATTERNS: () => NON_APP_PATH_PATTERNS,
48
+ PLAN_CAUSES: () => PLAN_CAUSES,
49
+ PLAN_UNVERIFIED_NOTICE: () => PLAN_UNVERIFIED_NOTICE,
44
50
  PRO_RULE_COUNT: () => PRO_RULE_COUNT,
45
51
  PUBLIC_ENV_PREFIX_RE: () => PUBLIC_ENV_PREFIX_RE,
46
52
  QUALITY_EXAMPLES: () => QUALITY_EXAMPLES,
47
53
  RULE_IMPACTS: () => RULE_IMPACTS,
48
54
  SCANNER_VERSION: () => SCANNER_VERSION,
55
+ SCAN_AI_DEGRADED_KEYS: () => SCAN_AI_DEGRADED_KEYS,
56
+ SCAN_TOKEN_NULL_KEYS: () => SCAN_TOKEN_NULL_KEYS,
49
57
  SERVER_ACTION_WRITE_RE: () => SERVER_ACTION_WRITE_RE,
50
58
  TEST_FILE_PATTERN: () => TEST_FILE_PATTERN,
51
59
  TOTAL_RULE_COUNT: () => TOTAL_RULE_COUNT,
60
+ WEBHOOK_EVENT_TYPES: () => WEBHOOK_EVENT_TYPES,
61
+ WEBHOOK_REASONS: () => WEBHOOK_REASONS,
62
+ aiStatusLine: () => aiStatusLine,
52
63
  allRules: () => allRules,
53
64
  assessHeaders: () => assessHeaders,
54
65
  astMatch: () => astMatch,
66
+ billingWebhookUnmatchedProps: () => billingWebhookUnmatchedProps,
67
+ bucketFiles: () => bucketFiles,
55
68
  buildProjectContext: () => buildProjectContext,
56
69
  buildQualityContext: () => buildQualityContext,
57
70
  buildReviewPrompt: () => buildReviewPrompt,
@@ -136,23 +149,30 @@ __export(index_exports, {
136
149
  parseFile: () => parseFile,
137
150
  parseScanTarget: () => parseScanTarget,
138
151
  parseSupabaseConfig: () => parseSupabaseConfig,
152
+ perCallTimeoutMs: () => perCallTimeoutMs,
153
+ planCause: () => planCause,
139
154
  qualityRules: () => qualityRules,
140
155
  replaceBlockComments: () => replaceBlockComments,
141
156
  routeForFile: () => routeForFile,
142
157
  runCustomRules: () => runCustomRules,
158
+ scanAiDegradedProps: () => scanAiDegradedProps,
143
159
  scanConfigs: () => scanConfigs,
144
160
  scanDependencies: () => scanDependencies,
145
161
  scanEntropy: () => scanEntropy,
146
162
  scanMultiFile: () => scanMultiFile,
147
163
  scanQuality: () => scanQuality,
164
+ scanTokenNullProps: () => scanTokenNullProps,
148
165
  sqlInjection: () => sqlInjection,
149
166
  stripeWebhookUnprotected: () => stripeWebhookUnprotected,
150
167
  supabaseFunctionName: () => supabaseFunctionName,
151
168
  supabaseNoRLS: () => supabaseNoRLS,
169
+ toAiDegraded: () => toAiDegraded,
152
170
  todoLeftInCode: () => todoLeftInCode,
153
171
  tryParse: () => tryParse,
172
+ unknownAiStatus: () => unknownAiStatus,
154
173
  unmeasuredQualityRules: () => unmeasuredQualityRules,
155
174
  unvalidatedRedirect: () => unvalidatedRedirect,
175
+ vc001TestFixtureSeverity: () => vc001TestFixtureSeverity,
156
176
  vendoredReason: () => vendoredReason,
157
177
  visitBinary: () => visitBinary,
158
178
  visitCalls: () => visitCalls,
@@ -162,7 +182,7 @@ __export(index_exports, {
162
182
  module.exports = __toCommonJS(index_exports);
163
183
 
164
184
  // src/version.ts
165
- var SCANNER_VERSION = "2.4.19";
185
+ var SCANNER_VERSION = "2.4.21";
166
186
 
167
187
  // src/snippet.ts
168
188
  var cacheContent = null;
@@ -870,6 +890,10 @@ function isUngradedFinding(finding, options = {}) {
870
890
  if (options.gradeVendored) return false;
871
891
  return isVendoredFinding(finding);
872
892
  }
893
+ function vc001TestFixtureSeverity(rule, testFile, severity) {
894
+ if (rule === "VC001" && testFile === true) return "low";
895
+ return severity;
896
+ }
873
897
 
874
898
  // src/routes.ts
875
899
  var API_RE = /^\/api(\/|$)|^\/_|\.(json|js|xml|txt|ico)$/;
@@ -2229,6 +2253,308 @@ function noteHardcodedSecret(secret) {
2229
2253
  const sink = hardcodedSecretValueSink[hardcodedSecretValueSink.length - 1];
2230
2254
  if (sink && secret) sink.push(secret);
2231
2255
  }
2256
+ var LOCKED_PLACEHOLDER_TOKENS = /* @__PURE__ */ new Set([
2257
+ "your_api_key_here",
2258
+ "your-key-here",
2259
+ "your_key",
2260
+ "<your_key>",
2261
+ "changeme"
2262
+ ]);
2263
+ function isEntireXBody(value) {
2264
+ if (!value) return false;
2265
+ for (let i = 0; i < value.length; i++) {
2266
+ const code = value.charCodeAt(i);
2267
+ if (code !== 120 && code !== 88) return false;
2268
+ }
2269
+ return true;
2270
+ }
2271
+ function bodyAfterKnownPrefix(token) {
2272
+ const lower = token.toLowerCase();
2273
+ const prefixes = ["sk_live_", "pk_live_", "sk_test_", "pk_test_", "rk_live_", "rk_test_"];
2274
+ for (const prefix of prefixes) {
2275
+ if (lower.startsWith(prefix)) return token.slice(prefix.length);
2276
+ }
2277
+ return null;
2278
+ }
2279
+ function isLockedVc001Placeholder(token) {
2280
+ if (!token) return false;
2281
+ const trimmed = token.trim();
2282
+ if (!trimmed) return false;
2283
+ const lower = trimmed.toLowerCase();
2284
+ if (LOCKED_PLACEHOLDER_TOKENS.has(lower) || isEntireXBody(trimmed)) return true;
2285
+ const body = bodyAfterKnownPrefix(trimmed);
2286
+ if (body === null || body.length === 0) return false;
2287
+ return LOCKED_PLACEHOLDER_TOKENS.has(body.toLowerCase()) || isEntireXBody(body);
2288
+ }
2289
+ function collapseIdenticalRuns(token) {
2290
+ let out = "";
2291
+ let i = 0;
2292
+ while (i < token.length) {
2293
+ let j = i + 1;
2294
+ while (j < token.length && token[j] === token[i]) j += 1;
2295
+ const keep = j - i >= 8 ? 7 : j - i;
2296
+ out += token[i].repeat(keep);
2297
+ i = j;
2298
+ }
2299
+ return out;
2300
+ }
2301
+ function liveDespiteIdenticalRun(text) {
2302
+ if (!text || textHasLiveCredential(text)) return false;
2303
+ const re = /(?:sk_live_|rk_live_)[A-Za-z0-9]{20,}/g;
2304
+ let found;
2305
+ while ((found = re.exec(text)) !== null) {
2306
+ const token = found[0];
2307
+ if (isLockedVc001Placeholder(token)) continue;
2308
+ const collapsed = collapseIdenticalRuns(token);
2309
+ if (collapsed === token) continue;
2310
+ if (!isPlaceholderToken(collapsed)) return true;
2311
+ }
2312
+ return false;
2313
+ }
2314
+ function stripeReportedSeverity(text) {
2315
+ if (/pk_live_[A-Za-z0-9]{20,}/.test(text)) return "low";
2316
+ if (/sk_test_[A-Za-z0-9]{20,}/.test(text)) return "medium";
2317
+ return void 0;
2318
+ }
2319
+ function decodeBase64UrlJson(segment) {
2320
+ try {
2321
+ if (!segment || segment.length > 8192) return null;
2322
+ const pad = segment.length % 4 === 0 ? "" : "=".repeat(4 - segment.length % 4);
2323
+ const b64 = segment.replace(/-/g, "+").replace(/_/g, "/") + pad;
2324
+ const binary = atob(b64);
2325
+ const bytes = new Uint8Array(binary.length);
2326
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i) & 255;
2327
+ return JSON.parse(new TextDecoder().decode(bytes));
2328
+ } catch {
2329
+ return null;
2330
+ }
2331
+ }
2332
+ function decodeSupabaseJwt(token) {
2333
+ const parts = token.split(".");
2334
+ if (parts.length !== 3) return null;
2335
+ if (parts.some((part) => !/^[A-Za-z0-9_-]{8,}$/.test(part))) return null;
2336
+ const payload = decodeBase64UrlJson(parts[1]);
2337
+ if (!payload || typeof payload !== "object") return null;
2338
+ const rec = payload;
2339
+ return {
2340
+ role: typeof rec.role === "string" ? rec.role : void 0,
2341
+ iss: typeof rec.iss === "string" ? rec.iss : void 0,
2342
+ payloadText: JSON.stringify(payload)
2343
+ };
2344
+ }
2345
+ var STRING_CONST_VALUE_MAX = 4096;
2346
+ var CREATE_CLIENT_CALL_CAP = 200;
2347
+ function collectStringConsts(content) {
2348
+ const map = /* @__PURE__ */ new Map();
2349
+ const head = /(?:const|let|var)\s+([A-Za-z_$][\w$]{0,64})\s*=\s*(['"`])/g;
2350
+ let match;
2351
+ while ((match = head.exec(content)) !== null) {
2352
+ const name = match[1];
2353
+ const quote = match[2];
2354
+ const valueStart = match.index + match[0].length;
2355
+ const limit = Math.min(content.length, valueStart + STRING_CONST_VALUE_MAX);
2356
+ let end = valueStart;
2357
+ while (end < limit && content[end] !== quote) end += 1;
2358
+ if (end >= limit || content[end] !== quote) continue;
2359
+ if (!map.has(name)) map.set(name, { value: content.slice(valueStart, end), index: valueStart });
2360
+ head.lastIndex = end + 1;
2361
+ }
2362
+ return map;
2363
+ }
2364
+ function stringConstValue(consts, name) {
2365
+ if (!/^[A-Za-z_$][\w$]{0,64}$/.test(name)) return null;
2366
+ const found = consts.get(name);
2367
+ return found ? found.value : null;
2368
+ }
2369
+ function isLoopbackClientUrl(raw) {
2370
+ const match = /^[a-z][a-z0-9+.-]*:\/\/([^/?#\s]+)/i.exec(raw.trim());
2371
+ if (!match) return false;
2372
+ let host = match[1];
2373
+ if (host.startsWith("[")) {
2374
+ const end = host.indexOf("]");
2375
+ if (end < 0) return false;
2376
+ host = host.slice(1, end);
2377
+ } else {
2378
+ host = host.replace(/:\d+$/, "");
2379
+ }
2380
+ host = host.toLowerCase();
2381
+ return host === "localhost" || host === "127.0.0.1" || host === "::1";
2382
+ }
2383
+ function quotedValue(text) {
2384
+ const trimmed = text.trim();
2385
+ if (!trimmed) return null;
2386
+ const lead = text.indexOf(trimmed);
2387
+ if (/^(?:process\.env|import\.meta\.env)\.[A-Za-z0-9_]+!?$/.test(trimmed)) return null;
2388
+ const fallback = /(?:process\.env|import\.meta\.env)\.[A-Za-z0-9_]+!?\s*(?:\?\?|\|\|)\s*(['"`])([\s\S]*?)\1/.exec(trimmed);
2389
+ if (fallback?.[2]) {
2390
+ const rel = text.indexOf(fallback[2]);
2391
+ return { token: fallback[2], rel: rel < 0 ? lead : rel };
2392
+ }
2393
+ const literal = /^(['"`])([\s\S]*)\1$/.exec(trimmed);
2394
+ if (literal) {
2395
+ const rel = text.indexOf(literal[2]);
2396
+ return { token: literal[2], rel: rel < 0 ? lead + 1 : rel };
2397
+ }
2398
+ return null;
2399
+ }
2400
+ function splitCallArgs(content, openParen, cap) {
2401
+ const endLimit = Math.min(content.length, openParen + cap);
2402
+ const args = [];
2403
+ let start = openParen + 1;
2404
+ let depth = 1;
2405
+ let quote = null;
2406
+ let i = openParen + 1;
2407
+ while (i < endLimit && depth > 0) {
2408
+ const ch = content[i];
2409
+ if (quote) {
2410
+ if (ch === "\\") {
2411
+ i += 2;
2412
+ continue;
2413
+ }
2414
+ if (ch === quote) quote = null;
2415
+ i++;
2416
+ continue;
2417
+ }
2418
+ if (ch === "'" || ch === '"' || ch === "`") {
2419
+ quote = ch;
2420
+ i++;
2421
+ continue;
2422
+ }
2423
+ if (ch === "(" || ch === "[" || ch === "{") {
2424
+ depth++;
2425
+ i++;
2426
+ continue;
2427
+ }
2428
+ if (ch === ")" || ch === "]" || ch === "}") {
2429
+ depth--;
2430
+ if (depth === 0) {
2431
+ args.push({ text: content.slice(start, i), start });
2432
+ return { args, end: i + 1 };
2433
+ }
2434
+ i++;
2435
+ continue;
2436
+ }
2437
+ if (ch === "," && depth === 1) {
2438
+ args.push({ text: content.slice(start, i), start });
2439
+ start = i + 1;
2440
+ if (args.length >= 4) {
2441
+ return { args, end: i + 1 };
2442
+ }
2443
+ }
2444
+ i++;
2445
+ }
2446
+ return { args, end: i };
2447
+ }
2448
+ function objectKeyToken(arg, consts) {
2449
+ const named = /\b(?:supabaseKey|serviceRoleKey|service_role_key|apiKey|key)\s*:\s*(?:(['"`])([\s\S]*?)\1|([A-Za-z_$][\w$]{0,64}))/.exec(arg.text);
2450
+ if (!named) return null;
2451
+ if (named[2]) {
2452
+ const rel2 = arg.text.indexOf(named[2]);
2453
+ return { token: named[2], index: arg.start + (rel2 < 0 ? 0 : rel2) };
2454
+ }
2455
+ const ident = named[3];
2456
+ if (!ident) return null;
2457
+ const resolved = stringConstValue(consts, ident);
2458
+ if (resolved === null) return null;
2459
+ const rel = arg.text.indexOf(ident);
2460
+ return { token: resolved, index: arg.start + (rel < 0 ? 0 : rel) };
2461
+ }
2462
+ function valueToken(arg, consts) {
2463
+ const quoted = quotedValue(arg.text);
2464
+ if (quoted) return { token: quoted.token, index: arg.start + quoted.rel };
2465
+ const trimmed = arg.text.trim();
2466
+ if (/^[A-Za-z_$][\w$]{0,64}$/.test(trimmed)) {
2467
+ const resolved = stringConstValue(consts, trimmed);
2468
+ if (resolved === null) return null;
2469
+ const rel = arg.text.indexOf(trimmed);
2470
+ return { token: resolved, index: arg.start + (rel < 0 ? 0 : rel) };
2471
+ }
2472
+ if (trimmed.startsWith("{")) return objectKeyToken(arg, consts);
2473
+ return null;
2474
+ }
2475
+ function clientUrl(args) {
2476
+ if (args.length === 0) return "";
2477
+ const first = args[0].text.trim();
2478
+ const literal = /^(['"`])([\s\S]*)\1$/.exec(first);
2479
+ if (literal) return literal[2];
2480
+ if (first.startsWith("{")) {
2481
+ const url = /\b(?:supabaseUrl|url)\s*:\s*(['"`])([\s\S]*?)\1/.exec(first);
2482
+ return url?.[2] ?? "";
2483
+ }
2484
+ return "";
2485
+ }
2486
+ function nextCreateClient(content, from, cursor) {
2487
+ if (cursor.camel >= 0 && cursor.camel < from) {
2488
+ cursor.camel = content.indexOf("createClient", from);
2489
+ }
2490
+ if (cursor.snake >= 0 && cursor.snake < from) {
2491
+ cursor.snake = content.indexOf("create_client", from);
2492
+ }
2493
+ if (cursor.camel < 0) return cursor.snake;
2494
+ if (cursor.snake < 0) return cursor.camel;
2495
+ return cursor.camel < cursor.snake ? cursor.camel : cursor.snake;
2496
+ }
2497
+ function collectSupabaseCreateClientKeys(content, filePath, matches, rule, fix) {
2498
+ if (!content.includes("createClient") && !content.includes("create_client")) return;
2499
+ const consts = content.includes("createClient") ? collectStringConsts(content) : /* @__PURE__ */ new Map();
2500
+ const cap = 2e4;
2501
+ let from = 0;
2502
+ let calls = 0;
2503
+ const cursor = {
2504
+ camel: content.indexOf("createClient"),
2505
+ snake: content.indexOf("create_client")
2506
+ };
2507
+ while (from < content.length) {
2508
+ const at = nextCreateClient(content, from, cursor);
2509
+ if (at < 0) break;
2510
+ const nameLen = content.startsWith("create_client", at) ? "create_client".length : "createClient".length;
2511
+ const before = at === 0 ? "" : content[at - 1];
2512
+ const afterName = at + nameLen;
2513
+ if (before && /[A-Za-z0-9_$]/.test(before) || /[A-Za-z0-9_$]/.test(content[afterName] ?? "")) {
2514
+ from = afterName;
2515
+ continue;
2516
+ }
2517
+ let i = afterName;
2518
+ while (i < content.length && (content[i] === " " || content[i] === " " || content[i] === "\n" || content[i] === "\r")) i++;
2519
+ if (content[i] !== "(") {
2520
+ from = afterName;
2521
+ continue;
2522
+ }
2523
+ calls += 1;
2524
+ if (calls > CREATE_CLIENT_CALL_CAP) break;
2525
+ const parsed = splitCallArgs(content, i, cap);
2526
+ from = parsed?.end ?? Math.min(content.length, i + cap);
2527
+ if (!parsed || parsed.args.length === 0) continue;
2528
+ if (isCommentLine(content, at) || isInsideFixMessage(content, at)) continue;
2529
+ const first = parsed.args[0].text.trim();
2530
+ const keyArg = first.startsWith("{") ? parsed.args[0] : parsed.args[1];
2531
+ if (!keyArg) continue;
2532
+ const extracted = first.startsWith("{") ? objectKeyToken(keyArg, consts) : valueToken(keyArg, consts);
2533
+ if (!extracted || !extracted.token) continue;
2534
+ const token = extracted.token.trim();
2535
+ if (isPlaceholderToken(token) || isLockedVc001Placeholder(token)) continue;
2536
+ const decoded = decodeSupabaseJwt(token);
2537
+ if (!decoded || decoded.role !== "service_role") continue;
2538
+ const url = clientUrl(parsed.args);
2539
+ const downgrade = isTestPath(filePath) && (decoded.iss === "supabase-demo" || isLoopbackClientUrl(url));
2540
+ const line = lineNumberAt(content, extracted.index);
2541
+ const lineStart = content.lastIndexOf("\n", Math.max(0, extracted.index - 1)) + 1;
2542
+ const column = extracted.index - lineStart + 1;
2543
+ matches.push({
2544
+ rule: rule.id,
2545
+ title: rule.title,
2546
+ severity: downgrade ? "low" : "critical",
2547
+ category: rule.category,
2548
+ file: filePath,
2549
+ line,
2550
+ column,
2551
+ snippet: getSnippet(content, line),
2552
+ fix,
2553
+ ...downgrade ? {} : { live: true }
2554
+ });
2555
+ noteHardcodedSecret(token);
2556
+ }
2557
+ }
2232
2558
  var hardcodedSecrets = {
2233
2559
  id: "VC001",
2234
2560
  title: "Hardcoded API Key or Secret",
@@ -2330,10 +2656,9 @@ var hardcodedSecrets = {
2330
2656
  50,
2331
2657
  // [3] Supabase JWT
2332
2658
  // [4] OpenAI and [11]–[14] fixed-prefix tokens: the regex already
2333
- // fixes the length. The floor check reads the FIRST quoted value on the
2334
- // line, which in `a = "x"; key = "sk-proj-…"` is not the token, so it
2335
- // must not run for them. ([4] was 40, which the regex's minimum of 48
2336
- // made redundant everywhere except that misread.)
2659
+ // fixes the length, so the floor is 0. Every other floor measures this
2660
+ // match's own value. A live credential skips the floor. A placeholder
2661
+ // is dropped first, so a template key is never reported.
2337
2662
  0,
2338
2663
  20,
2339
2664
  // [5] generic tokens with {20,} in the regex
@@ -2360,6 +2685,27 @@ var hardcodedSecrets = {
2360
2685
  const lines = content.split("\n");
2361
2686
  const fileIsGemini = GEMINI_FILE_CONTEXT_RE.test(content);
2362
2687
  const matches = [];
2688
+ const columnFrom = /* @__PURE__ */ new Map();
2689
+ const locate = (lineNo, line, secret) => {
2690
+ if (!secret) return void 0;
2691
+ const key = `${lineNo}\0${secret}`;
2692
+ const start = columnFrom.get(key) ?? 0;
2693
+ const at = line.indexOf(secret, start);
2694
+ if (at < 0) return void 0;
2695
+ columnFrom.set(key, at + secret.length);
2696
+ return at + 1;
2697
+ };
2698
+ const emit = (rm, secret, extra = {}) => {
2699
+ const column = locate(rm.line, lines[rm.line - 1] || "", secret);
2700
+ const stripeSev = extra.live || extra.severity ? void 0 : stripeReportedSeverity(secret);
2701
+ matches.push({
2702
+ ...rm,
2703
+ ...extra,
2704
+ ...stripeSev ? { severity: stripeSev } : {},
2705
+ ...column ? { column } : {}
2706
+ });
2707
+ noteHardcodedSecret(secret);
2708
+ };
2363
2709
  for (let pi = 0; pi < patterns.length; pi++) {
2364
2710
  const pattern = patterns[pi];
2365
2711
  if (pi === GOOGLE_PI && !fileIsGemini && !GEMINI_NAME_RE.test(content)) continue;
@@ -2384,30 +2730,27 @@ var hardcodedSecrets = {
2384
2730
  if (isPlaceholderToken(token)) continue;
2385
2731
  if (pi === GOOGLE_PI) {
2386
2732
  if (!isGeminiKeyContext(lines, rm.line, fileIsGemini)) continue;
2387
- matches.push(textHasLiveCredential(token) ? { ...rm, severity: "high", live: true } : { ...rm, severity: "high" });
2388
- noteHardcodedSecret(secretText[ri] ?? "");
2733
+ emit(rm, secretText[ri] ?? token, textHasLiveCredential(token) ? { severity: "high", live: true } : { severity: "high" });
2389
2734
  continue;
2390
2735
  }
2391
2736
  if (pi === STRIPE_RESTRICTED_PI && !token.startsWith("rk_live_")) {
2392
- matches.push({ ...rm, severity: "high" });
2393
- noteHardcodedSecret(secretText[ri] ?? "");
2737
+ emit(rm, secretText[ri] ?? token, { severity: "high" });
2394
2738
  continue;
2395
2739
  }
2396
2740
  if (textHasLiveCredential(token)) {
2397
- matches.push({ ...rm, live: true });
2398
- noteHardcodedSecret(secretText[ri] ?? "");
2741
+ emit(rm, secretText[ri] ?? token, { live: true });
2399
2742
  continue;
2400
2743
  }
2401
2744
  }
2402
- if (floor > 0) {
2403
- const secretMatch = lineText.match(/[:=]\s*["'`]([^"'`]*)["'`]/);
2404
- if (secretMatch && secretMatch[1].length < floor) continue;
2405
- }
2745
+ const judged = secretText[ri] && secretText[ri].length > 0 ? secretText[ri] : matchedText[ri] ?? "";
2746
+ const judgedLive = textHasLiveCredential(judged) || liveDespiteIdenticalRun(judged);
2747
+ if (pi !== 9 && pi !== 10 && !judgedLive && isLockedVc001Placeholder(judged)) continue;
2748
+ const matchedLive = textHasLiveCredential(matchedText[ri] ?? "") || judgedLive;
2749
+ if (!matchedLive && floor > 0 && judged.length < floor) continue;
2406
2750
  if (pi === 6) {
2407
- const valMatch = lineText.match(/[:=]\s*["'`]([^"'`]+)["'`]/);
2751
+ const value = judged;
2408
2752
  const nameMatch = (matchedText[ri] ?? "").match(/^[A-Z][A-Z0-9_]{0,64}_(?:SECRET|TOKEN|KEY|PASSWORD|PASSWD)\b/);
2409
- if (valMatch && nameMatch) {
2410
- const value = valMatch[1];
2753
+ if (value && nameMatch) {
2411
2754
  const isKeySuffix = nameMatch[0].endsWith("_KEY");
2412
2755
  const isSlotIdentifier = value.length < 40 && (/^[a-z0-9]+([_-][a-z0-9]+)+$/.test(value) || isNamespacedSlotKey(nameMatch[0], value));
2413
2756
  if (isKeySuffix && isSlotIdentifier) continue;
@@ -2416,15 +2759,18 @@ var hardcodedSecrets = {
2416
2759
  if (pi === 10) {
2417
2760
  const url = matchedText[ri] ?? "";
2418
2761
  if (dbUrlLacksRealCredential(url)) continue;
2419
- matches.push(isLoopbackDevDefault(url) ? { ...rm, severity: "low" } : textHasLiveCredential(url) ? { ...rm, live: true } : rm);
2420
- noteHardcodedSecret(secretText[ri] ?? "");
2762
+ emit(
2763
+ rm,
2764
+ secretText[ri] ?? url,
2765
+ isLoopbackDevDefault(url) ? { severity: "low" } : textHasLiveCredential(url) ? { live: true } : {}
2766
+ );
2421
2767
  continue;
2422
2768
  }
2423
2769
  const matched = matchedText[ri] ?? "";
2424
- matches.push(textHasLiveCredential(matched) ? { ...rm, live: true } : rm);
2425
- noteHardcodedSecret(secretText[ri] ?? "");
2770
+ emit(rm, judged, textHasLiveCredential(matched) || matchedLive ? { live: true } : {});
2426
2771
  }
2427
2772
  }
2773
+ collectSupabaseCreateClientKeys(content, filePath, matches, hardcodedSecrets, fixMessages[3]);
2428
2774
  return matches;
2429
2775
  }
2430
2776
  };
@@ -4001,7 +4347,7 @@ var hardcodedJWTSecret = {
4001
4347
  category: "Secrets",
4002
4348
  description: "JWT tokens signed with a hardcoded string secret can be forged by anyone who reads the source code.",
4003
4349
  check(content, filePath) {
4004
- if (filePath.endsWith(".example") || filePath.endsWith(".template") || filePath.includes("test")) return [];
4350
+ if (filePath.endsWith(".example") || filePath.endsWith(".template") || isTestFile(filePath)) return [];
4005
4351
  const patterns = [
4006
4352
  /jwt\.sign\s*\([^,]{1,300},\s*["'`][^"'`]{3,}["'`]/g,
4007
4353
  /jwt\.verify\s*\([^,]{1,300},\s*["'`][^"'`]{3,}["'`]/g,
@@ -4093,7 +4439,7 @@ var exposedDebugMode = {
4093
4439
  category: "Configuration",
4094
4440
  description: "Debug mode, verbose logging, or development configuration left in production code exposes internal details and may enable debug endpoints.",
4095
4441
  check(content, filePath) {
4096
- if (filePath.includes("test") || filePath.endsWith(".example") || filePath.includes("node_modules")) return [];
4442
+ if (isTestFile(filePath) || filePath.endsWith(".example") || filePath.includes("node_modules")) return [];
4097
4443
  if (filePath.match(/\.env\.development$/)) return [];
4098
4444
  const matches = [];
4099
4445
  const patterns = [
@@ -4257,7 +4603,7 @@ var weakHashing = {
4257
4603
  category: "Cryptography",
4258
4604
  description: "MD5 and SHA1/SHA256 are too fast for password hashing \u2014 they can be brute-forced at billions of attempts per second. Use bcrypt, scrypt, or argon2 instead.",
4259
4605
  check(content, filePath) {
4260
- if (filePath.includes("test") || filePath.includes("mock")) return [];
4606
+ if (isTestFile(filePath)) return [];
4261
4607
  if (/bcrypt|scrypt|argon2/i.test(content)) return [];
4262
4608
  const matches = [];
4263
4609
  const inlinePatterns = [
@@ -5031,13 +5377,14 @@ function runCustomRules(content, filePath, disabledRules = [], tier = "free", ex
5031
5377
  live: match.live,
5032
5378
  snippet: match.snippet
5033
5379
  });
5380
+ const testFixture = onTestPath && !live;
5034
5381
  findings.push({
5035
5382
  ...vendored ? { vendored: true } : {},
5036
- ...onTestPath && !live ? { testFile: true } : {},
5383
+ ...testFixture ? { testFile: true } : {},
5037
5384
  ...live ? { live: true } : {},
5038
5385
  id: `${match.rule}-${match.file}:${match.line}`,
5039
5386
  rule: match.rule,
5040
- severity: match.severity,
5387
+ severity: vc001TestFixtureSeverity(match.rule, testFixture ? true : void 0, match.severity),
5041
5388
  title: match.title,
5042
5389
  description: rule.description,
5043
5390
  file: match.file,
@@ -5704,6 +6051,255 @@ function scanEntropyFiles(files, collect) {
5704
6051
  return findings;
5705
6052
  }
5706
6053
 
6054
+ // src/ai-status-constants.ts
6055
+ var AI_STATUSES = ["reviewed", "partial", "skipped", "failed", "unknown"];
6056
+ var AI_REASONS = [
6057
+ "no_api_key",
6058
+ "client_init",
6059
+ "capped",
6060
+ "budget_timeout",
6061
+ "model_bad_output",
6062
+ "model_error",
6063
+ "missing_content",
6064
+ "exception",
6065
+ "opted_out",
6066
+ "auth_failed",
6067
+ "jti_missing",
6068
+ "token_unverified",
6069
+ "pro_rules_unavailable",
6070
+ "engine_unavailable",
6071
+ "upload_failed",
6072
+ "upload_blocked",
6073
+ "upload_duplicate",
6074
+ "persist_failed",
6075
+ "quality_unavailable",
6076
+ "intent_unavailable",
6077
+ "not_supported",
6078
+ "token_secret_missing",
6079
+ "rate_limited",
6080
+ "jti_unavailable",
6081
+ "credit_error",
6082
+ "daily_limit",
6083
+ "signed_out"
6084
+ ];
6085
+ var AI_SURFACES = ["upload", "cli", "action", "app", "api", "mcp", "web", "save"];
6086
+ var PLAN_CAUSES = [
6087
+ "missing",
6088
+ "malformed",
6089
+ "expired",
6090
+ "revoked",
6091
+ "network",
6092
+ "upstream_5xx",
6093
+ "unknown"
6094
+ ];
6095
+ var WEBHOOK_REASONS = [
6096
+ "no_metadata_user",
6097
+ "malformed_user",
6098
+ "unknown_user",
6099
+ "user_bound_other_customer",
6100
+ "race_no_row",
6101
+ "deleted_unmatched",
6102
+ "clerk_lookup_failed"
6103
+ ];
6104
+ var WEBHOOK_EVENT_TYPES = [
6105
+ "checkout.session.completed",
6106
+ "customer.subscription.created",
6107
+ "customer.subscription.updated",
6108
+ "customer.subscription.deleted",
6109
+ "invoice.paid",
6110
+ "invoice.payment_failed",
6111
+ "created",
6112
+ "updated"
6113
+ ];
6114
+
6115
+ // src/ai-status.ts
6116
+ var PLAN_UNVERIFIED_NOTICE = "Couldn't verify your plan, scanned with free rules only.";
6117
+ var FAIL_REASONS = /* @__PURE__ */ new Set([
6118
+ "budget_timeout",
6119
+ "model_error",
6120
+ "model_bad_output",
6121
+ "auth_failed",
6122
+ "exception",
6123
+ "client_init"
6124
+ ]);
6125
+ function clampCount(raw) {
6126
+ if (typeof raw !== "number" || !Number.isFinite(raw) || raw < 0) return 0;
6127
+ return Math.min(Math.trunc(raw), 1e6);
6128
+ }
6129
+ function isStatus(raw) {
6130
+ return typeof raw === "string" && AI_STATUSES.includes(raw);
6131
+ }
6132
+ function isReason(raw) {
6133
+ return typeof raw === "string" && AI_REASONS.includes(raw);
6134
+ }
6135
+ function isSurface(raw) {
6136
+ return typeof raw === "string" && AI_SURFACES.includes(raw);
6137
+ }
6138
+ function bucketFiles(n) {
6139
+ if (typeof n !== "number" || !Number.isFinite(n) || n <= 0) return "0";
6140
+ const v = Math.trunc(n);
6141
+ if (v < 5) return "1-4";
6142
+ if (v < 20) return "5-19";
6143
+ return "20+";
6144
+ }
6145
+ function planCause(specific) {
6146
+ switch (specific) {
6147
+ case "secret_missing":
6148
+ return "missing";
6149
+ case "bad_shape":
6150
+ case "sig_mismatch":
6151
+ case "sig_length_mismatch":
6152
+ case "hmac_error":
6153
+ case "payload_parse_error":
6154
+ case "uid_or_tier_wrong_type":
6155
+ return "malformed";
6156
+ case "expired":
6157
+ case "exp_missing_or_nan":
6158
+ return "expired";
6159
+ case "tier_not_paid_unknown_value":
6160
+ case "http_401":
6161
+ case "http_403":
6162
+ return "revoked";
6163
+ case "no_cached_bundle_and_network_error":
6164
+ case "timeout":
6165
+ case "network":
6166
+ return "network";
6167
+ case "http_5xx":
6168
+ case "upstream_5xx":
6169
+ return "upstream_5xx";
6170
+ default:
6171
+ return "unknown";
6172
+ }
6173
+ }
6174
+ function toAiDegraded(input = {}) {
6175
+ const total = clampCount(input.total);
6176
+ let reviewed = clampCount(input.reviewed);
6177
+ let capped = clampCount(input.capped);
6178
+ if (reviewed > total) reviewed = total;
6179
+ if (reviewed + capped > total) capped = total - reviewed;
6180
+ const unreviewed = total - reviewed - capped;
6181
+ let status = isStatus(input.status) ? input.status : "unknown";
6182
+ let reason = isReason(input.reason) ? input.reason : null;
6183
+ const eligible = total - capped;
6184
+ if (status === "reviewed" && reviewed !== eligible) {
6185
+ status = reviewed === 0 && reason != null && FAIL_REASONS.has(reason) ? "failed" : "partial";
6186
+ }
6187
+ if (status === "reviewed" && unreviewed > 0) status = "partial";
6188
+ if (status === "skipped" && reason != null && FAIL_REASONS.has(reason)) status = "failed";
6189
+ if (status === "reviewed" || status === "unknown") {
6190
+ if (status === "unknown") reason = null;
6191
+ }
6192
+ const modelStatus = reason === "model_error" && typeof input.modelStatus === "number" && Number.isFinite(input.modelStatus) ? Math.trunc(input.modelStatus) : null;
6193
+ return {
6194
+ status,
6195
+ reason,
6196
+ surface: isSurface(input.surface) ? input.surface : "cli",
6197
+ total,
6198
+ reviewed,
6199
+ unreviewed,
6200
+ capped,
6201
+ modelStatus
6202
+ };
6203
+ }
6204
+ function unknownAiStatus(surface = "save") {
6205
+ return toAiDegraded({ status: "unknown", reason: null, surface, total: 0, reviewed: 0, unreviewed: 0, capped: 0 });
6206
+ }
6207
+ function aiStatusLine(d) {
6208
+ const shown = Math.max(0, d.total - d.capped);
6209
+ switch (d.reason) {
6210
+ case "no_api_key":
6211
+ return "AI review skipped: no Anthropic API key is set.";
6212
+ case "opted_out":
6213
+ return "AI review skipped: user opted out.";
6214
+ case "not_supported":
6215
+ return "AI review not run on MCP scans.";
6216
+ case "auth_failed":
6217
+ return "AI review failed: the Anthropic API key was rejected.";
6218
+ case "capped":
6219
+ return `AI review covered the first ${shown} of ${d.total} findings.`;
6220
+ case "budget_timeout":
6221
+ return d.status === "failed" ? `AI review failed: every batch timed out (${d.reviewed} reviewed, ${d.unreviewed} unreviewed, ${d.capped} capped, ${d.total} total).` : `AI review was partial: the time limit ran out (${d.reviewed} reviewed of ${d.total}).`;
6222
+ case "client_init":
6223
+ return "AI review failed: the AI client could not start.";
6224
+ case "model_bad_output":
6225
+ return "AI review failed: the model returned unusable output.";
6226
+ case "model_error":
6227
+ return `AI review failed: the model request was rejected (HTTP ${d.modelStatus ?? "error"}).`;
6228
+ case "missing_content":
6229
+ return "AI review was partial: source content was missing for some findings.";
6230
+ case "exception":
6231
+ return "AI review failed: an unexpected error occurred.";
6232
+ case "token_secret_missing":
6233
+ return "AI review skipped: scan token verification is not configured.";
6234
+ case "rate_limited":
6235
+ return "AI review skipped: rate limited.";
6236
+ case "jti_unavailable":
6237
+ return "AI review skipped: the review token could not be checked in time.";
6238
+ case "jti_missing":
6239
+ return "AI review skipped: the review token had no single-use id.";
6240
+ case "credit_error":
6241
+ return "AI review skipped: the review credit could not be spent.";
6242
+ case "daily_limit":
6243
+ return "AI review skipped: daily limit reached.";
6244
+ case "signed_out":
6245
+ return "AI review skipped: signed out.";
6246
+ case "quality_unavailable":
6247
+ return "Quality checks were unavailable for this scan.";
6248
+ case "intent_unavailable":
6249
+ return "Intent check was unavailable for this scan.";
6250
+ case "engine_unavailable":
6251
+ return "A scan engine was unavailable.";
6252
+ case "upload_failed":
6253
+ return "The scan could not be uploaded.";
6254
+ case "upload_blocked":
6255
+ return "The scan was not uploaded: the plan limit blocked it.";
6256
+ case "upload_duplicate":
6257
+ return "The scan was already uploaded for this job.";
6258
+ case "persist_failed":
6259
+ return "The scan status could not be stored.";
6260
+ case "token_unverified":
6261
+ case "pro_rules_unavailable":
6262
+ return PLAN_UNVERIFIED_NOTICE;
6263
+ default:
6264
+ if (d.status === "reviewed") return "AI review completed.";
6265
+ if (d.status === "unknown") return "AI review status is unknown.";
6266
+ if (d.status === "partial") return `AI review was partial: ${d.reviewed} of ${d.total} findings reviewed.`;
6267
+ if (d.status === "failed") return "AI review failed.";
6268
+ return "AI review skipped.";
6269
+ }
6270
+ }
6271
+ var SCAN_AI_DEGRADED_KEYS = [
6272
+ "status",
6273
+ "reason",
6274
+ "surface",
6275
+ "total",
6276
+ "reviewed",
6277
+ "capped",
6278
+ "files_received_bucket"
6279
+ ];
6280
+ function scanAiDegradedProps(d, filesReceived) {
6281
+ return {
6282
+ status: d.status,
6283
+ reason: d.reason,
6284
+ surface: d.surface,
6285
+ total: d.total,
6286
+ reviewed: d.reviewed,
6287
+ capped: d.capped,
6288
+ files_received_bucket: bucketFiles(filesReceived)
6289
+ };
6290
+ }
6291
+ var SCAN_TOKEN_NULL_KEYS = ["cause", "surface", "tier_expected"];
6292
+ function scanTokenNullProps(cause, surface) {
6293
+ const safeSurface = isSurface(surface) ? surface : "api";
6294
+ return { cause, surface: safeSurface, tier_expected: "paid" };
6295
+ }
6296
+ var BILLING_WEBHOOK_UNMATCHED_KEYS = ["type", "reason", "final"];
6297
+ function billingWebhookUnmatchedProps(input) {
6298
+ const reason = typeof input.reason === "string" && WEBHOOK_REASONS.includes(input.reason) ? input.reason : "race_no_row";
6299
+ const type = typeof input.type === "string" && input.type.length > 0 && input.type.length < 80 ? input.type : "unknown";
6300
+ return { type, reason, final: input.final === true };
6301
+ }
6302
+
5707
6303
  // src/ai-fp-filter.ts
5708
6304
  var REVIEW_SYSTEM_PROMPT = `You are reviewing security scan findings for false positives. Your job is to look at each finding and the surrounding code to determine if it's a REAL security vulnerability or a FALSE POSITIVE.
5709
6305
 
@@ -5763,6 +6359,15 @@ var AI_FILTER_BUDGET_MS = (() => {
5763
6359
  return Math.min(n, 6e4);
5764
6360
  })();
5765
6361
  var PER_CALL_TIMEOUT_MS = 8e3;
6362
+ function perCallTimeoutMs(budgetMs) {
6363
+ const budget = Number.isFinite(budgetMs) && budgetMs >= 1 ? Math.min(Math.trunc(budgetMs), 6e4) : DEFAULT_AI_FILTER_BUDGET_MS;
6364
+ const scaled = Math.floor(budget * 0.6);
6365
+ const perCall = Math.min(PER_CALL_TIMEOUT_MS, scaled);
6366
+ return perCall;
6367
+ }
6368
+ if (!(perCallTimeoutMs(AI_FILTER_BUDGET_MS) < AI_FILTER_BUDGET_MS)) {
6369
+ throw new Error("per-call AI timeout must be strictly below the filter budget");
6370
+ }
5766
6371
  function isAbortError(err) {
5767
6372
  if (!err || typeof err !== "object") return false;
5768
6373
  const name = "name" in err ? String(err.name) : "";
@@ -5775,6 +6380,16 @@ function isTimeoutError(err) {
5775
6380
  const message = err instanceof Error ? err.message : String(err);
5776
6381
  return /\b(?:request|connection|operation|model call)\s+(?:has\s+)?timed out\b/i.test(message) || /\bETIMEDOUT\b/i.test(message);
5777
6382
  }
6383
+ function errorHttpStatus(err) {
6384
+ if (!err || typeof err !== "object") return null;
6385
+ const status = err.status;
6386
+ return typeof status === "number" && Number.isFinite(status) ? Math.trunc(status) : null;
6387
+ }
6388
+ function callWasAborted(err) {
6389
+ if (!err || typeof err !== "object") return false;
6390
+ const name = "name" in err ? String(err.name) : "";
6391
+ return name === "AbortError" || name === "APIUserAbortError";
6392
+ }
5778
6393
  var SEVERITY_PRIORITY = {
5779
6394
  critical: 0,
5780
6395
  high: 1,
@@ -5924,8 +6539,10 @@ function parseReviewResponse(text) {
5924
6539
  return null;
5925
6540
  }
5926
6541
  }
5927
- async function filterFalsePositives(findings, fileContents, budgetMs = AI_FILTER_BUDGET_MS) {
5928
- const empty = {
6542
+ async function filterFalsePositives(findings, fileContents, budgetMs = AI_FILTER_BUDGET_MS, options) {
6543
+ const surface = options?.surface ?? "cli";
6544
+ const emptyMask = { prompt_batches: 0, prompt_chars: 0, masked_count: 0, had_secret_pattern: false, raw_after_mask: 0 };
6545
+ const early = (status2, reason2, extra) => ({
5929
6546
  findings,
5930
6547
  filteredFindings: [],
5931
6548
  policyRetainedFindings: [],
@@ -5933,15 +6550,27 @@ async function filterFalsePositives(findings, fileContents, budgetMs = AI_FILTER
5933
6550
  removedCount: 0,
5934
6551
  policyRetainedCount: 0,
5935
6552
  totalBefore: findings.length,
5936
- reviewedCount: 0,
5937
- unreviewedCount: findings.length,
5938
- cappedCount: 0,
6553
+ reviewedCount: extra?.reviewed ?? 0,
6554
+ unreviewedCount: extra?.unreviewed ?? findings.length,
6555
+ cappedCount: extra?.capped ?? 0,
5939
6556
  missingContentCount: 0,
5940
6557
  timedOut: false,
5941
- maskStats: { prompt_batches: 0, prompt_chars: 0, masked_count: 0, had_secret_pattern: false, raw_after_mask: 0 }
5942
- };
5943
- if (findings.length === 0) return empty;
5944
- if (!process.env.ANTHROPIC_API_KEY) return empty;
6558
+ maskStats: emptyMask,
6559
+ aiDegraded: toAiDegraded({
6560
+ status: status2,
6561
+ reason: reason2,
6562
+ surface,
6563
+ total: findings.length,
6564
+ reviewed: extra?.reviewed ?? 0,
6565
+ unreviewed: extra?.unreviewed ?? findings.length,
6566
+ capped: extra?.capped ?? 0,
6567
+ modelStatus: extra?.modelStatus ?? null
6568
+ })
6569
+ });
6570
+ if (findings.length === 0) {
6571
+ return early("reviewed", null, { reviewed: 0, unreviewed: 0, capped: 0 });
6572
+ }
6573
+ if (!process.env.ANTHROPIC_API_KEY) return early("skipped", "no_api_key");
5945
6574
  const deadlineMs = Date.now() + Math.max(0, budgetMs);
5946
6575
  const abortController = new AbortController();
5947
6576
  let budgetExpired = budgetMs <= 0;
@@ -5971,12 +6600,20 @@ async function filterFalsePositives(findings, fileContents, budgetMs = AI_FILTER
5971
6600
  try {
5972
6601
  client = new import_sdk.default();
5973
6602
  } catch {
5974
- return empty;
6603
+ if (budgetTimer) clearTimeout(budgetTimer);
6604
+ return early("failed", "client_init", {
6605
+ reviewed: 0,
6606
+ capped: overflow.length,
6607
+ unreviewed: findings.length - overflow.length
6608
+ });
5975
6609
  }
5976
6610
  const fpMap = /* @__PURE__ */ new Map();
5977
6611
  const policyRetainedMap = /* @__PURE__ */ new Map();
5978
6612
  const reviewedIndices = /* @__PURE__ */ new Set();
5979
6613
  let firstError = null;
6614
+ let firstErrorStatus = null;
6615
+ let authFailed = false;
6616
+ let badOutput = false;
5980
6617
  const maskStats = { prompt_batches: 0, prompt_chars: 0, masked_count: 0, had_secret_pattern: false, raw_after_mask: 0 };
5981
6618
  let failedBatches = 0;
5982
6619
  let timedOutCount = 0;
@@ -6002,9 +6639,11 @@ async function filterFalsePositives(findings, fileContents, budgetMs = AI_FILTER
6002
6639
  const reviewBatch = async (task) => {
6003
6640
  const { targets, content, detections } = task;
6004
6641
  const batch = targets.map((target) => target.finding);
6005
- if (abortController.signal.aborted || Date.now() >= deadlineMs) {
6006
- budgetExpired = true;
6007
- timedOutCount += batch.length;
6642
+ if (authFailed || abortController.signal.aborted || Date.now() >= deadlineMs) {
6643
+ if (!authFailed) {
6644
+ budgetExpired = true;
6645
+ timedOutCount += batch.length;
6646
+ }
6008
6647
  return;
6009
6648
  }
6010
6649
  try {
@@ -6016,7 +6655,7 @@ async function filterFalsePositives(findings, fileContents, budgetMs = AI_FILTER
6016
6655
  maskStats.masked_count += proof.detected - proof.raw;
6017
6656
  maskStats.raw_after_mask += proof.raw;
6018
6657
  if (proof.detected > 0) maskStats.had_secret_pattern = true;
6019
- console.info(
6658
+ console.error(
6020
6659
  `[ai-fp-filter] batch prompt ${prompt.length} chars (~${Math.ceil(prompt.length / 4)} tokens), ${batch.length} finding(s)`
6021
6660
  );
6022
6661
  if (prompt.length > MAX_BATCH_PROMPT_CHARS) {
@@ -6024,38 +6663,52 @@ async function filterFalsePositives(findings, fileContents, budgetMs = AI_FILTER
6024
6663
  `[ai-fp-filter] batch prompt ${prompt.length} chars exceeds ${MAX_BATCH_PROMPT_CHARS} cap (single oversized finding after truncation)`
6025
6664
  );
6026
6665
  }
6027
- const response = await client.messages.create(
6028
- {
6029
- model: MODEL_TRIAGE,
6030
- max_tokens: 2048,
6031
- // Haiku 5.5 rejects non-default sampling params with HTTP 400
6032
- // ("temperature is deprecated for this model"). Omit temperature /
6033
- // top_p / top_k entirely — do NOT send MODEL_TEMPERATURE (0).
6034
- // Adaptive thinking is on by default for 5.5; disable it here: this
6035
- // is binary FP classification, not open-ended analysis, and thinking
6036
- // burns the shared AI budget (Isobar rescan: every call 400'd on
6037
- // temperature, then timed_out with aiReviewed:false → grade D).
6038
- thinking: { type: "disabled" },
6039
- system: REVIEW_SYSTEM_PROMPT,
6040
- messages: [{ role: "user", content: prompt }]
6041
- },
6042
- // Shared AbortController plus a per-call timeout capped at remaining
6043
- // budget. Previously 20s with no overall deadline.
6044
- { timeout: Math.min(PER_CALL_TIMEOUT_MS, remaining), signal: abortController.signal }
6045
- );
6666
+ const perCall = perCallTimeoutMs(budgetMs);
6667
+ const callTimeout = Math.min(perCall, remaining);
6668
+ const callAbort = new AbortController();
6669
+ const onParentAbort = () => callAbort.abort();
6670
+ if (abortController.signal.aborted) callAbort.abort();
6671
+ else abortController.signal.addEventListener("abort", onParentAbort, { once: true });
6672
+ const callTimer = setTimeout(() => callAbort.abort(), callTimeout);
6673
+ let response;
6674
+ try {
6675
+ response = await client.messages.create(
6676
+ {
6677
+ model: MODEL_TRIAGE,
6678
+ max_tokens: 2048,
6679
+ // Haiku 5.5 rejects non-default sampling params with HTTP 400
6680
+ // ("temperature is deprecated for this model"). Omit temperature /
6681
+ // top_p / top_k entirely — do NOT send MODEL_TEMPERATURE (0).
6682
+ // Adaptive thinking is on by default for 5.5; disable it here: this
6683
+ // is binary FP classification, not open-ended analysis, and thinking
6684
+ // burns the shared AI budget (Isobar rescan: every call 400'd on
6685
+ // temperature, then timed_out with aiReviewed:false → grade D).
6686
+ thinking: { type: "disabled" },
6687
+ system: REVIEW_SYSTEM_PROMPT,
6688
+ messages: [{ role: "user", content: prompt }]
6689
+ },
6690
+ { timeout: callTimeout, signal: callAbort.signal }
6691
+ );
6692
+ } finally {
6693
+ clearTimeout(callTimer);
6694
+ abortController.signal.removeEventListener("abort", onParentAbort);
6695
+ }
6046
6696
  const text = response.content.filter((b) => b.type === "text").map((b) => b.text).join("");
6047
6697
  const results = parseReviewResponse(text);
6048
- if (!results) throw new Error("AI review returned malformed JSON");
6698
+ if (!results) {
6699
+ badOutput = true;
6700
+ throw new Error("AI review returned malformed JSON");
6701
+ }
6049
6702
  for (const r of results) {
6050
6703
  if (r.index >= batch.length) continue;
6051
6704
  const target = targets[r.index];
6052
6705
  reviewedIndices.add(target.originalIndex);
6053
6706
  if (r.verdict !== "fp") continue;
6054
- const reason = truncateChars(applySecretMasks(r.reason, secrets), MAX_FIELD_CHARS);
6707
+ const reason2 = truncateChars(applySecretMasks(r.reason, secrets), MAX_FIELD_CHARS);
6055
6708
  if (isProtectedFromAiRemoval(target.finding)) {
6056
- policyRetainedMap.set(target.originalIndex, reason);
6709
+ policyRetainedMap.set(target.originalIndex, reason2);
6057
6710
  } else {
6058
- fpMap.set(target.originalIndex, reason);
6711
+ fpMap.set(target.originalIndex, reason2);
6059
6712
  }
6060
6713
  }
6061
6714
  if (results.filter((result) => result.index < batch.length).length < batch.length) {
@@ -6063,21 +6716,35 @@ async function filterFalsePositives(findings, fileContents, budgetMs = AI_FILTER
6063
6716
  if (!firstError) firstError = new Error("AI review returned incomplete verdicts");
6064
6717
  }
6065
6718
  } catch (err) {
6066
- const callTimedOut = isAbortError(err) || isTimeoutError(err) || abortController.signal.aborted;
6719
+ const status2 = errorHttpStatus(err);
6720
+ if (status2 === 401 || status2 === 403) {
6721
+ authFailed = true;
6722
+ failedBatches++;
6723
+ if (!firstError) {
6724
+ firstError = err;
6725
+ firstErrorStatus = status2;
6726
+ }
6727
+ console.error(`[ai-fp-filter] AI review failed: auth status ${status2}`);
6728
+ return;
6729
+ }
6730
+ const callTimedOut = isAbortError(err) || isTimeoutError(err) || abortController.signal.aborted || callWasAborted(err);
6067
6731
  if (callTimedOut) {
6068
6732
  timedOutCount += batch.length;
6069
6733
  budgetExpired = true;
6070
6734
  return;
6071
6735
  }
6072
6736
  failedBatches++;
6073
- if (!firstError) firstError = err;
6737
+ if (!firstError) {
6738
+ firstError = err;
6739
+ firstErrorStatus = status2;
6740
+ }
6074
6741
  }
6075
6742
  };
6076
6743
  try {
6077
6744
  let next = 0;
6078
6745
  const workerCount = Math.min(MAX_CONCURRENT, tasks.length);
6079
6746
  const workers = Array.from({ length: workerCount }, async () => {
6080
- while (next < tasks.length) {
6747
+ while (next < tasks.length && !authFailed) {
6081
6748
  const cur = next++;
6082
6749
  await reviewBatch(tasks[cur]);
6083
6750
  }
@@ -6095,28 +6762,70 @@ async function filterFalsePositives(findings, fileContents, budgetMs = AI_FILTER
6095
6762
  `[ai-fp-filter] budget expired or model call timed out \u2014 ${timedOutCount} finding(s) not reviewed; returning them unchanged`
6096
6763
  );
6097
6764
  }
6098
- if (firstError) {
6099
- const msg = firstError instanceof Error ? firstError.message : String(firstError);
6765
+ if (firstError && !authFailed) {
6766
+ const statusLabel = firstErrorStatus == null ? "none" : String(firstErrorStatus);
6100
6767
  if (!reviewedAny) {
6101
6768
  console.error(
6102
- "[ai-fp-filter] AI review unavailable \u2014 every model call failed; returning unreviewed findings:",
6103
- msg
6769
+ `[ai-fp-filter] AI review unavailable \u2014 every model call failed; status ${statusLabel}`
6104
6770
  );
6105
6771
  } else {
6106
6772
  console.warn(
6107
- `[ai-fp-filter] partial AI review \u2014 ${failedBatches} of ${tasks.length} batch(es) failed; those findings were not reviewed:`,
6108
- msg
6773
+ `[ai-fp-filter] partial AI review \u2014 ${failedBatches} of ${tasks.length} batch(es) failed; status ${statusLabel}`
6109
6774
  );
6110
6775
  }
6111
6776
  }
6112
6777
  const filtered = findings.filter((_, index) => !fpMap.has(index));
6113
6778
  const filteredFindings = [];
6114
- for (const [index, reason] of [...fpMap].sort((a, b) => a[0] - b[0])) {
6115
- filteredFindings.push({ finding: findings[index], reason });
6779
+ for (const [index, reason2] of [...fpMap].sort((a, b) => a[0] - b[0])) {
6780
+ filteredFindings.push({ finding: findings[index], reason: reason2 });
6116
6781
  }
6117
6782
  const policyRetainedFindings = [];
6118
- for (const [index, reason] of [...policyRetainedMap].sort((a, b) => a[0] - b[0])) {
6119
- policyRetainedFindings.push({ finding: findings[index], reason });
6783
+ for (const [index, reason2] of [...policyRetainedMap].sort((a, b) => a[0] - b[0])) {
6784
+ policyRetainedFindings.push({ finding: findings[index], reason: reason2 });
6785
+ }
6786
+ const cappedCount = overflow.length;
6787
+ const eligible = totalBefore - cappedCount;
6788
+ let reason = null;
6789
+ let status = "reviewed";
6790
+ let modelStatus = null;
6791
+ if (authFailed) {
6792
+ status = "failed";
6793
+ reason = "auth_failed";
6794
+ } else if (reviewedCount === 0 && (timedOut || budgetExpired && tasks.length > 0)) {
6795
+ status = "failed";
6796
+ reason = "budget_timeout";
6797
+ } else if (reviewedCount === 0 && badOutput) {
6798
+ status = "failed";
6799
+ reason = "model_bad_output";
6800
+ } else if (reviewedCount === 0 && firstErrorStatus != null) {
6801
+ status = "failed";
6802
+ reason = "model_error";
6803
+ modelStatus = firstErrorStatus;
6804
+ } else if (reviewedCount === 0 && firstError) {
6805
+ status = "failed";
6806
+ reason = "exception";
6807
+ } else if (reviewedCount === eligible && cappedCount > 0 && missingContentCount === 0) {
6808
+ status = "partial";
6809
+ reason = "capped";
6810
+ } else if (reviewedCount === eligible && missingContentCount === 0 && !firstError && !timedOut) {
6811
+ status = "reviewed";
6812
+ reason = null;
6813
+ } else if (timedOut) {
6814
+ status = reviewedCount === 0 ? "failed" : "partial";
6815
+ reason = "budget_timeout";
6816
+ } else if (missingContentCount > 0 && !firstError && !badOutput) {
6817
+ status = reviewedCount === 0 ? "partial" : "partial";
6818
+ reason = "missing_content";
6819
+ } else if (badOutput) {
6820
+ status = reviewedCount === 0 ? "failed" : "partial";
6821
+ reason = "model_bad_output";
6822
+ } else if (firstErrorStatus != null) {
6823
+ status = "partial";
6824
+ reason = "model_error";
6825
+ modelStatus = firstErrorStatus;
6826
+ } else if (firstError || reviewedCount < eligible) {
6827
+ status = reviewedCount === 0 ? "failed" : "partial";
6828
+ reason = "exception";
6120
6829
  }
6121
6830
  return {
6122
6831
  findings: filtered,
@@ -6128,10 +6837,20 @@ async function filterFalsePositives(findings, fileContents, budgetMs = AI_FILTER
6128
6837
  totalBefore,
6129
6838
  reviewedCount,
6130
6839
  unreviewedCount,
6131
- cappedCount: overflow.length,
6840
+ cappedCount,
6132
6841
  missingContentCount,
6133
6842
  timedOut,
6134
- maskStats
6843
+ maskStats,
6844
+ aiDegraded: toAiDegraded({
6845
+ status,
6846
+ reason,
6847
+ surface,
6848
+ total: totalBefore,
6849
+ reviewed: reviewedCount,
6850
+ unreviewed: totalBefore - reviewedCount - cappedCount,
6851
+ capped: cappedCount,
6852
+ modelStatus
6853
+ })
6135
6854
  };
6136
6855
  }
6137
6856
 
@@ -8244,10 +8963,10 @@ var READ_VERB = /\b(?:select|from|find\w*|query|scan|rows|fetchAll|getAll|list)\
8244
8963
  function repoReselects(files, originPath, originIndex, table, value) {
8245
8964
  const tableToken = table.replace(/["'`]/g, "");
8246
8965
  if (tableToken.length < 3) return false;
8247
- const valueToken = normValue(value);
8248
- if (!valueToken || valueToken.length < 2) return false;
8966
+ const valueToken2 = normValue(value);
8967
+ if (!valueToken2 || valueToken2.length < 2) return false;
8249
8968
  const tableRe = new RegExp(`\\b${escapeRe(tableToken)}s?\\b`, "gi");
8250
- const valueRe = new RegExp(`\\b${escapeRe(valueToken)}\\b`, "i");
8969
+ const valueRe = new RegExp(`\\b${escapeRe(valueToken2)}\\b`, "i");
8251
8970
  for (const f of files) {
8252
8971
  if (f.excluded) continue;
8253
8972
  for (const m of f.code.matchAll(tableRe)) {
@@ -10774,6 +11493,10 @@ function scanQuality(input, rules = qualityRules) {
10774
11493
  }
10775
11494
  // Annotate the CommonJS export names for ESM import in node:
10776
11495
  0 && (module.exports = {
11496
+ AI_REASONS,
11497
+ AI_STATUSES,
11498
+ AI_SURFACES,
11499
+ BILLING_WEBHOOK_UNMATCHED_KEYS,
10777
11500
  CHECKABLE_CLAIMS,
10778
11501
  DOTENV_ASSIGN_RE,
10779
11502
  FREE_RULE_COUNT,
@@ -10785,17 +11508,26 @@ function scanQuality(input, rules = qualityRules) {
10785
11508
  MODEL_TEMPERATURE,
10786
11509
  MODEL_TRIAGE,
10787
11510
  NON_APP_PATH_PATTERNS,
11511
+ PLAN_CAUSES,
11512
+ PLAN_UNVERIFIED_NOTICE,
10788
11513
  PRO_RULE_COUNT,
10789
11514
  PUBLIC_ENV_PREFIX_RE,
10790
11515
  QUALITY_EXAMPLES,
10791
11516
  RULE_IMPACTS,
10792
11517
  SCANNER_VERSION,
11518
+ SCAN_AI_DEGRADED_KEYS,
11519
+ SCAN_TOKEN_NULL_KEYS,
10793
11520
  SERVER_ACTION_WRITE_RE,
10794
11521
  TEST_FILE_PATTERN,
10795
11522
  TOTAL_RULE_COUNT,
11523
+ WEBHOOK_EVENT_TYPES,
11524
+ WEBHOOK_REASONS,
11525
+ aiStatusLine,
10796
11526
  allRules,
10797
11527
  assessHeaders,
10798
11528
  astMatch,
11529
+ billingWebhookUnmatchedProps,
11530
+ bucketFiles,
10799
11531
  buildProjectContext,
10800
11532
  buildQualityContext,
10801
11533
  buildReviewPrompt,
@@ -10880,23 +11612,30 @@ function scanQuality(input, rules = qualityRules) {
10880
11612
  parseFile,
10881
11613
  parseScanTarget,
10882
11614
  parseSupabaseConfig,
11615
+ perCallTimeoutMs,
11616
+ planCause,
10883
11617
  qualityRules,
10884
11618
  replaceBlockComments,
10885
11619
  routeForFile,
10886
11620
  runCustomRules,
11621
+ scanAiDegradedProps,
10887
11622
  scanConfigs,
10888
11623
  scanDependencies,
10889
11624
  scanEntropy,
10890
11625
  scanMultiFile,
10891
11626
  scanQuality,
11627
+ scanTokenNullProps,
10892
11628
  sqlInjection,
10893
11629
  stripeWebhookUnprotected,
10894
11630
  supabaseFunctionName,
10895
11631
  supabaseNoRLS,
11632
+ toAiDegraded,
10896
11633
  todoLeftInCode,
10897
11634
  tryParse,
11635
+ unknownAiStatus,
10898
11636
  unmeasuredQualityRules,
10899
11637
  unvalidatedRedirect,
11638
+ vc001TestFixtureSeverity,
10900
11639
  vendoredReason,
10901
11640
  visitBinary,
10902
11641
  visitCalls,