xploitscan-shared-rules 1.35.1 → 1.36.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
@@ -181,8 +181,10 @@ __export(index_exports, {
181
181
  insecureWebSocket: () => insecureWebSocket,
182
182
  ipcPathTraversal: () => ipcPathTraversal,
183
183
  isCalleeNamed: () => isCalleeNamed,
184
+ isClientTarget: () => isClientTarget,
184
185
  isMethodCall: () => isMethodCall,
185
186
  isPrivateAddress: () => isPrivateAddress,
187
+ isServerTarget: () => isServerTarget,
186
188
  isVendoredFinding: () => isVendoredFinding,
187
189
  isVendoredPath: () => isVendoredPath,
188
190
  javaDeserialization: () => javaDeserialization,
@@ -10413,6 +10415,12 @@ function buildQualityContext(files) {
10413
10415
  });
10414
10416
  return { files: built, byPath: new Map(built.map((f) => [f.path, f])) };
10415
10417
  }
10418
+ function isClientTarget(file) {
10419
+ return !file.excluded && file.isClient && !file.isServer;
10420
+ }
10421
+ function isServerTarget(file) {
10422
+ return !file.excluded && file.isServer;
10423
+ }
10416
10424
  function lineAt(content, index) {
10417
10425
  let line = 1;
10418
10426
  for (let i = 0; i < index && i < content.length; i++) {
@@ -12627,6 +12635,55 @@ var unassociatedLabel = {
12627
12635
 
12628
12636
  // src/quality/rules/failed-read-empty-state.ts
12629
12637
  var import_traverse5 = __toESM(require("@babel/traverse"), 1);
12638
+ var import_types = require("@babel/types");
12639
+
12640
+ // src/quality/rules/scope.ts
12641
+ function unwrap(node) {
12642
+ let cur = node;
12643
+ while (cur.type === "TSAsExpression" || cur.type === "TSNonNullExpression" || cur.type === "TSTypeAssertion" || cur.type === "TSSatisfiesExpression") {
12644
+ cur = cur.expression;
12645
+ }
12646
+ return cur;
12647
+ }
12648
+ function calleeName3(node) {
12649
+ if (node.type !== "CallExpression" && node.type !== "OptionalCallExpression") return null;
12650
+ const c = node.callee;
12651
+ if (c.type === "Identifier") return c.name;
12652
+ if ((c.type === "MemberExpression" || c.type === "OptionalMemberExpression") && c.property.type === "Identifier") {
12653
+ return c.property.name;
12654
+ }
12655
+ return null;
12656
+ }
12657
+ function useStateBinding(at, name) {
12658
+ const binding = at.scope.getBinding(name);
12659
+ if (!binding) return void 0;
12660
+ const decl = binding.path;
12661
+ if (!decl.isVariableDeclarator()) return void 0;
12662
+ const id = decl.node.id;
12663
+ const init = decl.node.init;
12664
+ if (id.type !== "ArrayPattern") return void 0;
12665
+ if (!init || calleeName3(init) !== "useState") return void 0;
12666
+ const first = id.elements[0];
12667
+ if (!first || first.type !== "Identifier" || first.name !== name) return void 0;
12668
+ const second = id.elements[1];
12669
+ return {
12670
+ initial: init.arguments[0],
12671
+ setter: second && second.type === "Identifier" ? second.name : null,
12672
+ decl
12673
+ };
12674
+ }
12675
+ function isEmptyInitial(node) {
12676
+ if (!node) return false;
12677
+ if (node.type === "ArrayExpression") return node.elements.length === 0;
12678
+ if (node.type === "ObjectExpression") return node.properties.length === 0;
12679
+ if (node.type === "StringLiteral") return node.value === "";
12680
+ if (node.type === "TemplateLiteral") {
12681
+ return node.quasis.length === 1 && node.quasis[0].value.raw === "";
12682
+ }
12683
+ return false;
12684
+ }
12685
+
12686
+ // src/quality/rules/failed-read-empty-state.ts
12630
12687
  var traverse4 = typeof import_traverse5.default === "function" ? import_traverse5.default : import_traverse5.default.default;
12631
12688
  var READ_ERROR_PATH_SIGNALS = ERROR_PATH_SIGNALS.filter(
12632
12689
  (re) => re.source !== /\.catch\s*\(/.source
@@ -12644,28 +12701,57 @@ function setterName(callee) {
12644
12701
  function isPropertyRead(node) {
12645
12702
  return node.type === "MemberExpression" || node.type === "OptionalMemberExpression";
12646
12703
  }
12704
+ function mentionsJsonParse(node, code) {
12705
+ return /\.json\s*\(/.test(code.slice(nodeStart(node), nodeEnd(node)));
12706
+ }
12707
+ function chainParsesBody(node, code) {
12708
+ let cur = unwrap(node);
12709
+ for (; ; ) {
12710
+ if (cur.type === "CallExpression" || cur.type === "OptionalCallExpression") {
12711
+ const callee = unwrap(cur.callee);
12712
+ if ((callee.type === "MemberExpression" || callee.type === "OptionalMemberExpression") && callee.property.type === "Identifier") {
12713
+ const method = callee.property.name;
12714
+ if (method === "json") return true;
12715
+ if (method === "then" || method === "catch") {
12716
+ const cb = cur.arguments[0];
12717
+ if (cb && (cb.type === "ArrowFunctionExpression" || cb.type === "FunctionExpression") && /\.json\s*\(/.test(code.slice(nodeStart(cb), nodeEnd(cb)))) {
12718
+ return true;
12719
+ }
12720
+ }
12721
+ cur = unwrap(callee.object);
12722
+ continue;
12723
+ }
12724
+ cur = callee;
12725
+ continue;
12726
+ }
12727
+ if (cur.type === "MemberExpression" || cur.type === "OptionalMemberExpression") {
12728
+ cur = unwrap(cur.object);
12729
+ continue;
12730
+ }
12731
+ return false;
12732
+ }
12733
+ return false;
12734
+ }
12735
+ function boundNames(id, into) {
12736
+ for (const name of Object.keys((0, import_types.getBindingIdentifiers)(id))) into.add(name);
12737
+ }
12647
12738
  function parsedBodyBindings(unit, code) {
12648
12739
  const names = /* @__PURE__ */ new Set();
12740
+ const record = (id, init) => {
12741
+ if (!id || !init) return;
12742
+ const awaited = unwrap(init);
12743
+ if (awaited.type !== "AwaitExpression") return;
12744
+ if (!chainParsesBody(awaited.argument, code)) return;
12745
+ boundNames(id, names);
12746
+ };
12649
12747
  unit.traverse({
12650
12748
  VariableDeclarator(decl) {
12651
- const init = decl.node.init;
12652
- if (!init || init.type !== "AwaitExpression") return;
12653
- const arg = init.argument;
12654
- if (arg.type !== "CallExpression" && arg.type !== "OptionalCallExpression") return;
12655
- const callee = arg.callee;
12656
- if (callee.type !== "MemberExpression" && callee.type !== "OptionalMemberExpression")
12657
- return;
12658
- if (callee.property.type !== "Identifier") return;
12659
- const method = callee.property.name;
12660
- let isBody = method === "json";
12661
- if (!isBody && method === "then") {
12662
- const cb = arg.arguments[0];
12663
- if (cb && (cb.type === "ArrowFunctionExpression" || cb.type === "FunctionExpression")) {
12664
- isBody = /\.json\s*\(/.test(code.slice(nodeStart(cb), nodeEnd(cb)));
12665
- }
12666
- }
12667
- if (!isBody) return;
12668
- if (decl.node.id.type === "Identifier") names.add(decl.node.id.name);
12749
+ record(decl.node.id, decl.node.init);
12750
+ },
12751
+ // `let data; data = await res.json();` — the same read, not a declaration.
12752
+ AssignmentExpression(assign) {
12753
+ if (assign.node.operator !== "=") return;
12754
+ record(assign.node.left, assign.node.right);
12669
12755
  },
12670
12756
  // The promise-chain spelling, which is the shipped defect's own:
12671
12757
  // fetch(u).then(r => r.json()).then(data => setRows(data.rows || []))
@@ -12678,26 +12764,24 @@ function parsedBodyBindings(unit, code) {
12678
12764
  return;
12679
12765
  if (callee.property.type !== "Identifier" || callee.property.name !== "then") return;
12680
12766
  const receiver = callee.object;
12681
- if (!/\.json\s*\(/.test(code.slice(nodeStart(receiver), nodeEnd(receiver)))) return;
12767
+ if (!mentionsJsonParse(receiver, code)) return;
12682
12768
  const cb = call.node.arguments[0];
12683
12769
  if (!cb) return;
12684
12770
  if (cb.type !== "ArrowFunctionExpression" && cb.type !== "FunctionExpression") return;
12685
12771
  const param = cb.params[0];
12686
- if (param && param.type === "Identifier") names.add(param.name);
12772
+ if (param) boundNames(param, names);
12687
12773
  }
12688
12774
  });
12689
12775
  return names;
12690
12776
  }
12691
12777
  function derivesFromParsedBody(node, bodies, code) {
12692
- let cur = node;
12693
- while (cur.type === "MemberExpression" || cur.type === "OptionalMemberExpression") {
12694
- cur = cur.object;
12778
+ let cur = unwrap(node);
12779
+ while (cur && (cur.type === "MemberExpression" || cur.type === "OptionalMemberExpression")) {
12780
+ cur = unwrap(cur.object);
12695
12781
  }
12696
12782
  if (cur.type === "Identifier") return bodies.has(cur.name);
12697
- if (cur.type === "AwaitExpression" || cur.type === "CallExpression" || cur.type === "OptionalCallExpression") {
12698
- return /\.json\s*\(/.test(code.slice(nodeStart(cur), nodeEnd(cur)));
12699
- }
12700
- return false;
12783
+ if (cur.type === "AwaitExpression") cur = unwrap(cur.argument);
12784
+ return chainParsesBody(cur, code);
12701
12785
  }
12702
12786
  function emptyFallbackArgument(node) {
12703
12787
  if (node.type !== "LogicalExpression") return null;
@@ -12739,7 +12823,7 @@ var failedReadEmptyState = {
12739
12823
  category: "Correctness",
12740
12824
  description: "This loader turns a failed or unexpected response into an empty list and renders it, so the page shows the same thing it would show a brand-new account: no sessions, no scans, no members. Nothing tells the user the request failed, and anything they do next \u2014 including saving \u2014 acts on data the app never actually received.",
12741
12825
  fix: "Check the response before using it: on a non-2xx, or a body without the field you expected, set an error state and render that instead of the empty state. Keep the `|| []` only for a response you have already confirmed arrived.",
12742
- precisionNotes: "Client files only, and only a unit containing the literal global `fetch(` \u2014 throwing clients (ky, wretch, ofetch) reject on non-2xx, so `|| []` after them is correct, and in-file wrappers that check `.ok` and rethrow leave their callers containing no `fetch(` at all. The empty fallback must be `|| []`/`?? []`/`{}` over a PROPERTY READ passed straight to a `setX` state setter: `setRows(rows || [])` defaults a value the component already holds, and a pure helper's argument is never rendered. The unit is the effect callback, or the outermost non-component function \u2014 the nearest function cannot see the `.catch` below it, and the whole component would let an unrelated toast.error exonerate a broken loader. Exoneration is QA002's ERROR_PATH_SIGNALS with `.catch(` REMOVED: for a write a `.catch` means the author handled it, for a read `.catch(() => setLoaded(true))` is the defect itself. The defaulted value must come from a body the unit itself parsed \u2014 `await res.json()`, a `.then` off a receiver containing `.json(`, or the inline `(await res.json()).rows` \u2014 because a unit can hold more than one read, and a nearby real fetch was found satisfying the clause for a fallback belonging to a throwing helper. Measured at 6 fires over 5 sites in 437 .tsx files with zero false positives, then across 168 third-party repositories and 16,601 files: 8 fires over 5 repositories, every one re-read in full and every one real.",
12826
+ precisionNotes: "Client files only, and only a unit containing the literal global `fetch(` \u2014 throwing clients (ky, wretch, ofetch) reject on non-2xx, so `|| []` after them is correct, and in-file wrappers that check `.ok` and rethrow leave their callers containing no `fetch(` at all. The empty fallback must be `|| []`/`?? []`/`{}` over a PROPERTY READ passed straight to a `setX` state setter: `setRows(rows || [])` defaults a value the component already holds, and a pure helper's argument is never rendered. The unit is the effect callback, or the outermost non-component function \u2014 the nearest function cannot see the `.catch` below it, and the whole component would let an unrelated toast.error exonerate a broken loader. Exoneration is QA002's ERROR_PATH_SIGNALS with `.catch(` REMOVED: for a write a `.catch` means the author handled it, for a read `.catch(() => setLoaded(true))` is the defect itself. The defaulted value must come from a body the unit itself parsed \u2014 `await res.json()`, a `.then` off a receiver containing `.json(`, or the inline `(await res.json()).rows` \u2014 because a unit can hold more than one read, and a nearby real fetch was found satisfying the clause for a fallback belonging to a throwing helper. Measured at 6 fires over 5 sites in 437 .tsx files with zero false positives, then across 168 third-party repositories: 8 fires over 5 of them, every one re-read in full and every one real. That is a precision result, not a recall one \u2014 the client files those repositories hold are about a third of them, and the parsed-body clause recognised only one spelling of the read at the time it was measured.",
12743
12827
  check(ctx) {
12744
12828
  const hits = [];
12745
12829
  for (const file of ctx.files) {
@@ -12747,16 +12831,18 @@ var failedReadEmptyState = {
12747
12831
  if (!file.isClient) continue;
12748
12832
  if (file.isServer) continue;
12749
12833
  if (/^\s*["']use server["']/m.test(file.code)) continue;
12834
+ if (!file.code.includes("fetch")) continue;
12750
12835
  const parsed = file.parsed;
12751
12836
  if (!parsed) continue;
12752
- const reported = /* @__PURE__ */ new Set();
12837
+ const examined = /* @__PURE__ */ new Set();
12753
12838
  traverse4(parsed.ast, {
12754
12839
  CallExpression(path) {
12755
12840
  if (!isFetchCallee(path.node.callee)) return;
12756
12841
  const unit = unitFor(path);
12757
12842
  if (!unit) return;
12758
12843
  const start = nodeStart(unit.node);
12759
- if (reported.has(start)) return;
12844
+ if (examined.has(start)) return;
12845
+ examined.add(start);
12760
12846
  const unitSource = file.code.slice(start, nodeEnd(unit.node));
12761
12847
  if (READ_ERROR_PATH_SIGNALS.some((re) => re.test(unitSource))) return;
12762
12848
  const bodies = parsedBodyBindings(unit, file.code);
@@ -12775,7 +12861,6 @@ var failedReadEmptyState = {
12775
12861
  }
12776
12862
  });
12777
12863
  if (!hit) return;
12778
- reported.add(start);
12779
12864
  const { line, setter } = hit;
12780
12865
  hits.push({
12781
12866
  file: file.path,
@@ -12792,6 +12877,20 @@ var failedReadEmptyState = {
12792
12877
  // src/quality/rules/autosave-armed-by-failed-load.ts
12793
12878
  var import_traverse6 = __toESM(require("@babel/traverse"), 1);
12794
12879
  var traverse5 = typeof import_traverse6.default === "function" ? import_traverse6.default : import_traverse6.default.default;
12880
+ function writerTouchesEmptyState(writers) {
12881
+ for (const writer of writers) {
12882
+ let found = false;
12883
+ writer.traverse({
12884
+ Identifier(id) {
12885
+ if (found) return;
12886
+ if (!id.isReferencedIdentifier()) return;
12887
+ if (isEmptyInitial(useStateBinding(id, id.node.name)?.initial)) found = true;
12888
+ }
12889
+ });
12890
+ if (found) return true;
12891
+ }
12892
+ return false;
12893
+ }
12795
12894
  var PERSISTENT_WRITE = /\bfetch\s*\([^)]{0,400}?method\s*:\s*["'`](?:POST|PUT|PATCH)["'`]|\blocalStorage\s*\.\s*setItem\s*\(|\bsessionStorage\s*\.\s*setItem\s*\(/is;
12796
12895
  var EMPTY_INITIAL = /\buseState\s*(?:<[^>]*>)?\s*\(\s*(?:\[\s*\]|\{\s*\}|""|''|``)\s*\)/;
12797
12896
  function calleeIdentifier(node) {
@@ -12848,32 +12947,14 @@ var autosaveArmedByFailedLoad = {
12848
12947
  category: "Correctness",
12849
12948
  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.",
12850
12949
  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.",
12851
- 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. The value matters too \u2014 a `finally` that sets the flag back to the literal `useState` started it as is a reset and cannot arm anything, which is what separates this from the hundreds of correct `finally` blocks around it. Measured across 168 third-party repositories and 16,601 files: 0 fires.',
12950
+ 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. The value matters too \u2014 a `finally` that sets the flag back to the literal `useState` started it as is a reset and cannot arm anything, which is what separates this from the hundreds of correct `finally` blocks around it. Measured across 168 third-party repositories: 0 fires. The denominator is the client files among them, not the whole corpus.',
12852
12951
  check(ctx) {
12853
12952
  const hits = [];
12854
12953
  for (const file of ctx.files) {
12855
- if (file.excluded) continue;
12856
- if (!file.isClient) continue;
12857
- if (file.isServer) continue;
12954
+ if (!isClientTarget(file)) continue;
12858
12955
  const parsed = file.parsed;
12859
12956
  if (!parsed) continue;
12860
12957
  if (!EMPTY_INITIAL.test(file.code)) continue;
12861
- const initialValues = /* @__PURE__ */ new Map();
12862
- traverse5(parsed.ast, {
12863
- VariableDeclarator(decl) {
12864
- const id = decl.node.id;
12865
- const init = decl.node.init;
12866
- if (!id || id.type !== "ArrayPattern") return;
12867
- if (!init || init.type !== "CallExpression") return;
12868
- const callee = init.callee;
12869
- const name = callee.type === "Identifier" ? callee.name : callee.type === "MemberExpression" && callee.property.type === "Identifier" ? callee.property.name : null;
12870
- if (name !== "useState") return;
12871
- const first = id.elements[0];
12872
- const arg = init.arguments[0];
12873
- if (!first || first.type !== "Identifier" || !arg) return;
12874
- initialValues.set(first.name, arg);
12875
- }
12876
- });
12877
12958
  const armedInFinally = /* @__PURE__ */ new Map();
12878
12959
  traverse5(parsed.ast, {
12879
12960
  TryStatement(path) {
@@ -12885,29 +12966,32 @@ var autosaveArmedByFailedLoad = {
12885
12966
  if (!name) return;
12886
12967
  const state = stateFromSetter(name);
12887
12968
  if (!state) return;
12888
- if (setsBackToInitial(call.node, initialValues.get(state))) return;
12969
+ if (setsBackToInitial(call.node, useStateBinding(call, state)?.initial)) return;
12889
12970
  armedInFinally.set(state, nodeStart(call.node));
12890
12971
  }
12891
12972
  });
12892
12973
  }
12893
12974
  });
12894
12975
  if (armedInFinally.size === 0) continue;
12895
- const writingFunctions = /* @__PURE__ */ new Set();
12976
+ const writingFunctions = /* @__PURE__ */ new Map();
12896
12977
  traverse5(parsed.ast, {
12897
12978
  Function(path) {
12898
12979
  const src = file.code.slice(nodeStart(path.node), nodeEnd(path.node));
12899
12980
  if (!PERSISTENT_WRITE.test(src)) return;
12981
+ const deps = [];
12900
12982
  let owner = path.parentPath;
12901
12983
  for (let hops = 0; owner && hops < 3; hops++, owner = owner.parentPath) {
12902
12984
  const node = owner.node;
12903
12985
  if (node.type === "VariableDeclarator" && node.id.type === "Identifier") {
12904
- writingFunctions.add(node.id.name);
12986
+ writingFunctions.set(node.id.name, [path, ...deps]);
12905
12987
  break;
12906
12988
  }
12907
12989
  if (node.type !== "CallExpression") break;
12990
+ const depArg = owner.get("arguments.1");
12991
+ if (depArg && depArg.node) deps.push(depArg);
12908
12992
  }
12909
12993
  const n = path.node;
12910
- if (n.id && n.id.name) writingFunctions.add(n.id.name);
12994
+ if (n.id && n.id.name) writingFunctions.set(n.id.name, [path, ...deps]);
12911
12995
  }
12912
12996
  });
12913
12997
  const reported = /* @__PURE__ */ new Set();
@@ -12919,8 +13003,15 @@ var autosaveArmedByFailedLoad = {
12919
13003
  const body = file.code.slice(nodeStart(cb.node), nodeEnd(cb.node));
12920
13004
  const names = identifiersIn(cb);
12921
13005
  const writesDirectly = PERSISTENT_WRITE.test(body);
12922
- const writesViaCallback = [...writingFunctions].some((fn) => names.has(fn));
12923
- if (!writesDirectly && !writesViaCallback) return;
13006
+ const calledWriters = [...writingFunctions.entries()].filter(([fn]) => names.has(fn)).flatMap(([, paths]) => paths);
13007
+ if (!writesDirectly && calledWriters.length === 0) return;
13008
+ const effectDeps = path.get("arguments.1");
13009
+ const writers = [
13010
+ ...writesDirectly ? [cb] : [],
13011
+ ...calledWriters,
13012
+ ...effectDeps && effectDeps.node ? [effectDeps] : []
13013
+ ];
13014
+ if (!writerTouchesEmptyState(writers)) return;
12924
13015
  for (const [state, armLine] of armedInFinally) {
12925
13016
  if (!names.has(state)) continue;
12926
13017
  if (reported.has(state)) continue;
@@ -12947,7 +13038,7 @@ var DURABLE_WRITE = /\b(?:INSERT\s+INTO\b|UPDATE\s+\w+\s+SET\b|DELETE\s+FROM\b)|
12947
13038
  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;
12948
13039
  var BOOKKEEPING = /analytics|telemetry|track|metric|event|beacon|log|audit|ping/i;
12949
13040
  var DIRECT_ENV_TEST = /\bprocess\s*\.\s*env\b|\bDeno\s*\.\s*env\s*\.\s*get\s*\(/;
12950
- function calleeName3(node) {
13041
+ function calleeName4(node) {
12951
13042
  if (node.type !== "CallExpression") return null;
12952
13043
  const c = node.callee;
12953
13044
  if (c.type === "Identifier") return c.name;
@@ -12969,11 +13060,11 @@ function successPayloadShape(ret, source, offset) {
12969
13060
  if (!arg || arg.type !== "CallExpression") return null;
12970
13061
  const text = source.slice(nodeStart(ret) - offset, nodeEnd(ret) - offset);
12971
13062
  if (/status\s*:\s*[45]\d\d|,\s*\{\s*status\s*:\s*[45]\d\d/.test(text)) return null;
12972
- const name = calleeName3(arg);
13063
+ const name = calleeName4(arg);
12973
13064
  if (name !== "json" && name !== "Response" && name !== "NextResponse") return null;
12974
13065
  const first = arg.arguments[0];
12975
13066
  if (!first) return null;
12976
- if (first.type === "CallExpression" && calleeName3(first) === "stringify") {
13067
+ if (first.type === "CallExpression" && calleeName4(first) === "stringify") {
12977
13068
  return keyShape(first.arguments[0]);
12978
13069
  }
12979
13070
  return keyShape(first);
@@ -13149,13 +13240,11 @@ var staleResponseWins = {
13149
13240
  category: "Correctness",
13150
13241
  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.",
13151
13242
  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.",
13152
- 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.',
13243
+ 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: three distinct defects now, across two codebases \u2014 two in this product, and one found across 168 third-party repositories, verified real, with no false positives beside it. Precise on everything it has been run against; still rare. Shipped at medium for that reason.',
13153
13244
  check(ctx) {
13154
13245
  const hits = [];
13155
13246
  for (const file of ctx.files) {
13156
- if (file.excluded) continue;
13157
- if (!file.isClient) continue;
13158
- if (file.isServer) continue;
13247
+ if (!isClientTarget(file)) continue;
13159
13248
  const parsed = file.parsed;
13160
13249
  if (!parsed) continue;
13161
13250
  traverse7(parsed.ast, {
@@ -13200,7 +13289,10 @@ var staleResponseWins = {
13200
13289
  for (const ident2 of interpolated) {
13201
13290
  if (!derivesFromDep(ident2, deps, cb, file.code)) continue;
13202
13291
  if (new RegExp(`\\b${ident2}\\b`).test(afterCall)) continue;
13203
- if (![...deps].some((d) => userDriven(d, file.code))) continue;
13292
+ const driving = [...deps].filter(
13293
+ (d) => derivesFromDep(ident2, /* @__PURE__ */ new Set([d]), cb, file.code)
13294
+ );
13295
+ if (!driving.some((d) => userDriven(d, cb))) continue;
13204
13296
  hit = { line: lineAt(file.content, nodeStart(inner.node)), ident: ident2 };
13205
13297
  return;
13206
13298
  }
@@ -13219,10 +13311,26 @@ var staleResponseWins = {
13219
13311
  return hits;
13220
13312
  }
13221
13313
  };
13222
- function userDriven(dep, code) {
13223
- const setter = `set${dep.charAt(0).toUpperCase()}${dep.slice(1)}`;
13224
- if (!new RegExp(`\\[\\s*${dep}\\s*,\\s*${setter}\\s*\\]\\s*=\\s*useState`).test(code)) return false;
13225
- return new RegExp(`on(?:Change|Click|Input|Select)\\s*=\\s*\\{[^}]{0,200}\\b${setter}\\b`, "s").test(code);
13314
+ function userDriven(dep, at) {
13315
+ const binding = useStateBinding(at, dep);
13316
+ const setter = binding?.setter;
13317
+ if (!setter) return false;
13318
+ const owner = binding.decl.getFunctionParent() ?? binding.decl.scope.path;
13319
+ let wired = false;
13320
+ owner.traverse({
13321
+ JSXAttribute(attr) {
13322
+ if (wired) return;
13323
+ const name = attr.node.name;
13324
+ if (name.type !== "JSXIdentifier") return;
13325
+ if (!/^on(?:Change|Click|Input|Select)$/.test(name.name)) return;
13326
+ attr.traverse({
13327
+ Identifier(id) {
13328
+ if (id.node.name === setter) wired = true;
13329
+ }
13330
+ });
13331
+ }
13332
+ });
13333
+ return wired;
13226
13334
  }
13227
13335
 
13228
13336
  // src/quality/rules/lost-update-counter.ts
@@ -13743,8 +13851,8 @@ var qualityRules = [
13743
13851
  var unmeasuredQualityRules = [
13744
13852
  lostUpdateCounter
13745
13853
  ];
13746
- function scanQuality(files, rules = qualityRules) {
13747
- const ctx = buildQualityContext(files);
13854
+ function scanQuality(input, rules = qualityRules) {
13855
+ const ctx = Array.isArray(input) ? buildQualityContext(input) : input;
13748
13856
  const findings = [];
13749
13857
  for (const rule of rules) {
13750
13858
  let hits;
@@ -13929,8 +14037,10 @@ function scanQuality(files, rules = qualityRules) {
13929
14037
  insecureWebSocket,
13930
14038
  ipcPathTraversal,
13931
14039
  isCalleeNamed,
14040
+ isClientTarget,
13932
14041
  isMethodCall,
13933
14042
  isPrivateAddress,
14043
+ isServerTarget,
13934
14044
  isVendoredFinding,
13935
14045
  isVendoredPath,
13936
14046
  javaDeserialization,