xploitscan-shared-rules 1.35.0 → 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
@@ -51,6 +51,7 @@ __export(index_exports, {
51
51
  assessHeaders: () => assessHeaders,
52
52
  blockingMainThread: () => blockingMainThread,
53
53
  buildProjectContext: () => buildProjectContext,
54
+ buildQualityContext: () => buildQualityContext,
54
55
  buildTaintMap: () => buildTaintMap,
55
56
  calculateGrade: () => calculateGrade,
56
57
  callSpreads: () => callSpreads,
@@ -12643,6 +12644,105 @@ function setterName(callee) {
12643
12644
  function isPropertyRead(node) {
12644
12645
  return node.type === "MemberExpression" || node.type === "OptionalMemberExpression";
12645
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
+ }
12694
+ function parsedBodyBindings(unit, code) {
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
+ };
12703
+ unit.traverse({
12704
+ VariableDeclarator(decl) {
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);
12711
+ },
12712
+ // The promise-chain spelling, which is the shipped defect's own:
12713
+ // fetch(u).then(r => r.json()).then(data => setRows(data.rows || []))
12714
+ // `data` is a callback parameter rather than a binding, and it is just as
12715
+ // much a body this unit parsed. Keyed on the RECEIVER containing `.json(`,
12716
+ // so `somePromise.then(x => …)` does not qualify.
12717
+ CallExpression(call) {
12718
+ const callee = call.node.callee;
12719
+ if (callee.type !== "MemberExpression" && callee.type !== "OptionalMemberExpression")
12720
+ return;
12721
+ if (callee.property.type !== "Identifier" || callee.property.name !== "then") return;
12722
+ const receiver = callee.object;
12723
+ if (!/\.json\s*\(/.test(code.slice(nodeStart(receiver), nodeEnd(receiver)))) return;
12724
+ const cb = call.node.arguments[0];
12725
+ if (!cb) return;
12726
+ if (cb.type !== "ArrowFunctionExpression" && cb.type !== "FunctionExpression") return;
12727
+ const param = cb.params[0];
12728
+ if (param) boundNames(param, names);
12729
+ }
12730
+ });
12731
+ return names;
12732
+ }
12733
+ function derivesFromParsedBody(node, bodies, code) {
12734
+ let cur = unwrap(node);
12735
+ while (cur && (cur.type === "MemberExpression" || cur.type === "OptionalMemberExpression")) {
12736
+ cur = unwrap(cur.object);
12737
+ }
12738
+ if (!cur) return false;
12739
+ if (cur.type === "Identifier") return bodies.has(cur.name);
12740
+ if (cur.type === "AwaitExpression") return chainParsesBody(cur.argument, code);
12741
+ if (cur.type === "CallExpression" || cur.type === "OptionalCallExpression") {
12742
+ return chainParsesBody(cur, code);
12743
+ }
12744
+ return false;
12745
+ }
12646
12746
  function emptyFallbackArgument(node) {
12647
12747
  if (node.type !== "LogicalExpression") return null;
12648
12748
  if (node.operator !== "||" && node.operator !== "??") return null;
@@ -12683,7 +12783,7 @@ var failedReadEmptyState = {
12683
12783
  category: "Correctness",
12684
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.",
12685
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.",
12686
- 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. Measured at 6 fires over 5 sites in 437 real .tsx files with zero false positives, and silent on all three sites after they were fixed by hand.",
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.",
12687
12787
  check(ctx) {
12688
12788
  const hits = [];
12689
12789
  for (const file of ctx.files) {
@@ -12693,16 +12793,18 @@ var failedReadEmptyState = {
12693
12793
  if (/^\s*["']use server["']/m.test(file.code)) continue;
12694
12794
  const parsed = file.parsed;
12695
12795
  if (!parsed) continue;
12696
- const reported = /* @__PURE__ */ new Set();
12796
+ const examined = /* @__PURE__ */ new Set();
12697
12797
  traverse4(parsed.ast, {
12698
12798
  CallExpression(path) {
12699
12799
  if (!isFetchCallee(path.node.callee)) return;
12700
12800
  const unit = unitFor(path);
12701
12801
  if (!unit) return;
12702
12802
  const start = nodeStart(unit.node);
12703
- if (reported.has(start)) return;
12803
+ if (examined.has(start)) return;
12804
+ examined.add(start);
12704
12805
  const unitSource = file.code.slice(start, nodeEnd(unit.node));
12705
12806
  if (READ_ERROR_PATH_SIGNALS.some((re) => re.test(unitSource))) return;
12807
+ const bodies = parsedBodyBindings(unit, file.code);
12706
12808
  let hit = null;
12707
12809
  unit.traverse({
12708
12810
  CallExpression(inner) {
@@ -12713,11 +12815,11 @@ var failedReadEmptyState = {
12713
12815
  if (!arg) return;
12714
12816
  const fallback = emptyFallbackArgument(arg);
12715
12817
  if (!fallback) return;
12818
+ if (!derivesFromParsedBody(fallback.left, bodies, file.code)) return;
12716
12819
  hit = { line: lineAt(file.content, nodeStart(fallback)), setter: name };
12717
12820
  }
12718
12821
  });
12719
12822
  if (!hit) return;
12720
- reported.add(start);
12721
12823
  const { line, setter } = hit;
12722
12824
  hits.push({
12723
12825
  file: file.path,
@@ -12747,6 +12849,42 @@ function isEffectCall2(node) {
12747
12849
  const name = calleeIdentifier(node);
12748
12850
  return name === "useEffect" || name === "useLayoutEffect";
12749
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
+ }
12868
+ function sameLiteral(a, b) {
12869
+ if (!a || !b || a.type !== b.type) return false;
12870
+ switch (a.type) {
12871
+ case "BooleanLiteral":
12872
+ return a.value === b.value;
12873
+ case "NumericLiteral":
12874
+ return a.value === b.value;
12875
+ case "StringLiteral":
12876
+ return a.value === b.value;
12877
+ case "NullLiteral":
12878
+ return true;
12879
+ default:
12880
+ return false;
12881
+ }
12882
+ }
12883
+ function setsBackToInitial(call, initial) {
12884
+ if (call.type !== "CallExpression") return false;
12885
+ if (call.arguments.length !== 1) return false;
12886
+ return sameLiteral(call.arguments[0], initial);
12887
+ }
12750
12888
  function stateFromSetter(setter) {
12751
12889
  const m = /^set([A-Z][A-Za-z0-9_]*)$/.exec(setter);
12752
12890
  if (!m) return null;
@@ -12770,7 +12908,7 @@ var autosaveArmedByFailedLoad = {
12770
12908
  category: "Correctness",
12771
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.",
12772
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.",
12773
- 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.',
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.',
12774
12912
  check(ctx) {
12775
12913
  const hits = [];
12776
12914
  for (const file of ctx.files) {
@@ -12791,6 +12929,7 @@ var autosaveArmedByFailedLoad = {
12791
12929
  if (!name) return;
12792
12930
  const state = stateFromSetter(name);
12793
12931
  if (!state) return;
12932
+ if (setsBackToInitial(call.node, initialFor(call, state))) return;
12794
12933
  armedInFinally.set(state, nodeStart(call.node));
12795
12934
  }
12796
12935
  });
@@ -13054,7 +13193,7 @@ var staleResponseWins = {
13054
13193
  category: "Correctness",
13055
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.",
13056
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.",
13057
- 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.',
13058
13197
  check(ctx) {
13059
13198
  const hits = [];
13060
13199
  for (const file of ctx.files) {
@@ -13648,8 +13787,8 @@ var qualityRules = [
13648
13787
  var unmeasuredQualityRules = [
13649
13788
  lostUpdateCounter
13650
13789
  ];
13651
- function scanQuality(files, rules = qualityRules) {
13652
- const ctx = buildQualityContext(files);
13790
+ function scanQuality(files, rules = qualityRules, prebuilt) {
13791
+ const ctx = prebuilt ?? buildQualityContext(files);
13653
13792
  const findings = [];
13654
13793
  for (const rule of rules) {
13655
13794
  let hits;
@@ -13704,6 +13843,7 @@ function scanQuality(files, rules = qualityRules) {
13704
13843
  assessHeaders,
13705
13844
  blockingMainThread,
13706
13845
  buildProjectContext,
13846
+ buildQualityContext,
13707
13847
  buildTaintMap,
13708
13848
  calculateGrade,
13709
13849
  callSpreads,