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.js CHANGED
@@ -12403,6 +12403,119 @@ var failedReadEmptyState = {
12403
12403
  }
12404
12404
  };
12405
12405
 
12406
+ // src/quality/rules/autosave-armed-by-failed-load.ts
12407
+ import _traverse5 from "@babel/traverse";
12408
+ var traverse5 = typeof _traverse5 === "function" ? _traverse5 : _traverse5.default;
12409
+ var PERSISTENT_WRITE = /\bfetch\s*\([^)]{0,400}?method\s*:\s*["'`](?:POST|PUT|PATCH)["'`]|\blocalStorage\s*\.\s*setItem\s*\(|\bsessionStorage\s*\.\s*setItem\s*\(/is;
12410
+ var EMPTY_INITIAL = /\buseState\s*(?:<[^>]*>)?\s*\(\s*(?:\[\s*\]|\{\s*\}|""|''|``)\s*\)/;
12411
+ function calleeIdentifier(node) {
12412
+ if (node.type !== "CallExpression") return null;
12413
+ const c = node.callee;
12414
+ if (c.type === "Identifier") return c.name;
12415
+ if (c.type === "MemberExpression" && c.property.type === "Identifier") return c.property.name;
12416
+ return null;
12417
+ }
12418
+ function isEffectCall2(node) {
12419
+ const name = calleeIdentifier(node);
12420
+ return name === "useEffect" || name === "useLayoutEffect";
12421
+ }
12422
+ function stateFromSetter(setter) {
12423
+ const m = /^set([A-Z][A-Za-z0-9_]*)$/.exec(setter);
12424
+ if (!m) return null;
12425
+ return m[1].charAt(0).toLowerCase() + m[1].slice(1);
12426
+ }
12427
+ function identifiersIn(path) {
12428
+ const names = /* @__PURE__ */ new Set();
12429
+ path.traverse({
12430
+ Identifier(id) {
12431
+ names.add(id.node.name);
12432
+ }
12433
+ });
12434
+ const n = path.node;
12435
+ if (n.type === "Identifier" && n.name) names.add(n.name);
12436
+ return names;
12437
+ }
12438
+ var autosaveArmedByFailedLoad = {
12439
+ id: "QA010",
12440
+ title: "Autosave is armed by a load that failed",
12441
+ severity: "high",
12442
+ category: "Correctness",
12443
+ 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.",
12444
+ 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.",
12445
+ 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.',
12446
+ check(ctx) {
12447
+ const hits = [];
12448
+ for (const file of ctx.files) {
12449
+ if (file.excluded) continue;
12450
+ if (!file.isClient) continue;
12451
+ if (file.isServer) continue;
12452
+ const parsed = file.parsed;
12453
+ if (!parsed) continue;
12454
+ if (!EMPTY_INITIAL.test(file.code)) continue;
12455
+ const armedInFinally = /* @__PURE__ */ new Map();
12456
+ traverse5(parsed.ast, {
12457
+ TryStatement(path) {
12458
+ const finalizer = path.get("finalizer");
12459
+ if (!finalizer || Array.isArray(finalizer) || !finalizer.node) return;
12460
+ finalizer.traverse({
12461
+ CallExpression(call) {
12462
+ const name = calleeIdentifier(call.node);
12463
+ if (!name) return;
12464
+ const state = stateFromSetter(name);
12465
+ if (!state) return;
12466
+ armedInFinally.set(state, nodeStart(call.node));
12467
+ }
12468
+ });
12469
+ }
12470
+ });
12471
+ if (armedInFinally.size === 0) continue;
12472
+ const writingFunctions = /* @__PURE__ */ new Set();
12473
+ traverse5(parsed.ast, {
12474
+ Function(path) {
12475
+ const src = file.code.slice(nodeStart(path.node), nodeEnd(path.node));
12476
+ if (!PERSISTENT_WRITE.test(src)) return;
12477
+ let owner = path.parentPath;
12478
+ for (let hops = 0; owner && hops < 3; hops++, owner = owner.parentPath) {
12479
+ const node = owner.node;
12480
+ if (node.type === "VariableDeclarator" && node.id.type === "Identifier") {
12481
+ writingFunctions.add(node.id.name);
12482
+ break;
12483
+ }
12484
+ if (node.type !== "CallExpression") break;
12485
+ }
12486
+ const n = path.node;
12487
+ if (n.id && n.id.name) writingFunctions.add(n.id.name);
12488
+ }
12489
+ });
12490
+ const reported = /* @__PURE__ */ new Set();
12491
+ traverse5(parsed.ast, {
12492
+ CallExpression(path) {
12493
+ if (!isEffectCall2(path.node)) return;
12494
+ const cb = path.get("arguments.0");
12495
+ if (!cb || !cb.node) return;
12496
+ const body = file.code.slice(nodeStart(cb.node), nodeEnd(cb.node));
12497
+ const names = identifiersIn(cb);
12498
+ const writesDirectly = PERSISTENT_WRITE.test(body);
12499
+ const writesViaCallback = [...writingFunctions].some((fn) => names.has(fn));
12500
+ if (!writesDirectly && !writesViaCallback) return;
12501
+ for (const [state, armLine] of armedInFinally) {
12502
+ if (!names.has(state)) continue;
12503
+ if (reported.has(state)) continue;
12504
+ if (!new RegExp(`\\bif\\s*\\([^)]*\\b${state}\\b`).test(body)) continue;
12505
+ reported.add(state);
12506
+ hits.push({
12507
+ file: file.path,
12508
+ line: lineAt(file.content, armLine),
12509
+ 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.`
12510
+ });
12511
+ }
12512
+ }
12513
+ });
12514
+ }
12515
+ return hits;
12516
+ }
12517
+ };
12518
+
12406
12519
  // src/quality/examples.ts
12407
12520
  var QUALITY_EXAMPLES = {
12408
12521
  QA001: {
@@ -12466,6 +12579,68 @@ export function ApiKeysSection() {
12466
12579
  };
12467
12580
 
12468
12581
  useEffect(() => { load(); }, []);
12582
+ }`
12583
+ },
12584
+ QA010: {
12585
+ path: "app/checklist/page.tsx",
12586
+ language: "tsx",
12587
+ 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.",
12588
+ vulnerable: `"use client";
12589
+
12590
+ export function Checklist() {
12591
+ const [overrides, setOverrides] = useState({});
12592
+ const [stateLoaded, setStateLoaded] = useState(false);
12593
+
12594
+ useEffect(() => {
12595
+ (async () => {
12596
+ try {
12597
+ const res = await fetch("/api/checklist");
12598
+ const data = await res.json();
12599
+ if (data.state) setOverrides(data.state.overrides);
12600
+ } catch {
12601
+ // Non-critical
12602
+ } finally {
12603
+ setStateLoaded(true);
12604
+ }
12605
+ })();
12606
+ }, []);
12607
+
12608
+ const saveState = useCallback(() => {
12609
+ fetch("/api/checklist", { method: "POST", body: JSON.stringify({ overrides }) });
12610
+ }, [overrides]);
12611
+
12612
+ useEffect(() => {
12613
+ if (stateLoaded) saveState();
12614
+ }, [overrides, stateLoaded, saveState]);
12615
+ }`,
12616
+ safe: `"use client";
12617
+
12618
+ export function Checklist() {
12619
+ const [overrides, setOverrides] = useState({});
12620
+ const [stateLoaded, setStateLoaded] = useState(false);
12621
+ const [stateLoadFailed, setStateLoadFailed] = useState(false);
12622
+
12623
+ useEffect(() => {
12624
+ (async () => {
12625
+ try {
12626
+ const res = await fetch("/api/checklist");
12627
+ if (!res.ok) throw new Error(\`checklist load failed: HTTP \${res.status}\`);
12628
+ const data = await res.json();
12629
+ if (data.state) setOverrides(data.state.overrides);
12630
+ setStateLoaded(true);
12631
+ } catch {
12632
+ setStateLoadFailed(true);
12633
+ }
12634
+ })();
12635
+ }, []);
12636
+
12637
+ const saveState = useCallback(() => {
12638
+ fetch("/api/checklist", { method: "POST", body: JSON.stringify({ overrides }) });
12639
+ }, [overrides]);
12640
+
12641
+ useEffect(() => {
12642
+ if (stateLoaded && !stateLoadFailed) saveState();
12643
+ }, [overrides, stateLoaded, stateLoadFailed, saveState]);
12469
12644
  }`
12470
12645
  },
12471
12646
  QA002: {
@@ -12675,7 +12850,8 @@ var qualityRules = [
12675
12850
  undeclaredModal,
12676
12851
  unboundedList,
12677
12852
  unassociatedLabel,
12678
- failedReadEmptyState
12853
+ failedReadEmptyState,
12854
+ autosaveArmedByFailedLoad
12679
12855
  ];
12680
12856
  function scanQuality(files, rules = qualityRules) {
12681
12857
  const ctx = buildQualityContext(files);