xploitscan-shared-rules 1.35.1 → 1.35.2

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
@@ -12644,28 +12644,70 @@ function setterName(callee) {
12644
12644
  function isPropertyRead(node) {
12645
12645
  return node.type === "MemberExpression" || node.type === "OptionalMemberExpression";
12646
12646
  }
12647
+ function unwrap(node) {
12648
+ let cur = node;
12649
+ while (cur && (cur.type === "TSAsExpression" || cur.type === "TSNonNullExpression" || cur.type === "TSTypeAssertion" || cur.type === "TSSatisfiesExpression" || cur.type === "ParenthesizedExpression")) {
12650
+ cur = cur.expression;
12651
+ }
12652
+ return cur;
12653
+ }
12654
+ function chainParsesBody(node, code) {
12655
+ let cur = unwrap(node);
12656
+ while (cur) {
12657
+ if (cur.type === "CallExpression" || cur.type === "OptionalCallExpression") {
12658
+ const callee = unwrap(cur.callee);
12659
+ if (callee && (callee.type === "MemberExpression" || callee.type === "OptionalMemberExpression") && callee.property.type === "Identifier") {
12660
+ const method = callee.property.name;
12661
+ if (method === "json") return true;
12662
+ if (method === "then" || method === "catch") {
12663
+ const cb = cur.arguments[0];
12664
+ if (cb && (cb.type === "ArrowFunctionExpression" || cb.type === "FunctionExpression") && /\.json\s*\(/.test(code.slice(nodeStart(cb), nodeEnd(cb)))) {
12665
+ return true;
12666
+ }
12667
+ }
12668
+ cur = unwrap(callee.object);
12669
+ continue;
12670
+ }
12671
+ cur = unwrap(cur.callee);
12672
+ continue;
12673
+ }
12674
+ if (cur.type === "MemberExpression" || cur.type === "OptionalMemberExpression") {
12675
+ cur = unwrap(cur.object);
12676
+ continue;
12677
+ }
12678
+ return false;
12679
+ }
12680
+ return false;
12681
+ }
12682
+ function boundNames(id, into) {
12683
+ if (id.type === "Identifier") {
12684
+ into.add(id.name);
12685
+ return;
12686
+ }
12687
+ if (id.type === "ObjectPattern") {
12688
+ for (const prop of id.properties) {
12689
+ if (prop.type === "ObjectProperty") boundNames(prop.value, into);
12690
+ else if (prop.type === "RestElement") boundNames(prop.argument, into);
12691
+ }
12692
+ }
12693
+ }
12647
12694
  function parsedBodyBindings(unit, code) {
12648
12695
  const names = /* @__PURE__ */ new Set();
12696
+ const record = (id, init) => {
12697
+ if (!id) return;
12698
+ const awaited = unwrap(init);
12699
+ if (!awaited || awaited.type !== "AwaitExpression") return;
12700
+ if (!chainParsesBody(awaited.argument, code)) return;
12701
+ boundNames(id, names);
12702
+ };
12649
12703
  unit.traverse({
12650
12704
  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);
12705
+ record(decl.node.id, decl.node.init);
12706
+ },
12707
+ // `let data; data = await res.json();` — the same read, not a declaration.
12708
+ AssignmentExpression(assign) {
12709
+ if (assign.node.operator !== "=") return;
12710
+ record(assign.node.left, assign.node.right);
12669
12711
  },
12670
12712
  // The promise-chain spelling, which is the shipped defect's own:
12671
12713
  // fetch(u).then(r => r.json()).then(data => setRows(data.rows || []))
@@ -12683,19 +12725,21 @@ function parsedBodyBindings(unit, code) {
12683
12725
  if (!cb) return;
12684
12726
  if (cb.type !== "ArrowFunctionExpression" && cb.type !== "FunctionExpression") return;
12685
12727
  const param = cb.params[0];
12686
- if (param && param.type === "Identifier") names.add(param.name);
12728
+ if (param) boundNames(param, names);
12687
12729
  }
12688
12730
  });
12689
12731
  return names;
12690
12732
  }
12691
12733
  function derivesFromParsedBody(node, bodies, code) {
12692
- let cur = node;
12693
- while (cur.type === "MemberExpression" || cur.type === "OptionalMemberExpression") {
12694
- cur = cur.object;
12734
+ let cur = unwrap(node);
12735
+ while (cur && (cur.type === "MemberExpression" || cur.type === "OptionalMemberExpression")) {
12736
+ cur = unwrap(cur.object);
12695
12737
  }
12738
+ if (!cur) return false;
12696
12739
  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)));
12740
+ if (cur.type === "AwaitExpression") return chainParsesBody(cur.argument, code);
12741
+ if (cur.type === "CallExpression" || cur.type === "OptionalCallExpression") {
12742
+ return chainParsesBody(cur, code);
12699
12743
  }
12700
12744
  return false;
12701
12745
  }
@@ -12739,7 +12783,7 @@ var failedReadEmptyState = {
12739
12783
  category: "Correctness",
12740
12784
  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
12785
  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.",
12786
+ 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
12787
  check(ctx) {
12744
12788
  const hits = [];
12745
12789
  for (const file of ctx.files) {
@@ -12749,14 +12793,15 @@ var failedReadEmptyState = {
12749
12793
  if (/^\s*["']use server["']/m.test(file.code)) continue;
12750
12794
  const parsed = file.parsed;
12751
12795
  if (!parsed) continue;
12752
- const reported = /* @__PURE__ */ new Set();
12796
+ const examined = /* @__PURE__ */ new Set();
12753
12797
  traverse4(parsed.ast, {
12754
12798
  CallExpression(path) {
12755
12799
  if (!isFetchCallee(path.node.callee)) return;
12756
12800
  const unit = unitFor(path);
12757
12801
  if (!unit) return;
12758
12802
  const start = nodeStart(unit.node);
12759
- if (reported.has(start)) return;
12803
+ if (examined.has(start)) return;
12804
+ examined.add(start);
12760
12805
  const unitSource = file.code.slice(start, nodeEnd(unit.node));
12761
12806
  if (READ_ERROR_PATH_SIGNALS.some((re) => re.test(unitSource))) return;
12762
12807
  const bodies = parsedBodyBindings(unit, file.code);
@@ -12775,7 +12820,6 @@ var failedReadEmptyState = {
12775
12820
  }
12776
12821
  });
12777
12822
  if (!hit) return;
12778
- reported.add(start);
12779
12823
  const { line, setter } = hit;
12780
12824
  hits.push({
12781
12825
  file: file.path,
@@ -12805,6 +12849,22 @@ function isEffectCall2(node) {
12805
12849
  const name = calleeIdentifier(node);
12806
12850
  return name === "useEffect" || name === "useLayoutEffect";
12807
12851
  }
12852
+ function initialFor(call, state) {
12853
+ const binding = call.scope.getBinding(state);
12854
+ if (!binding) return void 0;
12855
+ const decl = binding.path;
12856
+ if (!decl.isVariableDeclarator()) return void 0;
12857
+ const id = decl.node.id;
12858
+ const init = decl.node.init;
12859
+ if (!id || id.type !== "ArrayPattern") return void 0;
12860
+ if (!init || init.type !== "CallExpression") return void 0;
12861
+ const callee = init.callee;
12862
+ const name = callee.type === "Identifier" ? callee.name : callee.type === "MemberExpression" && callee.property.type === "Identifier" ? callee.property.name : null;
12863
+ if (name !== "useState") return void 0;
12864
+ const first = id.elements[0];
12865
+ if (!first || first.type !== "Identifier" || first.name !== state) return void 0;
12866
+ return init.arguments[0];
12867
+ }
12808
12868
  function sameLiteral(a, b) {
12809
12869
  if (!a || !b || a.type !== b.type) return false;
12810
12870
  switch (a.type) {
@@ -12848,7 +12908,7 @@ var autosaveArmedByFailedLoad = {
12848
12908
  category: "Correctness",
12849
12909
  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
12910
  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.',
12911
+ 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
12912
  check(ctx) {
12853
12913
  const hits = [];
12854
12914
  for (const file of ctx.files) {
@@ -12858,22 +12918,6 @@ var autosaveArmedByFailedLoad = {
12858
12918
  const parsed = file.parsed;
12859
12919
  if (!parsed) continue;
12860
12920
  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
12921
  const armedInFinally = /* @__PURE__ */ new Map();
12878
12922
  traverse5(parsed.ast, {
12879
12923
  TryStatement(path) {
@@ -12885,7 +12929,7 @@ var autosaveArmedByFailedLoad = {
12885
12929
  if (!name) return;
12886
12930
  const state = stateFromSetter(name);
12887
12931
  if (!state) return;
12888
- if (setsBackToInitial(call.node, initialValues.get(state))) return;
12932
+ if (setsBackToInitial(call.node, initialFor(call, state))) return;
12889
12933
  armedInFinally.set(state, nodeStart(call.node));
12890
12934
  }
12891
12935
  });
@@ -13149,7 +13193,7 @@ var staleResponseWins = {
13149
13193
  category: "Correctness",
13150
13194
  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
13195
  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.',
13196
+ 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
13197
  check(ctx) {
13154
13198
  const hits = [];
13155
13199
  for (const file of ctx.files) {
@@ -13743,8 +13787,8 @@ var qualityRules = [
13743
13787
  var unmeasuredQualityRules = [
13744
13788
  lostUpdateCounter
13745
13789
  ];
13746
- function scanQuality(files, rules = qualityRules) {
13747
- const ctx = buildQualityContext(files);
13790
+ function scanQuality(files, rules = qualityRules, prebuilt) {
13791
+ const ctx = prebuilt ?? buildQualityContext(files);
13748
13792
  const findings = [];
13749
13793
  for (const rule of rules) {
13750
13794
  let hits;