xploitscan-shared-rules 1.27.5 → 1.28.1

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
@@ -41,6 +41,7 @@ __export(index_exports, {
41
41
  NON_APP_PATH_PATTERNS: () => NON_APP_PATH_PATTERNS,
42
42
  PRO_RULE_COUNT: () => PRO_RULE_COUNT,
43
43
  RULE_IMPACTS: () => RULE_IMPACTS,
44
+ TEST_FILE_PATTERN: () => TEST_FILE_PATTERN,
44
45
  TOTAL_RULE_COUNT: () => TOTAL_RULE_COUNT,
45
46
  accountStateFromWebStorage: () => accountStateFromWebStorage,
46
47
  allCustomRules: () => allCustomRules,
@@ -196,6 +197,7 @@ __export(index_exports, {
196
197
  llmSystemPromptInjection: () => llmSystemPromptInjection,
197
198
  logInjection: () => logInjection,
198
199
  magicNumbers: () => magicNumbers,
200
+ maskComments: () => maskComments,
199
201
  massAssignment: () => massAssignment,
200
202
  middlewareMatcherExcludesApi: () => middlewareMatcherExcludesApi,
201
203
  missingAIRateLimit: () => missingAIRateLimit,
@@ -241,6 +243,7 @@ __export(index_exports, {
241
243
  pyParamikoAutoAdd: () => pyParamikoAutoAdd,
242
244
  pyRequestsVerifyFalse: () => pyRequestsVerifyFalse,
243
245
  pyTempfileMktemp: () => pyTempfileMktemp,
246
+ qualityRules: () => qualityRules,
244
247
  raceCondition: () => raceCondition,
245
248
  rdsPubliclyAccessible: () => rdsPubliclyAccessible,
246
249
  reflectedCORSOrigin: () => reflectedCORSOrigin,
@@ -249,6 +252,7 @@ __export(index_exports, {
249
252
  runCustomRules: () => runCustomRules,
250
253
  s3BucketNoEncryption: () => s3BucketNoEncryption,
251
254
  scanEntropy: () => scanEntropy,
255
+ scanQuality: () => scanQuality,
252
256
  secretInBundleConfig: () => secretInBundleConfig,
253
257
  secretInCLIArgument: () => secretInCLIArgument,
254
258
  secretInErrorResponse: () => secretInErrorResponse,
@@ -10343,6 +10347,2304 @@ function extractScriptUrls(html, pageUrl, limit = 12) {
10343
10347
  }
10344
10348
  return [...new Set(out)];
10345
10349
  }
10350
+
10351
+ // src/quality/context.ts
10352
+ function isExcludedPath(path) {
10353
+ if (TEST_FILE_PATTERN.test(path)) return true;
10354
+ if (/(?:^|\/)[\w.-]*(?:fixtures?|mocks?|examples?|samples?)\//i.test(path)) return true;
10355
+ if (isVendoredPath(path)) return true;
10356
+ if (/(?:^|\/)(?:\.next|dist|build|out|coverage|node_modules)\//.test(path)) return true;
10357
+ if (/\.(?:md|mdx|snap|lock|json|yml|yaml|txt)$/i.test(path)) return true;
10358
+ if (/(?:^|\/)(?:migrations?|seeds?|scripts?)\//i.test(path)) return true;
10359
+ return false;
10360
+ }
10361
+ function looksClient(code) {
10362
+ if (/^\s*["']use client["']/m.test(code)) return true;
10363
+ return /\b(?:useState|useEffect|useTransition|useReducer)\s*\(/.test(code);
10364
+ }
10365
+ function looksServer(path, code) {
10366
+ if (/(?:^|\/)route\.(?:ts|js)$/.test(path)) return true;
10367
+ if (/(?:^|\/)middleware\.(?:ts|js)$/.test(path)) return true;
10368
+ if (/(?:^|\/)(?:api|server|functions|edge-functions)\//.test(path)) return true;
10369
+ if (/^\s*["']use server["']/m.test(code)) return true;
10370
+ if (/\bDeno\s*\.\s*serve\s*\(/.test(code)) return true;
10371
+ if (/\bserve\s*\(\s*(?:async\s*)?\(/.test(code) && /deno\.land|@std\/http/i.test(code)) return true;
10372
+ if (/\bexport\s+(?:async\s+)?function\s+(?:GET|POST|PUT|PATCH|DELETE|HEAD)\s*\(/.test(code)) return true;
10373
+ return false;
10374
+ }
10375
+ function buildQualityContext(files) {
10376
+ const built = files.map((f) => {
10377
+ const code = maskComments(f.content);
10378
+ return {
10379
+ path: f.path,
10380
+ content: f.content,
10381
+ code,
10382
+ // Parsing is cached by (path, content-hash) in parse.ts, so this is the
10383
+ // only place the cost is paid even with eight rules running.
10384
+ parsed: parseFile(f.content, f.path),
10385
+ excluded: isExcludedPath(f.path),
10386
+ isClient: looksClient(code),
10387
+ isServer: looksServer(f.path, code)
10388
+ };
10389
+ });
10390
+ return { files: built, byPath: new Map(built.map((f) => [f.path, f])) };
10391
+ }
10392
+ function lineAt(content, index) {
10393
+ let line = 1;
10394
+ for (let i = 0; i < index && i < content.length; i++) {
10395
+ if (content[i] === "\n") line++;
10396
+ }
10397
+ return line;
10398
+ }
10399
+
10400
+ // src/quality/rules/silent-failed-read.ts
10401
+ var EMPTY_LITERAL = /^(?:\[\s*\]|null|undefined|\{\s*\}|0|""|''|``|false)$/;
10402
+ function splitTopLevel(body) {
10403
+ const parts = [];
10404
+ let depth = 0;
10405
+ let current = "";
10406
+ for (const ch of body) {
10407
+ if (ch === "{" || ch === "[" || ch === "(") depth++;
10408
+ else if (ch === "}" || ch === "]" || ch === ")") depth--;
10409
+ if (ch === "," && depth === 0) {
10410
+ parts.push(current);
10411
+ current = "";
10412
+ continue;
10413
+ }
10414
+ current += ch;
10415
+ }
10416
+ if (current.trim()) parts.push(current);
10417
+ return parts;
10418
+ }
10419
+ function allValuesEmpty(payload) {
10420
+ const inner = payload.trim().replace(/^\{/, "").replace(/\}$/, "");
10421
+ const entries = splitTopLevel(inner).map((e) => e.trim()).filter(Boolean);
10422
+ if (entries.length === 0) return false;
10423
+ return entries.every((entry) => {
10424
+ const colon = entry.indexOf(":");
10425
+ if (colon === -1) return false;
10426
+ return EMPTY_LITERAL.test(entry.slice(colon + 1).trim());
10427
+ });
10428
+ }
10429
+ var HAS_MARKER = /\b(?:error|degraded|stale|partial|failed|unavailable)\b|ok\s*:\s*false/i;
10430
+ function catchBlocks(code) {
10431
+ const out = [];
10432
+ for (const m of code.matchAll(/\bcatch\b[^{]*\{/g)) {
10433
+ let depth = 1;
10434
+ let i = m.index + m[0].length;
10435
+ for (; i < code.length && depth > 0; i++) {
10436
+ if (code[i] === "{") depth++;
10437
+ else if (code[i] === "}") depth--;
10438
+ }
10439
+ out.push({ body: code.slice(m.index + m[0].length, i), index: m.index });
10440
+ }
10441
+ return out;
10442
+ }
10443
+ function inReadHandler(code, offset) {
10444
+ const heads = [
10445
+ /\bexport\s+(?:async\s+)?function\s+(?:GET|HEAD)\s*\([^)]*\)\s*\{/g,
10446
+ /\bexport\s+const\s+(?:GET|HEAD)\s*(?::[^=]+)?=\s*(?:async\s*)?\([^)]*\)\s*=>\s*\{/g,
10447
+ /\b(?:Deno\s*\.\s*)?serve\s*\(\s*(?:async\s*)?\([^)]*\)\s*=>\s*\{/g
10448
+ ];
10449
+ for (const re of heads) {
10450
+ for (const m of code.matchAll(re)) {
10451
+ const start = m.index + m[0].length;
10452
+ if (offset < start) continue;
10453
+ let depth = 1;
10454
+ let i = start;
10455
+ for (; i < code.length && depth > 0; i++) {
10456
+ if (code[i] === "{") depth++;
10457
+ else if (code[i] === "}") depth--;
10458
+ }
10459
+ if (offset < i) return true;
10460
+ }
10461
+ }
10462
+ return false;
10463
+ }
10464
+ function jsonResponses(block) {
10465
+ const out = [];
10466
+ const patterns = [
10467
+ /(?:NextResponse|Response)\s*\.\s*json\s*\(([\s\S]{0,400}?)\)\s*;/g,
10468
+ /new\s+Response\s*\(\s*JSON\s*\.\s*stringify\s*\(([\s\S]{0,400}?)\)/g
10469
+ ];
10470
+ for (const re of patterns) {
10471
+ for (const m of block.matchAll(re)) out.push(m[1]);
10472
+ }
10473
+ return out;
10474
+ }
10475
+ var silentFailedRead = {
10476
+ id: "QA001",
10477
+ title: "A failed read is served as an empty one",
10478
+ severity: "high",
10479
+ category: "Correctness",
10480
+ description: "This handler answers a read failure with a success status and an empty payload, so callers cannot tell a broken query from an account that genuinely has no data. Pages render their empty state, and anything that saves after loading can write that emptiness back.",
10481
+ fix: "Answer with a non-2xx status and an error, or include a marker the caller can check. Keep the empty payload only for a genuinely empty result.",
10482
+ precisionNotes: "GET/HEAD handlers only; unconditional catches only; every key in the payload must be empty; no error/degraded marker and no explicit error status. Each clause removes a class of correct code: nullable helpers, typed catches, best-effort enrichment, partial success.",
10483
+ check(ctx) {
10484
+ const hits = [];
10485
+ for (const file of ctx.files) {
10486
+ if (file.excluded || !file.isServer) continue;
10487
+ for (const { body, index } of catchBlocks(file.code)) {
10488
+ if (/\b(?:if|switch|instanceof)\b/.test(body)) continue;
10489
+ if (/\bthrow\b/.test(body)) continue;
10490
+ if (!inReadHandler(file.code, index)) continue;
10491
+ for (const payload of jsonResponses(body)) {
10492
+ if (!allValuesEmpty(payload)) continue;
10493
+ if (HAS_MARKER.test(payload)) continue;
10494
+ if (/\bstatus\s*:\s*[45]\d\d/.test(body)) continue;
10495
+ hits.push({ file: file.path, line: lineAt(file.content, index) });
10496
+ break;
10497
+ }
10498
+ }
10499
+ }
10500
+ return hits;
10501
+ }
10502
+ };
10503
+
10504
+ // src/quality/rules/silent-failed-write.ts
10505
+ var import_traverse4 = __toESM(require("@babel/traverse"), 1);
10506
+ var traverse3 = typeof import_traverse4.default === "function" ? import_traverse4.default : import_traverse4.default.default;
10507
+ var EXTRA_EXCLUDED_PATHS = [
10508
+ /(?:^|\/)generated\//i,
10509
+ /(?:^|\/)__generated__\//i,
10510
+ /\.gen\./i,
10511
+ /(?:^|\/)(?:e2e|playwright|cypress)\//i,
10512
+ /(?:^|\/)(?:mocks|__mocks__)\//i,
10513
+ /\bmsw\b/i,
10514
+ /\.stories\./i,
10515
+ /(?:^|\/)seed[^/]*$/i
10516
+ ];
10517
+ var NEVER_CLIENT_PATH = /(?:^|\/)(?:route|middleware|instrumentation)\.[jt]sx?$/;
10518
+ var BEACON_URL = /analytics|telemetry|track|metric|event|beacon|log|ping|presence|heartbeat|revalidate|impression|view/i;
10519
+ var TRANSPORT_NAME = /^(?:api|http|request|fetch|post|put|patch|del|delete|call|mutate)/i;
10520
+ var LIBRARY_CALLBACK_KEYS = /* @__PURE__ */ new Set(["mutationFn", "queryFn", "action"]);
10521
+ var ERROR_PATH_SIGNALS = [
10522
+ /\.catch\s*\(/,
10523
+ /\bthrow\b/,
10524
+ /\b\w*(?:assert|ensure|throwIf|unwrap|handleRes|checkRes|raiseFor)\w*\s*\(/i,
10525
+ /\btoast\s*\.\s*error\b/,
10526
+ /\balert\s*\(/,
10527
+ /\bset[A-Za-z0-9_]*(?:Error|Message|Status|Toast)\s*\(/,
10528
+ // A read of a parsed body property named error/message/detail — the handler
10529
+ // is pulling the server's complaint out, so it knows failures happen.
10530
+ // `console.error` is excluded by the lookbehind rather than by omission.
10531
+ /(?<!\bconsole)\.(?:error|message|detail)\b/,
10532
+ // The destructured spelling of the same read: `const { error } = await r.json()`.
10533
+ /\{[^}]*\b(?:error|message|detail)\b[^}]*\}\s*=/
10534
+ ];
10535
+ var SUCCESS_WORD = "saved|deleted|revoked|updated|sent|removed";
10536
+ var SUCCESS_ASSERTIONS = [
10537
+ /\btoast\s*\.\s*success\s*\(/,
10538
+ /\bset[A-Za-z0-9_]*(?:Saved|Success|Done)\s*\(/,
10539
+ // A success string written to state or handed to a notifier. Built from
10540
+ // SUCCESS_WORD so the vocabulary lives in exactly one place.
10541
+ new RegExp(
10542
+ `\\b(?:set[A-Z]\\w*|toast|showToast|notify|message\\s*\\.\\s*\\w+)\\s*\\(\\s*[^)]{0,60}?["'\`][^"'\`]{0,120}?(?:${SUCCESS_WORD})`,
10543
+ "i"
10544
+ ),
10545
+ // Navigating away IS the assertion — the user is moved on as though it worked.
10546
+ /\brouter\s*\.\s*(?:push|replace)\s*\(/,
10547
+ /\bwindow\s*\.\s*location\b/,
10548
+ // react-router's spelling of the same thing. The corpus this rule targets is
10549
+ // mostly Vite, where `router.push` does not exist and `navigate(` is it.
10550
+ /\bnavigate\s*\(\s*["'`/]/,
10551
+ // Optimistic local mutation: the row is gone from the UI whatever the server said.
10552
+ /\bset[A-Z]\w*\s*\(\s*\(?\s*\w+\s*\)?\s*=>\s*[\s\S]{0,140}?\.(?:filter|map|concat)\s*\(/
10553
+ ];
10554
+ var REVALIDATION = /\bmutate\s*\(|\brefetch\s*\(|\brouter\s*\.\s*refresh\s*\(|\binvalidateQueries\s*\(|\brevalidate/;
10555
+ var CONSEQUENCE = /revoke|delete|remove|disable|deactivate|rotate|sign-?out|logout|session|api-?key|token|secret|member|invite|permission|2fa|mfa|password|billing|cancel/i;
10556
+ var DESTRUCTIVE_CONFIRM = /delete|remove|revoke|permanent|irreversible|cannot be undone|can't be undone|are you sure/i;
10557
+ function nodeStart(node) {
10558
+ return node.start ?? 0;
10559
+ }
10560
+ function nodeEnd(node) {
10561
+ return node.end ?? 0;
10562
+ }
10563
+ function calleeName(callee) {
10564
+ if (callee.type === "Identifier") return callee.name;
10565
+ if ((callee.type === "MemberExpression" || callee.type === "OptionalMemberExpression") && callee.property.type === "Identifier") {
10566
+ return callee.property.name;
10567
+ }
10568
+ return null;
10569
+ }
10570
+ function isFetchCallee(callee) {
10571
+ if (callee.type === "Identifier") return callee.name === "fetch";
10572
+ if ((callee.type === "MemberExpression" || callee.type === "OptionalMemberExpression") && callee.property.type === "Identifier" && callee.property.name === "fetch" && callee.object.type === "Identifier") {
10573
+ return /^(?:window|globalThis|self)$/.test(callee.object.name);
10574
+ }
10575
+ return false;
10576
+ }
10577
+ function functionName(path) {
10578
+ const n = path.node;
10579
+ if (n.type === "FunctionDeclaration" && n.id) return n.id.name;
10580
+ if ((n.type === "ObjectMethod" || n.type === "ClassMethod") && n.key.type === "Identifier") {
10581
+ return n.key.name;
10582
+ }
10583
+ const parent = path.parentPath;
10584
+ if (!parent) return null;
10585
+ if (parent.isVariableDeclarator() && parent.node.id.type === "Identifier") {
10586
+ return parent.node.id.name;
10587
+ }
10588
+ if (parent.isObjectProperty() && parent.node.key.type === "Identifier") {
10589
+ return parent.node.key.name;
10590
+ }
10591
+ if (parent.isClassProperty() && parent.node.key.type === "Identifier") {
10592
+ return parent.node.key.name;
10593
+ }
10594
+ if (parent.isAssignmentExpression()) {
10595
+ const left = parent.node.left;
10596
+ if (left.type === "Identifier") return left.name;
10597
+ if (left.type === "MemberExpression" && left.property.type === "Identifier") {
10598
+ return left.property.name;
10599
+ }
10600
+ }
10601
+ if (parent.isCallExpression() && parent.parentPath?.isVariableDeclarator()) {
10602
+ const id = parent.parentPath.node.id;
10603
+ if (id.type === "Identifier") return id.name;
10604
+ }
10605
+ return null;
10606
+ }
10607
+ var HANDLER_ATTRIBUTE = /^on(?:Click|Submit|Change)$/;
10608
+ function isJsxHandlerValue(path) {
10609
+ let p = path.parentPath;
10610
+ if (p?.isCallExpression()) p = p.parentPath;
10611
+ if (!p?.isJSXExpressionContainer()) return false;
10612
+ const attr = p.parentPath;
10613
+ if (!attr?.isJSXAttribute()) return false;
10614
+ const name = attr.node.name;
10615
+ return name.type === "JSXIdentifier" && /^on(?:Click|Submit|Change)$/.test(name.name);
10616
+ }
10617
+ function inAmbientContext(path) {
10618
+ let p = path.parentPath;
10619
+ while (p) {
10620
+ if (p.isCallExpression()) {
10621
+ const name = calleeName(p.node.callee);
10622
+ if (name === "useEffect" || name === "useLayoutEffect" || name === "setInterval") return true;
10623
+ if (name === "addEventListener") {
10624
+ const first = p.node.arguments[0];
10625
+ if (first && first.type === "StringLiteral" && /^(?:pagehide|beforeunload|visibilitychange|unload)$/.test(first.value)) {
10626
+ return true;
10627
+ }
10628
+ }
10629
+ }
10630
+ p = p.parentPath;
10631
+ }
10632
+ return false;
10633
+ }
10634
+ function collectFunctions(file) {
10635
+ const parsed = file.parsed;
10636
+ const all = [];
10637
+ const byNode = /* @__PURE__ */ new Map();
10638
+ if (!parsed) return { reachable: /* @__PURE__ */ new Map() };
10639
+ const handlerRefNames = /* @__PURE__ */ new Set();
10640
+ traverse3(parsed.ast, {
10641
+ JSXAttribute(path) {
10642
+ const name = path.node.name;
10643
+ if (name.type !== "JSXIdentifier" || !HANDLER_ATTRIBUTE.test(name.name)) return;
10644
+ const value = path.node.value;
10645
+ if (!value || value.type !== "JSXExpressionContainer") return;
10646
+ const expr = value.expression;
10647
+ if (expr.type === "Identifier") handlerRefNames.add(expr.name);
10648
+ }
10649
+ });
10650
+ traverse3(parsed.ast, {
10651
+ Function(path) {
10652
+ const info = {
10653
+ path,
10654
+ start: nodeStart(path.node),
10655
+ end: nodeEnd(path.node),
10656
+ name: functionName(path),
10657
+ exported: !!path.findParent(
10658
+ (p) => p.isExportNamedDeclaration() || p.isExportDefaultDeclaration()
10659
+ ),
10660
+ jsxHandler: isJsxHandlerValue(path),
10661
+ callees: /* @__PURE__ */ new Set()
10662
+ };
10663
+ all.push(info);
10664
+ byNode.set(path.node, info);
10665
+ }
10666
+ });
10667
+ traverse3(parsed.ast, {
10668
+ CallExpression(path) {
10669
+ const name = calleeName(path.node.callee);
10670
+ if (!name) return;
10671
+ let fn = path.getFunctionParent();
10672
+ while (fn) {
10673
+ byNode.get(fn.node)?.callees.add(name);
10674
+ fn = fn.getFunctionParent();
10675
+ }
10676
+ }
10677
+ });
10678
+ const byName = /* @__PURE__ */ new Map();
10679
+ for (const info of all) {
10680
+ if (!info.name) continue;
10681
+ const list = byName.get(info.name);
10682
+ if (list) list.push(info);
10683
+ else byName.set(info.name, [info]);
10684
+ }
10685
+ const seeds = all.filter((info) => {
10686
+ const name = info.name;
10687
+ return info.jsxHandler || name !== null && (/^(?:handle|on)[A-Z]/.test(name) || handlerRefNames.has(name));
10688
+ });
10689
+ const reachable = /* @__PURE__ */ new Map();
10690
+ for (const seed of seeds) {
10691
+ const seen = /* @__PURE__ */ new Set([seed]);
10692
+ const queue = [seed];
10693
+ while (queue.length > 0) {
10694
+ const current = queue.pop();
10695
+ for (const callee of current.callees) {
10696
+ for (const target of byName.get(callee) ?? []) {
10697
+ if (seen.has(target)) continue;
10698
+ seen.add(target);
10699
+ queue.push(target);
10700
+ }
10701
+ }
10702
+ }
10703
+ for (const fn of seen) {
10704
+ const names = reachable.get(fn) ?? /* @__PURE__ */ new Set();
10705
+ if (seed.name) names.add(seed.name);
10706
+ reachable.set(fn, names);
10707
+ }
10708
+ }
10709
+ return { reachable };
10710
+ }
10711
+ function responseBinding(fetchPath) {
10712
+ let p = fetchPath.parentPath;
10713
+ if (p?.isAwaitExpression()) p = p.parentPath;
10714
+ if (p?.isVariableDeclarator()) {
10715
+ const id = p.node.id;
10716
+ if (id.type === "Identifier") return { ident: id.name, destructuredOk: [] };
10717
+ if (id.type === "ObjectPattern") {
10718
+ const names = [];
10719
+ for (const prop of id.properties) {
10720
+ if (prop.type === "ObjectProperty" && prop.key.type === "Identifier" && /^(?:ok|status|statusText)$/.test(prop.key.name)) {
10721
+ names.push(prop.value.type === "Identifier" ? prop.value.name : prop.key.name);
10722
+ }
10723
+ }
10724
+ return { ident: null, destructuredOk: names };
10725
+ }
10726
+ }
10727
+ if (p && (p.isMemberExpression() || p.isOptionalMemberExpression()) && calleeName(p.node) === "then") {
10728
+ const call = p.parentPath;
10729
+ if (call?.isCallExpression()) {
10730
+ const cb = call.node.arguments[0];
10731
+ if (cb && (cb.type === "ArrowFunctionExpression" || cb.type === "FunctionExpression")) {
10732
+ const param = cb.params[0];
10733
+ if (param && param.type === "Identifier") {
10734
+ return { ident: param.name, destructuredOk: [] };
10735
+ }
10736
+ }
10737
+ }
10738
+ }
10739
+ return { ident: null, destructuredOk: [] };
10740
+ }
10741
+ function testIsNegative(test) {
10742
+ if (test.type === "UnaryExpression" && test.operator === "!") return true;
10743
+ if (test.type === "BinaryExpression") {
10744
+ if (test.operator === "!==" || test.operator === "!=") return true;
10745
+ if (test.operator === ">=" || test.operator === ">") return true;
10746
+ if (test.operator === "===" || test.operator === "==") {
10747
+ if (test.right.type === "BooleanLiteral" && test.right.value === false) return true;
10748
+ if (test.left.type === "BooleanLiteral" && test.left.value === false) return true;
10749
+ }
10750
+ }
10751
+ if (test.type === "LogicalExpression") {
10752
+ return testIsNegative(test.left) || testIsNegative(test.right);
10753
+ }
10754
+ return false;
10755
+ }
10756
+ function isEmptyElseOkCheck(ref) {
10757
+ const ifPath = ref.findParent((p) => p.isIfStatement());
10758
+ if (!ifPath) return false;
10759
+ const stmt = ifPath.node;
10760
+ const refStart = nodeStart(ref.node);
10761
+ if (refStart < nodeStart(stmt.test) || refStart >= nodeEnd(stmt.test)) return false;
10762
+ if (stmt.alternate) return false;
10763
+ if (!testIsNegative(stmt.test)) return true;
10764
+ const consequent = stmt.consequent;
10765
+ if (consequent.type === "ReturnStatement") return !consequent.argument;
10766
+ if (consequent.type === "BlockStatement") {
10767
+ return consequent.body.length === 1 && consequent.body[0].type === "ReturnStatement" && !consequent.body[0].argument;
10768
+ }
10769
+ return false;
10770
+ }
10771
+ function statusReferencesAreEmptyElse(unit, binding) {
10772
+ const refs = [];
10773
+ const { ident, destructuredOk } = binding;
10774
+ unit.path.traverse({
10775
+ MemberExpression(p) {
10776
+ if (!ident) return;
10777
+ const { object, property } = p.node;
10778
+ if (object.type !== "Identifier" || object.name !== ident) return;
10779
+ if (property.type !== "Identifier") return;
10780
+ if (!/^(?:ok|status|statusText)$/.test(property.name)) return;
10781
+ refs.push(p);
10782
+ },
10783
+ OptionalMemberExpression(p) {
10784
+ if (!ident) return;
10785
+ const { object, property } = p.node;
10786
+ if (object.type !== "Identifier" || object.name !== ident) return;
10787
+ if (property.type !== "Identifier") return;
10788
+ if (!/^(?:ok|status|statusText)$/.test(property.name)) return;
10789
+ refs.push(p);
10790
+ },
10791
+ Identifier(p) {
10792
+ if (destructuredOk.length === 0) return;
10793
+ if (!destructuredOk.includes(p.node.name)) return;
10794
+ if (!p.isReferencedIdentifier()) return;
10795
+ refs.push(p);
10796
+ }
10797
+ });
10798
+ if (refs.length === 0) return null;
10799
+ return refs.every((ref) => isEmptyElseOkCheck(ref));
10800
+ }
10801
+ function inLibraryCallback(fetchPath) {
10802
+ let p = fetchPath.parentPath;
10803
+ while (p) {
10804
+ if (p.isObjectProperty()) {
10805
+ const key = p.node.key;
10806
+ if (key.type === "Identifier" && LIBRARY_CALLBACK_KEYS.has(key.name)) return true;
10807
+ if (key.type === "StringLiteral" && LIBRARY_CALLBACK_KEYS.has(key.value)) return true;
10808
+ }
10809
+ if (p.isCallExpression()) {
10810
+ const name = calleeName(p.node.callee);
10811
+ if (name === "useSWRMutation" || name === "useMutation") return true;
10812
+ }
10813
+ p = p.parentPath;
10814
+ }
10815
+ return false;
10816
+ }
10817
+ function returnsTheResponse(fetchPath, unit, unitSource, responseIdent) {
10818
+ let p = fetchPath.parentPath;
10819
+ while (p && nodeStart(p.node) >= unit.start) {
10820
+ if (p.isReturnStatement()) return true;
10821
+ if (p.isArrowFunctionExpression() && p.node.body.type !== "BlockStatement") return true;
10822
+ if (p.isFunction()) break;
10823
+ p = p.parentPath;
10824
+ }
10825
+ if (responseIdent) {
10826
+ const re = new RegExp(`\\breturn\\s+(?:await\\s+)?${responseIdent}\\b`);
10827
+ if (re.test(unitSource)) return true;
10828
+ }
10829
+ return false;
10830
+ }
10831
+ var silentFailedWrite = {
10832
+ id: "QA002",
10833
+ title: "A user action reports success it did not get",
10834
+ severity: "high",
10835
+ category: "Correctness",
10836
+ description: "This handler fires a destructive write, never looks at whether it succeeded, and then tells the user it worked \u2014 a success toast, an optimistic row removal, or a redirect. When the server rejects the request the user is left believing a key was revoked, a member removed or a session ended when none of it happened.",
10837
+ fix: "Check the response before you assert anything: `if (!res.ok) { toast.error(...); return; }`. Only then show the success state, remove the row, or navigate away.",
10838
+ precisionNotes: "Client files only, never route handlers or server actions. The fetch must be lexically inside a function reachable from an onClick/onSubmit/onChange handler (never module scope, useEffect, setInterval or a pagehide beacon), must not be a telemetry URL or carry keepalive, and must not sit in a transport wrapper or a react-query/SWR mutationFn where the caller owns the error path. The enclosing function must contain NO error path at all \u2014 no try/catch, .catch, throw, assert helper, toast.error/alert/setError, or read of body.error \u2014 except the empty-else shape (`if (!res.ok) return;` / `if (res.ok) {...}` with no alternate), which is the shipped defect. A success assertion must follow the fetch, no revalidation may follow it, and the URL, handler name or a destructive confirm() must carry real consequence (revoke/delete/api-key/session/billing); low-stakes writes are dropped rather than reported at a severity they do not deserve.",
10839
+ check(ctx) {
10840
+ const hits = [];
10841
+ for (const file of ctx.files) {
10842
+ if (file.excluded) continue;
10843
+ if (EXTRA_EXCLUDED_PATHS.some((re) => re.test(file.path))) continue;
10844
+ if (!file.isClient) continue;
10845
+ if (file.isServer) continue;
10846
+ if (NEVER_CLIENT_PATH.test(file.path)) continue;
10847
+ if (/^\s*["']use server["']/m.test(file.code)) continue;
10848
+ const parsed = file.parsed;
10849
+ if (!parsed) continue;
10850
+ const { reachable } = collectFunctions(file);
10851
+ if (reachable.size === 0) continue;
10852
+ const reachableByNode = /* @__PURE__ */ new Map();
10853
+ for (const info of reachable.keys()) reachableByNode.set(info.path.node, info);
10854
+ const reportedUnits = /* @__PURE__ */ new Set();
10855
+ traverse3(parsed.ast, {
10856
+ CallExpression(path) {
10857
+ if (!isFetchCallee(path.node.callee)) return;
10858
+ if (inAmbientContext(path)) return;
10859
+ const chain = [];
10860
+ for (let fn = path.getFunctionParent(); fn !== null; fn = fn.getFunctionParent()) {
10861
+ const info = reachableByNode.get(fn.node);
10862
+ if (info) chain.push(info);
10863
+ }
10864
+ if (chain.length === 0) return;
10865
+ const unit = chain[chain.length - 1];
10866
+ if (reportedUnits.has(unit.start)) return;
10867
+ const call = path.node;
10868
+ const callSource = file.code.slice(nodeStart(call), nodeEnd(call));
10869
+ if (/\bkeepalive\s*:\s*true/.test(callSource)) return;
10870
+ const urlArg = call.arguments[0];
10871
+ if (urlArg && (urlArg.type === "StringLiteral" || urlArg.type === "TemplateLiteral")) {
10872
+ const urlSource = file.code.slice(nodeStart(urlArg), nodeEnd(urlArg));
10873
+ if (BEACON_URL.test(urlSource)) return;
10874
+ }
10875
+ if (inLibraryCallback(path)) return;
10876
+ const unitSource = file.code.slice(unit.start, unit.end);
10877
+ const binding = responseBinding(path);
10878
+ if (returnsTheResponse(path, unit, unitSource, binding.ident)) return;
10879
+ for (const candidate of chain) {
10880
+ if (candidate.exported && candidate.name && TRANSPORT_NAME.test(candidate.name)) return;
10881
+ }
10882
+ if (path.findParent((p) => p.isTryStatement() && nodeStart(p.node) >= unit.start)) return;
10883
+ if (ERROR_PATH_SIGNALS.some((re) => re.test(unitSource))) return;
10884
+ const okShape = statusReferencesAreEmptyElse(unit, binding);
10885
+ if (okShape === false) return;
10886
+ const after = file.code.slice(nodeEnd(call), unit.end);
10887
+ if (!SUCCESS_ASSERTIONS.some((re) => re.test(after))) return;
10888
+ if (REVALIDATION.test(after)) return;
10889
+ const before = file.code.slice(unit.start, nodeStart(call));
10890
+ let destructiveConfirm = false;
10891
+ for (const m of before.matchAll(/\bconfirm\s*\(/g)) {
10892
+ if (DESTRUCTIVE_CONFIRM.test(before.slice(m.index, m.index + 200))) {
10893
+ destructiveConfirm = true;
10894
+ break;
10895
+ }
10896
+ }
10897
+ const handlerNames = [...reachable.get(unit) ?? /* @__PURE__ */ new Set()].join(" ");
10898
+ const consequenceText = `${callSource} ${unit.name ?? ""} ${handlerNames}`;
10899
+ if (!destructiveConfirm && !CONSEQUENCE.test(consequenceText)) return;
10900
+ reportedUnits.add(unit.start);
10901
+ hits.push({
10902
+ file: file.path,
10903
+ line: lineAt(file.content, nodeStart(call)),
10904
+ detail: okShape === true ? `${unit.name ? `\`${unit.name}\` ` : "This handler "}checks the response status and then does nothing with the failure \u2014 it falls through to the same success message, optimistic update or redirect it would show on a 200. The user is told a destructive change landed when it may not have.` : void 0
10905
+ });
10906
+ }
10907
+ });
10908
+ }
10909
+ return hits;
10910
+ }
10911
+ };
10912
+
10913
+ // src/quality/rules/state-before-effect.ts
10914
+ var BILLING_MEMBER_CALLS = /* @__PURE__ */ new Set([
10915
+ // Stripe
10916
+ "customers.createbalancetransaction",
10917
+ "refunds.create",
10918
+ "transfers.create",
10919
+ "payouts.create",
10920
+ "invoices.create",
10921
+ "invoiceitems.create",
10922
+ "subscriptions.update",
10923
+ "creditgrants.create",
10924
+ "paymentintents.capture",
10925
+ // Chargebee (singular resource names)
10926
+ "refund.create",
10927
+ "payout.create",
10928
+ "invoice.create",
10929
+ "invoice.refund",
10930
+ "subscription.update",
10931
+ "subscription.updateforitems",
10932
+ "transaction.refund",
10933
+ "transactions.refund",
10934
+ "promotionalcredit.add",
10935
+ "promotionalcredit.set",
10936
+ "creditnote.create",
10937
+ "creditnotes.create",
10938
+ // Paddle — adjustments are its refund/credit primitive
10939
+ "adjustments.create",
10940
+ "adjustment.create",
10941
+ "paymentintent.capture"
10942
+ ]);
10943
+ var BILLING_BARE_CALLS = /* @__PURE__ */ new Set([
10944
+ "createbalancetransaction",
10945
+ "createrefund",
10946
+ "issuerefund",
10947
+ "refundorder",
10948
+ "refundpayment",
10949
+ "createpayout",
10950
+ "sendpayout",
10951
+ "createtransfer",
10952
+ "updatesubscription",
10953
+ "createinvoiceitem",
10954
+ "capturepaymentintent",
10955
+ "creditgrant",
10956
+ "createcreditgrant",
10957
+ "grantcredits",
10958
+ "grantcredit",
10959
+ "addcredits",
10960
+ "awardcredits",
10961
+ "issuecredits",
10962
+ "issuecredit",
10963
+ "applycredit",
10964
+ "creditaccount",
10965
+ "credituser",
10966
+ "incrementcredits",
10967
+ "grantentitlement",
10968
+ "upgradeplan",
10969
+ "activatesubscription",
10970
+ "addbalance"
10971
+ ]);
10972
+ var ENTITLEMENT_COLUMN = /^(?:credit|credits|creditbalance|creditsremaining|remainingcredits|balance|quota|quotaremaining|token|tokens|seat|seats|plan|plantier|tier|premium|ispro|proplan|entitlement|allowance|subscriptionstatus|subscriptiontier|scansremaining|minutes|usageallowance)$/;
10973
+ var ENTITLEMENT_TABLE = /^(?:credit|creditledger|creditledgerentry|creditgrant|creditentry|wallet|balance|entitlement|quota|tokengrant|usercredit|accountcredit|subscription|plan)$/;
10974
+ var PENDING_VALUES = /* @__PURE__ */ new Set([
10975
+ "pending",
10976
+ "unprocessed",
10977
+ "queued",
10978
+ "awaiting",
10979
+ "unpaid",
10980
+ "unsent",
10981
+ "unclaimed",
10982
+ "uncredited",
10983
+ "notstarted",
10984
+ "false",
10985
+ "0",
10986
+ "null"
10987
+ ]);
10988
+ var WALK_SKIP_KEYS = /* @__PURE__ */ new Set([
10989
+ "loc",
10990
+ "leadingComments",
10991
+ "trailingComments",
10992
+ "innerComments",
10993
+ "comments",
10994
+ "tokens",
10995
+ "extra"
10996
+ ]);
10997
+ var FUNCTION_TYPES = /* @__PURE__ */ new Set([
10998
+ "FunctionDeclaration",
10999
+ "FunctionExpression",
11000
+ "ArrowFunctionExpression",
11001
+ "ObjectMethod",
11002
+ "ClassMethod",
11003
+ "ClassPrivateMethod"
11004
+ ]);
11005
+ function isNode(value) {
11006
+ return typeof value === "object" && value !== null && typeof value.type === "string";
11007
+ }
11008
+ function spanOf(node) {
11009
+ const n = node;
11010
+ return { start: n?.start ?? 0, end: n?.end ?? 0 };
11011
+ }
11012
+ function walkAst(value, visit) {
11013
+ if (Array.isArray(value)) {
11014
+ for (const item of value) walkAst(item, visit);
11015
+ return;
11016
+ }
11017
+ if (!isNode(value)) return;
11018
+ visit(value);
11019
+ for (const key of Object.keys(value)) {
11020
+ if (WALK_SKIP_KEYS.has(key)) continue;
11021
+ const child = value[key];
11022
+ if (child && typeof child === "object") walkAst(child, visit);
11023
+ }
11024
+ }
11025
+ function calleeChain(callee) {
11026
+ const parts = [];
11027
+ let cur = callee;
11028
+ for (let guard = 0; guard < 12 && cur; guard++) {
11029
+ if (!isNode(cur)) break;
11030
+ const node = cur;
11031
+ if (node.type === "Identifier") {
11032
+ parts.unshift(String(node.name ?? ""));
11033
+ break;
11034
+ }
11035
+ if (node.type === "ThisExpression") {
11036
+ parts.unshift("this");
11037
+ break;
11038
+ }
11039
+ if (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") {
11040
+ const prop = node.property;
11041
+ if (isNode(prop) && prop.type === "Identifier") {
11042
+ parts.unshift(String(prop.name ?? ""));
11043
+ } else if (isNode(prop) && prop.type === "StringLiteral") {
11044
+ parts.unshift(String(prop.value ?? ""));
11045
+ } else {
11046
+ parts.unshift("*");
11047
+ }
11048
+ cur = node.object;
11049
+ continue;
11050
+ }
11051
+ if (node.type === "CallExpression" || node.type === "OptionalCallExpression" || node.type === "TSNonNullExpression" || node.type === "AwaitExpression") {
11052
+ cur = node.callee ?? node.expression ?? node.argument;
11053
+ continue;
11054
+ }
11055
+ break;
11056
+ }
11057
+ return parts;
11058
+ }
11059
+ function flatten(text) {
11060
+ return text.toLowerCase().replace(/[^a-z0-9.]/g, "");
11061
+ }
11062
+ function shapeOf(file) {
11063
+ if (!file.parsed) return null;
11064
+ const shape = {
11065
+ functions: [],
11066
+ tryCatches: [],
11067
+ catchCalls: [],
11068
+ transactions: [],
11069
+ effects: []
11070
+ };
11071
+ walkAst(file.parsed.ast.program, (node) => {
11072
+ if (FUNCTION_TYPES.has(node.type)) {
11073
+ shape.functions.push(spanOf(node));
11074
+ return;
11075
+ }
11076
+ if (node.type === "TryStatement") {
11077
+ const handler = node.handler;
11078
+ const block = node.block;
11079
+ if (isNode(handler) && isNode(block)) {
11080
+ const body = handler.body;
11081
+ shape.tryCatches.push({ covered: spanOf(block), catchBody: spanOf(body ?? handler) });
11082
+ }
11083
+ return;
11084
+ }
11085
+ if (node.type !== "CallExpression" && node.type !== "OptionalCallExpression") return;
11086
+ const callee = node.callee;
11087
+ const args = node.arguments ?? [];
11088
+ const chain = calleeChain(callee);
11089
+ const last = flatten(chain[chain.length - 1] ?? "");
11090
+ const lastTwo = flatten(chain.slice(-2).join("."));
11091
+ if (last === "catch" && isNode(callee)) {
11092
+ const target = callee.object;
11093
+ const cb = args[0];
11094
+ if (isNode(target) && isNode(cb)) {
11095
+ shape.catchCalls.push({ covered: spanOf(target), catchBody: spanOf(cb) });
11096
+ }
11097
+ return;
11098
+ }
11099
+ if (last === "transaction" || last === "$transaction" || last === "transactionsql") {
11100
+ for (const arg of args) {
11101
+ if (isNode(arg) && FUNCTION_TYPES.has(arg.type)) shape.transactions.push(spanOf(arg));
11102
+ }
11103
+ return;
11104
+ }
11105
+ if (BILLING_MEMBER_CALLS.has(lastTwo) || BILLING_BARE_CALLS.has(last)) {
11106
+ shape.effects.push({ span: spanOf(node), label: chain.join(".") });
11107
+ }
11108
+ });
11109
+ return shape;
11110
+ }
11111
+ function handlerSpan(shape, offset, fallback) {
11112
+ let best = null;
11113
+ for (const fn of shape.functions) {
11114
+ if (offset < fn.start || offset >= fn.end) continue;
11115
+ if (!best || fn.start < best.start) best = fn;
11116
+ }
11117
+ return best ?? fallback;
11118
+ }
11119
+ function catchCovering(shape, offset) {
11120
+ let best = null;
11121
+ for (const entry of [...shape.tryCatches, ...shape.catchCalls]) {
11122
+ if (offset < entry.covered.start || offset >= entry.covered.end) continue;
11123
+ if (!best || entry.covered.start > best.covered.start) best = entry;
11124
+ }
11125
+ return best ? best.catchBody : null;
11126
+ }
11127
+ function insideTransaction(shape, offset) {
11128
+ return shape.transactions.some((t) => offset >= t.start && offset < t.end);
11129
+ }
11130
+ function normTable(raw) {
11131
+ const last = raw.trim().replace(/["'`]/g, "").split(".").pop() ?? "";
11132
+ const flat = last.toLowerCase().replace(/[^a-z0-9]/g, "");
11133
+ return flat.endsWith("s") ? flat.slice(0, -1) : flat;
11134
+ }
11135
+ function normColumn(raw) {
11136
+ const last = raw.trim().replace(/["'`]/g, "").split(".").pop() ?? "";
11137
+ return last.toLowerCase().replace(/[^a-z0-9]/g, "");
11138
+ }
11139
+ function normValue(raw) {
11140
+ return raw.trim().replace(/^["'`]|["'`]$/g, "").trim().toLowerCase();
11141
+ }
11142
+ function isPending(value) {
11143
+ return PENDING_VALUES.has(normValue(value).replace(/[^a-z0-9]/g, ""));
11144
+ }
11145
+ function balancedSlice(src, openIndex, open, close, cap = 900) {
11146
+ if (src[openIndex] !== open) return "";
11147
+ let depth = 0;
11148
+ const limit = Math.min(src.length, openIndex + cap);
11149
+ for (let i = openIndex; i < limit; i++) {
11150
+ const ch = src[i];
11151
+ if (ch === open) depth++;
11152
+ else if (ch === close) {
11153
+ depth--;
11154
+ if (depth === 0) return src.slice(openIndex + 1, i);
11155
+ }
11156
+ }
11157
+ return src.slice(openIndex + 1, limit);
11158
+ }
11159
+ function objectAfterKey(src, key) {
11160
+ const m = new RegExp(`\\b${key}\\s*:\\s*\\{`).exec(src);
11161
+ if (!m) return "";
11162
+ return balancedSlice(src, m.index + m[0].length - 1, "{", "}");
11163
+ }
11164
+ function splitTopLevel2(body) {
11165
+ const parts = [];
11166
+ let depth = 0;
11167
+ let current = "";
11168
+ for (const ch of body) {
11169
+ if (ch === "{" || ch === "[" || ch === "(") depth++;
11170
+ else if (ch === "}" || ch === "]" || ch === ")") depth--;
11171
+ if (ch === "," && depth === 0) {
11172
+ parts.push(current);
11173
+ current = "";
11174
+ continue;
11175
+ }
11176
+ current += ch;
11177
+ }
11178
+ if (current.trim()) parts.push(current);
11179
+ return parts;
11180
+ }
11181
+ function assignments(body, separator) {
11182
+ const out = [];
11183
+ for (const part of splitTopLevel2(body)) {
11184
+ const at = part.indexOf(separator);
11185
+ if (at === -1) continue;
11186
+ const column = part.slice(0, at).trim();
11187
+ const value = part.slice(at + 1).trim();
11188
+ if (!column || !/^["'`]?[\w.$]+["'`]?$/.test(column)) continue;
11189
+ out.push({ column, value });
11190
+ }
11191
+ return out;
11192
+ }
11193
+ function sqlPredicates(text) {
11194
+ const out = [];
11195
+ const re = /([\w."`]+)\s*(?:=\s*(?:(['"`])([\w-]+)\2|(\d+|true|false|null))|\s+is\s+(not\s+)?null)/gi;
11196
+ for (const m of text.matchAll(re)) {
11197
+ let value;
11198
+ if (m[3] !== void 0) value = m[3];
11199
+ else if (m[4] !== void 0) value = m[4];
11200
+ else value = m[5] ? "notnull" : "null";
11201
+ out.push({ column: m[1], value });
11202
+ }
11203
+ return out;
11204
+ }
11205
+ function builderPredicates(text) {
11206
+ const out = [];
11207
+ for (const m of text.matchAll(
11208
+ /\beq\(\s*(?:[\w$]+\.)?([\w$]+)\s*,\s*(?:(['"`])([\w-]+)\2|(false|true|0|null))\s*\)/g
11209
+ )) {
11210
+ out.push({ column: m[1], value: m[3] ?? m[4] ?? "" });
11211
+ }
11212
+ for (const m of text.matchAll(/\bisNull\(\s*(?:[\w$]+\.)?([\w$]+)\s*\)/g)) {
11213
+ out.push({ column: m[1], value: "null" });
11214
+ }
11215
+ for (const m of text.matchAll(
11216
+ /\.eq\(\s*(['"`])([\w.]+)\1\s*,\s*(?:(['"`])([\w-]+)\3|(false|true|0|null))\s*\)/g
11217
+ )) {
11218
+ out.push({ column: m[2], value: m[4] ?? m[5] ?? "" });
11219
+ }
11220
+ for (const m of text.matchAll(/\.is\(\s*(['"`])([\w.]+)\1\s*,\s*null\s*\)/gi)) {
11221
+ out.push({ column: m[2], value: "null" });
11222
+ }
11223
+ return out;
11224
+ }
11225
+ function objectPredicates(text) {
11226
+ const out = [];
11227
+ for (const { column, value } of assignments(text, ":")) {
11228
+ if (/^[[{]/.test(value)) continue;
11229
+ out.push({ column, value });
11230
+ }
11231
+ return out;
11232
+ }
11233
+ function collectPendingReads(src) {
11234
+ const out = [];
11235
+ const push = (table, index, preds) => {
11236
+ for (const p of preds) {
11237
+ if (!isPending(p.value)) continue;
11238
+ out.push({ table, column: p.column, value: p.value, index });
11239
+ }
11240
+ };
11241
+ for (const m of src.matchAll(/\bselect\b[\s\S]{0,400}?\bfrom\s+["'`]?([\w.]+)["'`]?/gi)) {
11242
+ const at = (m.index ?? 0) + m[0].length;
11243
+ push(m[1], m.index ?? 0, sqlPredicates(src.slice(at, at + 300)));
11244
+ }
11245
+ for (const m of src.matchAll(/\.from\(\s*(['"`]?)([\w$]+)\1\s*\)/g)) {
11246
+ const idx = m.index ?? 0;
11247
+ const before = src.slice(Math.max(0, idx - 160), idx);
11248
+ const after = src.slice(idx + m[0].length, idx + m[0].length + 400);
11249
+ const isRead = /\bselect\s*\(/i.test(before) || /^[\s\S]{0,120}?\.select\s*\(/.test(after);
11250
+ if (!isRead) continue;
11251
+ push(m[2], idx, builderPredicates(after));
11252
+ }
11253
+ for (const m of src.matchAll(
11254
+ /\.\s*([\w$]+)\s*\.\s*(?:findFirst|findUnique|findMany|findFirstOrThrow|findUniqueOrThrow)\s*\(/g
11255
+ )) {
11256
+ const idx = m.index ?? 0;
11257
+ const args = balancedSlice(src, idx + m[0].length - 1, "(", ")");
11258
+ const where = objectAfterKey(args, "where");
11259
+ push(m[1], idx, objectPredicates(where));
11260
+ push(m[1], idx, builderPredicates(args));
11261
+ }
11262
+ return out;
11263
+ }
11264
+ function collectWrites(src) {
11265
+ const out = [];
11266
+ const push = (table, index, end, kind, pairs) => {
11267
+ const trailing = src.slice(end, end + 300);
11268
+ for (const p of pairs) {
11269
+ out.push({ table, column: p.column, value: p.value, index, trailing, kind });
11270
+ }
11271
+ };
11272
+ for (const m of src.matchAll(/\bupdate\s+["'`]?([\w.]+)["'`]?\s+set\s+([\s\S]{0,300}?)(?=\bwhere\b|;|`|\)|$)/gi)) {
11273
+ const idx = m.index ?? 0;
11274
+ push(m[1], idx, idx + m[0].length, "update", assignments(m[2], "="));
11275
+ }
11276
+ for (const m of src.matchAll(/\binsert\s+into\s+["'`]?([\w.]+)["'`]?\s*\(([\s\S]{0,200}?)\)/gi)) {
11277
+ const idx = m.index ?? 0;
11278
+ const cols = m[2].split(",").map((c) => ({ column: c.trim(), value: "" }));
11279
+ push(m[1], idx, idx + m[0].length, "insert", cols);
11280
+ }
11281
+ for (const m of src.matchAll(/\.update\(\s*([\w$]+)\s*\)[\s\S]{0,80}?\.set\(\s*\{/g)) {
11282
+ const idx = m.index ?? 0;
11283
+ const open = idx + m[0].length - 1;
11284
+ const body = balancedSlice(src, open, "{", "}");
11285
+ push(m[1], idx, open + body.length + 2, "update", assignments(body, ":"));
11286
+ }
11287
+ for (const m of src.matchAll(/\.insert\(\s*([\w$]+)\s*\)[\s\S]{0,80}?\.values\(\s*\{/g)) {
11288
+ const idx = m.index ?? 0;
11289
+ const open = idx + m[0].length - 1;
11290
+ const body = balancedSlice(src, open, "{", "}");
11291
+ push(m[1], idx, open + body.length + 2, "insert", assignments(body, ":"));
11292
+ }
11293
+ for (const m of src.matchAll(/\.from\(\s*(['"`])([\w]+)\1\s*\)[\s\S]{0,80}?\.(update|insert|upsert)\(\s*\{/g)) {
11294
+ const idx = m.index ?? 0;
11295
+ const open = idx + m[0].length - 1;
11296
+ const body = balancedSlice(src, open, "{", "}");
11297
+ push(
11298
+ m[2],
11299
+ idx,
11300
+ open + body.length + 2,
11301
+ m[3] === "insert" ? "insert" : "update",
11302
+ assignments(body, ":")
11303
+ );
11304
+ }
11305
+ for (const m of src.matchAll(/\.\s*([\w$]+)\s*\.\s*(update|updateMany|upsert|create)\s*\(/g)) {
11306
+ const idx = m.index ?? 0;
11307
+ const args = balancedSlice(src, idx + m[0].length - 1, "(", ")");
11308
+ const data = objectAfterKey(args, "data") || objectAfterKey(args, "update");
11309
+ if (!data) continue;
11310
+ push(
11311
+ m[1],
11312
+ idx,
11313
+ idx + m[0].length + args.length,
11314
+ m[2] === "create" ? "insert" : "update",
11315
+ assignments(data, ":")
11316
+ );
11317
+ }
11318
+ return out;
11319
+ }
11320
+ var ENQUEUES = /\b(?:queue\s*\.\s*add|inngest\s*\.\s*send|qstash|boss\s*\.\s*send|after\s*\(|waitUntil\s*\(|\.\s*enqueue\s*\(|\.\s*publish\s*\(|\.\s*sendMessage\s*\(|outbox|dead[_-]?letter|deadLetter|retryQueue|scheduleRetry|schedule\s*\()/i;
11321
+ var NON_2XX = /\bstatus\s*:\s*[45]\d\d|\.\s*status\s*\(\s*[45]\d\d|\bsendStatus\s*\(\s*[45]\d\d|\bHTTPException\s*\(\s*[45]\d\d|new\s+Response\s*\([^)]{0,200}?\b[45]\d\d/;
11322
+ var STALENESS = /\b(?:lt|lte|gt|gte|older|stale|timeout|timedout|retry|retries|attempt|attempts|updated_?at|created_?at|processed_?at|last_?\w+|since|interval|current_?timestamp)\b|\bDate\.now\b|\bnow\s*\(|\bdate(?:time)?\s*\(|\bdate_?sub\s*\(|['"`]\s*now\s*['"`]/i;
11323
+ var READ_VERB = /\b(?:select|from|find\w*|query|scan|rows|fetchAll|getAll|list)\b/i;
11324
+ function repoReselects(files, originPath, originIndex, table, value) {
11325
+ const tableToken = table.replace(/["'`]/g, "");
11326
+ if (tableToken.length < 3) return false;
11327
+ const valueToken = normValue(value);
11328
+ if (!valueToken || valueToken.length < 2) return false;
11329
+ const tableRe = new RegExp(`\\b${escapeRe(tableToken)}s?\\b`, "gi");
11330
+ const valueRe = new RegExp(`\\b${escapeRe(valueToken)}\\b`, "i");
11331
+ for (const f of files) {
11332
+ if (f.excluded) continue;
11333
+ for (const m of f.code.matchAll(tableRe)) {
11334
+ const at = m.index ?? 0;
11335
+ if (f.path === originPath && at > originIndex - 200 && at < originIndex + 400) continue;
11336
+ const window = f.code.slice(Math.max(0, at - 200), at + 400);
11337
+ if (!READ_VERB.test(window)) continue;
11338
+ if (!valueRe.test(window)) continue;
11339
+ if (!STALENESS.test(window)) continue;
11340
+ return true;
11341
+ }
11342
+ }
11343
+ return false;
11344
+ }
11345
+ function escapeRe(s) {
11346
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
11347
+ }
11348
+ var stateBeforeEffect = {
11349
+ id: "QA003",
11350
+ title: "A record is written before the payment it stands for",
11351
+ severity: "high",
11352
+ category: "Correctness",
11353
+ description: "This handler moves a row out of its pending state and only then makes the payment or entitlement grant that the row stands for, with the failure swallowed. If the transfer fails the record still reads as settled, the money never moved, and nothing will look at that row again because it no longer matches the pending query.",
11354
+ fix: "Make the transfer first and record it after, or make the transfer replayable: pass an idempotency key, keep the row pending until the transfer confirms, or write an outbox row that a reconciler retries.",
11355
+ precisionNotes: "Four gates, all required. (1) The effect must be a billing/entitlement mutation \u2014 Stripe/Paddle/Chargebee/Lemon Squeezy money movement or a local credits/quota/plan grant. Email, push, webhooks, analytics, revalidation, audit logs, search and CRM sync, and bare fetch() are excluded on purpose and must not be added back. (2) The preceding write must CONSUME eligibility: a read with a pending-ish predicate on a table/column, then a write moving that same column out of it \u2014 a plain INSERT of the subject does not qualify. (3) The catch covering the effect must be terminal: no rethrow, no non-2xx, no revert of the column, no enqueue. An effect with no catch at all is not reported \u2014 the error is loud. (4) Suppressed by an idempotency key, by a transaction whose handler rethrows, or by ANY file in the repo re-selecting the transitioned value with a staleness predicate (the outbox pattern).",
11356
+ check(ctx) {
11357
+ const hits = [];
11358
+ for (const file of ctx.files) {
11359
+ if (file.excluded) continue;
11360
+ const shape = shapeOf(file);
11361
+ if (!shape) continue;
11362
+ const src = file.code;
11363
+ const wholeFile = { start: 0, end: src.length };
11364
+ const allWrites = collectWrites(src);
11365
+ const localGrants = allWrites.filter(
11366
+ (w) => w.kind === "update" && ENTITLEMENT_COLUMN.test(normColumn(w.column)) || w.kind === "insert" && ENTITLEMENT_TABLE.test(normTable(w.table))
11367
+ );
11368
+ const effects = [
11369
+ ...shape.effects.map((e) => ({ index: e.span.start, span: e.span, label: e.label })),
11370
+ ...localGrants.map((w) => ({
11371
+ index: w.index,
11372
+ span: { start: w.index, end: w.index + 200 },
11373
+ label: `${w.table}.${w.column}`
11374
+ }))
11375
+ ];
11376
+ if (effects.length === 0) continue;
11377
+ const reported = /* @__PURE__ */ new Set();
11378
+ for (const effect of effects) {
11379
+ const handler = handlerSpan(shape, effect.index, wholeFile);
11380
+ if (reported.has(handler.start)) continue;
11381
+ const body = src.slice(handler.start, handler.end);
11382
+ const base = handler.start;
11383
+ const reads = collectPendingReads(body).map((r) => ({ ...r, index: r.index + base }));
11384
+ const writes = collectWrites(body).map((w) => ({ ...w, index: w.index + base }));
11385
+ let transition = null;
11386
+ let consumed = null;
11387
+ for (const write of writes) {
11388
+ if (write.index >= effect.index) continue;
11389
+ if (write.kind !== "update") continue;
11390
+ if (isPending(write.value)) continue;
11391
+ if (write.index === effect.index) continue;
11392
+ const read = reads.find(
11393
+ (r) => r.index < write.index && normTable(r.table) === normTable(write.table) && normColumn(r.column) === normColumn(write.column) && normValue(r.value) !== normValue(write.value)
11394
+ );
11395
+ if (read) {
11396
+ transition = write;
11397
+ consumed = read;
11398
+ break;
11399
+ }
11400
+ const cas = [...sqlPredicates(write.trailing), ...builderPredicates(write.trailing)].find(
11401
+ (p) => normColumn(p.column) === normColumn(write.column) && isPending(p.value)
11402
+ );
11403
+ if (cas) {
11404
+ transition = write;
11405
+ consumed = { table: write.table, column: cas.column, value: cas.value, index: write.index };
11406
+ break;
11407
+ }
11408
+ }
11409
+ if (!transition || !consumed) continue;
11410
+ if (transition.index === effect.index) continue;
11411
+ const catchBody = catchCovering(shape, effect.index);
11412
+ if (!catchBody) continue;
11413
+ const catchText = src.slice(catchBody.start, catchBody.end);
11414
+ if (/\bthrow\b/.test(catchText)) continue;
11415
+ if (NON_2XX.test(catchText)) continue;
11416
+ if (ENQUEUES.test(catchText)) continue;
11417
+ const revertRe = new RegExp(`\\b${escapeRe(transition.table.replace(/["'`]/g, ""))}s?\\b`, "i");
11418
+ if (revertRe.test(catchText) && /\b(?:update|set|revert|rollback|restore)\b/i.test(catchText)) {
11419
+ continue;
11420
+ }
11421
+ const effectText = src.slice(effect.span.start, Math.min(src.length, effect.span.end));
11422
+ if (/idempotency[_-]?key/i.test(effectText)) continue;
11423
+ if (insideTransaction(shape, effect.index) && /\bthrow\b/.test(body)) continue;
11424
+ if (repoReselects(ctx.files, file.path, transition.index, transition.table, transition.value)) {
11425
+ continue;
11426
+ }
11427
+ reported.add(handler.start);
11428
+ const columnLabel = `${transition.table.replace(/["'`]/g, "")}.${transition.column.replace(/["'`]/g, "")}`;
11429
+ hits.push({
11430
+ file: file.path,
11431
+ line: lineAt(file.content, effect.index),
11432
+ detail: `\`${columnLabel}\` is moved out of \`${normValue(consumed.value)}\` on line ${lineAt(file.content, transition.index)}, and only then does \`${effect.label}\` run \u2014 with its failure caught and swallowed. If the transfer fails, the row says it was paid, the money never moved, and the pending query will never select that row again.`
11433
+ });
11434
+ }
11435
+ }
11436
+ return hits;
11437
+ }
11438
+ };
11439
+
11440
+ // src/quality/rules/fail-open-secret-comparison.ts
11441
+ var SKIP_KEYS = /* @__PURE__ */ new Set([
11442
+ "loc",
11443
+ "extra",
11444
+ "comments",
11445
+ "tokens",
11446
+ "leadingComments",
11447
+ "trailingComments",
11448
+ "innerComments"
11449
+ ]);
11450
+ function walk(node, visit) {
11451
+ if (!node || typeof node !== "object") return;
11452
+ if (Array.isArray(node)) {
11453
+ for (const child of node) walk(child, visit);
11454
+ return;
11455
+ }
11456
+ const record = node;
11457
+ if (typeof record.type === "string") visit(node);
11458
+ for (const key of Object.keys(record)) {
11459
+ if (SKIP_KEYS.has(key)) continue;
11460
+ walk(record[key], visit);
11461
+ }
11462
+ }
11463
+ function containsType(root, types) {
11464
+ let found = false;
11465
+ walk(root, (n) => {
11466
+ if (types.includes(n.type)) found = true;
11467
+ });
11468
+ return found;
11469
+ }
11470
+ function envVarName(node) {
11471
+ if (!node) return null;
11472
+ if (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") {
11473
+ const owner = node.object;
11474
+ if ((owner.type === "MemberExpression" || owner.type === "OptionalMemberExpression") && owner.object.type === "Identifier" && owner.object.name === "process" && owner.property.type === "Identifier" && owner.property.name === "env") {
11475
+ if (!node.computed && node.property.type === "Identifier") return node.property.name;
11476
+ if (node.property.type === "StringLiteral") return node.property.value;
11477
+ }
11478
+ return null;
11479
+ }
11480
+ if (node.type === "CallExpression" || node.type === "OptionalCallExpression") {
11481
+ const callee = node.callee;
11482
+ if ((callee.type === "MemberExpression" || callee.type === "OptionalMemberExpression") && callee.property.type === "Identifier" && callee.property.name === "get") {
11483
+ const owner = callee.object;
11484
+ if ((owner.type === "MemberExpression" || owner.type === "OptionalMemberExpression") && owner.object.type === "Identifier" && (owner.object.name === "Deno" || owner.object.name === "process") && owner.property.type === "Identifier" && owner.property.name === "env") {
11485
+ const arg = node.arguments[0];
11486
+ if (arg && arg.type === "StringLiteral") return arg.value;
11487
+ }
11488
+ }
11489
+ }
11490
+ return null;
11491
+ }
11492
+ function isSecretName(name) {
11493
+ if (/(?:^|_)(?:secret|token|key|apikey)s?$/i.test(name)) return true;
11494
+ return /[a-z0-9](?:Secret|Token|Key|ApiKey)s?$/.test(name);
11495
+ }
11496
+ function refName(node, facts) {
11497
+ if (!node) return null;
11498
+ const direct = envVarName(node);
11499
+ if (direct) return direct;
11500
+ if (node.type === "Identifier") return facts.envAlias.get(node.name) ?? null;
11501
+ return null;
11502
+ }
11503
+ function baseRefName(node, facts) {
11504
+ let current = node;
11505
+ for (let depth = 0; current && depth < 6; depth++) {
11506
+ const direct = refName(current, facts);
11507
+ if (direct) return direct;
11508
+ if (current.type === "MemberExpression" || current.type === "OptionalMemberExpression") {
11509
+ current = current.object;
11510
+ } else if (current.type === "CallExpression" || current.type === "OptionalCallExpression") {
11511
+ current = current.callee;
11512
+ } else {
11513
+ return null;
11514
+ }
11515
+ }
11516
+ return null;
11517
+ }
11518
+ function logicalOperands(node) {
11519
+ if (node.type === "LogicalExpression") {
11520
+ return [...logicalOperands(node.left), ...logicalOperands(node.right)];
11521
+ }
11522
+ return [node];
11523
+ }
11524
+ var EQUALITY = /* @__PURE__ */ new Set(["===", "!==", "==", "!="]);
11525
+ function isNullishLiteral(node) {
11526
+ if (node.type === "Identifier") return node.name === "undefined";
11527
+ if (node.type === "NullLiteral") return true;
11528
+ if (node.type === "StringLiteral") return node.value === "";
11529
+ if (node.type === "NumericLiteral") return node.value === 0;
11530
+ return false;
11531
+ }
11532
+ function isMissingCheck(operand, name, facts) {
11533
+ if (operand.type === "UnaryExpression" && operand.operator === "!") {
11534
+ if (baseRefName(operand.argument, facts) === name) return true;
11535
+ return isMissingCheck(operand.argument, name, facts);
11536
+ }
11537
+ if (operand.type === "BinaryExpression" && EQUALITY.has(operand.operator)) {
11538
+ const left = operand.left;
11539
+ const right = operand.right;
11540
+ const typeofSide = (a, b) => a.type === "UnaryExpression" && a.operator === "typeof" && baseRefName(a.argument, facts) === name && b.type === "StringLiteral";
11541
+ if (typeofSide(left, right) || typeofSide(right, left)) return true;
11542
+ if (baseRefName(left, facts) === name && isNullishLiteral(right)) return true;
11543
+ if (baseRefName(right, facts) === name && isNullishLiteral(left)) return true;
11544
+ return false;
11545
+ }
11546
+ return false;
11547
+ }
11548
+ function failsClosedOn(test, name, facts) {
11549
+ for (const operand of logicalOperands(test)) {
11550
+ if (isMissingCheck(operand, name, facts)) return true;
11551
+ if (refName(operand, facts) === name) return true;
11552
+ }
11553
+ return false;
11554
+ }
11555
+ var ASSERT_CALLEE = /^(?:assert|invariant|ensure|require|required|must|validate|verify|guard|check)/i;
11556
+ var ENV_ASSERT_CALLEE = /(?:env|secret|token|key|config|settings|vars?)/i;
11557
+ function calleeName2(node) {
11558
+ if (node.type === "Identifier") return node.name;
11559
+ if ((node.type === "MemberExpression" || node.type === "OptionalMemberExpression") && node.property.type === "Identifier") {
11560
+ return node.property.name;
11561
+ }
11562
+ return null;
11563
+ }
11564
+ function isThrowingFallback(node) {
11565
+ if (node.type === "CallExpression" || node.type === "OptionalCallExpression") return true;
11566
+ if (node.type === "NewExpression") return true;
11567
+ if (node.type === "ArrowFunctionExpression" || node.type === "FunctionExpression") {
11568
+ return containsType(node.body, ["ThrowStatement"]);
11569
+ }
11570
+ return containsType(node, ["ThrowStatement"]);
11571
+ }
11572
+ var ENV_SCHEMA_CALL = /(?:safeParse|parse)\s*\(\s*(?:process\s*\.\s*env|Deno\s*\.\s*env\s*\.\s*toObject\s*\(\s*\))|\b(?:cleanEnv|createEnv|envsafe)\s*\(/;
11573
+ function hasEnvSchemaFor(code, name) {
11574
+ if (!ENV_SCHEMA_CALL.test(code)) return false;
11575
+ return new RegExp(`(?:^|[^\\w.])${name}\\s*:`, "m").test(code);
11576
+ }
11577
+ function readsRequestHeader(node, facts) {
11578
+ let found = false;
11579
+ walk(node, (n) => {
11580
+ if (found) return;
11581
+ if (n.type === "Identifier" && n.name === "headers") found = true;
11582
+ if (n.type === "CallExpression" || n.type === "OptionalCallExpression") {
11583
+ const name = calleeName2(n.callee);
11584
+ if (name === "header" || name === "getHeader" || name === "headers") found = true;
11585
+ }
11586
+ if (n.type === "Identifier" && facts.headerAlias.has(n.name)) found = true;
11587
+ });
11588
+ return found;
11589
+ }
11590
+ function collectFacts(file) {
11591
+ const facts = {
11592
+ envAlias: /* @__PURE__ */ new Map(),
11593
+ headerAlias: /* @__PURE__ */ new Set(),
11594
+ guarded: /* @__PURE__ */ new Set(),
11595
+ defaulted: /* @__PURE__ */ new Set()
11596
+ };
11597
+ const ast = file.parsed?.ast;
11598
+ if (!ast) return facts;
11599
+ walk(ast, (n) => {
11600
+ if (n.type !== "VariableDeclarator" || !n.init) return;
11601
+ const init = n.init;
11602
+ let source = init;
11603
+ let fallback = null;
11604
+ if (init.type === "LogicalExpression" && (init.operator === "??" || init.operator === "||")) {
11605
+ source = init.left;
11606
+ fallback = init.right;
11607
+ }
11608
+ if (source.type === "TSNonNullExpression") source = source.expression;
11609
+ const envName = envVarName(source);
11610
+ if (envName && n.id.type === "Identifier") {
11611
+ facts.envAlias.set(n.id.name, envName);
11612
+ }
11613
+ if (envName && fallback) {
11614
+ if (isThrowingFallback(fallback)) facts.guarded.add(envName);
11615
+ else facts.defaulted.add(envName);
11616
+ }
11617
+ if ((init.type === "CallExpression" || init.type === "OptionalCallExpression") && !envName) {
11618
+ const name = calleeName2(init.callee);
11619
+ if (name && ASSERT_CALLEE.test(name)) {
11620
+ const arg = init.arguments[0];
11621
+ if (arg && arg.type === "StringLiteral") {
11622
+ facts.guarded.add(arg.value);
11623
+ if (n.id.type === "Identifier") facts.envAlias.set(n.id.name, arg.value);
11624
+ } else if (name && ENV_ASSERT_CALLEE.test(name) && n.id.type === "Identifier") {
11625
+ const inner = arg ? envVarName(arg) : null;
11626
+ if (inner) {
11627
+ facts.guarded.add(inner);
11628
+ facts.envAlias.set(n.id.name, inner);
11629
+ }
11630
+ }
11631
+ }
11632
+ }
11633
+ if (n.id.type === "Identifier" && readsRequestHeader(init, facts)) {
11634
+ facts.headerAlias.add(n.id.name);
11635
+ }
11636
+ if (n.id.type === "ObjectPattern" && readsRequestHeader(init, facts)) {
11637
+ for (const prop of n.id.properties) {
11638
+ if (prop.type === "ObjectProperty" && prop.value.type === "Identifier") {
11639
+ facts.headerAlias.add(prop.value.name);
11640
+ }
11641
+ }
11642
+ }
11643
+ });
11644
+ const names = /* @__PURE__ */ new Set([...facts.envAlias.values()]);
11645
+ walk(ast, (n) => {
11646
+ if (n.type === "MemberExpression" || n.type === "CallExpression") {
11647
+ const direct = envVarName(n);
11648
+ if (direct) names.add(direct);
11649
+ }
11650
+ });
11651
+ walk(ast, (n) => {
11652
+ if (n.type === "IfStatement") {
11653
+ for (const name of names) {
11654
+ if (facts.guarded.has(name)) continue;
11655
+ if (!failsClosedOn(n.test, name, facts)) continue;
11656
+ if (containsType(n, ["ReturnStatement", "ThrowStatement"])) facts.guarded.add(name);
11657
+ }
11658
+ return;
11659
+ }
11660
+ if (n.type === "LogicalExpression" && (n.operator === "??" || n.operator === "||")) {
11661
+ const name = refName(n.left, facts);
11662
+ if (name) {
11663
+ if (isThrowingFallback(n.right)) facts.guarded.add(name);
11664
+ else facts.defaulted.add(name);
11665
+ }
11666
+ return;
11667
+ }
11668
+ if (n.type === "CallExpression" || n.type === "OptionalCallExpression") {
11669
+ const name = calleeName2(n.callee);
11670
+ if (!name || !ASSERT_CALLEE.test(name)) return;
11671
+ const argNames = /* @__PURE__ */ new Set();
11672
+ for (const arg of n.arguments) {
11673
+ if (arg.type === "StringLiteral") argNames.add(arg.value);
11674
+ const viaEnv = refName(arg, facts);
11675
+ if (viaEnv) argNames.add(viaEnv);
11676
+ }
11677
+ if (argNames.size > 0) {
11678
+ for (const candidate of argNames) {
11679
+ if (names.has(candidate) || isSecretName(candidate)) facts.guarded.add(candidate);
11680
+ }
11681
+ } else if (ENV_ASSERT_CALLEE.test(name)) {
11682
+ for (const name2 of names) facts.guarded.add(name2);
11683
+ }
11684
+ }
11685
+ });
11686
+ for (const name of names) {
11687
+ if (hasEnvSchemaFor(file.code, name)) facts.guarded.add(name);
11688
+ }
11689
+ return facts;
11690
+ }
11691
+ function templateAsMissing(tpl, facts) {
11692
+ for (const expr of tpl.expressions) {
11693
+ if (!refName(expr, facts)) return null;
11694
+ }
11695
+ let out = "";
11696
+ tpl.quasis.forEach((quasi, i) => {
11697
+ out += quasi.value.cooked ?? quasi.value.raw;
11698
+ if (i < tpl.expressions.length) out += "undefined";
11699
+ });
11700
+ return out;
11701
+ }
11702
+ function concatOperands(node) {
11703
+ if (node.type === "BinaryExpression" && node.operator === "+") {
11704
+ return [...concatOperands(node.left), ...concatOperands(node.right)];
11705
+ }
11706
+ return [node];
11707
+ }
11708
+ function interpolatedSecret(node, facts) {
11709
+ if (node.type === "TemplateLiteral") {
11710
+ if (node.expressions.length === 0) return null;
11711
+ for (const expr of node.expressions) {
11712
+ const name = refName(expr, facts);
11713
+ if (name && isSecretName(name)) {
11714
+ return { name, literal: templateAsMissing(node, facts) };
11715
+ }
11716
+ }
11717
+ return null;
11718
+ }
11719
+ if (node.type === "BinaryExpression" && node.operator === "+") {
11720
+ const operands = concatOperands(node);
11721
+ if (!operands.some((o) => o.type === "StringLiteral" || o.type === "TemplateLiteral")) {
11722
+ return null;
11723
+ }
11724
+ for (const operand of operands) {
11725
+ const name = refName(operand, facts);
11726
+ if (!name || !isSecretName(name)) continue;
11727
+ let literal = "";
11728
+ let computable = true;
11729
+ for (const o of operands) {
11730
+ if (o.type === "StringLiteral") literal += o.value;
11731
+ else if (refName(o, facts)) literal += "undefined";
11732
+ else computable = false;
11733
+ }
11734
+ return { name, literal: computable ? literal : null };
11735
+ }
11736
+ }
11737
+ return null;
11738
+ }
11739
+ var WEBHOOK_PATH = /webhook/i;
11740
+ var failOpenSecretComparison = {
11741
+ id: "QA004",
11742
+ title: 'A secret comparison that authenticates "Bearer undefined"',
11743
+ severity: "high",
11744
+ category: "Authentication",
11745
+ description: 'This handler checks its authorization header against a secret interpolated into a string, and nothing in the file refuses to run when that variable is missing. With the variable unset the check compares against the literal text "Bearer undefined", so anyone who sends exactly that header is authorized \u2014 in a new environment, a preview deployment, or after the variable is renamed.',
11746
+ fix: 'Read the secret into a variable and refuse the request when it is missing \u2014 `const secret = process.env.CRON_SECRET; if (!secret) return new Response("Unauthorized", { status: 401 });` \u2014 before comparing. An environment with no secret configured can authorize nothing.',
11747
+ precisionNotes: "Fires only on an equality comparison between an inbound request header and an env secret INTERPOLATED into a string (template literal or `+` concatenation) whose name is *_SECRET / *_TOKEN / *_KEY, where no fail-closed check on that same variable \u2014 `if (!x) return/throw`, an assertEnv-style call, a zod/envalid schema over process.env, or a throwing `??` fallback \u2014 appears anywhere in the file, and where the variable has no literal fallback (that is a hardcoded-credential finding, not this one). Webhook paths are left to VC062/VC209. Each clause removes a class of correct code: bare non-interpolated compares, non-secret env vars, guarded handlers, validated-env projects.",
11748
+ check(ctx) {
11749
+ const hits = [];
11750
+ for (const file of ctx.files) {
11751
+ if (file.excluded) continue;
11752
+ if (WEBHOOK_PATH.test(file.path)) continue;
11753
+ const parsed = file.parsed;
11754
+ if (!parsed) continue;
11755
+ const facts = collectFacts(file);
11756
+ const reported = /* @__PURE__ */ new Set();
11757
+ visitBinary(parsed, (node) => {
11758
+ if (!EQUALITY.has(node.operator)) return;
11759
+ const left = node.left;
11760
+ const right = node.right;
11761
+ const secret = interpolatedSecret(right, facts) ?? interpolatedSecret(left, facts);
11762
+ if (!secret) return;
11763
+ if (!isSecretName(secret.name)) return;
11764
+ if (facts.guarded.has(secret.name)) return;
11765
+ if (facts.defaulted.has(secret.name)) return;
11766
+ const other = interpolatedSecret(right, facts) ? left : right;
11767
+ if (!readsRequestHeader(other, facts)) return;
11768
+ const line = node.loc?.start.line ?? 1;
11769
+ if (reported.has(line)) return;
11770
+ const offset = node.start ?? 0;
11771
+ if (isInlineSilenced(file.content, offset, "QA004")) return;
11772
+ reported.add(line);
11773
+ hits.push({
11774
+ file: file.path,
11775
+ line,
11776
+ detail: secret.literal ? `With ${secret.name} unset, this comparison authorizes the literal header value "${secret.literal}" \u2014 an attacker can send exactly that. Nothing in this file refuses to run when the variable is missing.` : `With ${secret.name} unset, this comparison interpolates the missing value into a guessable literal and authorizes anyone who sends it. Nothing in this file refuses to run when the variable is missing.`
11777
+ });
11778
+ });
11779
+ }
11780
+ return hits;
11781
+ }
11782
+ };
11783
+
11784
+ // src/quality/rules/mouse-only-control.ts
11785
+ var FOCUSABLE_TAGS = /* @__PURE__ */ new Set([
11786
+ "a",
11787
+ "area",
11788
+ "button",
11789
+ "input",
11790
+ "label",
11791
+ "option",
11792
+ "select",
11793
+ "summary",
11794
+ "textarea"
11795
+ ]);
11796
+ var STRUCTURAL_TAGS = /* @__PURE__ */ new Set(["tr", "li", "tbody"]);
11797
+ var INTERACTIVE_DESCENDANT_TAGS = /* @__PURE__ */ new Set([
11798
+ "a",
11799
+ "button",
11800
+ "input",
11801
+ "select",
11802
+ "summary",
11803
+ "textarea"
11804
+ ]);
11805
+ var INTERACTIVE_COMPONENT = /(?:Button|Link|Trigger|Menu|Input|Select|Field)$/;
11806
+ var DECLARED_ATTR = /^(?:role|tabIndex|tabindex|onKey[A-Z]\w*)$/;
11807
+ var BARRIER_METHODS = /* @__PURE__ */ new Set(["stopPropagation", "preventDefault", "stopImmediatePropagation"]);
11808
+ var AFFORDANCE = /\bcursor-pointer\b|\bselect-none\b|\bhover:|cursor\s*:\s*["'`]?\s*pointer/;
11809
+ function walkNodes(value, visit) {
11810
+ if (!value || typeof value !== "object") return;
11811
+ if (Array.isArray(value)) {
11812
+ for (const item of value) walkNodes(item, visit);
11813
+ return;
11814
+ }
11815
+ const record = value;
11816
+ if (typeof record.type === "string") visit(value);
11817
+ for (const key of Object.keys(record)) {
11818
+ if (key === "loc" || key === "leadingComments" || key === "trailingComments") continue;
11819
+ if (key === "innerComments" || key === "extra" || key === "tokens") continue;
11820
+ walkNodes(record[key], visit);
11821
+ }
11822
+ }
11823
+ function eachJsxElement(root, visit) {
11824
+ const descend = (value, parent) => {
11825
+ if (!value || typeof value !== "object") return;
11826
+ if (Array.isArray(value)) {
11827
+ for (const item of value) descend(item, parent);
11828
+ return;
11829
+ }
11830
+ const record = value;
11831
+ let nextParent = parent;
11832
+ if (record.type === "JSXElement") {
11833
+ const element = value;
11834
+ visit(element, parent);
11835
+ nextParent = element;
11836
+ }
11837
+ for (const key of Object.keys(record)) {
11838
+ if (key === "loc" || key === "leadingComments" || key === "trailingComments") continue;
11839
+ if (key === "innerComments" || key === "extra" || key === "tokens") continue;
11840
+ descend(record[key], nextParent);
11841
+ }
11842
+ };
11843
+ descend(root, null);
11844
+ }
11845
+ function tagName(name) {
11846
+ if (name.type === "JSXIdentifier") return name.name;
11847
+ if (name.type === "JSXMemberExpression") return name.property.name;
11848
+ if (name.type === "JSXNamespacedName") return name.name.name;
11849
+ return "";
11850
+ }
11851
+ function isNativeTag(name) {
11852
+ if (name.type === "JSXIdentifier") return /^[a-z]/.test(name.name);
11853
+ if (name.type === "JSXMemberExpression") {
11854
+ return name.object.type === "JSXIdentifier" && name.object.name === "motion" && /^[a-z]/.test(name.property.name);
11855
+ }
11856
+ return false;
11857
+ }
11858
+ function attributeName(attr) {
11859
+ return attr.name.type === "JSXIdentifier" ? attr.name.name : `${attr.name.namespace.name}:${attr.name.name.name}`;
11860
+ }
11861
+ function findAttribute(element, name) {
11862
+ for (const attr of element.attributes) {
11863
+ if (attr.type !== "JSXAttribute") continue;
11864
+ if (attributeName(attr) === name) return attr;
11865
+ }
11866
+ return null;
11867
+ }
11868
+ function hasSpread(element) {
11869
+ return element.attributes.some((attr) => attr.type === "JSXSpreadAttribute");
11870
+ }
11871
+ function declaresKeyboardAccess(element) {
11872
+ for (const attr of element.attributes) {
11873
+ if (attr.type !== "JSXAttribute") continue;
11874
+ if (DECLARED_ATTR.test(attributeName(attr))) return true;
11875
+ }
11876
+ return false;
11877
+ }
11878
+ function isAsChildTrigger(element) {
11879
+ if (!element) return false;
11880
+ return findAttribute(element.openingElement, "asChild") !== null;
11881
+ }
11882
+ function hasInteractiveDescendant(element) {
11883
+ let found = false;
11884
+ walkNodes(element, (node) => {
11885
+ if (found) return;
11886
+ if (node.type !== "JSXOpeningElement") return;
11887
+ if (node === element.openingElement) return;
11888
+ const name = tagName(node.name);
11889
+ if (!name) return;
11890
+ if (/^[a-z]/.test(name)) {
11891
+ if (INTERACTIVE_DESCENDANT_TAGS.has(name)) found = true;
11892
+ return;
11893
+ }
11894
+ if (name === "Link" || INTERACTIVE_COMPONENT.test(name)) found = true;
11895
+ });
11896
+ return found;
11897
+ }
11898
+ function isBarrierCall(node) {
11899
+ if (node.type !== "CallExpression") return false;
11900
+ const callee = node.callee;
11901
+ if (callee.type !== "MemberExpression" && callee.type !== "OptionalMemberExpression") return false;
11902
+ if (callee.property.type !== "Identifier") return false;
11903
+ return BARRIER_METHODS.has(callee.property.name);
11904
+ }
11905
+ function isBarrierHandler(fn) {
11906
+ const body = fn.body;
11907
+ if (body.type !== "BlockStatement") return isBarrierCall(body);
11908
+ if (body.body.length === 0) return true;
11909
+ return body.body.every(
11910
+ (stmt) => stmt.type === "ExpressionStatement" && isBarrierCall(stmt.expression)
11911
+ );
11912
+ }
11913
+ function collectHandlers(root) {
11914
+ const handlers = /* @__PURE__ */ new Map();
11915
+ walkNodes(root, (node) => {
11916
+ if (node.type === "FunctionDeclaration" && node.id) {
11917
+ handlers.set(node.id.name, node);
11918
+ return;
11919
+ }
11920
+ if (node.type !== "VariableDeclarator") return;
11921
+ if (node.id.type !== "Identifier" || !node.init) return;
11922
+ if (node.init.type === "ArrowFunctionExpression" || node.init.type === "FunctionExpression") {
11923
+ handlers.set(node.id.name, node.init);
11924
+ }
11925
+ });
11926
+ return handlers;
11927
+ }
11928
+ function attributeSource(attr, code) {
11929
+ if (!attr || attr.start == null || attr.end == null) return "";
11930
+ return code.slice(attr.start, attr.end);
11931
+ }
11932
+ var mouseOnlyControl = {
11933
+ id: "QA005",
11934
+ title: "A control only a mouse can reach",
11935
+ severity: "medium",
11936
+ category: "Accessibility",
11937
+ description: "This element is styled and wired as a button but is not one: it has a click handler and no role, no tabIndex and no key handler, so it cannot be reached by Tab, activated by Enter or Space, announced by a screen reader, or driven by voice control. Anyone not using a mouse cannot perform this action at all.",
11938
+ fix: 'Make it a <button type="button"> \u2014 that is the whole fix, and it keeps the styling. If the tag cannot change, add role="button", tabIndex={0} and an onKeyDown that fires the same handler on Enter and Space.',
11939
+ precisionNotes: "Native non-focusable tags only (a capitalised component's semantics live in another file); no spread attribute; the handler must do more than stopPropagation/preventDefault; no interactive descendant; not the child of an asChild trigger; never tr/li/tbody; and the element must carry a click affordance (cursor-pointer, select-none, hover:). Each clause removes a class of correct code: prop-forwarding wrappers, click barriers, redundant row affordances, and Radix triggers that merge their attributes into the child at runtime.",
11940
+ check(ctx) {
11941
+ const hits = [];
11942
+ for (const file of ctx.files) {
11943
+ if (file.excluded) continue;
11944
+ const parsed = file.parsed;
11945
+ if (!parsed) continue;
11946
+ if (parsed.language !== "jsx" && parsed.language !== "tsx") continue;
11947
+ const handlers = collectHandlers(parsed.ast.program);
11948
+ eachJsxElement(parsed.ast.program, (element, jsxParent) => {
11949
+ const opening = element.openingElement;
11950
+ if (!isNativeTag(opening.name)) return;
11951
+ const tag = tagName(opening.name);
11952
+ if (FOCUSABLE_TAGS.has(tag)) return;
11953
+ if (STRUCTURAL_TAGS.has(tag)) return;
11954
+ const onClick = findAttribute(opening, "onClick");
11955
+ if (!onClick) return;
11956
+ if (declaresKeyboardAccess(opening)) return;
11957
+ if (hasSpread(opening)) return;
11958
+ const value = onClick.value;
11959
+ if (!value || value.type !== "JSXExpressionContainer") return;
11960
+ const expr = value.expression;
11961
+ let handler = null;
11962
+ if (expr.type === "ArrowFunctionExpression" || expr.type === "FunctionExpression") {
11963
+ handler = expr;
11964
+ } else if (expr.type === "Identifier") {
11965
+ handler = handlers.get(expr.name) ?? null;
11966
+ }
11967
+ if (handler && isBarrierHandler(handler)) return;
11968
+ if (hasInteractiveDescendant(element)) return;
11969
+ if (isAsChildTrigger(jsxParent)) return;
11970
+ const dressed = attributeSource(findAttribute(opening, "className"), file.code) + " " + attributeSource(findAttribute(opening, "class"), file.code) + " " + attributeSource(findAttribute(opening, "style"), file.code);
11971
+ if (!AFFORDANCE.test(dressed)) return;
11972
+ const line = opening.loc?.start.line ?? lineAt(file.content, opening.start ?? 0);
11973
+ hits.push({ file: file.path, line });
11974
+ });
11975
+ }
11976
+ return hits;
11977
+ }
11978
+ };
11979
+
11980
+ // src/quality/rules/undeclared-modal.ts
11981
+ var NON_NODE_KEYS = /* @__PURE__ */ new Set([
11982
+ "loc",
11983
+ "leadingComments",
11984
+ "trailingComments",
11985
+ "innerComments",
11986
+ "extra",
11987
+ "tokens"
11988
+ ]);
11989
+ var OVERLAY_TOKENS = ["fixed", "inset-0"];
11990
+ function isSuppressingClassToken(token) {
11991
+ const bare = token.replace(/^(?:[a-z0-9_-]+:)+/, "");
11992
+ if (bare === "pointer-events-none") return true;
11993
+ if (bare === "z-0") return true;
11994
+ if (/^-z-/.test(bare) || /^z-\[-/.test(bare)) return true;
11995
+ if (/^(?:max-)?(?:sm|md|lg|xl|2xl):hidden$/.test(token)) return true;
11996
+ return false;
11997
+ }
11998
+ var FOCUSABLE_TAGS2 = /* @__PURE__ */ new Set(["a", "button", "form", "input", "select", "textarea"]);
11999
+ var FOCUSABLE_COMPONENT = /(?:Button|Input)$/;
12000
+ var OPEN_IDENTIFIER = /open|show|visible|modal|dialog|expand|selected|editing|creating|confirm/i;
12001
+ var MODAL_FILENAME = /(?:modal|dialog|sheet|drawer|lightbox|popup)$/i;
12002
+ var DISMISSAL_SIGNAL = /\bEscape\b|\bEsc\b|\b(?:key|keyCode|which|charCode)\b[^;\n]{0,60}={2,3}\s*27|\bonEscapeKeyDown\b|\buseHotkeys\b|\buseKey\b|\buseKeyPress\b|\buseEventListener\b|addEventListener\s*\(\s*["'`]keydown/;
12003
+ var FOCUS_SIGNAL = /\.focus\s*\(|\bautoFocus\b|\binitialFocus\b|\bFocusLock\b|\bFocusTrap\b|focus-trap|\binert\b/;
12004
+ var DIALOG_PRIMITIVE = /@radix-ui\/react-dialog|@radix-ui\/react-alert-dialog|@headlessui\/react|["'`]react-modal["'`]|["'`]vaul["'`]|["'`]cmdk["'`]|@reach\/dialog|react-aria|@mui\/material|["'`]antd["'`]|@mantine|@chakra-ui|@ark-ui|react-bootstrap|flowbite|@nextui/;
12005
+ var EXAMPLE_OR_DOC_PATH = /(?:^|\/)(?:examples?|docs?)\//i;
12006
+ var MAX_HITS_PER_SCAN = 5;
12007
+ function walkNodes2(value, visit) {
12008
+ if (!value || typeof value !== "object") return;
12009
+ if (Array.isArray(value)) {
12010
+ for (const item of value) walkNodes2(item, visit);
12011
+ return;
12012
+ }
12013
+ const record = value;
12014
+ if (typeof record.type === "string") visit(value);
12015
+ for (const key of Object.keys(record)) {
12016
+ if (NON_NODE_KEYS.has(key)) continue;
12017
+ walkNodes2(record[key], visit);
12018
+ }
12019
+ }
12020
+ function buildParents(root) {
12021
+ const parents = /* @__PURE__ */ new Map();
12022
+ const descend = (value, parent) => {
12023
+ if (!value || typeof value !== "object") return;
12024
+ if (Array.isArray(value)) {
12025
+ for (const item of value) descend(item, parent);
12026
+ return;
12027
+ }
12028
+ const record = value;
12029
+ let nextParent = parent;
12030
+ if (typeof record.type === "string") {
12031
+ const node = value;
12032
+ if (parent) parents.set(node, parent);
12033
+ nextParent = node;
12034
+ }
12035
+ for (const key of Object.keys(record)) {
12036
+ if (NON_NODE_KEYS.has(key)) continue;
12037
+ descend(record[key], nextParent);
12038
+ }
12039
+ };
12040
+ descend(root, null);
12041
+ return parents;
12042
+ }
12043
+ function tagName2(name) {
12044
+ if (name.type === "JSXIdentifier") return name.name;
12045
+ if (name.type === "JSXMemberExpression") return name.property.name;
12046
+ if (name.type === "JSXNamespacedName") return name.name.name;
12047
+ return "";
12048
+ }
12049
+ function isNativeOverlayTag(name) {
12050
+ if (name.type === "JSXIdentifier") return /^[a-z]/.test(name.name);
12051
+ if (name.type === "JSXMemberExpression") {
12052
+ return name.object.type === "JSXIdentifier" && name.object.name === "motion" && /^[a-z]/.test(name.property.name);
12053
+ }
12054
+ return false;
12055
+ }
12056
+ function attributeName2(attr) {
12057
+ return attr.name.type === "JSXIdentifier" ? attr.name.name : `${attr.name.namespace.name}:${attr.name.name.name}`;
12058
+ }
12059
+ function findAttribute2(opening, name) {
12060
+ for (const attr of opening.attributes) {
12061
+ if (attr.type !== "JSXAttribute") continue;
12062
+ if (attributeName2(attr) === name) return attr;
12063
+ }
12064
+ return null;
12065
+ }
12066
+ function ownClassTokens(opening) {
12067
+ const attr = findAttribute2(opening, "className") ?? findAttribute2(opening, "class");
12068
+ if (!attr || !attr.value) return [];
12069
+ const strings = [];
12070
+ walkNodes2(attr.value, (node) => {
12071
+ if (node.type === "StringLiteral") strings.push(node.value);
12072
+ else if (node.type === "TemplateElement") strings.push(node.value.cooked ?? node.value.raw);
12073
+ });
12074
+ return strings.join(" ").split(/\s+/).filter(Boolean);
12075
+ }
12076
+ function hasClassToken(tokens, name) {
12077
+ return tokens.some((t) => t === name || t.endsWith(`:${name}`));
12078
+ }
12079
+ function rendersElementChild(element) {
12080
+ for (const child of element.children) {
12081
+ if (child.type === "JSXElement" || child.type === "JSXFragment") return true;
12082
+ if (child.type !== "JSXExpressionContainer") continue;
12083
+ let found = false;
12084
+ walkNodes2(child.expression, (node) => {
12085
+ if (node.type === "JSXElement" || node.type === "JSXFragment") found = true;
12086
+ });
12087
+ if (found) return true;
12088
+ }
12089
+ return false;
12090
+ }
12091
+ function hasFocusableDescendant(element) {
12092
+ let found = false;
12093
+ walkNodes2(element, (node) => {
12094
+ if (found) return;
12095
+ if (node.type !== "JSXOpeningElement") return;
12096
+ if (node === element.openingElement) return;
12097
+ const name = tagName2(node.name);
12098
+ if (!name) return;
12099
+ if (/^[a-z]/.test(name)) {
12100
+ if (FOCUSABLE_TAGS2.has(name)) found = true;
12101
+ return;
12102
+ }
12103
+ if (FOCUSABLE_COMPONENT.test(name)) found = true;
12104
+ });
12105
+ return found;
12106
+ }
12107
+ function declaresSemantics(element) {
12108
+ let found = false;
12109
+ walkNodes2(element, (node) => {
12110
+ if (found) return;
12111
+ if (node.type === "JSXAttribute") {
12112
+ const name = attributeName2(node);
12113
+ if (name === "role" || name === "aria-modal") found = true;
12114
+ return;
12115
+ }
12116
+ if (node.type === "JSXOpeningElement" && tagName2(node.name).toLowerCase() === "dialog") {
12117
+ found = true;
12118
+ }
12119
+ });
12120
+ return found;
12121
+ }
12122
+ function mentionsOpenState(node) {
12123
+ if (!node) return false;
12124
+ let found = false;
12125
+ walkNodes2(node, (n) => {
12126
+ if (found) return;
12127
+ if (n.type === "Identifier" && OPEN_IDENTIFIER.test(n.name)) found = true;
12128
+ });
12129
+ return found;
12130
+ }
12131
+ var FUNCTION_TYPES2 = /* @__PURE__ */ new Set([
12132
+ "FunctionDeclaration",
12133
+ "FunctionExpression",
12134
+ "ArrowFunctionExpression",
12135
+ "ObjectMethod",
12136
+ "ClassMethod"
12137
+ ]);
12138
+ function hasOpenStateEarlyReturn(fn) {
12139
+ const body = fn.body;
12140
+ if (!body || body.type !== "BlockStatement") return false;
12141
+ const returnsNothing = (stmt) => {
12142
+ if (stmt.type === "ReturnStatement") {
12143
+ const arg = stmt.argument;
12144
+ if (!arg) return true;
12145
+ if (arg.type === "NullLiteral") return true;
12146
+ if (arg.type === "Identifier" && arg.name === "undefined") return true;
12147
+ if (arg.type === "BooleanLiteral" && arg.value === false) return true;
12148
+ return false;
12149
+ }
12150
+ if (stmt.type === "BlockStatement") return stmt.body.some((s) => returnsNothing(s));
12151
+ return false;
12152
+ };
12153
+ for (const stmt of body.body) {
12154
+ if (stmt.type !== "IfStatement") continue;
12155
+ if (!mentionsOpenState(stmt.test)) continue;
12156
+ if (returnsNothing(stmt.consequent)) return true;
12157
+ }
12158
+ return false;
12159
+ }
12160
+ function isOpenGated(element, parents, baseName) {
12161
+ if (MODAL_FILENAME.test(baseName)) return true;
12162
+ let child = element;
12163
+ let parent = parents.get(child);
12164
+ for (let steps = 0; parent && steps < 256; steps++) {
12165
+ if (parent.type === "LogicalExpression" && (parent.operator === "&&" || parent.operator === "||")) {
12166
+ if (parent.right === child && mentionsOpenState(parent.left)) return true;
12167
+ } else if (parent.type === "ConditionalExpression") {
12168
+ const isBranch = parent.consequent === child || parent.alternate === child;
12169
+ if (isBranch && mentionsOpenState(parent.test)) return true;
12170
+ } else if (FUNCTION_TYPES2.has(parent.type)) {
12171
+ if (hasOpenStateEarlyReturn(parent)) return true;
12172
+ }
12173
+ child = parent;
12174
+ parent = parents.get(parent);
12175
+ }
12176
+ return false;
12177
+ }
12178
+ function baseNameWithoutExtension(path) {
12179
+ const base = path.split("/").pop() ?? path;
12180
+ return base.replace(/\.[^.]+$/, "");
12181
+ }
12182
+ var undeclaredModal = {
12183
+ id: "QA006",
12184
+ title: "A modal that is not announced as a dialog",
12185
+ severity: "medium",
12186
+ category: "Accessibility",
12187
+ description: "This full-screen overlay renders a panel with controls in it, but declares no dialog semantics: no role, no aria-modal, no Escape handler and no focus management. A screen reader announces nothing when it opens and keeps reading the page behind it, and a keyboard user has to tab through the covered page to reach the controls \u2014 or tabs straight past them into content they can see is obscured.",
12188
+ fix: 'Put role="dialog" and aria-modal="true" on the panel, point aria-labelledby at its heading, move focus into it when it opens and restore focus when it closes, and close it on Escape. A dialog primitive (Radix, Headless UI) or one shared shell component gets all of that once instead of per modal.',
12189
+ precisionNotes: "The fixed+inset-0 tokens must come from the element's OWN className, resolved through cn()/clsx/template literals and never from a string elsewhere in the file \u2014 that single clause separates this from a rule that flags this repo's correct LegalModal.tsx. Then: native lowercase or motion.* tags only; must render an element child and contain a focusable one; no role of any kind, no aria-modal and no dialog element anywhere in the subtree; no pointer-events-none, z-0, negative z or responsive hidden; must be gated on an open-ish condition or live in a *Modal/Dialog/Sheet/Drawer/Lightbox/Popup file; and the file must carry no Escape handling, no focus management and no dialog-primitive import. Capped at one finding per file and five per scan, because the worst corpus repo fires 82 times and volume is its own precision problem.",
12190
+ check(ctx) {
12191
+ const hits = [];
12192
+ for (const file of ctx.files) {
12193
+ if (hits.length >= MAX_HITS_PER_SCAN) break;
12194
+ if (file.excluded) continue;
12195
+ if (EXAMPLE_OR_DOC_PATH.test(file.path)) continue;
12196
+ const parsed = file.parsed;
12197
+ if (!parsed) continue;
12198
+ if (parsed.language !== "jsx" && parsed.language !== "tsx") continue;
12199
+ if (DISMISSAL_SIGNAL.test(file.code)) continue;
12200
+ if (FOCUS_SIGNAL.test(file.code)) continue;
12201
+ if (DIALOG_PRIMITIVE.test(file.code)) continue;
12202
+ const program = parsed.ast.program;
12203
+ const parents = buildParents(program);
12204
+ const baseName = baseNameWithoutExtension(file.path);
12205
+ const elements = [];
12206
+ walkNodes2(program, (node) => {
12207
+ if (node.type === "JSXElement") elements.push(node);
12208
+ });
12209
+ for (const element of elements) {
12210
+ const opening = element.openingElement;
12211
+ if (!isNativeOverlayTag(opening.name)) continue;
12212
+ const tokens = ownClassTokens(opening);
12213
+ if (!OVERLAY_TOKENS.every((t) => hasClassToken(tokens, t))) continue;
12214
+ if (tokens.some(isSuppressingClassToken)) continue;
12215
+ if (opening.selfClosing) continue;
12216
+ if (!rendersElementChild(element)) continue;
12217
+ if (!hasFocusableDescendant(element)) continue;
12218
+ if (declaresSemantics(element)) continue;
12219
+ if (!isOpenGated(element, parents, baseName)) continue;
12220
+ const line = opening.loc?.start.line ?? lineAt(file.content, opening.start ?? 0);
12221
+ hits.push({ file: file.path, line });
12222
+ break;
12223
+ }
12224
+ }
12225
+ return hits;
12226
+ }
12227
+ };
12228
+
12229
+ // src/quality/rules/unbounded-list.ts
12230
+ var DATA_LAYER_PATH = /(?:^|\/)actions\.[jt]sx?$|(?:^|\/)actions\//i;
12231
+ var LIB_DATA_PATH = /(?:^|\/)lib\/(?:db|queries|data)(?:\/|\.[jt]sx?$)/i;
12232
+ var BULK_PATH = /(?:export|download|csv|pdf|print|sitemap|rss|feed|cron|backup|report|admin)/i;
12233
+ var USER_SCOPE = /\b(?:user|org|team|workspace|account)_?id\b/i;
12234
+ var UNIQUE_KEY_EQ = [
12235
+ // drizzle: eq(scans.id, scanId) / eq(posts.slug, slug)
12236
+ /\beq\s*\(\s*[A-Za-z_$][\w$]*\s*\.\s*(?:id|slug)\s*,/,
12237
+ // supabase: .eq("id", id)
12238
+ /\beq\s*\(\s*["'`](?:id|slug)["'`]\s*,/,
12239
+ // prisma: where: { id: … } and its shorthand `where: { userId, id }`.
12240
+ // Anchored to the where object, because `id:` in a `select:` projection is
12241
+ // naming a column to RETURN, not one to match on. The lookbehind is
12242
+ // load-bearing in the other direction: `where: { userId: session.user.id }`
12243
+ // is the single most common per-user query there is, and without it the
12244
+ // trailing `.id` reads as a unique-key match and silences the rule.
12245
+ /\bwhere\s*:\s*\{[^{}]*(?<![.\w$])(?:id|slug)\s*[,:}]/,
12246
+ // SQL: `id = $1`, `p.slug = ?`. The trailing [^=>] is load-bearing: without
12247
+ // it `.map(id => …)` reads as an equality and silences the rule.
12248
+ /\b(?:[A-Za-z_$][\w$]*\s*\.\s*)?(?:id|slug)\s*=[^=>]/i
12249
+ ];
12250
+ var GROWTH_NOUNS = /* @__PURE__ */ new Set([
12251
+ "event",
12252
+ "log",
12253
+ "message",
12254
+ "notification",
12255
+ "comment",
12256
+ "post",
12257
+ "order",
12258
+ "scan",
12259
+ "submission",
12260
+ "response",
12261
+ "activity",
12262
+ "view",
12263
+ "session",
12264
+ "history",
12265
+ "item",
12266
+ "entry"
12267
+ ]);
12268
+ function singular(word) {
12269
+ if (word.endsWith("ies") && word.length > 3) return `${word.slice(0, -3)}y`;
12270
+ if (word.endsWith("ss")) return word;
12271
+ if (word.endsWith("s") && word.length > 1) return word.slice(0, -1);
12272
+ return word;
12273
+ }
12274
+ function headNoun(table) {
12275
+ const tokens = table.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[^A-Za-z0-9]+/g, " ").trim().split(/\s+/).filter(Boolean);
12276
+ if (tokens.length === 0) return "";
12277
+ return singular(tokens[tokens.length - 1].toLowerCase());
12278
+ }
12279
+ var BOUND_TOKEN = /\b(?:limit|take|first|cursor|offset|paginate|page|per_?page)\b|\.\s*(?:range|slice)\s*\(/i;
12280
+ var TIME_WINDOW = /\bgte\s*\(|\bbetween\b|\b(?:created_?at|updated_?at|timestamp)\s*[><]|\b(?:since|after)\b/i;
12281
+ var REDUCED_IN_PLACE = /\bcount\s*\(|\bPromise\s*\.\s*all\s*\(/;
12282
+ var REDUCING_MEMBER = /^\s*\.\s*(?:length\b|reduce\s*\()/;
12283
+ var ID_PROJECTION = /^\s*\.\s*map\s*\(\s*\(?\s*(\w+)\s*\)?\s*=>\s*(\w+)\s*(?:\.|\[)/;
12284
+ var STATEMENT_TYPES = /* @__PURE__ */ new Set([
12285
+ "ExpressionStatement",
12286
+ "VariableDeclaration",
12287
+ "ReturnStatement",
12288
+ "ThrowStatement"
12289
+ ]);
12290
+ function eachNodeWithStatement(root, visit) {
12291
+ const descend = (value, statement) => {
12292
+ if (!value || typeof value !== "object") return;
12293
+ if (Array.isArray(value)) {
12294
+ for (const item of value) descend(item, statement);
12295
+ return;
12296
+ }
12297
+ const record = value;
12298
+ let next = statement;
12299
+ if (typeof record.type === "string") {
12300
+ const node = value;
12301
+ if (STATEMENT_TYPES.has(node.type)) next = node;
12302
+ visit(node, next);
12303
+ }
12304
+ for (const key of Object.keys(record)) {
12305
+ if (key === "loc" || key === "leadingComments" || key === "trailingComments") continue;
12306
+ if (key === "innerComments" || key === "extra" || key === "tokens") continue;
12307
+ descend(record[key], next);
12308
+ }
12309
+ };
12310
+ descend(root, null);
12311
+ }
12312
+ function asCall(node) {
12313
+ if (node.type === "CallExpression" || node.type === "OptionalCallExpression") {
12314
+ return node;
12315
+ }
12316
+ return null;
12317
+ }
12318
+ function calleeObject(call) {
12319
+ const callee = call.callee;
12320
+ if (callee.type === "MemberExpression" || callee.type === "OptionalMemberExpression") {
12321
+ return callee.object;
12322
+ }
12323
+ return null;
12324
+ }
12325
+ function tableArgName(node) {
12326
+ if (!node) return "";
12327
+ if (node.type === "Identifier") return node.name;
12328
+ if (node.type === "StringLiteral") return node.value;
12329
+ if (node.type === "MemberExpression" && node.property.type === "Identifier") {
12330
+ return node.property.name;
12331
+ }
12332
+ return "";
12333
+ }
12334
+ var SQL_SELECT_FROM = /\bselect\b[\s\S]{0,600}?\bfrom\s+["'`[]?([A-Za-z_][\w$]*)/i;
12335
+ function ormReadTable(call) {
12336
+ const callee = call.callee;
12337
+ if (isCalleeNamed(callee, "from")) {
12338
+ const receiver = calleeObject(call);
12339
+ const receiverCall = receiver ? asCall(receiver) : null;
12340
+ if (receiverCall && isCalleeNamed(receiverCall.callee, "select")) {
12341
+ return tableArgName(call.arguments[0]) || null;
12342
+ }
12343
+ return null;
12344
+ }
12345
+ if (isCalleeNamed(callee, "select")) {
12346
+ const receiver = calleeObject(call);
12347
+ const receiverCall = receiver ? asCall(receiver) : null;
12348
+ if (receiverCall && isCalleeNamed(receiverCall.callee, "from")) {
12349
+ const arg = receiverCall.arguments[0];
12350
+ if (arg && arg.type === "StringLiteral") return arg.value;
12351
+ }
12352
+ return null;
12353
+ }
12354
+ if (isCalleeNamed(callee, "findMany")) {
12355
+ const receiver = calleeObject(call);
12356
+ if (receiver && (receiver.type === "MemberExpression" || receiver.type === "OptionalMemberExpression") && receiver.property.type === "Identifier") {
12357
+ return receiver.property.name;
12358
+ }
12359
+ return null;
12360
+ }
12361
+ return null;
12362
+ }
12363
+ function sqlReadTable(node) {
12364
+ let text = "";
12365
+ if (node.type === "StringLiteral") {
12366
+ text = node.value;
12367
+ } else if (node.type === "TemplateLiteral") {
12368
+ text = node.quasis.map((q) => q.value.cooked ?? q.value.raw).join(" ? ");
12369
+ } else {
12370
+ return null;
12371
+ }
12372
+ const m = SQL_SELECT_FROM.exec(text);
12373
+ return m ? m[1] : null;
12374
+ }
12375
+ function resultBinding(statement) {
12376
+ if (!statement || statement.type !== "VariableDeclaration") return null;
12377
+ const decl = statement.declarations[0];
12378
+ if (!decl) return null;
12379
+ if (decl.id.type === "Identifier") return decl.id.name;
12380
+ if (decl.id.type === "ObjectPattern") {
12381
+ for (const prop of decl.id.properties) {
12382
+ if (prop.type !== "ObjectProperty") continue;
12383
+ const key = prop.key.type === "Identifier" ? prop.key.name : "";
12384
+ if (key !== "data" && key !== "rows") continue;
12385
+ if (prop.value.type === "Identifier") return prop.value.name;
12386
+ }
12387
+ }
12388
+ return null;
12389
+ }
12390
+ function nextUseReduces(code, name, from) {
12391
+ const re = new RegExp(`\\b${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`, "g");
12392
+ re.lastIndex = from;
12393
+ const m = re.exec(code);
12394
+ if (!m) return false;
12395
+ const tail = code.slice(m.index + m[0].length, m.index + m[0].length + 160);
12396
+ if (REDUCING_MEMBER.test(tail)) return true;
12397
+ const projection = ID_PROJECTION.exec(tail);
12398
+ return projection !== null && projection[1] === projection[2];
12399
+ }
12400
+ var MAX_PER_SCAN = 3;
12401
+ var unboundedList = {
12402
+ id: "QA007",
12403
+ title: "A per-user query with no limit",
12404
+ severity: "medium",
12405
+ category: "Performance",
12406
+ description: "This query reads every row a user or tenant owns from a table that only ever grows \u2014 messages, events, scans, orders \u2014 with no LIMIT, no cursor and no date window. It is fast for a new account and gets slower for every account worth keeping, until the page it feeds stops loading.",
12407
+ fix: "Add a bound the query itself enforces: a LIMIT with a cursor or offset for pages, or a date window for a feed. Bounding it in the caller does not help \u2014 the database still reads and ships every row.",
12408
+ precisionNotes: "Server files only; an ORM or SQL read, identified from the AST rather than a text window; the WHERE must be scoped to a user/tenant column AND carry no unique-key equality; the table's head noun must be on a closed append-only growth list, so configuration tables read whole are never flagged; no bound token (limit/take/cursor/offset/.range/.slice) and no time-window predicate anywhere in the file; bulk-read paths (export, csv, sitemap, cron, backup, admin) exempt; and suppressed when the rows are immediately reduced by .length/.reduce/count()/Promise.all or projected to ids. Capped at one finding per file and three per scan. The render-side half of the original rule \u2014 bounding `.map(` in JSX \u2014 was deleted outright, not narrowed.",
12409
+ check(ctx) {
12410
+ const hits = [];
12411
+ for (const file of ctx.files) {
12412
+ if (hits.length >= MAX_PER_SCAN) break;
12413
+ if (file.excluded) continue;
12414
+ const isDataLayer = DATA_LAYER_PATH.test(file.path) || LIB_DATA_PATH.test(file.path);
12415
+ if (!file.isServer && !isDataLayer) continue;
12416
+ if (file.isClient) continue;
12417
+ if (BULK_PATH.test(file.path)) continue;
12418
+ if (BOUND_TOKEN.test(file.code)) continue;
12419
+ if (TIME_WINDOW.test(file.code)) continue;
12420
+ const parsed = file.parsed;
12421
+ if (!parsed) continue;
12422
+ let reported = false;
12423
+ eachNodeWithStatement(parsed.ast.program, (node, statement) => {
12424
+ if (reported) return;
12425
+ const call = asCall(node);
12426
+ const table = call ? ormReadTable(call) : sqlReadTable(node);
12427
+ if (!table) return;
12428
+ if (!GROWTH_NOUNS.has(headNoun(table))) return;
12429
+ const start = statement?.start ?? node.start;
12430
+ const end = statement?.end ?? node.end;
12431
+ if (start == null || end == null) return;
12432
+ const region = file.code.slice(start, end);
12433
+ if (!USER_SCOPE.test(region)) return;
12434
+ if (UNIQUE_KEY_EQ.some((re) => re.test(region))) return;
12435
+ if (REDUCED_IN_PLACE.test(region)) return;
12436
+ const afterQuery = file.code.slice(node.end ?? start, end);
12437
+ if (REDUCING_MEMBER.test(afterQuery)) return;
12438
+ const binding = resultBinding(statement);
12439
+ if (binding && nextUseReduces(file.code, binding, end)) return;
12440
+ const line = node.loc?.start.line ?? lineAt(file.content, node.start ?? 0);
12441
+ hits.push({ file: file.path, line });
12442
+ reported = true;
12443
+ });
12444
+ }
12445
+ return hits.slice(0, MAX_PER_SCAN);
12446
+ }
12447
+ };
12448
+
12449
+ // src/quality/rules/unassociated-label.ts
12450
+ var CONTROL_TAGS = /* @__PURE__ */ new Set(["input", "select", "textarea"]);
12451
+ var BANNED_CHILD_TAGS = /* @__PURE__ */ new Set(["input", "select", "textarea", "button"]);
12452
+ var CONTROL_WINDOW = 200;
12453
+ var DOC_PATH = /(?:^|\/)(?:docs?|examples?|demos?)\//i;
12454
+ var A11Y_LINT = /eslint-plugin-jsx-a11y|jsx-a11y\/label-has-associated-control/;
12455
+ function repoLintsA11y(ctx) {
12456
+ for (const file of ctx.files) {
12457
+ if (!/(?:^|\/)package\.json$/.test(file.path)) continue;
12458
+ if (A11Y_LINT.test(file.content)) return true;
12459
+ }
12460
+ return false;
12461
+ }
12462
+ function walkNodes3(value, visit) {
12463
+ if (!value || typeof value !== "object") return;
12464
+ if (Array.isArray(value)) {
12465
+ for (const item of value) walkNodes3(item, visit);
12466
+ return;
12467
+ }
12468
+ const record = value;
12469
+ if (typeof record.type === "string") visit(value);
12470
+ for (const key of Object.keys(record)) {
12471
+ if (key === "loc" || key === "leadingComments" || key === "trailingComments") continue;
12472
+ if (key === "innerComments" || key === "extra" || key === "tokens") continue;
12473
+ walkNodes3(record[key], visit);
12474
+ }
12475
+ }
12476
+ function tagName3(name) {
12477
+ if (name.type === "JSXIdentifier") return name.name;
12478
+ if (name.type === "JSXMemberExpression") return name.property.name;
12479
+ if (name.type === "JSXNamespacedName") return name.name.name;
12480
+ return "";
12481
+ }
12482
+ function isNativeTag2(name) {
12483
+ return name.type === "JSXIdentifier" && /^[a-z]/.test(name.name);
12484
+ }
12485
+ function attributeName3(attr) {
12486
+ return attr.name.type === "JSXIdentifier" ? attr.name.name : `${attr.name.namespace.name}:${attr.name.name.name}`;
12487
+ }
12488
+ function attributeString(attr) {
12489
+ const value = attr.value;
12490
+ if (!value) return null;
12491
+ if (value.type === "StringLiteral") return value.value;
12492
+ if (value.type === "JSXExpressionContainer" && value.expression.type === "StringLiteral") {
12493
+ return value.expression.value;
12494
+ }
12495
+ return null;
12496
+ }
12497
+ function isBareLabel(opening) {
12498
+ for (const attr of opening.attributes) {
12499
+ if (attr.type === "JSXSpreadAttribute") return false;
12500
+ const name = attributeName3(attr).toLowerCase();
12501
+ if (name === "htmlfor" || name === "for") return false;
12502
+ if (name === "id") return false;
12503
+ if (name.startsWith("aria-")) return false;
12504
+ }
12505
+ return true;
12506
+ }
12507
+ function inspectChildren(children, facts) {
12508
+ for (const child of children) {
12509
+ switch (child.type) {
12510
+ case "JSXText":
12511
+ if (child.value.trim()) facts.text = true;
12512
+ break;
12513
+ case "JSXExpressionContainer":
12514
+ if (child.expression.type !== "JSXEmptyExpression") facts.slot = true;
12515
+ break;
12516
+ case "JSXSpreadChild":
12517
+ facts.slot = true;
12518
+ break;
12519
+ case "JSXFragment":
12520
+ inspectChildren(child.children, facts);
12521
+ break;
12522
+ case "JSXElement": {
12523
+ const name = child.openingElement.name;
12524
+ if (!isNativeTag2(name)) {
12525
+ facts.component = true;
12526
+ break;
12527
+ }
12528
+ if (BANNED_CHILD_TAGS.has(tagName3(name))) {
12529
+ facts.control = true;
12530
+ break;
12531
+ }
12532
+ inspectChildren(child.children, facts);
12533
+ break;
12534
+ }
12535
+ }
12536
+ }
12537
+ }
12538
+ function fieldAfter(labelEnd, openings) {
12539
+ for (const opening of openings) {
12540
+ const start = opening.start ?? 0;
12541
+ if (start < labelEnd) continue;
12542
+ if (start - labelEnd > CONTROL_WINDOW) break;
12543
+ if (!isNativeTag2(opening.name)) continue;
12544
+ const tag = tagName3(opening.name);
12545
+ if (tag === "label") return null;
12546
+ if (CONTROL_TAGS.has(tag)) return opening;
12547
+ }
12548
+ return null;
12549
+ }
12550
+ function fieldIsNamed(opening) {
12551
+ for (const attr of opening.attributes) {
12552
+ if (attr.type !== "JSXAttribute") continue;
12553
+ const name = attributeName3(attr).toLowerCase();
12554
+ if (name === "aria-label" || name === "aria-labelledby") return true;
12555
+ if (name === "type" && attributeString(attr) === "hidden") return true;
12556
+ }
12557
+ return false;
12558
+ }
12559
+ var unassociatedLabel = {
12560
+ id: "QA008",
12561
+ title: "A label that names nothing",
12562
+ severity: "low",
12563
+ category: "Accessibility",
12564
+ description: "This <label> has no htmlFor and no id, and the field beside it carries no name of its own, so the two are never connected. Clicking the text does not focus the field, a screen reader announces the input as unlabelled, voice control has no name to address it by, and browser autofill loses the hint it uses to fill the form.",
12565
+ fix: 'Give the field an id and point the label at it \u2014 <label htmlFor="email">Email</label><input id="email" />. Wrapping the input inside the label works too and needs no ids.',
12566
+ precisionNotes: 'JSX files only, outside tests/docs/examples; the label must be non-self-closing with no htmlFor/for, no id, no aria-* and no spread; its children must be literal text with no {expression}, no nested control and no capitalised component; a NATIVE input/select/textarea must follow within ~200 characters with no other <label> intervening; that field must not carry aria-label/aria-labelledby or type="hidden"; and the whole rule stands down if the repo already runs eslint-plugin-jsx-a11y. Each clause removes a class of correct code: for= in non-JSX templates, aria-labelledby pairs, prop-forwarding wrappers, slot children, implicit wrapping, and design-system fields that thread their own id.',
12567
+ check(ctx) {
12568
+ const hits = [];
12569
+ if (repoLintsA11y(ctx)) return hits;
12570
+ for (const file of ctx.files) {
12571
+ if (file.excluded) continue;
12572
+ if (!/\.(?:jsx|tsx)$/i.test(file.path)) continue;
12573
+ if (DOC_PATH.test(file.path)) continue;
12574
+ const parsed = file.parsed;
12575
+ if (!parsed) continue;
12576
+ if (parsed.language !== "jsx" && parsed.language !== "tsx") continue;
12577
+ const elements = [];
12578
+ const openings = [];
12579
+ walkNodes3(parsed.ast.program, (node) => {
12580
+ if (node.type === "JSXElement") elements.push(node);
12581
+ else if (node.type === "JSXOpeningElement") openings.push(node);
12582
+ });
12583
+ openings.sort((a, b) => (a.start ?? 0) - (b.start ?? 0));
12584
+ for (const element of elements) {
12585
+ const opening = element.openingElement;
12586
+ if (!isNativeTag2(opening.name) || tagName3(opening.name) !== "label") continue;
12587
+ if (opening.selfClosing) continue;
12588
+ if (!isBareLabel(opening)) continue;
12589
+ const facts = { text: false, slot: false, control: false, component: false };
12590
+ inspectChildren(element.children, facts);
12591
+ if (!facts.text || facts.slot || facts.control || facts.component) continue;
12592
+ if (element.end == null) continue;
12593
+ const field = fieldAfter(element.end, openings);
12594
+ if (!field) continue;
12595
+ if (fieldIsNamed(field)) continue;
12596
+ const line = opening.loc?.start.line ?? lineAt(file.content, opening.start ?? 0);
12597
+ hits.push({ file: file.path, line });
12598
+ }
12599
+ }
12600
+ return hits;
12601
+ }
12602
+ };
12603
+
12604
+ // src/quality/index.ts
12605
+ var qualityRules = [
12606
+ silentFailedRead,
12607
+ silentFailedWrite,
12608
+ stateBeforeEffect,
12609
+ failOpenSecretComparison,
12610
+ mouseOnlyControl,
12611
+ undeclaredModal,
12612
+ unboundedList,
12613
+ unassociatedLabel
12614
+ ];
12615
+ function scanQuality(files, rules = qualityRules) {
12616
+ const ctx = buildQualityContext(files);
12617
+ const findings = [];
12618
+ for (const rule of rules) {
12619
+ let hits;
12620
+ try {
12621
+ hits = rule.check(ctx);
12622
+ } catch {
12623
+ continue;
12624
+ }
12625
+ for (const hit of hits) {
12626
+ const file = ctx.byPath.get(hit.file);
12627
+ findings.push({
12628
+ id: `${rule.id}-${hit.file}:${hit.line}`,
12629
+ rule: rule.id,
12630
+ severity: rule.severity,
12631
+ // Every rule here shipped only with a narrowing that survived an
12632
+ // adversarial review, but none of them is a proof. "high" would put
12633
+ // them beside confirmed secrets.
12634
+ confidence: "medium",
12635
+ title: rule.title,
12636
+ description: hit.detail ?? rule.description,
12637
+ file: hit.file,
12638
+ line: hit.line,
12639
+ snippet: file ? getSnippet(file.content, hit.line) : "",
12640
+ fix: rule.fix,
12641
+ category: rule.category,
12642
+ source: "custom"
12643
+ });
12644
+ }
12645
+ }
12646
+ return findings;
12647
+ }
10346
12648
  // Annotate the CommonJS export names for ESM import in node:
10347
12649
  0 && (module.exports = {
10348
12650
  CHECKABLE_CLAIMS,
@@ -10356,6 +12658,7 @@ function extractScriptUrls(html, pageUrl, limit = 12) {
10356
12658
  NON_APP_PATH_PATTERNS,
10357
12659
  PRO_RULE_COUNT,
10358
12660
  RULE_IMPACTS,
12661
+ TEST_FILE_PATTERN,
10359
12662
  TOTAL_RULE_COUNT,
10360
12663
  accountStateFromWebStorage,
10361
12664
  allCustomRules,
@@ -10511,6 +12814,7 @@ function extractScriptUrls(html, pageUrl, limit = 12) {
10511
12814
  llmSystemPromptInjection,
10512
12815
  logInjection,
10513
12816
  magicNumbers,
12817
+ maskComments,
10514
12818
  massAssignment,
10515
12819
  middlewareMatcherExcludesApi,
10516
12820
  missingAIRateLimit,
@@ -10556,6 +12860,7 @@ function extractScriptUrls(html, pageUrl, limit = 12) {
10556
12860
  pyParamikoAutoAdd,
10557
12861
  pyRequestsVerifyFalse,
10558
12862
  pyTempfileMktemp,
12863
+ qualityRules,
10559
12864
  raceCondition,
10560
12865
  rdsPubliclyAccessible,
10561
12866
  reflectedCORSOrigin,
@@ -10564,6 +12869,7 @@ function extractScriptUrls(html, pageUrl, limit = 12) {
10564
12869
  runCustomRules,
10565
12870
  s3BucketNoEncryption,
10566
12871
  scanEntropy,
12872
+ scanQuality,
10567
12873
  secretInBundleConfig,
10568
12874
  secretInCLIArgument,
10569
12875
  secretInErrorResponse,