xploitscan-shared-rules 1.30.0 → 1.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -12403,6 +12403,493 @@ var failedReadEmptyState = {
12403
12403
  }
12404
12404
  };
12405
12405
 
12406
+ // src/quality/rules/autosave-armed-by-failed-load.ts
12407
+ import _traverse5 from "@babel/traverse";
12408
+ var traverse5 = typeof _traverse5 === "function" ? _traverse5 : _traverse5.default;
12409
+ var PERSISTENT_WRITE = /\bfetch\s*\([^)]{0,400}?method\s*:\s*["'`](?:POST|PUT|PATCH)["'`]|\blocalStorage\s*\.\s*setItem\s*\(|\bsessionStorage\s*\.\s*setItem\s*\(/is;
12410
+ var EMPTY_INITIAL = /\buseState\s*(?:<[^>]*>)?\s*\(\s*(?:\[\s*\]|\{\s*\}|""|''|``)\s*\)/;
12411
+ function calleeIdentifier(node) {
12412
+ if (node.type !== "CallExpression") return null;
12413
+ const c = node.callee;
12414
+ if (c.type === "Identifier") return c.name;
12415
+ if (c.type === "MemberExpression" && c.property.type === "Identifier") return c.property.name;
12416
+ return null;
12417
+ }
12418
+ function isEffectCall2(node) {
12419
+ const name = calleeIdentifier(node);
12420
+ return name === "useEffect" || name === "useLayoutEffect";
12421
+ }
12422
+ function stateFromSetter(setter) {
12423
+ const m = /^set([A-Z][A-Za-z0-9_]*)$/.exec(setter);
12424
+ if (!m) return null;
12425
+ return m[1].charAt(0).toLowerCase() + m[1].slice(1);
12426
+ }
12427
+ function identifiersIn(path) {
12428
+ const names = /* @__PURE__ */ new Set();
12429
+ path.traverse({
12430
+ Identifier(id) {
12431
+ names.add(id.node.name);
12432
+ }
12433
+ });
12434
+ const n = path.node;
12435
+ if (n.type === "Identifier" && n.name) names.add(n.name);
12436
+ return names;
12437
+ }
12438
+ var autosaveArmedByFailedLoad = {
12439
+ id: "QA010",
12440
+ title: "Autosave is armed by a load that failed",
12441
+ severity: "high",
12442
+ category: "Correctness",
12443
+ description: "The flag that permits this component to write the user's state back is set in a `finally`, so a load that failed arms it exactly like one that succeeded \u2014 while the component is still holding the empty values it initialised with. Opening the page during a blip is enough to write those empties over whatever the user had saved, and the write looks like any other.",
12444
+ fix: "Set the arming flag on the success path only, and record the failure in its own state. The component can stay readable and interactive; it just must not write anything back until a load actually succeeds.",
12445
+ precisionNotes: 'Fires on the ARMING, not on a missing guard: the shipped defect had a guard (`if (stateLoaded && !stateLoadFailed) saveState()`), and a rule keyed on unguarded writes would have missed it while reporting every correct autosave. Requires all of: a client file; a `useEffect` whose body reaches a persistent write (fetch with POST/PUT/PATCH, or localStorage/sessionStorage.setItem) either directly or through a same-file callback it names; that write gated on an identifier; a `set<Identifier>` for that same identifier called inside a `finally` block; and at least one `useState` in the file initialised to an empty literal \u2014 `[]`, `{}` or `""`, never `0`, because the empty literal is what turns "wrote too early" into "erased what was there". The join between the finally-set flag and the write\'s guard is the whole narrowing: `finally { setLoading(false) }` is everywhere and correct, and is only reportable when that same flag is what permits the write.',
12446
+ check(ctx) {
12447
+ const hits = [];
12448
+ for (const file of ctx.files) {
12449
+ if (file.excluded) continue;
12450
+ if (!file.isClient) continue;
12451
+ if (file.isServer) continue;
12452
+ const parsed = file.parsed;
12453
+ if (!parsed) continue;
12454
+ if (!EMPTY_INITIAL.test(file.code)) continue;
12455
+ const armedInFinally = /* @__PURE__ */ new Map();
12456
+ traverse5(parsed.ast, {
12457
+ TryStatement(path) {
12458
+ const finalizer = path.get("finalizer");
12459
+ if (!finalizer || Array.isArray(finalizer) || !finalizer.node) return;
12460
+ finalizer.traverse({
12461
+ CallExpression(call) {
12462
+ const name = calleeIdentifier(call.node);
12463
+ if (!name) return;
12464
+ const state = stateFromSetter(name);
12465
+ if (!state) return;
12466
+ armedInFinally.set(state, nodeStart(call.node));
12467
+ }
12468
+ });
12469
+ }
12470
+ });
12471
+ if (armedInFinally.size === 0) continue;
12472
+ const writingFunctions = /* @__PURE__ */ new Set();
12473
+ traverse5(parsed.ast, {
12474
+ Function(path) {
12475
+ const src = file.code.slice(nodeStart(path.node), nodeEnd(path.node));
12476
+ if (!PERSISTENT_WRITE.test(src)) return;
12477
+ let owner = path.parentPath;
12478
+ for (let hops = 0; owner && hops < 3; hops++, owner = owner.parentPath) {
12479
+ const node = owner.node;
12480
+ if (node.type === "VariableDeclarator" && node.id.type === "Identifier") {
12481
+ writingFunctions.add(node.id.name);
12482
+ break;
12483
+ }
12484
+ if (node.type !== "CallExpression") break;
12485
+ }
12486
+ const n = path.node;
12487
+ if (n.id && n.id.name) writingFunctions.add(n.id.name);
12488
+ }
12489
+ });
12490
+ const reported = /* @__PURE__ */ new Set();
12491
+ traverse5(parsed.ast, {
12492
+ CallExpression(path) {
12493
+ if (!isEffectCall2(path.node)) return;
12494
+ const cb = path.get("arguments.0");
12495
+ if (!cb || !cb.node) return;
12496
+ const body = file.code.slice(nodeStart(cb.node), nodeEnd(cb.node));
12497
+ const names = identifiersIn(cb);
12498
+ const writesDirectly = PERSISTENT_WRITE.test(body);
12499
+ const writesViaCallback = [...writingFunctions].some((fn) => names.has(fn));
12500
+ if (!writesDirectly && !writesViaCallback) return;
12501
+ for (const [state, armLine] of armedInFinally) {
12502
+ if (!names.has(state)) continue;
12503
+ if (reported.has(state)) continue;
12504
+ if (!new RegExp(`\\bif\\s*\\([^)]*\\b${state}\\b`).test(body)) continue;
12505
+ reported.add(state);
12506
+ hits.push({
12507
+ file: file.path,
12508
+ line: lineAt(file.content, armLine),
12509
+ detail: `\`${state}\` is what permits this component to write the user's state back, and it is set in a \`finally\` \u2014 so a load that threw arms the write exactly like one that succeeded, while the component still holds its initial empty values.`
12510
+ });
12511
+ }
12512
+ }
12513
+ });
12514
+ }
12515
+ return hits;
12516
+ }
12517
+ };
12518
+
12519
+ // src/quality/rules/config-skipped-work.ts
12520
+ import _traverse6 from "@babel/traverse";
12521
+ var traverse6 = typeof _traverse6 === "function" ? _traverse6 : _traverse6.default;
12522
+ var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
12523
+ var DURABLE_WRITE = /\b(?:INSERT\s+INTO|UPDATE\s+\w|DELETE\s+FROM)\b|\bprisma\s*\.\s*\w+\s*\.\s*(?:create|createMany|update|updateMany|delete|deleteMany|upsert)\s*\(|\.from\s*\([^)]*\)\s*\.\s*(?:insert|update|delete|upsert)\s*\(|\b(?:db|tx|trx)\s*\.\s*(?:insert|update|delete)\s*\(/i;
12524
+ var EXTERNAL_MUTATION = /\b\w+\s*\.\s*\w+\s*\.\s*(?:create|send|update|delete|cancel|charge|capture|refund)\s*\(|\bfetch\s*\([^)]{0,300}?method\s*:\s*["'`](?:POST|PUT|PATCH|DELETE)["'`]/is;
12525
+ var BOOKKEEPING = /analytics|telemetry|track|metric|event|beacon|log|audit|ping/i;
12526
+ var DIRECT_ENV_TEST = /\bprocess\s*\.\s*env\b|\bDeno\s*\.\s*env\s*\.\s*get\s*\(/;
12527
+ function calleeName3(node) {
12528
+ if (node.type !== "CallExpression") return null;
12529
+ const c = node.callee;
12530
+ if (c.type === "Identifier") return c.name;
12531
+ if (c.type === "MemberExpression" && c.property.type === "Identifier") return c.property.name;
12532
+ return null;
12533
+ }
12534
+ function keyShape(node) {
12535
+ if (!node || node.type !== "ObjectExpression") return null;
12536
+ const keys = [];
12537
+ for (const prop of node.properties) {
12538
+ if (prop.type === "ObjectProperty" && prop.key.type === "Identifier") keys.push(prop.key.name);
12539
+ else if (prop.type === "ObjectProperty" && prop.key.type === "StringLiteral") keys.push(prop.key.value);
12540
+ else return null;
12541
+ }
12542
+ return keys.sort().join(",");
12543
+ }
12544
+ function successPayloadShape(ret, source, offset) {
12545
+ const arg = ret.argument;
12546
+ if (!arg || arg.type !== "CallExpression") return null;
12547
+ const text = source.slice(nodeStart(ret) - offset, nodeEnd(ret) - offset);
12548
+ if (/status\s*:\s*[45]\d\d|,\s*\{\s*status\s*:\s*[45]\d\d/.test(text)) return null;
12549
+ const name = calleeName3(arg);
12550
+ if (name !== "json" && name !== "Response" && name !== "NextResponse") return null;
12551
+ const first = arg.arguments[0];
12552
+ if (!first) return null;
12553
+ if (first.type === "CallExpression" && calleeName3(first) === "stringify") {
12554
+ return keyShape(first.arguments[0]);
12555
+ }
12556
+ return keyShape(first);
12557
+ }
12558
+ var configSkippedWork = {
12559
+ id: "QA011",
12560
+ title: "Success is reported for work a missing setting skipped",
12561
+ severity: "high",
12562
+ category: "Correctness",
12563
+ description: "When this setting is absent the handler returns early \u2014 with the same success payload it returns when the work actually happened. The caller cannot tell the two apart, so a request that did nothing is reported as one that did: the row was never written, and whoever asked is told it was.",
12564
+ fix: "Answer differently when the work was skipped. Either fail with a non-2xx so the caller can retry, or return a payload that says what did not happen. Returning the success shape is only correct if the success actually occurred.",
12565
+ precisionNotes: 'The claim is not "an env var might be unset" \u2014 that is a deployment-convention judgement, and unshippable. It is "the guarded response is byte-indistinguishable from the success response", which is decidable from the file, and it is the sharpest clause: the shapes are compared as sorted top-level key sets, and a spread makes the shape undecidable so the rule declines rather than guesses. On top of that: exported POST/PUT/PATCH/DELETE only; the absence test must read process.env/Deno.env directly or test a local bound from a ZERO-ARG accessor (`getTenantDb(orgId)` is a per-tenant fact, not a config fact); the guard must DOMINATE the effects \u2014 no durable write and no external mutating call before it, at least one durable write after it, which kills both the cache-invalidation handler with no durable effect at all and the handler whose primary insert already happened; and bookkeeping vocabulary (analytics, telemetry, audit, log, metric, ping) on the route path, the accessor name or the target noun is exonerated, because a skipped audit row is the app lying about its own records rather than about the user\'s work.',
12566
+ check(ctx) {
12567
+ const hits = [];
12568
+ for (const file of ctx.files) {
12569
+ if (file.excluded) continue;
12570
+ if (!file.isServer) continue;
12571
+ if (BOOKKEEPING.test(file.path)) continue;
12572
+ const parsed = file.parsed;
12573
+ if (!parsed) continue;
12574
+ traverse6(parsed.ast, {
12575
+ Function(path) {
12576
+ const node = path.node;
12577
+ let name = node.id?.name ?? null;
12578
+ if (!name && path.parent.type === "VariableDeclarator" && path.parent.id.type === "Identifier") {
12579
+ name = path.parent.id.name;
12580
+ }
12581
+ if (!name || !MUTATING_METHODS.has(name)) return;
12582
+ const fnStart = nodeStart(path.node);
12583
+ const fnSource = file.code.slice(fnStart, nodeEnd(path.node));
12584
+ let terminal = null;
12585
+ const guards = [];
12586
+ path.traverse({
12587
+ ReturnStatement(ret) {
12588
+ const shape = successPayloadShape(ret.node, file.code, 0);
12589
+ if (shape === null) return;
12590
+ const start = nodeStart(ret.node);
12591
+ const ifPath = ret.findParent((p) => p.isIfStatement());
12592
+ if (ifPath) {
12593
+ const test = file.code.slice(nodeStart(ifPath.node.test), nodeEnd(ifPath.node.test));
12594
+ if (isConfigAbsenceTest(test, ifPath, file.code)) {
12595
+ guards.push({ shape, start, test });
12596
+ return;
12597
+ }
12598
+ }
12599
+ if (!terminal || start > terminal.start) terminal = { shape, start };
12600
+ }
12601
+ });
12602
+ if (!terminal || guards.length === 0) return;
12603
+ const term = terminal;
12604
+ for (const guard of guards) {
12605
+ if (guard.shape !== term.shape) continue;
12606
+ if (BOOKKEEPING.test(guard.test)) continue;
12607
+ const before = file.code.slice(fnStart, guard.start);
12608
+ const after = file.code.slice(guard.start, nodeEnd(path.node));
12609
+ if (DURABLE_WRITE.test(before)) continue;
12610
+ if (EXTERNAL_MUTATION.test(before)) continue;
12611
+ if (!DURABLE_WRITE.test(after)) continue;
12612
+ const writeMatch = DURABLE_WRITE.exec(after);
12613
+ if (writeMatch && BOOKKEEPING.test(after.slice(writeMatch.index, writeMatch.index + 120))) continue;
12614
+ hits.push({
12615
+ file: file.path,
12616
+ line: lineAt(file.content, guard.start),
12617
+ detail: `This early return answers with the same payload shape (\`{${guard.shape}}\`) as the handler's success return, so a caller cannot tell that the work was skipped. ${fnSource.length > 0 ? "" : ""}The write below it never runs, and whoever made the request is told it did.`
12618
+ });
12619
+ break;
12620
+ }
12621
+ }
12622
+ });
12623
+ }
12624
+ return hits;
12625
+ }
12626
+ };
12627
+ function isConfigAbsenceTest(test, ifPath, code) {
12628
+ if (DIRECT_ENV_TEST.test(test)) return true;
12629
+ const m = /^!\s*([A-Za-z_$][\w$]*)$/.exec(test.trim());
12630
+ if (!m) return false;
12631
+ const local = m[1];
12632
+ const fn = ifPath.getFunctionParent();
12633
+ if (!fn) return false;
12634
+ const scope = code.slice(nodeStart(fn.node), nodeEnd(fn.node));
12635
+ return new RegExp(`\\b(?:const|let|var)\\s+${local}\\s*=\\s*(?:await\\s+)?[A-Za-z_$][\\w$]*\\s*\\(\\s*\\)`).test(scope);
12636
+ }
12637
+
12638
+ // src/quality/rules/stale-response-wins.ts
12639
+ import _traverse7 from "@babel/traverse";
12640
+ var traverse7 = typeof _traverse7 === "function" ? _traverse7 : _traverse7.default;
12641
+ var ORDERING_GUARD = /\breturn\s*\(\s*\)\s*=>|\bAbortController\b|\bsignal\b|\bcancell?ed\b|\bignore\b|\bstale\b|\bisMounted\b|\baborted\b/i;
12642
+ var SETTER2 = /^set[A-Z][A-Za-z0-9_]*$/;
12643
+ function calleeIdentifier2(node) {
12644
+ if (node.type !== "CallExpression") return null;
12645
+ const c = node.callee;
12646
+ if (c.type === "Identifier") return c.name;
12647
+ if (c.type === "MemberExpression" && c.property.type === "Identifier") return c.property.name;
12648
+ return null;
12649
+ }
12650
+ function isEffectCall3(node) {
12651
+ const n = calleeIdentifier2(node);
12652
+ return n === "useEffect" || n === "useLayoutEffect";
12653
+ }
12654
+ function templateIdentifiers(node) {
12655
+ if (node.type !== "TemplateLiteral") return [];
12656
+ const out = [];
12657
+ for (const expr of node.expressions) {
12658
+ collectIdentifiers(expr, out);
12659
+ }
12660
+ return out;
12661
+ }
12662
+ function collectIdentifiers(node, out) {
12663
+ if (!node || typeof node !== "object") return;
12664
+ if (node.type === "Identifier") {
12665
+ out.push(node.name);
12666
+ return;
12667
+ }
12668
+ for (const key of Object.keys(node)) {
12669
+ if (key === "loc" || key === "leadingComments" || key === "trailingComments") continue;
12670
+ const v = node[key];
12671
+ if (Array.isArray(v)) v.forEach((c) => c && typeof c === "object" && collectIdentifiers(c, out));
12672
+ else if (v && typeof v === "object" && "type" in v) collectIdentifiers(v, out);
12673
+ }
12674
+ }
12675
+ function derivesFromDep(name, deps, effect, code) {
12676
+ if (deps.has(name)) return true;
12677
+ let found = false;
12678
+ const seen = /* @__PURE__ */ new Set([name]);
12679
+ const frontier = [name];
12680
+ for (let depth = 0; depth < 4 && frontier.length && !found; depth++) {
12681
+ const current = frontier.splice(0, frontier.length);
12682
+ for (const target of current) {
12683
+ effect.traverse({
12684
+ VariableDeclarator(p) {
12685
+ if (found) return;
12686
+ if (p.node.id.type !== "Identifier" || p.node.id.name !== target) return;
12687
+ if (!p.node.init) return;
12688
+ const names = [];
12689
+ collectIdentifiers(p.node.init, names);
12690
+ for (const n of names) {
12691
+ if (deps.has(n)) {
12692
+ found = true;
12693
+ return;
12694
+ }
12695
+ if (!seen.has(n)) {
12696
+ seen.add(n);
12697
+ frontier.push(n);
12698
+ }
12699
+ }
12700
+ },
12701
+ AssignmentExpression(p) {
12702
+ if (found) return;
12703
+ if (p.node.left.type !== "Identifier" || p.node.left.name !== target) return;
12704
+ const names = [];
12705
+ collectIdentifiers(p.node.right, names);
12706
+ for (const n of names) {
12707
+ if (deps.has(n)) {
12708
+ found = true;
12709
+ return;
12710
+ }
12711
+ if (!seen.has(n)) {
12712
+ seen.add(n);
12713
+ frontier.push(n);
12714
+ }
12715
+ }
12716
+ }
12717
+ });
12718
+ }
12719
+ }
12720
+ return found;
12721
+ }
12722
+ var staleResponseWins = {
12723
+ id: "QA012",
12724
+ title: "A stale response can overwrite a newer one",
12725
+ severity: "medium",
12726
+ category: "Correctness",
12727
+ description: "This effect refetches whenever the user changes their selection, and does nothing to cancel the request already in flight. Pick one thing, then another before the first answers, and the first response lands last and wins: the selector says one thing and the panel shows another. Nothing errors, the data is real \u2014 it is just the wrong data, and it stays wrong until the next interaction.",
12728
+ fix: "Return a cleanup function from the effect that makes the late response a no-op \u2014 set a `cancelled` flag the `.then` checks, or abort the request with an AbortController and pass its `signal` to fetch. React calls the cleanup before it re-runs the effect, which is exactly when the older request becomes irrelevant.",
12729
+ precisionNotes: 'Two clauses came from being wrong. The first draft asked whether the interpolated identifier was ASSIGNED INSIDE THE EFFECT, which an effect-local constant satisfies (`const base = process.env.NEXT_PUBLIC_API ?? ""`), so it fired on URLs that cannot vary between renders; what matters is that the identifier is DERIVED FROM A DEPENDENCY, since only a dependency can change mid-flight. The second: an identifier REFERENCED AGAIN AFTER the network call is the signature of code that already handles ordering \u2014 the keyed write `setCache(prev => ({ ...prev, [id]: data }))`, where out-of-order arrival is harmless, and the hand-rolled `if (latest.current === id) setScan(data)`, which is a cleanup function written by hand. Neither mentions cancelled/AbortController/signal, so nothing else excludes them. Also required: a non-empty dep array, a literal `fetch(`, a state setter after it, and the dependency must be a useState in this file wired to an onChange \u2014 the strict form, because relaxing it to "or any dep" reopens the child that fetches on a prop whose parent remounts it with a `key`, and that remount is invisible from the child\'s file. Frequency is this rule\'s weak point and is worth stating: two distinct defects, one codebase, one author. Shipped at medium for that reason.',
12730
+ check(ctx) {
12731
+ const hits = [];
12732
+ for (const file of ctx.files) {
12733
+ if (file.excluded) continue;
12734
+ if (!file.isClient) continue;
12735
+ if (file.isServer) continue;
12736
+ const parsed = file.parsed;
12737
+ if (!parsed) continue;
12738
+ traverse7(parsed.ast, {
12739
+ CallExpression(path) {
12740
+ if (!isEffectCall3(path.node)) return;
12741
+ const args = path.node.arguments;
12742
+ const cbNode = args[0];
12743
+ const depNode = args[1];
12744
+ if (!cbNode || !depNode || depNode.type !== "ArrayExpression") return;
12745
+ if (depNode.elements.length === 0) return;
12746
+ const deps = /* @__PURE__ */ new Set();
12747
+ for (const el of depNode.elements) {
12748
+ if (el && el.type === "Identifier") deps.add(el.name);
12749
+ }
12750
+ if (deps.size === 0) return;
12751
+ const cb = path.get("arguments.0");
12752
+ if (!cb || !cb.node) return;
12753
+ const bodyStart = nodeStart(cb.node);
12754
+ const bodySource = file.code.slice(bodyStart, nodeEnd(cb.node));
12755
+ if (ORDERING_GUARD.test(bodySource)) return;
12756
+ let hit = null;
12757
+ cb.traverse({
12758
+ CallExpression(inner) {
12759
+ if (hit) return;
12760
+ if (!isFetchCallee(inner.node.callee)) return;
12761
+ const url = inner.node.arguments[0];
12762
+ if (!url) return;
12763
+ const interpolated = templateIdentifiers(url);
12764
+ if (interpolated.length === 0) return;
12765
+ const callEnd = nodeEnd(inner.node);
12766
+ const afterCall = file.code.slice(callEnd, nodeEnd(cb.node));
12767
+ let setsState = false;
12768
+ cb.traverse({
12769
+ CallExpression(c) {
12770
+ if (setsState) return;
12771
+ if (nodeStart(c.node) < callEnd) return;
12772
+ const n = calleeIdentifier2(c.node);
12773
+ if (n && SETTER2.test(n)) setsState = true;
12774
+ }
12775
+ });
12776
+ if (!setsState) return;
12777
+ for (const ident2 of interpolated) {
12778
+ if (!derivesFromDep(ident2, deps, cb, file.code)) continue;
12779
+ if (new RegExp(`\\b${ident2}\\b`).test(afterCall)) continue;
12780
+ if (![...deps].some((d) => userDriven(d, file.code))) continue;
12781
+ hit = { line: lineAt(file.content, nodeStart(inner.node)), ident: ident2 };
12782
+ return;
12783
+ }
12784
+ }
12785
+ });
12786
+ if (!hit) return;
12787
+ const { line, ident } = hit;
12788
+ hits.push({
12789
+ file: file.path,
12790
+ line,
12791
+ detail: `This request's URL depends on \`${ident}\`, which changes when the user does, and the effect returns no cleanup \u2014 so a response for the previous selection can arrive after the current one and overwrite it. The screen then shows data that does not match the control above it.`
12792
+ });
12793
+ }
12794
+ });
12795
+ }
12796
+ return hits;
12797
+ }
12798
+ };
12799
+ function userDriven(dep, code) {
12800
+ const setter = `set${dep.charAt(0).toUpperCase()}${dep.slice(1)}`;
12801
+ if (!new RegExp(`\\[\\s*${dep}\\s*,\\s*${setter}\\s*\\]\\s*=\\s*useState`).test(code)) return false;
12802
+ return new RegExp(`on(?:Change|Click|Input|Select)\\s*=\\s*\\{[^}]{0,200}\\b${setter}\\b`, "s").test(code);
12803
+ }
12804
+
12805
+ // src/quality/rules/lost-update-counter.ts
12806
+ import _traverse8 from "@babel/traverse";
12807
+ var traverse8 = typeof _traverse8 === "function" ? _traverse8 : _traverse8.default;
12808
+ var COUNTER_COLUMN = /^(?:credits?|balance|stock|quantity|qty|tokens?|seats?|points?|inventory|remaining|available)$/i;
12809
+ var WRITE_CALL = /\bUPDATE\s+\w|\.\s*update\s*\(|\.\s*set\s*\(|\bprisma\s*\.\s*\w+\s*\.\s*update\b/i;
12810
+ var ATOMIC_OR_SERIALISED = /\b(?:increment|decrement)\s*:|\bsql`[^`]*\b\w+\s*[-+]\s*|\bSET\s+(\w+)\s*=\s*\1\s*[-+]|\.\s*rpc\s*\(|\btransaction\s*\(|\bBEGIN\s+IMMEDIATE\b|\bFOR\s+UPDATE\b|\block\s*\.\s*acquire\s*\(|\bmutex\b|\bredlock\b|\bWHERE[^;]{0,120}\b\w+\s*=\s*\?[^;]{0,40}\bAND\b[^;]{0,120}\bversion\b/i;
12811
+ var SCHEDULED_PATH = /(?:^|\/)(?:cron|jobs?|scheduled|tasks?|workers?)\//i;
12812
+ var INSERT_RETURNING = /\bINSERT\b[\s\S]{0,400}?\bRETURNING\b/i;
12813
+ function memberColumn(node) {
12814
+ if (node.type !== "MemberExpression" && node.type !== "OptionalMemberExpression") return null;
12815
+ const prop = node.property;
12816
+ if (prop.type !== "Identifier") return null;
12817
+ return COUNTER_COLUMN.test(prop.name) ? prop.name : null;
12818
+ }
12819
+ function rootObject(node) {
12820
+ let cur = node;
12821
+ while (cur.type === "MemberExpression" || cur.type === "OptionalMemberExpression") {
12822
+ cur = cur.object;
12823
+ }
12824
+ return cur.type === "Identifier" ? cur.name : null;
12825
+ }
12826
+ var MAX_PER_SCAN2 = 3;
12827
+ var lostUpdateCounter = {
12828
+ id: "QA013",
12829
+ title: "A balance is read, changed in JavaScript, and written back",
12830
+ severity: "high",
12831
+ category: "Correctness",
12832
+ description: "This reads the current value, does the arithmetic in the application, and writes the result back. Two requests that arrive together both read the same starting value and both write the same answer, so one of the two changes is lost \u2014 a spend that was never charged, or stock sold twice. The window is the round trip between the read and the write, and nothing about it shows up in development, where requests arrive one at a time.",
12833
+ fix: "Let the database do the arithmetic, so the read and the write are one statement: `UPDATE users SET credits = credits - 1 WHERE id = ? AND credits >= 1`, or the ORM's atomic form (`{ credits: { decrement: 1 } }`). Check the affected row count to find out whether it applied. A transaction or an explicit lock also works.",
12834
+ precisionNotes: "NOT ENABLED BY DEFAULT \u2014 its false-positive rate is unmeasured, not low. This repository contains no counters at all, so its 0 fires are 0 out of 0, and every other rule in this catalogue quotes a real denominator. It ships so it can be run against a corpus that contains counters. The narrowing, for when it is: the column must be on a short money/inventory allowlist, because a denormalised comment_count reconciled nightly loses an update and nobody cares, and only money and inventory make the consequence sentence true; the read local must be a DIRECT operand of `+`/`-`, so an idempotent absolute assignment computed from a plan table is not reported; exonerate on any atomic or serialised form (ORM increment/decrement, SQL arithmetic, .rpc(, a transaction, an explicit lock, FOR UPDATE, an optimistic version predicate); exonerate when the db handle is a PARAMETER of the enclosing function, because the caller opened the transaction; exonerate a read that is a RETURNING from an INSERT in the same function, since the row was created here; and skip cron and job paths, which have one invocation and no concurrent writer. Capped at one finding per file and three per scan, the volume discipline QA006 already uses.",
12835
+ check(ctx) {
12836
+ const hits = [];
12837
+ for (const file of ctx.files) {
12838
+ if (hits.length >= MAX_PER_SCAN2) break;
12839
+ if (file.excluded) continue;
12840
+ if (!file.isServer) continue;
12841
+ if (SCHEDULED_PATH.test(file.path)) continue;
12842
+ const parsed = file.parsed;
12843
+ if (!parsed) continue;
12844
+ let firedInFile = false;
12845
+ traverse8(parsed.ast, {
12846
+ BinaryExpression(path) {
12847
+ if (firedInFile || hits.length >= MAX_PER_SCAN2) return;
12848
+ const op = path.node.operator;
12849
+ if (op !== "+" && op !== "-") return;
12850
+ const left = path.node.left;
12851
+ const right = path.node.right;
12852
+ const column = memberColumn(left) ?? memberColumn(right);
12853
+ if (!column) return;
12854
+ const readLocal = rootObject(memberColumn(left) ? left : right);
12855
+ if (!readLocal) return;
12856
+ const fn = path.getFunctionParent();
12857
+ if (!fn) return;
12858
+ const fnSource = file.code.slice(nodeStart(fn.node), nodeEnd(fn.node));
12859
+ if (!WRITE_CALL.test(fnSource)) return;
12860
+ let serialised = false;
12861
+ for (let scope = fn; scope !== null && !serialised; scope = scope.getFunctionParent()) {
12862
+ const src = file.code.slice(nodeStart(scope.node), nodeEnd(scope.node));
12863
+ if (ATOMIC_OR_SERIALISED.test(src)) serialised = true;
12864
+ }
12865
+ if (serialised) return;
12866
+ if (INSERT_RETURNING.test(fnSource)) return;
12867
+ if (handleIsParameter(fn, fnSource)) return;
12868
+ if (!new RegExp(`\\b(?:const|let|var)\\s+(?:\\{[^}]*\\}|${readLocal})\\s*=\\s*await\\b`).test(fnSource)) return;
12869
+ firedInFile = true;
12870
+ hits.push({
12871
+ file: file.path,
12872
+ line: lineAt(file.content, nodeStart(path.node)),
12873
+ detail: `\`${readLocal}.${column}\` is read, changed here, and written back, so two requests that arrive together both start from the same value and one of the two changes is lost. Let the database do the arithmetic instead.`
12874
+ });
12875
+ }
12876
+ });
12877
+ }
12878
+ return hits;
12879
+ }
12880
+ };
12881
+ function handleIsParameter(fn, source) {
12882
+ const params = fn.node.params;
12883
+ for (const p of params) {
12884
+ if (p.type !== "Identifier") continue;
12885
+ if (/^(?:tx|trx|db|conn|client|transaction)$/i.test(p.name)) return true;
12886
+ if (new RegExp(`\\b${p.name}\\s*\\.\\s*(?:execute|run|query|update|insert)\\s*\\(`).test(source)) {
12887
+ return true;
12888
+ }
12889
+ }
12890
+ return false;
12891
+ }
12892
+
12406
12893
  // src/quality/examples.ts
12407
12894
  var QUALITY_EXAMPLES = {
12408
12895
  QA001: {
@@ -12466,6 +12953,156 @@ export function ApiKeysSection() {
12466
12953
  };
12467
12954
 
12468
12955
  useEffect(() => { load(); }, []);
12956
+ }`
12957
+ },
12958
+ QA010: {
12959
+ path: "app/checklist/page.tsx",
12960
+ language: "tsx",
12961
+ difference: "The arming flag is set on the success path only and the failure is recorded separately, so a load that threw leaves autosave disarmed and the saved state untouched.",
12962
+ vulnerable: `"use client";
12963
+
12964
+ export function Checklist() {
12965
+ const [overrides, setOverrides] = useState({});
12966
+ const [stateLoaded, setStateLoaded] = useState(false);
12967
+
12968
+ useEffect(() => {
12969
+ (async () => {
12970
+ try {
12971
+ const res = await fetch("/api/checklist");
12972
+ const data = await res.json();
12973
+ if (data.state) setOverrides(data.state.overrides);
12974
+ } catch {
12975
+ // Non-critical
12976
+ } finally {
12977
+ setStateLoaded(true);
12978
+ }
12979
+ })();
12980
+ }, []);
12981
+
12982
+ const saveState = useCallback(() => {
12983
+ fetch("/api/checklist", { method: "POST", body: JSON.stringify({ overrides }) });
12984
+ }, [overrides]);
12985
+
12986
+ useEffect(() => {
12987
+ if (stateLoaded) saveState();
12988
+ }, [overrides, stateLoaded, saveState]);
12989
+ }`,
12990
+ safe: `"use client";
12991
+
12992
+ export function Checklist() {
12993
+ const [overrides, setOverrides] = useState({});
12994
+ const [stateLoaded, setStateLoaded] = useState(false);
12995
+ const [stateLoadFailed, setStateLoadFailed] = useState(false);
12996
+
12997
+ useEffect(() => {
12998
+ (async () => {
12999
+ try {
13000
+ const res = await fetch("/api/checklist");
13001
+ if (!res.ok) throw new Error(\`checklist load failed: HTTP \${res.status}\`);
13002
+ const data = await res.json();
13003
+ if (data.state) setOverrides(data.state.overrides);
13004
+ setStateLoaded(true);
13005
+ } catch {
13006
+ setStateLoadFailed(true);
13007
+ }
13008
+ })();
13009
+ }, []);
13010
+
13011
+ const saveState = useCallback(() => {
13012
+ fetch("/api/checklist", { method: "POST", body: JSON.stringify({ overrides }) });
13013
+ }, [overrides]);
13014
+
13015
+ useEffect(() => {
13016
+ if (stateLoaded && !stateLoadFailed) saveState();
13017
+ }, [overrides, stateLoaded, stateLoadFailed, saveState]);
13018
+ }`
13019
+ },
13020
+ QA011: {
13021
+ path: "app/api/scans/route.ts",
13022
+ language: "typescript",
13023
+ difference: "The skipped path answers 503 with an error instead of the success payload, so the caller can tell the scan was not stored \u2014 and retry.",
13024
+ vulnerable: `export async function POST(request: Request) {
13025
+ const body = await request.json();
13026
+ const id = \`scan_\${Date.now()}\`;
13027
+
13028
+ const db = getDb();
13029
+ if (!db) {
13030
+ // No database configured \u2014 return success anyway
13031
+ return NextResponse.json({ scan: { id } });
13032
+ }
13033
+
13034
+ await db.execute({
13035
+ sql: "INSERT INTO scans (id, findings_json) VALUES (?, ?)",
13036
+ args: [id, JSON.stringify(body.findings)],
13037
+ });
13038
+
13039
+ return NextResponse.json({ scan: { id } });
13040
+ }`,
13041
+ safe: `export async function POST(request: Request) {
13042
+ const body = await request.json();
13043
+ const id = \`scan_\${Date.now()}\`;
13044
+
13045
+ const db = getDb();
13046
+ if (!db) {
13047
+ return NextResponse.json(
13048
+ { error: "Scan storage is not configured \u2014 this scan was not saved." },
13049
+ { status: 503 },
13050
+ );
13051
+ }
13052
+
13053
+ await db.execute({
13054
+ sql: "INSERT INTO scans (id, findings_json) VALUES (?, ?)",
13055
+ args: [id, JSON.stringify(body.findings)],
13056
+ });
13057
+
13058
+ return NextResponse.json({ scan: { id } });
13059
+ }`
13060
+ },
13061
+ QA012: {
13062
+ path: "app/panel/ScanPanel.tsx",
13063
+ language: "tsx",
13064
+ difference: "The effect returns a cleanup that flips `cancelled`, so React disarms the in-flight request before re-running \u2014 a response for the previous selection can no longer land last and win.",
13065
+ vulnerable: `"use client";
13066
+
13067
+ export function ScanPanel() {
13068
+ const [projectId, setProjectId] = useState("latest");
13069
+ const [scan, setScan] = useState(null);
13070
+
13071
+ useEffect(() => {
13072
+ fetch(\`/api/scans/\${projectId}\`)
13073
+ .then((r) => r.json())
13074
+ .then((d) => setScan(d.scan));
13075
+ }, [projectId]);
13076
+
13077
+ return (
13078
+ <select value={projectId} onChange={(e) => setProjectId(e.target.value)}>
13079
+ {/* \u2026 */}
13080
+ </select>
13081
+ );
13082
+ }`,
13083
+ safe: `"use client";
13084
+
13085
+ export function ScanPanel() {
13086
+ const [projectId, setProjectId] = useState("latest");
13087
+ const [scan, setScan] = useState(null);
13088
+
13089
+ useEffect(() => {
13090
+ let cancelled = false;
13091
+ fetch(\`/api/scans/\${projectId}\`)
13092
+ .then((r) => r.json())
13093
+ .then((d) => {
13094
+ if (!cancelled) setScan(d.scan);
13095
+ });
13096
+ return () => {
13097
+ cancelled = true;
13098
+ };
13099
+ }, [projectId]);
13100
+
13101
+ return (
13102
+ <select value={projectId} onChange={(e) => setProjectId(e.target.value)}>
13103
+ {/* \u2026 */}
13104
+ </select>
13105
+ );
12469
13106
  }`
12470
13107
  },
12471
13108
  QA002: {
@@ -12675,7 +13312,13 @@ var qualityRules = [
12675
13312
  undeclaredModal,
12676
13313
  unboundedList,
12677
13314
  unassociatedLabel,
12678
- failedReadEmptyState
13315
+ failedReadEmptyState,
13316
+ autosaveArmedByFailedLoad,
13317
+ configSkippedWork,
13318
+ staleResponseWins
13319
+ ];
13320
+ var unmeasuredQualityRules = [
13321
+ lostUpdateCounter
12679
13322
  ];
12680
13323
  function scanQuality(files, rules = qualityRules) {
12681
13324
  const ctx = buildQualityContext(files);
@@ -12960,6 +13603,7 @@ export {
12960
13603
  timingAttack,
12961
13604
  todoLeftInCode,
12962
13605
  unencryptedPII,
13606
+ unmeasuredQualityRules,
12963
13607
  unpinnedGitHubAction,
12964
13608
  unprotectedAPIRoutes,
12965
13609
  unprotectedDownload,