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.cjs CHANGED
@@ -279,6 +279,7 @@ __export(index_exports, {
279
279
  timingAttack: () => timingAttack,
280
280
  todoLeftInCode: () => todoLeftInCode,
281
281
  unencryptedPII: () => unencryptedPII,
282
+ unmeasuredQualityRules: () => unmeasuredQualityRules,
282
283
  unpinnedGitHubAction: () => unpinnedGitHubAction,
283
284
  unprotectedAPIRoutes: () => unprotectedAPIRoutes,
284
285
  unprotectedDownload: () => unprotectedDownload,
@@ -12709,6 +12710,493 @@ var failedReadEmptyState = {
12709
12710
  }
12710
12711
  };
12711
12712
 
12713
+ // src/quality/rules/autosave-armed-by-failed-load.ts
12714
+ var import_traverse6 = __toESM(require("@babel/traverse"), 1);
12715
+ var traverse5 = typeof import_traverse6.default === "function" ? import_traverse6.default : import_traverse6.default.default;
12716
+ var PERSISTENT_WRITE = /\bfetch\s*\([^)]{0,400}?method\s*:\s*["'`](?:POST|PUT|PATCH)["'`]|\blocalStorage\s*\.\s*setItem\s*\(|\bsessionStorage\s*\.\s*setItem\s*\(/is;
12717
+ var EMPTY_INITIAL = /\buseState\s*(?:<[^>]*>)?\s*\(\s*(?:\[\s*\]|\{\s*\}|""|''|``)\s*\)/;
12718
+ function calleeIdentifier(node) {
12719
+ if (node.type !== "CallExpression") return null;
12720
+ const c = node.callee;
12721
+ if (c.type === "Identifier") return c.name;
12722
+ if (c.type === "MemberExpression" && c.property.type === "Identifier") return c.property.name;
12723
+ return null;
12724
+ }
12725
+ function isEffectCall2(node) {
12726
+ const name = calleeIdentifier(node);
12727
+ return name === "useEffect" || name === "useLayoutEffect";
12728
+ }
12729
+ function stateFromSetter(setter) {
12730
+ const m = /^set([A-Z][A-Za-z0-9_]*)$/.exec(setter);
12731
+ if (!m) return null;
12732
+ return m[1].charAt(0).toLowerCase() + m[1].slice(1);
12733
+ }
12734
+ function identifiersIn(path) {
12735
+ const names = /* @__PURE__ */ new Set();
12736
+ path.traverse({
12737
+ Identifier(id) {
12738
+ names.add(id.node.name);
12739
+ }
12740
+ });
12741
+ const n = path.node;
12742
+ if (n.type === "Identifier" && n.name) names.add(n.name);
12743
+ return names;
12744
+ }
12745
+ var autosaveArmedByFailedLoad = {
12746
+ id: "QA010",
12747
+ title: "Autosave is armed by a load that failed",
12748
+ severity: "high",
12749
+ category: "Correctness",
12750
+ 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.",
12751
+ 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.",
12752
+ 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.',
12753
+ check(ctx) {
12754
+ const hits = [];
12755
+ for (const file of ctx.files) {
12756
+ if (file.excluded) continue;
12757
+ if (!file.isClient) continue;
12758
+ if (file.isServer) continue;
12759
+ const parsed = file.parsed;
12760
+ if (!parsed) continue;
12761
+ if (!EMPTY_INITIAL.test(file.code)) continue;
12762
+ const armedInFinally = /* @__PURE__ */ new Map();
12763
+ traverse5(parsed.ast, {
12764
+ TryStatement(path) {
12765
+ const finalizer = path.get("finalizer");
12766
+ if (!finalizer || Array.isArray(finalizer) || !finalizer.node) return;
12767
+ finalizer.traverse({
12768
+ CallExpression(call) {
12769
+ const name = calleeIdentifier(call.node);
12770
+ if (!name) return;
12771
+ const state = stateFromSetter(name);
12772
+ if (!state) return;
12773
+ armedInFinally.set(state, nodeStart(call.node));
12774
+ }
12775
+ });
12776
+ }
12777
+ });
12778
+ if (armedInFinally.size === 0) continue;
12779
+ const writingFunctions = /* @__PURE__ */ new Set();
12780
+ traverse5(parsed.ast, {
12781
+ Function(path) {
12782
+ const src = file.code.slice(nodeStart(path.node), nodeEnd(path.node));
12783
+ if (!PERSISTENT_WRITE.test(src)) return;
12784
+ let owner = path.parentPath;
12785
+ for (let hops = 0; owner && hops < 3; hops++, owner = owner.parentPath) {
12786
+ const node = owner.node;
12787
+ if (node.type === "VariableDeclarator" && node.id.type === "Identifier") {
12788
+ writingFunctions.add(node.id.name);
12789
+ break;
12790
+ }
12791
+ if (node.type !== "CallExpression") break;
12792
+ }
12793
+ const n = path.node;
12794
+ if (n.id && n.id.name) writingFunctions.add(n.id.name);
12795
+ }
12796
+ });
12797
+ const reported = /* @__PURE__ */ new Set();
12798
+ traverse5(parsed.ast, {
12799
+ CallExpression(path) {
12800
+ if (!isEffectCall2(path.node)) return;
12801
+ const cb = path.get("arguments.0");
12802
+ if (!cb || !cb.node) return;
12803
+ const body = file.code.slice(nodeStart(cb.node), nodeEnd(cb.node));
12804
+ const names = identifiersIn(cb);
12805
+ const writesDirectly = PERSISTENT_WRITE.test(body);
12806
+ const writesViaCallback = [...writingFunctions].some((fn) => names.has(fn));
12807
+ if (!writesDirectly && !writesViaCallback) return;
12808
+ for (const [state, armLine] of armedInFinally) {
12809
+ if (!names.has(state)) continue;
12810
+ if (reported.has(state)) continue;
12811
+ if (!new RegExp(`\\bif\\s*\\([^)]*\\b${state}\\b`).test(body)) continue;
12812
+ reported.add(state);
12813
+ hits.push({
12814
+ file: file.path,
12815
+ line: lineAt(file.content, armLine),
12816
+ 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.`
12817
+ });
12818
+ }
12819
+ }
12820
+ });
12821
+ }
12822
+ return hits;
12823
+ }
12824
+ };
12825
+
12826
+ // src/quality/rules/config-skipped-work.ts
12827
+ var import_traverse7 = __toESM(require("@babel/traverse"), 1);
12828
+ var traverse6 = typeof import_traverse7.default === "function" ? import_traverse7.default : import_traverse7.default.default;
12829
+ var MUTATING_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
12830
+ 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;
12831
+ 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;
12832
+ var BOOKKEEPING = /analytics|telemetry|track|metric|event|beacon|log|audit|ping/i;
12833
+ var DIRECT_ENV_TEST = /\bprocess\s*\.\s*env\b|\bDeno\s*\.\s*env\s*\.\s*get\s*\(/;
12834
+ function calleeName3(node) {
12835
+ if (node.type !== "CallExpression") return null;
12836
+ const c = node.callee;
12837
+ if (c.type === "Identifier") return c.name;
12838
+ if (c.type === "MemberExpression" && c.property.type === "Identifier") return c.property.name;
12839
+ return null;
12840
+ }
12841
+ function keyShape(node) {
12842
+ if (!node || node.type !== "ObjectExpression") return null;
12843
+ const keys = [];
12844
+ for (const prop of node.properties) {
12845
+ if (prop.type === "ObjectProperty" && prop.key.type === "Identifier") keys.push(prop.key.name);
12846
+ else if (prop.type === "ObjectProperty" && prop.key.type === "StringLiteral") keys.push(prop.key.value);
12847
+ else return null;
12848
+ }
12849
+ return keys.sort().join(",");
12850
+ }
12851
+ function successPayloadShape(ret, source, offset) {
12852
+ const arg = ret.argument;
12853
+ if (!arg || arg.type !== "CallExpression") return null;
12854
+ const text = source.slice(nodeStart(ret) - offset, nodeEnd(ret) - offset);
12855
+ if (/status\s*:\s*[45]\d\d|,\s*\{\s*status\s*:\s*[45]\d\d/.test(text)) return null;
12856
+ const name = calleeName3(arg);
12857
+ if (name !== "json" && name !== "Response" && name !== "NextResponse") return null;
12858
+ const first = arg.arguments[0];
12859
+ if (!first) return null;
12860
+ if (first.type === "CallExpression" && calleeName3(first) === "stringify") {
12861
+ return keyShape(first.arguments[0]);
12862
+ }
12863
+ return keyShape(first);
12864
+ }
12865
+ var configSkippedWork = {
12866
+ id: "QA011",
12867
+ title: "Success is reported for work a missing setting skipped",
12868
+ severity: "high",
12869
+ category: "Correctness",
12870
+ 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.",
12871
+ 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.",
12872
+ 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.',
12873
+ check(ctx) {
12874
+ const hits = [];
12875
+ for (const file of ctx.files) {
12876
+ if (file.excluded) continue;
12877
+ if (!file.isServer) continue;
12878
+ if (BOOKKEEPING.test(file.path)) continue;
12879
+ const parsed = file.parsed;
12880
+ if (!parsed) continue;
12881
+ traverse6(parsed.ast, {
12882
+ Function(path) {
12883
+ const node = path.node;
12884
+ let name = node.id?.name ?? null;
12885
+ if (!name && path.parent.type === "VariableDeclarator" && path.parent.id.type === "Identifier") {
12886
+ name = path.parent.id.name;
12887
+ }
12888
+ if (!name || !MUTATING_METHODS.has(name)) return;
12889
+ const fnStart = nodeStart(path.node);
12890
+ const fnSource = file.code.slice(fnStart, nodeEnd(path.node));
12891
+ let terminal = null;
12892
+ const guards = [];
12893
+ path.traverse({
12894
+ ReturnStatement(ret) {
12895
+ const shape = successPayloadShape(ret.node, file.code, 0);
12896
+ if (shape === null) return;
12897
+ const start = nodeStart(ret.node);
12898
+ const ifPath = ret.findParent((p) => p.isIfStatement());
12899
+ if (ifPath) {
12900
+ const test = file.code.slice(nodeStart(ifPath.node.test), nodeEnd(ifPath.node.test));
12901
+ if (isConfigAbsenceTest(test, ifPath, file.code)) {
12902
+ guards.push({ shape, start, test });
12903
+ return;
12904
+ }
12905
+ }
12906
+ if (!terminal || start > terminal.start) terminal = { shape, start };
12907
+ }
12908
+ });
12909
+ if (!terminal || guards.length === 0) return;
12910
+ const term = terminal;
12911
+ for (const guard of guards) {
12912
+ if (guard.shape !== term.shape) continue;
12913
+ if (BOOKKEEPING.test(guard.test)) continue;
12914
+ const before = file.code.slice(fnStart, guard.start);
12915
+ const after = file.code.slice(guard.start, nodeEnd(path.node));
12916
+ if (DURABLE_WRITE.test(before)) continue;
12917
+ if (EXTERNAL_MUTATION.test(before)) continue;
12918
+ if (!DURABLE_WRITE.test(after)) continue;
12919
+ const writeMatch = DURABLE_WRITE.exec(after);
12920
+ if (writeMatch && BOOKKEEPING.test(after.slice(writeMatch.index, writeMatch.index + 120))) continue;
12921
+ hits.push({
12922
+ file: file.path,
12923
+ line: lineAt(file.content, guard.start),
12924
+ 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.`
12925
+ });
12926
+ break;
12927
+ }
12928
+ }
12929
+ });
12930
+ }
12931
+ return hits;
12932
+ }
12933
+ };
12934
+ function isConfigAbsenceTest(test, ifPath, code) {
12935
+ if (DIRECT_ENV_TEST.test(test)) return true;
12936
+ const m = /^!\s*([A-Za-z_$][\w$]*)$/.exec(test.trim());
12937
+ if (!m) return false;
12938
+ const local = m[1];
12939
+ const fn = ifPath.getFunctionParent();
12940
+ if (!fn) return false;
12941
+ const scope = code.slice(nodeStart(fn.node), nodeEnd(fn.node));
12942
+ return new RegExp(`\\b(?:const|let|var)\\s+${local}\\s*=\\s*(?:await\\s+)?[A-Za-z_$][\\w$]*\\s*\\(\\s*\\)`).test(scope);
12943
+ }
12944
+
12945
+ // src/quality/rules/stale-response-wins.ts
12946
+ var import_traverse8 = __toESM(require("@babel/traverse"), 1);
12947
+ var traverse7 = typeof import_traverse8.default === "function" ? import_traverse8.default : import_traverse8.default.default;
12948
+ var ORDERING_GUARD = /\breturn\s*\(\s*\)\s*=>|\bAbortController\b|\bsignal\b|\bcancell?ed\b|\bignore\b|\bstale\b|\bisMounted\b|\baborted\b/i;
12949
+ var SETTER2 = /^set[A-Z][A-Za-z0-9_]*$/;
12950
+ function calleeIdentifier2(node) {
12951
+ if (node.type !== "CallExpression") return null;
12952
+ const c = node.callee;
12953
+ if (c.type === "Identifier") return c.name;
12954
+ if (c.type === "MemberExpression" && c.property.type === "Identifier") return c.property.name;
12955
+ return null;
12956
+ }
12957
+ function isEffectCall3(node) {
12958
+ const n = calleeIdentifier2(node);
12959
+ return n === "useEffect" || n === "useLayoutEffect";
12960
+ }
12961
+ function templateIdentifiers(node) {
12962
+ if (node.type !== "TemplateLiteral") return [];
12963
+ const out = [];
12964
+ for (const expr of node.expressions) {
12965
+ collectIdentifiers(expr, out);
12966
+ }
12967
+ return out;
12968
+ }
12969
+ function collectIdentifiers(node, out) {
12970
+ if (!node || typeof node !== "object") return;
12971
+ if (node.type === "Identifier") {
12972
+ out.push(node.name);
12973
+ return;
12974
+ }
12975
+ for (const key of Object.keys(node)) {
12976
+ if (key === "loc" || key === "leadingComments" || key === "trailingComments") continue;
12977
+ const v = node[key];
12978
+ if (Array.isArray(v)) v.forEach((c) => c && typeof c === "object" && collectIdentifiers(c, out));
12979
+ else if (v && typeof v === "object" && "type" in v) collectIdentifiers(v, out);
12980
+ }
12981
+ }
12982
+ function derivesFromDep(name, deps, effect, code) {
12983
+ if (deps.has(name)) return true;
12984
+ let found = false;
12985
+ const seen = /* @__PURE__ */ new Set([name]);
12986
+ const frontier = [name];
12987
+ for (let depth = 0; depth < 4 && frontier.length && !found; depth++) {
12988
+ const current = frontier.splice(0, frontier.length);
12989
+ for (const target of current) {
12990
+ effect.traverse({
12991
+ VariableDeclarator(p) {
12992
+ if (found) return;
12993
+ if (p.node.id.type !== "Identifier" || p.node.id.name !== target) return;
12994
+ if (!p.node.init) return;
12995
+ const names = [];
12996
+ collectIdentifiers(p.node.init, names);
12997
+ for (const n of names) {
12998
+ if (deps.has(n)) {
12999
+ found = true;
13000
+ return;
13001
+ }
13002
+ if (!seen.has(n)) {
13003
+ seen.add(n);
13004
+ frontier.push(n);
13005
+ }
13006
+ }
13007
+ },
13008
+ AssignmentExpression(p) {
13009
+ if (found) return;
13010
+ if (p.node.left.type !== "Identifier" || p.node.left.name !== target) return;
13011
+ const names = [];
13012
+ collectIdentifiers(p.node.right, names);
13013
+ for (const n of names) {
13014
+ if (deps.has(n)) {
13015
+ found = true;
13016
+ return;
13017
+ }
13018
+ if (!seen.has(n)) {
13019
+ seen.add(n);
13020
+ frontier.push(n);
13021
+ }
13022
+ }
13023
+ }
13024
+ });
13025
+ }
13026
+ }
13027
+ return found;
13028
+ }
13029
+ var staleResponseWins = {
13030
+ id: "QA012",
13031
+ title: "A stale response can overwrite a newer one",
13032
+ severity: "medium",
13033
+ category: "Correctness",
13034
+ 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.",
13035
+ 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.",
13036
+ 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.',
13037
+ check(ctx) {
13038
+ const hits = [];
13039
+ for (const file of ctx.files) {
13040
+ if (file.excluded) continue;
13041
+ if (!file.isClient) continue;
13042
+ if (file.isServer) continue;
13043
+ const parsed = file.parsed;
13044
+ if (!parsed) continue;
13045
+ traverse7(parsed.ast, {
13046
+ CallExpression(path) {
13047
+ if (!isEffectCall3(path.node)) return;
13048
+ const args = path.node.arguments;
13049
+ const cbNode = args[0];
13050
+ const depNode = args[1];
13051
+ if (!cbNode || !depNode || depNode.type !== "ArrayExpression") return;
13052
+ if (depNode.elements.length === 0) return;
13053
+ const deps = /* @__PURE__ */ new Set();
13054
+ for (const el of depNode.elements) {
13055
+ if (el && el.type === "Identifier") deps.add(el.name);
13056
+ }
13057
+ if (deps.size === 0) return;
13058
+ const cb = path.get("arguments.0");
13059
+ if (!cb || !cb.node) return;
13060
+ const bodyStart = nodeStart(cb.node);
13061
+ const bodySource = file.code.slice(bodyStart, nodeEnd(cb.node));
13062
+ if (ORDERING_GUARD.test(bodySource)) return;
13063
+ let hit = null;
13064
+ cb.traverse({
13065
+ CallExpression(inner) {
13066
+ if (hit) return;
13067
+ if (!isFetchCallee(inner.node.callee)) return;
13068
+ const url = inner.node.arguments[0];
13069
+ if (!url) return;
13070
+ const interpolated = templateIdentifiers(url);
13071
+ if (interpolated.length === 0) return;
13072
+ const callEnd = nodeEnd(inner.node);
13073
+ const afterCall = file.code.slice(callEnd, nodeEnd(cb.node));
13074
+ let setsState = false;
13075
+ cb.traverse({
13076
+ CallExpression(c) {
13077
+ if (setsState) return;
13078
+ if (nodeStart(c.node) < callEnd) return;
13079
+ const n = calleeIdentifier2(c.node);
13080
+ if (n && SETTER2.test(n)) setsState = true;
13081
+ }
13082
+ });
13083
+ if (!setsState) return;
13084
+ for (const ident2 of interpolated) {
13085
+ if (!derivesFromDep(ident2, deps, cb, file.code)) continue;
13086
+ if (new RegExp(`\\b${ident2}\\b`).test(afterCall)) continue;
13087
+ if (![...deps].some((d) => userDriven(d, file.code))) continue;
13088
+ hit = { line: lineAt(file.content, nodeStart(inner.node)), ident: ident2 };
13089
+ return;
13090
+ }
13091
+ }
13092
+ });
13093
+ if (!hit) return;
13094
+ const { line, ident } = hit;
13095
+ hits.push({
13096
+ file: file.path,
13097
+ line,
13098
+ 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.`
13099
+ });
13100
+ }
13101
+ });
13102
+ }
13103
+ return hits;
13104
+ }
13105
+ };
13106
+ function userDriven(dep, code) {
13107
+ const setter = `set${dep.charAt(0).toUpperCase()}${dep.slice(1)}`;
13108
+ if (!new RegExp(`\\[\\s*${dep}\\s*,\\s*${setter}\\s*\\]\\s*=\\s*useState`).test(code)) return false;
13109
+ return new RegExp(`on(?:Change|Click|Input|Select)\\s*=\\s*\\{[^}]{0,200}\\b${setter}\\b`, "s").test(code);
13110
+ }
13111
+
13112
+ // src/quality/rules/lost-update-counter.ts
13113
+ var import_traverse9 = __toESM(require("@babel/traverse"), 1);
13114
+ var traverse8 = typeof import_traverse9.default === "function" ? import_traverse9.default : import_traverse9.default.default;
13115
+ var COUNTER_COLUMN = /^(?:credits?|balance|stock|quantity|qty|tokens?|seats?|points?|inventory|remaining|available)$/i;
13116
+ var WRITE_CALL = /\bUPDATE\s+\w|\.\s*update\s*\(|\.\s*set\s*\(|\bprisma\s*\.\s*\w+\s*\.\s*update\b/i;
13117
+ 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;
13118
+ var SCHEDULED_PATH = /(?:^|\/)(?:cron|jobs?|scheduled|tasks?|workers?)\//i;
13119
+ var INSERT_RETURNING = /\bINSERT\b[\s\S]{0,400}?\bRETURNING\b/i;
13120
+ function memberColumn(node) {
13121
+ if (node.type !== "MemberExpression" && node.type !== "OptionalMemberExpression") return null;
13122
+ const prop = node.property;
13123
+ if (prop.type !== "Identifier") return null;
13124
+ return COUNTER_COLUMN.test(prop.name) ? prop.name : null;
13125
+ }
13126
+ function rootObject(node) {
13127
+ let cur = node;
13128
+ while (cur.type === "MemberExpression" || cur.type === "OptionalMemberExpression") {
13129
+ cur = cur.object;
13130
+ }
13131
+ return cur.type === "Identifier" ? cur.name : null;
13132
+ }
13133
+ var MAX_PER_SCAN2 = 3;
13134
+ var lostUpdateCounter = {
13135
+ id: "QA013",
13136
+ title: "A balance is read, changed in JavaScript, and written back",
13137
+ severity: "high",
13138
+ category: "Correctness",
13139
+ 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.",
13140
+ 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.",
13141
+ 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.",
13142
+ check(ctx) {
13143
+ const hits = [];
13144
+ for (const file of ctx.files) {
13145
+ if (hits.length >= MAX_PER_SCAN2) break;
13146
+ if (file.excluded) continue;
13147
+ if (!file.isServer) continue;
13148
+ if (SCHEDULED_PATH.test(file.path)) continue;
13149
+ const parsed = file.parsed;
13150
+ if (!parsed) continue;
13151
+ let firedInFile = false;
13152
+ traverse8(parsed.ast, {
13153
+ BinaryExpression(path) {
13154
+ if (firedInFile || hits.length >= MAX_PER_SCAN2) return;
13155
+ const op = path.node.operator;
13156
+ if (op !== "+" && op !== "-") return;
13157
+ const left = path.node.left;
13158
+ const right = path.node.right;
13159
+ const column = memberColumn(left) ?? memberColumn(right);
13160
+ if (!column) return;
13161
+ const readLocal = rootObject(memberColumn(left) ? left : right);
13162
+ if (!readLocal) return;
13163
+ const fn = path.getFunctionParent();
13164
+ if (!fn) return;
13165
+ const fnSource = file.code.slice(nodeStart(fn.node), nodeEnd(fn.node));
13166
+ if (!WRITE_CALL.test(fnSource)) return;
13167
+ let serialised = false;
13168
+ for (let scope = fn; scope !== null && !serialised; scope = scope.getFunctionParent()) {
13169
+ const src = file.code.slice(nodeStart(scope.node), nodeEnd(scope.node));
13170
+ if (ATOMIC_OR_SERIALISED.test(src)) serialised = true;
13171
+ }
13172
+ if (serialised) return;
13173
+ if (INSERT_RETURNING.test(fnSource)) return;
13174
+ if (handleIsParameter(fn, fnSource)) return;
13175
+ if (!new RegExp(`\\b(?:const|let|var)\\s+(?:\\{[^}]*\\}|${readLocal})\\s*=\\s*await\\b`).test(fnSource)) return;
13176
+ firedInFile = true;
13177
+ hits.push({
13178
+ file: file.path,
13179
+ line: lineAt(file.content, nodeStart(path.node)),
13180
+ 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.`
13181
+ });
13182
+ }
13183
+ });
13184
+ }
13185
+ return hits;
13186
+ }
13187
+ };
13188
+ function handleIsParameter(fn, source) {
13189
+ const params = fn.node.params;
13190
+ for (const p of params) {
13191
+ if (p.type !== "Identifier") continue;
13192
+ if (/^(?:tx|trx|db|conn|client|transaction)$/i.test(p.name)) return true;
13193
+ if (new RegExp(`\\b${p.name}\\s*\\.\\s*(?:execute|run|query|update|insert)\\s*\\(`).test(source)) {
13194
+ return true;
13195
+ }
13196
+ }
13197
+ return false;
13198
+ }
13199
+
12712
13200
  // src/quality/examples.ts
12713
13201
  var QUALITY_EXAMPLES = {
12714
13202
  QA001: {
@@ -12772,6 +13260,156 @@ export function ApiKeysSection() {
12772
13260
  };
12773
13261
 
12774
13262
  useEffect(() => { load(); }, []);
13263
+ }`
13264
+ },
13265
+ QA010: {
13266
+ path: "app/checklist/page.tsx",
13267
+ language: "tsx",
13268
+ 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.",
13269
+ vulnerable: `"use client";
13270
+
13271
+ export function Checklist() {
13272
+ const [overrides, setOverrides] = useState({});
13273
+ const [stateLoaded, setStateLoaded] = useState(false);
13274
+
13275
+ useEffect(() => {
13276
+ (async () => {
13277
+ try {
13278
+ const res = await fetch("/api/checklist");
13279
+ const data = await res.json();
13280
+ if (data.state) setOverrides(data.state.overrides);
13281
+ } catch {
13282
+ // Non-critical
13283
+ } finally {
13284
+ setStateLoaded(true);
13285
+ }
13286
+ })();
13287
+ }, []);
13288
+
13289
+ const saveState = useCallback(() => {
13290
+ fetch("/api/checklist", { method: "POST", body: JSON.stringify({ overrides }) });
13291
+ }, [overrides]);
13292
+
13293
+ useEffect(() => {
13294
+ if (stateLoaded) saveState();
13295
+ }, [overrides, stateLoaded, saveState]);
13296
+ }`,
13297
+ safe: `"use client";
13298
+
13299
+ export function Checklist() {
13300
+ const [overrides, setOverrides] = useState({});
13301
+ const [stateLoaded, setStateLoaded] = useState(false);
13302
+ const [stateLoadFailed, setStateLoadFailed] = useState(false);
13303
+
13304
+ useEffect(() => {
13305
+ (async () => {
13306
+ try {
13307
+ const res = await fetch("/api/checklist");
13308
+ if (!res.ok) throw new Error(\`checklist load failed: HTTP \${res.status}\`);
13309
+ const data = await res.json();
13310
+ if (data.state) setOverrides(data.state.overrides);
13311
+ setStateLoaded(true);
13312
+ } catch {
13313
+ setStateLoadFailed(true);
13314
+ }
13315
+ })();
13316
+ }, []);
13317
+
13318
+ const saveState = useCallback(() => {
13319
+ fetch("/api/checklist", { method: "POST", body: JSON.stringify({ overrides }) });
13320
+ }, [overrides]);
13321
+
13322
+ useEffect(() => {
13323
+ if (stateLoaded && !stateLoadFailed) saveState();
13324
+ }, [overrides, stateLoaded, stateLoadFailed, saveState]);
13325
+ }`
13326
+ },
13327
+ QA011: {
13328
+ path: "app/api/scans/route.ts",
13329
+ language: "typescript",
13330
+ 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.",
13331
+ vulnerable: `export async function POST(request: Request) {
13332
+ const body = await request.json();
13333
+ const id = \`scan_\${Date.now()}\`;
13334
+
13335
+ const db = getDb();
13336
+ if (!db) {
13337
+ // No database configured \u2014 return success anyway
13338
+ return NextResponse.json({ scan: { id } });
13339
+ }
13340
+
13341
+ await db.execute({
13342
+ sql: "INSERT INTO scans (id, findings_json) VALUES (?, ?)",
13343
+ args: [id, JSON.stringify(body.findings)],
13344
+ });
13345
+
13346
+ return NextResponse.json({ scan: { id } });
13347
+ }`,
13348
+ safe: `export async function POST(request: Request) {
13349
+ const body = await request.json();
13350
+ const id = \`scan_\${Date.now()}\`;
13351
+
13352
+ const db = getDb();
13353
+ if (!db) {
13354
+ return NextResponse.json(
13355
+ { error: "Scan storage is not configured \u2014 this scan was not saved." },
13356
+ { status: 503 },
13357
+ );
13358
+ }
13359
+
13360
+ await db.execute({
13361
+ sql: "INSERT INTO scans (id, findings_json) VALUES (?, ?)",
13362
+ args: [id, JSON.stringify(body.findings)],
13363
+ });
13364
+
13365
+ return NextResponse.json({ scan: { id } });
13366
+ }`
13367
+ },
13368
+ QA012: {
13369
+ path: "app/panel/ScanPanel.tsx",
13370
+ language: "tsx",
13371
+ 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.",
13372
+ vulnerable: `"use client";
13373
+
13374
+ export function ScanPanel() {
13375
+ const [projectId, setProjectId] = useState("latest");
13376
+ const [scan, setScan] = useState(null);
13377
+
13378
+ useEffect(() => {
13379
+ fetch(\`/api/scans/\${projectId}\`)
13380
+ .then((r) => r.json())
13381
+ .then((d) => setScan(d.scan));
13382
+ }, [projectId]);
13383
+
13384
+ return (
13385
+ <select value={projectId} onChange={(e) => setProjectId(e.target.value)}>
13386
+ {/* \u2026 */}
13387
+ </select>
13388
+ );
13389
+ }`,
13390
+ safe: `"use client";
13391
+
13392
+ export function ScanPanel() {
13393
+ const [projectId, setProjectId] = useState("latest");
13394
+ const [scan, setScan] = useState(null);
13395
+
13396
+ useEffect(() => {
13397
+ let cancelled = false;
13398
+ fetch(\`/api/scans/\${projectId}\`)
13399
+ .then((r) => r.json())
13400
+ .then((d) => {
13401
+ if (!cancelled) setScan(d.scan);
13402
+ });
13403
+ return () => {
13404
+ cancelled = true;
13405
+ };
13406
+ }, [projectId]);
13407
+
13408
+ return (
13409
+ <select value={projectId} onChange={(e) => setProjectId(e.target.value)}>
13410
+ {/* \u2026 */}
13411
+ </select>
13412
+ );
12775
13413
  }`
12776
13414
  },
12777
13415
  QA002: {
@@ -12981,7 +13619,13 @@ var qualityRules = [
12981
13619
  undeclaredModal,
12982
13620
  unboundedList,
12983
13621
  unassociatedLabel,
12984
- failedReadEmptyState
13622
+ failedReadEmptyState,
13623
+ autosaveArmedByFailedLoad,
13624
+ configSkippedWork,
13625
+ staleResponseWins
13626
+ ];
13627
+ var unmeasuredQualityRules = [
13628
+ lostUpdateCounter
12985
13629
  ];
12986
13630
  function scanQuality(files, rules = qualityRules) {
12987
13631
  const ctx = buildQualityContext(files);
@@ -13267,6 +13911,7 @@ function scanQuality(files, rules = qualityRules) {
13267
13911
  timingAttack,
13268
13912
  todoLeftInCode,
13269
13913
  unencryptedPII,
13914
+ unmeasuredQualityRules,
13270
13915
  unpinnedGitHubAction,
13271
13916
  unprotectedAPIRoutes,
13272
13917
  unprotectedDownload,