xploitscan-shared-rules 1.30.0 → 1.31.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
@@ -12709,6 +12709,119 @@ var failedReadEmptyState = {
12709
12709
  }
12710
12710
  };
12711
12711
 
12712
+ // src/quality/rules/autosave-armed-by-failed-load.ts
12713
+ var import_traverse6 = __toESM(require("@babel/traverse"), 1);
12714
+ var traverse5 = typeof import_traverse6.default === "function" ? import_traverse6.default : import_traverse6.default.default;
12715
+ var PERSISTENT_WRITE = /\bfetch\s*\([^)]{0,400}?method\s*:\s*["'`](?:POST|PUT|PATCH)["'`]|\blocalStorage\s*\.\s*setItem\s*\(|\bsessionStorage\s*\.\s*setItem\s*\(/is;
12716
+ var EMPTY_INITIAL = /\buseState\s*(?:<[^>]*>)?\s*\(\s*(?:\[\s*\]|\{\s*\}|""|''|``)\s*\)/;
12717
+ function calleeIdentifier(node) {
12718
+ if (node.type !== "CallExpression") return null;
12719
+ const c = node.callee;
12720
+ if (c.type === "Identifier") return c.name;
12721
+ if (c.type === "MemberExpression" && c.property.type === "Identifier") return c.property.name;
12722
+ return null;
12723
+ }
12724
+ function isEffectCall2(node) {
12725
+ const name = calleeIdentifier(node);
12726
+ return name === "useEffect" || name === "useLayoutEffect";
12727
+ }
12728
+ function stateFromSetter(setter) {
12729
+ const m = /^set([A-Z][A-Za-z0-9_]*)$/.exec(setter);
12730
+ if (!m) return null;
12731
+ return m[1].charAt(0).toLowerCase() + m[1].slice(1);
12732
+ }
12733
+ function identifiersIn(path) {
12734
+ const names = /* @__PURE__ */ new Set();
12735
+ path.traverse({
12736
+ Identifier(id) {
12737
+ names.add(id.node.name);
12738
+ }
12739
+ });
12740
+ const n = path.node;
12741
+ if (n.type === "Identifier" && n.name) names.add(n.name);
12742
+ return names;
12743
+ }
12744
+ var autosaveArmedByFailedLoad = {
12745
+ id: "QA010",
12746
+ title: "Autosave is armed by a load that failed",
12747
+ severity: "high",
12748
+ category: "Correctness",
12749
+ 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.",
12750
+ 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.",
12751
+ 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.',
12752
+ check(ctx) {
12753
+ const hits = [];
12754
+ for (const file of ctx.files) {
12755
+ if (file.excluded) continue;
12756
+ if (!file.isClient) continue;
12757
+ if (file.isServer) continue;
12758
+ const parsed = file.parsed;
12759
+ if (!parsed) continue;
12760
+ if (!EMPTY_INITIAL.test(file.code)) continue;
12761
+ const armedInFinally = /* @__PURE__ */ new Map();
12762
+ traverse5(parsed.ast, {
12763
+ TryStatement(path) {
12764
+ const finalizer = path.get("finalizer");
12765
+ if (!finalizer || Array.isArray(finalizer) || !finalizer.node) return;
12766
+ finalizer.traverse({
12767
+ CallExpression(call) {
12768
+ const name = calleeIdentifier(call.node);
12769
+ if (!name) return;
12770
+ const state = stateFromSetter(name);
12771
+ if (!state) return;
12772
+ armedInFinally.set(state, nodeStart(call.node));
12773
+ }
12774
+ });
12775
+ }
12776
+ });
12777
+ if (armedInFinally.size === 0) continue;
12778
+ const writingFunctions = /* @__PURE__ */ new Set();
12779
+ traverse5(parsed.ast, {
12780
+ Function(path) {
12781
+ const src = file.code.slice(nodeStart(path.node), nodeEnd(path.node));
12782
+ if (!PERSISTENT_WRITE.test(src)) return;
12783
+ let owner = path.parentPath;
12784
+ for (let hops = 0; owner && hops < 3; hops++, owner = owner.parentPath) {
12785
+ const node = owner.node;
12786
+ if (node.type === "VariableDeclarator" && node.id.type === "Identifier") {
12787
+ writingFunctions.add(node.id.name);
12788
+ break;
12789
+ }
12790
+ if (node.type !== "CallExpression") break;
12791
+ }
12792
+ const n = path.node;
12793
+ if (n.id && n.id.name) writingFunctions.add(n.id.name);
12794
+ }
12795
+ });
12796
+ const reported = /* @__PURE__ */ new Set();
12797
+ traverse5(parsed.ast, {
12798
+ CallExpression(path) {
12799
+ if (!isEffectCall2(path.node)) return;
12800
+ const cb = path.get("arguments.0");
12801
+ if (!cb || !cb.node) return;
12802
+ const body = file.code.slice(nodeStart(cb.node), nodeEnd(cb.node));
12803
+ const names = identifiersIn(cb);
12804
+ const writesDirectly = PERSISTENT_WRITE.test(body);
12805
+ const writesViaCallback = [...writingFunctions].some((fn) => names.has(fn));
12806
+ if (!writesDirectly && !writesViaCallback) return;
12807
+ for (const [state, armLine] of armedInFinally) {
12808
+ if (!names.has(state)) continue;
12809
+ if (reported.has(state)) continue;
12810
+ if (!new RegExp(`\\bif\\s*\\([^)]*\\b${state}\\b`).test(body)) continue;
12811
+ reported.add(state);
12812
+ hits.push({
12813
+ file: file.path,
12814
+ line: lineAt(file.content, armLine),
12815
+ 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.`
12816
+ });
12817
+ }
12818
+ }
12819
+ });
12820
+ }
12821
+ return hits;
12822
+ }
12823
+ };
12824
+
12712
12825
  // src/quality/examples.ts
12713
12826
  var QUALITY_EXAMPLES = {
12714
12827
  QA001: {
@@ -12772,6 +12885,68 @@ export function ApiKeysSection() {
12772
12885
  };
12773
12886
 
12774
12887
  useEffect(() => { load(); }, []);
12888
+ }`
12889
+ },
12890
+ QA010: {
12891
+ path: "app/checklist/page.tsx",
12892
+ language: "tsx",
12893
+ 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.",
12894
+ vulnerable: `"use client";
12895
+
12896
+ export function Checklist() {
12897
+ const [overrides, setOverrides] = useState({});
12898
+ const [stateLoaded, setStateLoaded] = useState(false);
12899
+
12900
+ useEffect(() => {
12901
+ (async () => {
12902
+ try {
12903
+ const res = await fetch("/api/checklist");
12904
+ const data = await res.json();
12905
+ if (data.state) setOverrides(data.state.overrides);
12906
+ } catch {
12907
+ // Non-critical
12908
+ } finally {
12909
+ setStateLoaded(true);
12910
+ }
12911
+ })();
12912
+ }, []);
12913
+
12914
+ const saveState = useCallback(() => {
12915
+ fetch("/api/checklist", { method: "POST", body: JSON.stringify({ overrides }) });
12916
+ }, [overrides]);
12917
+
12918
+ useEffect(() => {
12919
+ if (stateLoaded) saveState();
12920
+ }, [overrides, stateLoaded, saveState]);
12921
+ }`,
12922
+ safe: `"use client";
12923
+
12924
+ export function Checklist() {
12925
+ const [overrides, setOverrides] = useState({});
12926
+ const [stateLoaded, setStateLoaded] = useState(false);
12927
+ const [stateLoadFailed, setStateLoadFailed] = useState(false);
12928
+
12929
+ useEffect(() => {
12930
+ (async () => {
12931
+ try {
12932
+ const res = await fetch("/api/checklist");
12933
+ if (!res.ok) throw new Error(\`checklist load failed: HTTP \${res.status}\`);
12934
+ const data = await res.json();
12935
+ if (data.state) setOverrides(data.state.overrides);
12936
+ setStateLoaded(true);
12937
+ } catch {
12938
+ setStateLoadFailed(true);
12939
+ }
12940
+ })();
12941
+ }, []);
12942
+
12943
+ const saveState = useCallback(() => {
12944
+ fetch("/api/checklist", { method: "POST", body: JSON.stringify({ overrides }) });
12945
+ }, [overrides]);
12946
+
12947
+ useEffect(() => {
12948
+ if (stateLoaded && !stateLoadFailed) saveState();
12949
+ }, [overrides, stateLoaded, stateLoadFailed, saveState]);
12775
12950
  }`
12776
12951
  },
12777
12952
  QA002: {
@@ -12981,7 +13156,8 @@ var qualityRules = [
12981
13156
  undeclaredModal,
12982
13157
  unboundedList,
12983
13158
  unassociatedLabel,
12984
- failedReadEmptyState
13159
+ failedReadEmptyState,
13160
+ autosaveArmedByFailedLoad
12985
13161
  ];
12986
13162
  function scanQuality(files, rules = qualityRules) {
12987
13163
  const ctx = buildQualityContext(files);