xploitscan-shared-rules 2.0.1 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -53,9 +53,9 @@ function isInlineSilenced(content, matchIndex, ruleId) {
53
53
  }
54
54
  function isLineSilenced(lines, lineIdx, ruleId) {
55
55
  const matchLine = lines[lineIdx] ?? "";
56
- const marker = new RegExp(`(?://|/\\*|#)\\s*(?:${ruleId}|scanner)-OK\\b`, "i");
56
+ const marker = new RegExp(`(?://|/\\*|#|--)\\s*(?:${ruleId}|scanner)-OK\\b`, "i");
57
57
  if (marker.test(matchLine)) return true;
58
- const COMMENT_LINE = /^\s*[{(]?\s*(?:\/\/|#|\/\*|\*)/;
58
+ const COMMENT_LINE = /^\s*[{(]?\s*(?:\/\/|#|\/\*|\*|--)/;
59
59
  const MAX_BLOCK_LINES = 20;
60
60
  for (let i = lineIdx - 1, seen = 0; i >= 0 && seen < MAX_BLOCK_LINES; i--, seen++) {
61
61
  const line = lines[i] ?? "";
@@ -84,7 +84,7 @@ var RULE_IMPACTS = {
84
84
  VC008: "Without rate limiting, an attacker can flood your API with requests causing denial of service, brute-force attacks, or excessive cloud billing.",
85
85
  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.",
86
86
  VC010: "Hiding UI elements without server-side checks means an attacker can call your API directly and bypass the restriction entirely.",
87
- 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.",
87
+ VC011: "A browser-exposed prefix (NEXT_PUBLIC_, VITE_, REACT_APP_, EXPO_PUBLIC_ and the like) puts this value in the bundle shipped to every visitor or app user. If it's a secret, anyone viewing your site's JavaScript can extract it.",
88
88
  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.",
89
89
  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.",
90
90
  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 \u2014 including the entire internet if the repo is public.",
@@ -287,7 +287,16 @@ var RULE_IMPACTS = {
287
287
  VC211: "A real credit card number in source is cardholder data sitting in git history, CI logs, and every backup \u2014 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.",
288
288
  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.",
289
289
  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 \u2014 no exploit, no tooling, just typing. Every paid tier and admin panel gated this way is open to anyone who opens the console.",
290
- 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 \u2014 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."
290
+ 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 \u2014 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.",
291
+ VC215: "The Supabase anon key ships in every browser, so the row level security in your migrations is the only access control. Depending on the finding: with RLS off, or a write policy that is always true, anyone with that key can change or delete the table's rows (and read them, unless grants were revoked or a later migration fixed it); an insert-only open policy lets anyone add rows; a policy that reads user_metadata lets users grant themselves whatever role or tenant it checks.",
292
+ VC216: "A Firebase app has no server in front of its database, so the rules file is the only thing deciding who gets in. Depending on the finding: open rules let anyone, or anyone who signs up, read, change or delete the data behind the app, including other users' records and uploads; an open create rule lets anyone add records; and expired test-mode rules already deny everything, so the risk is that they get extended instead of replaced.",
293
+ VC217: "This key ends up in code shipped to every visitor or app user \u2014 the JavaScript bundle or the installed app \u2014 so anyone can copy it and run AI requests, or reach whatever the secret unlocks, on your account and your bill.",
294
+ VC220: "Anyone who finds this endpoint's URL \u2014 it ships in your JavaScript bundle \u2014 can send it requests that run your AI model on your account, so a script in a loop can burn through your AI credits or API budget while you pay the bill.",
295
+ VC218: "Base44 serves every backend function as a public endpoint, and asServiceRole ignores every access rule, so a function that uses it without asking who is calling lets anyone on the internet read, change or delete the records it touches.",
296
+ VC219: "Supabase user_metadata and Clerk unsafeMetadata can be rewritten by the signed-in user from the browser, so a role, plan or permission checked there can be granted by any user to themselves with one API call.",
297
+ VC221: "A server that takes the caller's identity from Supabase getSession(), jwt.decode() or a JWT decoded with signature checks off believes whatever the cookie or token says, so anyone can forge one and be treated as any user, including an admin.",
298
+ VC222: "Your API answers every website's origin with credentials allowed, so if it uses cookie sessions, any page a signed-in user visits can call it as that user and read the responses.",
299
+ VC223: "The check meant to stop path traversal also lets through any sibling folder whose name starts with the base folder's name, so a request for /srv/uploads-private passes a guard for /srv/uploads."
291
300
  };
292
301
 
293
302
  // src/exposure.ts
@@ -866,6 +875,77 @@ function checkIntent(files, findings) {
866
875
  return { statements, mismatches, sources, unchallenged, uncheckable };
867
876
  }
868
877
 
878
+ // src/public-env.ts
879
+ var PUBLIC_ENV_PREFIX_RE = /^(?:NEXT_PUBLIC_|NUXT_PUBLIC_|EXPO_PUBLIC_|REACT_APP_|GATSBY_|VITE_|PUBLIC_)/i;
880
+ var STRONG_SECRET_ENV_WORD_RE = /SECRET|PASSWORD|PASSWD|SERVICE_?ROLE|SUPABASE_SERVICE/;
881
+ var QUALIFIED_SECRET_ENV_WORD_RE = /PRIVATE|ADMIN|SERVER|SERVICE_?ACCOUNT|PERSONAL|MANAGEMENT|MASTER/;
882
+ var NON_SECRET_KEY_TAIL = "ADDRESS|ADDR|SYMBOL|URL|URI|ID|IDS|NAME|DECIMALS?|LIST|CONTRACT|LOGO|IMAGE|ICON|PRICE|MINT|CHAIN|AMOUNT|SUPPLY|TYPE|EXPIRY|EXPIRES|EXPIRATION|TTL|LIFETIME|ENDPOINT|HEADER|STORAGE|PREFIX|PATH|FILE|LENGTH|SIZE|LIMIT|ENABLED|DISABLED|MODE|COUNT|NETWORK|STANDARD|PAIR|PROGRAM|ACCOUNT|TICKER|DENOM|CURRENCY|UNIT|ISSUER|POOL|FACTORY|ROUTER|BRIDGE|GATE|GATED|GATING|HOLDER|BALANCE|VAULT";
883
+ var KEY_SEGMENT_RE = new RegExp(
884
+ `(?:^|_)(?:(?:API|ACCESS|AUTH|BEARER|REFRESH|SESSION)_?TOKENS|(?:API|ACCESS|AUTH|SECRET|PRIVATE|MASTER|SIGNING|ENCRYPTION|LICENSE|APP|SERVICE|WRITE|READ|ADMIN|BEARER|REFRESH|SESSION|OPENAI|GEMINI|GROQ|ANTHROPIC|CLAUDE|MISTRAL|COHERE|DEEPSEEK|PERPLEXITY|REPLICATE|ELEVENLABS|HUGGINGFACE|OPENROUTER)?(?:KEYS?|TOKEN))(?:_?V?\\d{1,3})?(?:_(?!(?:${NON_SECRET_KEY_TAIL})(?:_|\\d|$))[A-Z]{1,12}(?:_?\\d{1,3})?)?$`
885
+ );
886
+ var KEYISH_WORD_RE = /SECRET|PASSWORD|PASSWD|CREDENTIALS?$|(?:^|_)PRIVATE$/;
887
+ var NON_SECRET_WORD_VALUE_RE = /^(?:true|false|yes|no|on|off|null|undefined)$/i;
888
+ var NUMBER_VALUE_RE = /^-?\d+(?:\.\d+)?$/;
889
+ var SECRET_TAIL_RE = /(?:SECRET|PASSWORD|PASSWD|PASSCODE|PIN)(?:_KEY)?$/;
890
+ var NUMERIC_SECRET_VALUE_RE = /^\d{4,}$/;
891
+ var PLAIN_URL_VALUE_RE = /^https?:\/\/[^\s@]+$/i;
892
+ function urlCarriesToken(url) {
893
+ const rest = url.replace(/^https?:\/\/[^/?#]*/i, "");
894
+ for (const seg of rest.split(/[/?#&=.:;,]/)) {
895
+ if (seg.length < 20 || !/^[A-Za-z0-9_-]+$/.test(seg)) continue;
896
+ if (!/\d/.test(seg) || !/[A-Za-z]/.test(seg)) continue;
897
+ if (seg.split(/[-_]/).some((run) => run.length >= 16)) return true;
898
+ }
899
+ return false;
900
+ }
901
+ var PUBLIC_BY_DESIGN_ENV_RE = /PUBLISHABLE|ANON_?KEY|PUBLIC_?KEY|SITE_?KEY|FIREBASE|(?:^|_)MAPS?(?:_|$)|MAPBOX|PUSHER|REVERB|ALGOLIA_SEARCH|SEARCH_ONLY|POSTHOG|MIXPANEL|AMPLITUDE|SEGMENT_WRITE|CLIENT_?(?:KEY|TOKEN)|VAPID|RECAPTCHA|HCAPTCHA|TURNSTILE|(?:^|_)IDS?$|(?:WEB3FORMS|REVENUECAT|TINYMCE|BUGSNAG|OPTIMIZELY|FLAGSMITH|CONFIGCAT|VEXO)(?![A-Z0-9_]{0,80}TOKEN)|(?:^|_)SDK_?KEY(?:_?\d{1,3})?$/;
902
+ var PUBLIC_VALUE_PREFIX_RE = /^(?:pk_(?:test|live)_|sb_publishable_|phc_|pk\.ey|(?:appl|goog|amzn|strp)_)/;
903
+ var SECRET_VALUE_PREFIX_RE = /^(?:phx_|sk\.ey|sk_[A-Za-z0-9_]{16}|ser\.[A-Za-z0-9]{16}|sdk-[0-9a-f]{8}-)/;
904
+ function isAnonJwt(value) {
905
+ const m = /^eyJ[A-Za-z0-9_-]{1,200}\.(eyJ[A-Za-z0-9_-]{1,2000})\./.exec(value);
906
+ if (!m) return false;
907
+ try {
908
+ const b64 = m[1].replace(/-/g, "+").replace(/_/g, "/");
909
+ const json = typeof atob === "function" ? atob(b64 + "=".repeat((4 - b64.length % 4) % 4)) : "";
910
+ return /"role"\s*:\s*"anon"/.test(json);
911
+ } catch {
912
+ return false;
913
+ }
914
+ }
915
+ function classifyPublicEnvVar(name, value = "") {
916
+ const m = PUBLIC_ENV_PREFIX_RE.exec(name);
917
+ if (!m) return null;
918
+ const prefix = m[0].toUpperCase();
919
+ const upper = name.toUpperCase();
920
+ const rest = upper.slice(prefix.length);
921
+ const v = value.trim().replace(/^["'`]/, "");
922
+ const notSecret = { prefix, secret: false, publicByDesign: true };
923
+ if (PUBLIC_VALUE_PREFIX_RE.test(v) || NON_SECRET_WORD_VALUE_RE.test(v) || isAnonJwt(v)) return notSecret;
924
+ if (NUMBER_VALUE_RE.test(v) && !(SECRET_TAIL_RE.test(rest) && NUMERIC_SECRET_VALUE_RE.test(v))) return notSecret;
925
+ if (PLAIN_URL_VALUE_RE.test(v) && !urlCarriesToken(v)) return notSecret;
926
+ if (SECRET_VALUE_PREFIX_RE.test(v)) return { prefix, secret: true, publicByDesign: false };
927
+ const keyish = KEY_SEGMENT_RE.test(rest) || KEYISH_WORD_RE.test(rest);
928
+ if (STRONG_SECRET_ENV_WORD_RE.test(rest)) return { prefix, secret: true, publicByDesign: false };
929
+ if (QUALIFIED_SECRET_ENV_WORD_RE.test(rest) && keyish) return { prefix, secret: true, publicByDesign: false };
930
+ if (PUBLIC_BY_DESIGN_ENV_RE.test(upper)) return notSecret;
931
+ return { prefix, secret: keyish, publicByDesign: false };
932
+ }
933
+ var DOTENV_FILE_RE = /(?:^|\/)(?:\.env(?:\.[\w.-]+)?|[\w.-]+\.env)$/;
934
+ function isDotenvPath(filePath) {
935
+ return DOTENV_FILE_RE.test(filePath);
936
+ }
937
+ var DOTENV_ASSIGN_RE = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]{0,127})\s*=\s*([^\r\n]*)/;
938
+ function dotenvValue(raw) {
939
+ const v = raw.trim();
940
+ const q = v[0];
941
+ if (q === '"' || q === "'" || q === "`") {
942
+ const end = v.indexOf(q, 1);
943
+ return end === -1 ? v.slice(1) : v.slice(1, end);
944
+ }
945
+ const hash = v.search(/\s#/);
946
+ return (hash === -1 ? v : v.slice(0, hash)).trim();
947
+ }
948
+
869
949
  // src/ast/parse.ts
870
950
  import { parse } from "@babel/parser";
871
951
  var MAX_CACHE = 256;
@@ -1413,7 +1493,23 @@ function isTestFile(filePath) {
1413
1493
  }
1414
1494
  var HANDLER_HEADER_RE = /(?:\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;
1415
1495
  function maskComments(content) {
1416
- return content.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, " ")).replace(/(^|[^:])\/\/[^\n]*/gm, (m, p1) => p1 + " ".repeat(m.length - p1.length));
1496
+ return replaceBlockComments(content, (c) => c.replace(/[^\n]/g, " ")).replace(/(^|[^:])\/\/[^\n]*/gm, (m, p1) => p1 + " ".repeat(m.length - p1.length));
1497
+ }
1498
+ function replaceBlockComments(content, replace) {
1499
+ let open = content.indexOf("/*");
1500
+ if (open === -1) return content;
1501
+ const parts = [];
1502
+ let copied = 0;
1503
+ while (open !== -1) {
1504
+ const close = content.indexOf("*/", open + 2);
1505
+ if (close === -1) break;
1506
+ parts.push(content.slice(copied, open), replace(content.slice(open, close + 2)));
1507
+ copied = close + 2;
1508
+ open = content.indexOf("/*", copied);
1509
+ }
1510
+ if (parts.length === 0) return content;
1511
+ parts.push(content.slice(copied));
1512
+ return parts.join("");
1417
1513
  }
1418
1514
  function enclosingHandler(content, index) {
1419
1515
  const MAX_LEVELS = 6;
@@ -1486,10 +1582,11 @@ var SERVER_SIDE_PATH_RE = new RegExp(
1486
1582
  "i"
1487
1583
  );
1488
1584
  var SERVER_SIDE_CONTENT_RE = /\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/;
1585
+ var USE_SERVER_DIRECTIVE_RE = /^[ \t\uFEFF]*["']use server["']/m;
1489
1586
  function isServerSideFile(filePath, content) {
1490
1587
  if (isTestFile(filePath)) return false;
1491
1588
  if (SERVER_SIDE_PATH_RE.test(filePath)) return true;
1492
- if (content && /^\s*["']use server["']/m.test(content)) return true;
1589
+ if (content && USE_SERVER_DIRECTIVE_RE.test(content)) return true;
1493
1590
  if (content && SERVER_SIDE_CONTENT_RE.test(content)) return true;
1494
1591
  return false;
1495
1592
  }
@@ -1589,12 +1686,37 @@ function tryParse(content, filePath) {
1589
1686
  parseCacheValid = true;
1590
1687
  return result;
1591
1688
  }
1592
- function isNamespacedSlotKey(value) {
1689
+ function isNamespacedSlotKey(name, value) {
1690
+ if (CREDENTIAL_NAME.test(name)) return false;
1593
1691
  const words = value.split(/[.:/_-]/);
1594
1692
  if (words[words.length - 1] === "") words.pop();
1595
1693
  if (words.length < 2) return false;
1694
+ if (words.some((w) => CREDENTIAL_WORD.test(w))) return false;
1596
1695
  return words.every((w) => /^[a-z]+[0-9]*(?:[A-Z][a-z]+[0-9]*)*$/.test(w));
1597
1696
  }
1697
+ var 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/;
1698
+ var CREDENTIAL_WORD = /secret|passw|token|private|signing|apikey|credential/i;
1699
+ function isPlaceholderToken(token) {
1700
+ if (/(.)\1{7,}/.test(token)) return true;
1701
+ if (new Set(token).size < 8) return true;
1702
+ return /example|placeholder|redacted|your_?(?:api_?)?(?:key|token)|insert_?your|replace_?me/i.test(token);
1703
+ }
1704
+ var GEMINI_FILE_CONTEXT_RE = /generativelanguage\.googleapis\.com|@google\/generative-ai|@google\/genai|\bGoogleGenerativeAI\b|\bGoogleGenAI\b|\bgoogle\.generativeai\b|\bfrom\s+google\s+import\s+genai\b/;
1705
+ var GEMINI_NAME_RE = /gemini|generative/i;
1706
+ var PUBLIC_GOOGLE_KEY_NAME_RE = /firebase|maps?(?:\b|_)|places|recaptcha|youtube/i;
1707
+ var FIREBASE_CONFIG_FIELD_RE = /\b(?:authDomain|messagingSenderId|storageBucket)\b/;
1708
+ function isGeminiKeyContext(lines, line, fileIsGemini) {
1709
+ const lineText = lines[line - 1] ?? "";
1710
+ const keyAt = lineText.search(/AIza[\w-]{35}/);
1711
+ const before = keyAt === -1 ? lineText : lineText.slice(0, keyAt);
1712
+ if (PUBLIC_GOOGLE_KEY_NAME_RE.test(before)) return false;
1713
+ const from = Math.max(0, line - 4);
1714
+ const to = Math.min(lines.length, line + 3);
1715
+ for (let i = from; i < to; i++) {
1716
+ if (FIREBASE_CONFIG_FIELD_RE.test(lines[i])) return false;
1717
+ }
1718
+ return fileIsGemini || GEMINI_NAME_RE.test(before);
1719
+ }
1598
1720
  var hardcodedSecrets = {
1599
1721
  id: "VC001",
1600
1722
  title: "Hardcoded API Key or Secret",
@@ -1614,8 +1736,16 @@ var hardcodedSecrets = {
1614
1736
  /(?:sk_live|pk_live|sk_test|pk_test)_[a-zA-Z0-9]{20,}/g,
1615
1737
  // Supabase anon/service keys (JWT format)
1616
1738
  /(?:supabase[_-]?(?:anon|service)[_-]?key|SUPABASE_(?:ANON|SERVICE_ROLE)_KEY)\s*[:=]\s*["'`](eyJ[a-zA-Z0-9_-]{50,})["'`]/gi,
1617
- // OpenAI keys
1618
- /sk-[a-zA-Z0-9]{20,}T3BlbkFJ[a-zA-Z0-9]{20,}/g,
1739
+ // OpenAI keys. Every OpenAI secret key carries `T3BlbkFJ` (base64 of
1740
+ // "OpenAI") in the middle, which is what keeps this near zero false
1741
+ // positives. This used to be `sk-[a-zA-Z0-9]{20,}T3BlbkFJ…`, the legacy
1742
+ // user-key shape: its character class has no `-`, so it could not get
1743
+ // past the second hyphen of `sk-proj-`, and every project, service
1744
+ // account and admin key OpenAI has issued since 2024 went unreported.
1745
+ // Prefixes and the `-`/`_` body follow gitleaks' openai-api-key rule.
1746
+ // Bounded on both sides so a hostile run of key characters cannot
1747
+ // backtrack a whole line.
1748
+ /sk-(?:(?:proj|svcacct|admin)-[A-Za-z0-9_-]{20,80}|[A-Za-z0-9]{20,80})T3BlbkFJ[A-Za-z0-9_-]{20,80}/g,
1619
1749
  // Generic tokens in assignments — require standalone word and longer min length
1620
1750
  /(?:^|[\s,({])(?:token|secret|password|passwd|pwd)\s*[:=]\s*["'`]([a-zA-Z0-9_\-!@#$%^&*]{20,})["'`]/gim,
1621
1751
  // SCREAMING_CASE identifiers ending in SECRET/TOKEN/KEY/PASSWORD
@@ -1632,20 +1762,42 @@ var hardcodedSecrets = {
1632
1762
  // Private keys
1633
1763
  /-----BEGIN (?:RSA |EC |DSA )?PRIVATE KEY-----/g,
1634
1764
  // Database URLs with credentials
1635
- /(?:postgres|mysql|mongodb(?:\+srv)?):\/\/[^:]+:[^@]+@[^/\s"'`]+/gi
1765
+ /(?:postgres|mysql|mongodb(?:\+srv)?):\/\/[^:]+:[^@]+@[^/\s"'`]+/gi,
1766
+ // ── [11]–[14] Fixed-prefix AI-provider and payment keys ──
1767
+ // These match the token itself, so they fire whatever it is bound to:
1768
+ // `const k = "…"`, a positional `new OpenAI("…")`, an unquoted .env
1769
+ // value. The name-based patterns above only see a key that sits in a
1770
+ // slot called apiKey / token / *_KEY. Shapes follow gitleaks.
1771
+ // [11] Hugging Face user access token: `hf_` + 34 letters.
1772
+ /\bhf_[A-Za-z]{34}\b/g,
1773
+ // [12] OpenRouter: `sk-or-v1-` + 64 hex.
1774
+ /\bsk-or-v1-[a-f0-9]{64}\b/g,
1775
+ // [13] Stripe restricted key. `rk_` keys are scoped, but a live one can
1776
+ // still read customers or issue refunds, and [2] above only knows
1777
+ // `sk_`/`pk_`. No trailing anchor: Stripe keys run to ~100 characters
1778
+ // and the match only needs the prefix plus a real body.
1779
+ /\brk_(?:live|test)_[A-Za-z0-9]{20,200}/g,
1780
+ // [14] Google API key — reported only in a Gemini context, see
1781
+ // GEMINI_FILE_CONTEXT_RE. The lookahead stands in for `\b`, which the
1782
+ // `-` in the key alphabet would break.
1783
+ /AIza[\w-]{35}(?![\w-])/g
1636
1784
  ];
1637
1785
  const fixMessages = [
1638
1786
  "Move this API key to an environment variable. If this key has been committed, rotate it immediately \u2014 it may have already been scraped by bots.",
1639
1787
  "AWS access key detected \u2014 may grant full account access (EC2, S3, IAM, billing). Rotate immediately in AWS Console \u2192 IAM \u2192 Security Credentials. Use IAM roles or environment variables instead.",
1640
1788
  "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 \u2192 Developers \u2192 API Keys.",
1641
1789
  "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.",
1642
- "OpenAI API key detected \u2014 grants full API access and can incur charges. Rotate at platform.openai.com \u2192 API Keys.",
1790
+ "OpenAI API key detected (sk-proj-, sk-svcacct-, sk-admin- or a legacy sk- key). Anyone holding it can run models on your bill, and an admin key can also manage your organization's keys and members. Revoke it at platform.openai.com \u2192 API keys and load the replacement from server-side configuration. Browser code cannot keep a key secret, so browser features must reach OpenAI through your own backend.",
1643
1791
  "Hardcoded token or password detected. Move to an environment variable and rotate the credential if it has been committed to version control.",
1644
1792
  "Named secret constant detected (XXX_SECRET / XXX_TOKEN / XXX_KEY). If it's a real credential, move it to server-side configuration \u2014 an environment variable read by server code (`process.env.NAME` in Node) \u2014 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.",
1645
1793
  "Credential assigned to a config object property. Move to an environment variable \u2014 `apiKey: process.env.API_KEY` \u2014 and rotate the value if this file has been committed.",
1646
1794
  "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.",
1647
1795
  "Private key found in source code. If this has been committed to version control, consider the key compromised \u2014 generate a new key pair and revoke the old one.",
1648
- "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."
1796
+ "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.",
1797
+ "Hugging Face access token detected (hf_). Depending on its scope it can read your private models and datasets, push to your repos, and run paid Inference Endpoints. Revoke it at huggingface.co \u2192 Settings \u2192 Access Tokens and load the replacement from server-side configuration.",
1798
+ "OpenRouter API key detected (sk-or-v1-). It spends your OpenRouter credits on any model the account can reach. Delete it at openrouter.ai \u2192 Keys and load the replacement from server-side configuration. Browser features must reach OpenRouter through your own backend.",
1799
+ "Stripe restricted key detected (rk_). Whatever it was granted \u2014 reading customers, creating charges, issuing refunds \u2014 anyone with this file has too. Roll it in Stripe Dashboard \u2192 Developers \u2192 API keys and load the replacement from server-side configuration.",
1800
+ "Google API key in code that calls Gemini. If the Generative Language API is enabled on its project, anyone with the key can run Gemini requests billed to you. Delete or regenerate it in Google Cloud Console \u2192 APIs & Services \u2192 Credentials, and call Gemini from your own backend with a key that is not in source."
1649
1801
  ];
1650
1802
  const minLen = [
1651
1803
  12,
@@ -1656,8 +1808,12 @@ var hardcodedSecrets = {
1656
1808
  // [2] Stripe
1657
1809
  50,
1658
1810
  // [3] Supabase JWT
1659
- 40,
1660
- // [4] OpenAI
1811
+ // [4] OpenAI and [11]–[14] fixed-prefix tokens: the regex already
1812
+ // fixes the length. The floor check reads the FIRST quoted value on the
1813
+ // line, which in `a = "x"; key = "sk-proj-…"` is not the token, so it
1814
+ // must not run for them. ([4] was 40, which the regex's minimum of 48
1815
+ // made redundant everywhere except that misread.)
1816
+ 0,
1661
1817
  20,
1662
1818
  // [5] generic tokens with {20,} in the regex
1663
1819
  12,
@@ -1668,18 +1824,49 @@ var hardcodedSecrets = {
1668
1824
  // [8] password: "..." — lower floor per the pattern comment above
1669
1825
  0,
1670
1826
  // [9] private keys — no length check
1671
- 0
1827
+ 0,
1672
1828
  // [10] DB URLs — no length check
1829
+ 0,
1830
+ 0,
1831
+ 0,
1832
+ 0
1833
+ // [11]–[14] see [4]
1673
1834
  ];
1835
+ const OPENAI_PI = 4;
1836
+ const FIRST_TOKEN_PI = 11;
1837
+ const STRIPE_RESTRICTED_PI = 13;
1838
+ const GOOGLE_PI = 14;
1839
+ const lines = content.split("\n");
1840
+ const fileIsGemini = GEMINI_FILE_CONTEXT_RE.test(content);
1674
1841
  const matches = [];
1675
1842
  for (let pi = 0; pi < patterns.length; pi++) {
1676
1843
  const pattern = patterns[pi];
1677
- const rawMatches = findMatches(content, pattern, hardcodedSecrets, filePath, () => fixMessages[pi]);
1844
+ if (pi === GOOGLE_PI && !fileIsGemini && !GEMINI_NAME_RE.test(content)) continue;
1845
+ const matchedText = [];
1846
+ const rawMatches = findMatches(content, pattern, hardcodedSecrets, filePath, (m) => {
1847
+ matchedText.push(m[0]);
1848
+ return fixMessages[pi];
1849
+ });
1678
1850
  const floor = minLen[pi] ?? 12;
1679
- for (const rm of rawMatches) {
1680
- const lineText = content.split("\n")[rm.line - 1] || "";
1851
+ const isTokenPattern = pi === OPENAI_PI || pi >= FIRST_TOKEN_PI;
1852
+ for (let ri = 0; ri < rawMatches.length; ri++) {
1853
+ const rm = rawMatches[ri];
1854
+ const lineText = lines[rm.line - 1] || "";
1681
1855
  const trimmed = lineText.trimStart();
1682
1856
  if (trimmed.startsWith("//") || trimmed.startsWith("#")) continue;
1857
+ if (isTokenPattern) {
1858
+ const token = matchedText[ri] ?? "";
1859
+ if (isPlaceholderToken(token)) continue;
1860
+ if (pi === GOOGLE_PI) {
1861
+ if (!isGeminiKeyContext(lines, rm.line, fileIsGemini)) continue;
1862
+ matches.push({ ...rm, severity: "high" });
1863
+ continue;
1864
+ }
1865
+ if (pi === STRIPE_RESTRICTED_PI && !token.startsWith("rk_live_")) {
1866
+ matches.push({ ...rm, severity: "high" });
1867
+ continue;
1868
+ }
1869
+ }
1683
1870
  if (floor > 0) {
1684
1871
  const secretMatch = lineText.match(/[:=]\s*["'`]([^"'`]*)["'`]/);
1685
1872
  if (secretMatch && secretMatch[1].length < floor) continue;
@@ -1690,7 +1877,7 @@ var hardcodedSecrets = {
1690
1877
  if (valMatch && nameMatch) {
1691
1878
  const value = valMatch[1];
1692
1879
  const isKeySuffix = nameMatch[1].endsWith("_KEY");
1693
- const isSlotIdentifier = value.length < 40 && (/^[a-z0-9]+([_-][a-z0-9]+)+$/.test(value) || isNamespacedSlotKey(value));
1880
+ const isSlotIdentifier = value.length < 40 && (/^[a-z0-9]+([_-][a-z0-9]+)+$/.test(value) || isNamespacedSlotKey(nameMatch[1], value));
1694
1881
  if (isKeySuffix && isSlotIdentifier) continue;
1695
1882
  }
1696
1883
  }
@@ -1796,6 +1983,323 @@ function stripCorsHeaderList(codeOnly) {
1796
1983
  ""
1797
1984
  );
1798
1985
  }
1986
+ function blankKeepLines(s) {
1987
+ return s.replace(/[^\n]/g, " ");
1988
+ }
1989
+ function closingBrace(text, open, limit) {
1990
+ let depth = 0;
1991
+ const end = Math.min(text.length, open + limit);
1992
+ for (let i = open; i < end; i++) {
1993
+ const c = text.charCodeAt(i);
1994
+ if (c === 34 || c === 39) {
1995
+ let j = i + 1;
1996
+ while (j < end) {
1997
+ const d = text.charCodeAt(j);
1998
+ if (d === 92) {
1999
+ j += 2;
2000
+ continue;
2001
+ }
2002
+ if (d === c || d === 10) break;
2003
+ j++;
2004
+ }
2005
+ i = j;
2006
+ continue;
2007
+ }
2008
+ if (c === 123) depth++;
2009
+ else if (c === 125) {
2010
+ depth--;
2011
+ if (depth === 0) return i;
2012
+ }
2013
+ }
2014
+ return -1;
2015
+ }
2016
+ var INBOUND_CREDENTIAL_READ_RE = /\b(?:req|request|c\.req|ctx\.request|event)\s*\.\s*headers?\b|\.headers\s*\.\s*get\s*\(|\bget(?:Request)?Header\s*\(|\bauth(?:orization)?Header\b/i;
2017
+ function forwardsCallerCredential(headersInner, readsCaller) {
2018
+ const CRED_ENTRY_RE = /["']?(?:authorization|x-api-key|api-key|apikey|x-auth-token|x-access-token|cookie)["']?\s*:\s*([^,\n}]{0,300})/gi;
2019
+ let e;
2020
+ while ((e = CRED_ENTRY_RE.exec(headersInner)) !== null) {
2021
+ const value = e[1].replace(/process\.env\.\w{1,80}|import\.meta\.env\.\w{1,80}|Deno\.env\.get\([^)]{0,80}\)|\benv\.\w{1,80}/g, "");
2022
+ if (/\b(?:token|accessToken|access_token|idToken|id_token|authToken|userToken|bearerToken|jwt|session|cookies?)\b/i.test(value)) {
2023
+ return true;
2024
+ }
2025
+ if (readsCaller?.(value)) return true;
2026
+ }
2027
+ return false;
2028
+ }
2029
+ var INBOUND_REQUEST_READ_RE = /\b(?:req|request|c\.req|ctx\.req(?:uest)?|event)\s*\.\s*(?:headers?|cookies|body|json|text|formData|query|params)\b|\bcookies\s*\(\s*\)|\bheaders\s*\(\s*\)\s*\.\s*get\b|\b\w{0,40}[Cc]ookies?\w{0,20}\s*(?:\.\s*get\s*\(|\[)|\bget(?:Request)?(?:Header|Cookie)s?\s*\(|[\w$]\s*\(\s*(?:req|request|ctx|event)\s*[,)]/;
2030
+ var BINDING_RE = /\b(?:const|let|var)\s+(?:([A-Za-z_$][\w$]{0,60})|\{([^{}]{0,400})\})\s*(?::[^=\n]{0,120})?=(?![=>])\s*([^;\n]{0,300})/g;
2031
+ var MAX_BINDINGS = 4096;
2032
+ function collectBindings(code) {
2033
+ const byName = /* @__PURE__ */ new Map();
2034
+ const add = (name, at, rhs) => {
2035
+ const list = byName.get(name);
2036
+ if (list) list.push({ at, rhs });
2037
+ else byName.set(name, [{ at, rhs }]);
2038
+ };
2039
+ let count = 0;
2040
+ let b;
2041
+ BINDING_RE.lastIndex = 0;
2042
+ while ((b = BINDING_RE.exec(code)) !== null && count < MAX_BINDINGS) {
2043
+ count++;
2044
+ if (b[1]) {
2045
+ add(b[1], b.index, b[3]);
2046
+ continue;
2047
+ }
2048
+ for (const part of b[2].split(",")) {
2049
+ const local = part.replace(/=[^]*$/, "").replace(/^[^:]*:/, "").trim().replace(/^\.\.\./, "");
2050
+ if (/^[A-Za-z_$][\w$]{0,60}$/.test(local)) add(local, b.index, b[3]);
2051
+ }
2052
+ }
2053
+ return byName;
2054
+ }
2055
+ function credentialValueReadsCaller(value, at, bindings) {
2056
+ if (INBOUND_CREDENTIAL_READ_RE.test(value) || INBOUND_REQUEST_READ_RE.test(value)) return true;
2057
+ const roots = /* @__PURE__ */ new Set();
2058
+ const INTERP_RE = /\$\{\s*([A-Za-z_$][\w$]{0,60})/g;
2059
+ const ROOT_RE = /(?<![\w$.])[A-Za-z_$][\w$]{0,60}/g;
2060
+ let r;
2061
+ while ((r = INTERP_RE.exec(value)) !== null && roots.size < 6) roots.add(r[1]);
2062
+ const bare = value.replace(/"[^"\n]{0,300}"|'[^'\n]{0,300}'|`[^`]{0,300}(?:`|$)/g, " ");
2063
+ while ((r = ROOT_RE.exec(bare)) !== null && roots.size < 6) roots.add(r[0]);
2064
+ for (const name of roots) {
2065
+ const list = bindings().get(name);
2066
+ if (!list || list[0].at >= at) continue;
2067
+ let lo = 0;
2068
+ let hi = list.length - 1;
2069
+ while (lo < hi) {
2070
+ const mid = lo + hi + 1 >> 1;
2071
+ if (list[mid].at < at) lo = mid;
2072
+ else hi = mid - 1;
2073
+ }
2074
+ if (INBOUND_REQUEST_READ_RE.test(list[lo].rhs)) return true;
2075
+ }
2076
+ return false;
2077
+ }
2078
+ function maskOutboundAuthNoise(code) {
2079
+ let out = code.replace(
2080
+ /(["']?)role\1\s{0,20}:\s{0,20}["'](?:user|assistant|system|developer|tool|model|function)["']/g,
2081
+ blankKeepLines
2082
+ );
2083
+ if (/["'`]assistant["'`]/.test(out)) {
2084
+ out = out.replace(/["'`](?:user|assistant|system|developer|tool)["'`]/g, blankKeepLines);
2085
+ }
2086
+ const envNames = /* @__PURE__ */ new Set();
2087
+ const ENV_BIND_RE = /\b(?:const|let|var)\s+([A-Za-z_$][\w$]{0,60})\s*(?::[^=\n]{0,60})?=\s*(?:Deno\.env\.get\s*\(|process\.env\b|import\.meta\.env\b)/g;
2088
+ let b;
2089
+ while ((b = ENV_BIND_RE.exec(out)) !== null && envNames.size < 32) {
2090
+ if (!/secret|webhook|signing|cron|internal|admin|password|passwd/i.test(b[1])) envNames.add(b[1]);
2091
+ }
2092
+ if (envNames.size > 0) {
2093
+ const names = [...envNames].map((n) => n.replace(/\$/g, "\\$")).join("|");
2094
+ out = out.replace(new RegExp(`(?<![\\w$.])(?:${names})(?![\\w$])`, "g"), blankKeepLines);
2095
+ }
2096
+ out = out.replace(
2097
+ /\bapi_?key["']?\s{0,20}:\s{0,20}(?:process\.env\.\w{1,80}|Deno\.env\.get\(\s*["'][\w-]{1,80}["']\s*\)|import\.meta\.env\.\w{1,80}|[A-Z][A-Z0-9_]{2,79}\b)/gi,
2098
+ blankKeepLines
2099
+ );
2100
+ let bindingMap = null;
2101
+ const bindingSource = out;
2102
+ const bindings = () => bindingMap ??= collectBindings(bindingSource);
2103
+ out = out.replace(
2104
+ /\b\w{0,40}[Hh]eaders\s*\.\s*(?:set|append)\s*\(\s*["'](?:authorization|x-api-key|api-key|x-goog-api-key)["']\s*,([^\n]{0,300})/gi,
2105
+ (call, value, at) => credentialValueReadsCaller(value, at, bindings) ? call : blankKeepLines(call)
2106
+ );
2107
+ const OPEN_RE = /\b(?:headers\s*[:=]|new\s+Headers\s*\()\s*\{/g;
2108
+ const MAX_OBJECTS = 64;
2109
+ const MAX_OBJECT_LEN = 3e3;
2110
+ let examined = 0;
2111
+ let m;
2112
+ const parts = [];
2113
+ let copied = 0;
2114
+ while ((m = OPEN_RE.exec(out)) !== null) {
2115
+ if (++examined > MAX_OBJECTS) break;
2116
+ const open = m.index + m[0].length - 1;
2117
+ const close = closingBrace(out, open, MAX_OBJECT_LEN);
2118
+ if (close === -1) continue;
2119
+ const inner = out.slice(open + 1, close);
2120
+ const readsCaller = (value) => credentialValueReadsCaller(value, open, bindings);
2121
+ if (!INBOUND_CREDENTIAL_READ_RE.test(inner) && !forwardsCallerCredential(inner, readsCaller)) {
2122
+ parts.push(out.slice(copied, open + 1), blankKeepLines(inner));
2123
+ copied = close;
2124
+ }
2125
+ OPEN_RE.lastIndex = close + 1;
2126
+ }
2127
+ if (parts.length === 0) return out;
2128
+ parts.push(out.slice(copied));
2129
+ return parts.join("");
2130
+ }
2131
+ function maskProseStrings(code) {
2132
+ return code.replace(
2133
+ /(?<!\\)"(?:[^"\\\n]|\\.){0,2000}"|(?<!\\)'(?:[^'\\\n]|\\.){0,2000}'|(?<!\\)`(?:[^`\\]|\\.){0,8000}`/g,
2134
+ (lit) => /\S\s+\S+\s+\S+\s+\S/.test(lit) ? blankKeepLines(lit) : lit
2135
+ );
2136
+ }
2137
+ var TANSTACK_START_IMPORT_RE = /["']@tanstack\/(?:(?:react|solid)-)?start(?:\/[\w-]{1,40})?["']/;
2138
+ var TANSTACK_ROUTER_IMPORT_RE = /["']@tanstack\/(?:react|solid)-router["']/;
2139
+ var TANSTACK_AUTH_MIDDLEWARE_RE = /\bmiddleware\s*[:(]\s*\[([^\]]{0,600})\]/g;
2140
+ var AUTH_MIDDLEWARE_NAME_RE = /auth|session|protect|require|guard|user|admin|clerk|signed|logged|login|member|owner|role|permission/i;
2141
+ var TANSTACK_HANDLER_AUTH_RE = [
2142
+ /\bget(?:User|Claims|Session|ServerSession|Auth|Token)\s*\(/,
2143
+ /\bget(?:Authed|Authenticated|Current|Signed\w{0,8}|Logged\w{0,8}|Session)\w{0,30}\s*\(/,
2144
+ /\bcurrentUser\b/,
2145
+ /\buse\w{0,30}Session\s*\(/,
2146
+ /\b(?:check|verify|require|assert|ensure|validate)\w{0,30}(?:Auth|Admin|Session|User|Password|Token|Role|Owner|Permission|Access|Signature|Secret|Member)\w{0,30}\s*\(/i,
2147
+ // `requireX()` / `assertX()` / `ensureX()` / `authorizeX()` is the
2148
+ // near-universal spelling of a bespoke gate — tanstack.com's own
2149
+ // `requireModerateShowcases()`, `requireCaller()`. Suppression only.
2150
+ /\b(?:require|assert|ensure|guard|protect|authori[sz]e)[A-Z]\w{0,40}\s*\(/,
2151
+ /\b(?:can|has)(?:Permission|Access|Role|Capability|Scope)\w{0,30}\s*\(/,
2152
+ /\bisAuthenticated\b/,
2153
+ /\bauth\s*\(\s*\)/,
2154
+ /\bauth\s*\.\s*api\s*\.\s*getSession\b/,
2155
+ /\.auth\s*\.\s*(?:getUser|getClaims|getSession)\b/,
2156
+ /\bcontext\s*\.\s*(?:user|userId|session|auth|claims|supabase)\b/,
2157
+ /\b(?:jwt\.verify|jwtVerify|verifyIdToken|verifyToken|timingSafeEqual|constructEvent\w{0,20}|createHmac)\s*\(/,
2158
+ /\bstatus(?:Code)?\s*[:(]\s*401\b/,
2159
+ /\bunauthori[sz]ed\b/i,
2160
+ /\bnot\s+(?:authenticated|authori[sz]ed|logged\s+in|signed\s+in)\b/i,
2161
+ // Reads the caller's credential. Forwarding it to a row-level-security
2162
+ // client scopes every query to the caller, which is the safe Supabase shape.
2163
+ /\bauthorization\b/i,
2164
+ // A capability-token lookup: the row is found by an unguessable value the
2165
+ // caller holds (`.eq("token", data.token)`, `.eq("id", body.session_id)`).
2166
+ // Share links, anonymous votes, guest chat sessions — the token in the
2167
+ // request IS the credential, the same family VC003 already accepts via a
2168
+ // 401 on the Next.js shapes. Calibration: every such handler in the sample
2169
+ // was public by design.
2170
+ /\.(?:eq|match)\(\s*["'`]\w{0,40}(?:token|secret|code|hash|key)["'`]/i,
2171
+ /\.eq\(\s*["'`]\w{1,40}["'`]\s*,\s*[\w$.]{0,60}(?:[Tt]oken|[Ss]ession_?(?:[Ii]d|[Kk]ey)|[Ss]ecret|[Hh]ash)\b/,
2172
+ // A shared-secret comparison (`data.password !== process.env.ADMIN_PASSWORD`).
2173
+ /[!=]==?\s*(?:process\.env\.|import\.meta\.env\.|Deno\.env\.get\(\s*["']|\w{1,40}\.){0,2}\w{0,40}(?:SECRET|PASSWORD|Secret|Password|secret|password)\w{0,20}/
2174
+ ];
2175
+ var TANSTACK_MUTATION_RE = [
2176
+ // Supabase: .from("orders").update(…) / .upsert(…) / .delete()
2177
+ /\.from\(\s*["'`][\w.-]{1,64}["'`]\s*\)\s*\.\s*(?:update|upsert|delete)\s*\(/,
2178
+ // Supabase admin auth API: listUsers, deleteUser, updateUserById, …
2179
+ /\.auth\s*\.\s*admin\s*\.\s*\w{1,40}\s*\(/,
2180
+ // Prisma: prisma.order.delete(…), db.user.updateMany(…)
2181
+ /\b(?:prisma|db|tx)\s*\.\s*\w{1,64}\s*\.\s*(?:update|upsert|delete|updateMany|deleteMany)\s*\(/,
2182
+ // Drizzle: db.update(orders) / db.delete(orders)
2183
+ /\b(?:db|tx)\s*\.\s*(?:update|delete)\s*\(\s*\w/,
2184
+ // Firestore admin: .doc(id).update(…) / .delete()
2185
+ /\.doc\([^()\n]{0,200}\)\s*\.\s*(?:update|delete|set)\s*\(/,
2186
+ // Raw SQL
2187
+ /\b(?:UPDATE\s+["`]?\w{1,64}["`]?\s+SET|DELETE\s+FROM)\b/
2188
+ ];
2189
+ var SUPABASE_WRITE_TABLE_RE = /\.from\(\s*["'`]([\w.-]{1,64})["'`]\s*\)\s*\.\s*(?:update|upsert|delete)\s*\(/g;
2190
+ var ANALYTICS_TABLE_RE = /(?:^|[_.-])(?:page_?views?|views?|visits?|visitors?|analytics?|tracking|clicks?|impressions?|heartbeats?|presence|metrics?|stats?|counters?)(?:[_.-]|$)/i;
2191
+ var TANSTACK_PUBLIC_FN_NAME_RE = /^(?:sign[-_]?(?:in|up|out)|log[-_]?(?:in|out)|register|reset|forgot|verify|confirm|accept[-_]?invite|redeem|callback|oauth|magic|otp|request(?:Password|Magic|Otp|Reset|Access)|track|record(?:View|Visit|Click|Event|Impression)|log(?:View|Visit|Event|Click)|increment|bump|count(?:View|Visit|Click)|subscribe|unsubscribe|join(?:Waitlist|Newsletter)|submit(?:Contact|Lead|Feedback|Inquiry|Enquiry|Waitlist|Newsletter))/i;
2192
+ var TANSTACK_PUBLIC_ROUTE_PATH_RE = /(^|[/_.[-])(auth|login|signin|sign-in|signup|sign-up|register|logout|signout|sign-out|callback|oauth|sso|session|reset-password|forgot-password|forgot|magic-?link|verify-?email|confirm|otp|invite|token|webhooks?|cron|health(?:z|check)?|sitemap|robots|og)([/\]_.-]|$)/i;
2193
+ function closingParen(text, open, limit) {
2194
+ let depth = 0;
2195
+ const end = Math.min(text.length, limit);
2196
+ for (let i = open; i < end; i++) {
2197
+ const c = text.charCodeAt(i);
2198
+ if (c === 34 || c === 39 || c === 96) {
2199
+ let j = i + 1;
2200
+ while (j < end) {
2201
+ const d = text.charCodeAt(j);
2202
+ if (d === 92) {
2203
+ j += 2;
2204
+ continue;
2205
+ }
2206
+ if (d === c || c !== 96 && d === 10) break;
2207
+ j++;
2208
+ }
2209
+ i = j;
2210
+ continue;
2211
+ }
2212
+ if (c === 40) depth++;
2213
+ else if (c === 41) {
2214
+ depth--;
2215
+ if (depth === 0) return i;
2216
+ }
2217
+ }
2218
+ return -1;
2219
+ }
2220
+ function hasAuthMiddleware(text) {
2221
+ TANSTACK_AUTH_MIDDLEWARE_RE.lastIndex = 0;
2222
+ let m;
2223
+ while ((m = TANSTACK_AUTH_MIDDLEWARE_RE.exec(text)) !== null) {
2224
+ if (AUTH_MIDDLEWARE_NAME_RE.test(m[1])) return true;
2225
+ }
2226
+ return false;
2227
+ }
2228
+ function unauthenticatedTanStackHandlers(masked, filePath) {
2229
+ const isStart = TANSTACK_START_IMPORT_RE.test(masked);
2230
+ const hasServerFn = /\bcreateServerFn\s*\(/.test(masked);
2231
+ const hasServerRoute = /\bcreateServerFileRoute\s*\(|\bcreateAPIFileRoute\s*\(/.test(masked) || /\bserver\s*:\s*\{/.test(masked) && /\bhandlers\s*:/.test(masked);
2232
+ if (!hasServerFn && !hasServerRoute) return [];
2233
+ if (!isStart && !(hasServerRoute && TANSTACK_ROUTER_IMPORT_RE.test(masked))) return [];
2234
+ if (TANSTACK_PUBLIC_ROUTE_PATH_RE.test(filePath)) return [];
2235
+ const hits = [];
2236
+ const touchesData = (body) => {
2237
+ const supabaseWrites = [...body.matchAll(SUPABASE_WRITE_TABLE_RE)].map((w) => w[1]);
2238
+ const otherWrites = TANSTACK_MUTATION_RE.slice(1).some((p) => p.test(body));
2239
+ if (otherWrites) return true;
2240
+ return supabaseWrites.some((t) => !ANALYTICS_TABLE_RE.test(t));
2241
+ };
2242
+ const establishesCaller = (body) => hasAuthMiddleware(body) || TANSTACK_HANDLER_AUTH_RE.some((p) => p.test(body));
2243
+ if (hasServerFn) {
2244
+ const starts = [];
2245
+ const FN_RE = /\bcreateServerFn\s*\(/g;
2246
+ let m;
2247
+ while ((m = FN_RE.exec(masked)) !== null && starts.length < 500) starts.push(m.index);
2248
+ for (let k = 0; k < starts.length; k++) {
2249
+ const start = starts[k];
2250
+ const limit = k + 1 < starts.length ? starts[k + 1] : Math.min(masked.length, start + 4e4);
2251
+ const h = /\.handler\s*\(/.exec(masked.slice(start, limit));
2252
+ if (!h) continue;
2253
+ const open = start + h.index + h[0].length - 1;
2254
+ const close = closingParen(masked, open, limit);
2255
+ const chain = masked.slice(start, close === -1 ? limit : close + 1);
2256
+ const header = masked.slice(start, open);
2257
+ const body = masked.slice(open, close === -1 ? limit : close + 1);
2258
+ const before = masked.slice(Math.max(0, start - 120), start);
2259
+ const nameMatch = before.match(/\b(?:const|let|var)\s+(\w{1,80})\s*(?::[^=\n]{0,80})?=\s*$/);
2260
+ if (nameMatch && TANSTACK_PUBLIC_FN_NAME_RE.test(nameMatch[1])) continue;
2261
+ if (hasAuthMiddleware(header)) continue;
2262
+ if (!touchesData(body)) continue;
2263
+ if (establishesCaller(chain)) continue;
2264
+ hits.push(nameMatch && nameMatch.index !== void 0 ? start - before.length + nameMatch.index : start);
2265
+ if (hits.length >= 50) return hits;
2266
+ }
2267
+ }
2268
+ if (hasServerRoute) {
2269
+ const serverBlock = /\bserver\s*:\s*\{/.exec(masked);
2270
+ const routeLevelAuth = serverBlock !== null && (() => {
2271
+ const close = closingBrace(masked, serverBlock.index + serverBlock[0].length - 1, 6e4);
2272
+ const block = masked.slice(serverBlock.index, close === -1 ? masked.length : close);
2273
+ const handlersAt = block.search(/\bhandlers\s*:/);
2274
+ return hasAuthMiddleware(handlersAt === -1 ? block : block.slice(0, handlersAt));
2275
+ })();
2276
+ if (!routeLevelAuth) {
2277
+ const METHOD_RE = /\b(GET|POST|PUT|PATCH|DELETE)\s*:\s*(?:async\s+)?(?:\(|function\b|\{|[A-Za-z_$][\w$]{0,40}\s*=>)/g;
2278
+ const methodStarts = [];
2279
+ let m;
2280
+ while ((m = METHOD_RE.exec(masked)) !== null && methodStarts.length < 200) methodStarts.push(m.index);
2281
+ for (let k = 0; k < methodStarts.length; k++) {
2282
+ const start = methodStarts[k];
2283
+ const limit = k + 1 < methodStarts.length ? methodStarts[k + 1] : Math.min(masked.length, start + 4e4);
2284
+ const head = masked.slice(start, Math.min(limit, start + 400));
2285
+ const opener = /^\w+\s*:\s*\{/.exec(head) ?? /=>\s*\{/.exec(head) ?? /\)\s*\{/.exec(head);
2286
+ let body;
2287
+ if (opener) {
2288
+ const braceAt = start + opener.index + opener[0].length - 1;
2289
+ const close = closingBrace(masked, braceAt, limit - braceAt);
2290
+ body = masked.slice(start, close === -1 ? limit : close + 1);
2291
+ } else {
2292
+ body = masked.slice(start, limit);
2293
+ }
2294
+ if (!touchesData(body)) continue;
2295
+ if (establishesCaller(body)) continue;
2296
+ hits.push(start);
2297
+ if (hits.length >= 50) return hits;
2298
+ }
2299
+ }
2300
+ }
2301
+ return hits;
2302
+ }
1799
2303
  var missingAuthMiddleware = {
1800
2304
  id: "VC003",
1801
2305
  title: "API Route Missing Authentication",
@@ -1803,7 +2307,9 @@ var missingAuthMiddleware = {
1803
2307
  category: "Authentication",
1804
2308
  description: "API routes without authentication checks allow unauthorized access.",
1805
2309
  check(content, filePath, project) {
1806
- if (!isServerSideFile(filePath, content)) return [];
2310
+ const serverSide = isServerSideFile(filePath, content);
2311
+ const tanstackCandidate = !serverSide && !isTestFile(filePath) && /@tanstack\/(?:(?:react|solid)-)?(?:start|router)\b/.test(content);
2312
+ if (!serverSide && !tanstackCandidate) return [];
1807
2313
  if (PUBLIC_BY_CONVENTION_ROUTE.test(routeSegmentName(filePath))) return [];
1808
2314
  const routePatterns = [
1809
2315
  // Express/Hono style
@@ -1819,7 +2325,7 @@ var missingAuthMiddleware = {
1819
2325
  /module\.exports\s*=\s*(?:async\s+)?(?:function\b|\()/g
1820
2326
  );
1821
2327
  }
1822
- if (/^\s*["']use server["']/m.test(content)) {
2328
+ if (USE_SERVER_DIRECTIVE_RE.test(content)) {
1823
2329
  routePatterns.push(
1824
2330
  /export\s+(?:async\s+)?function\s+\w+\s*\(/g,
1825
2331
  /export\s+const\s+\w+\s*(?::[^=\n]{0,120})?=\s*(?:async\s*)?\(/g
@@ -1843,7 +2349,7 @@ var missingAuthMiddleware = {
1843
2349
  if (isAuthRoute) return [];
1844
2350
  const isWebhookRoute = /\/webhook/i.test(filePath) || /(?:^|[/_-])webhooks?(?:[/_.-]|$)/i.test(filePath);
1845
2351
  if (isWebhookRoute) return [];
1846
- const codeOnly = content.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:])\/\/.*$/gm, "$1").replace(/^\s*#.*$/gm, "");
2352
+ const codeOnly = replaceBlockComments(content, () => "").replace(/(^|[^:])\/\/.*$/gm, "$1").replace(/^[ \t\uFEFF]*#.*$/gm, "");
1847
2353
  const authPatterns = [
1848
2354
  /\bgetUser\b/i,
1849
2355
  /\bcurrentUser\b/i,
@@ -1859,6 +2365,13 @@ var missingAuthMiddleware = {
1859
2365
  /\bcheckApiKey\b/i,
1860
2366
  /\bverifyCronSecret\b/i,
1861
2367
  /\bverifySecret\b/i,
2368
+ // Signed-request receivers: `await verifyQstashSignature({ req, rawBody })`,
2369
+ // `verifyWebhookSignature(…)`, Upstash's `receiver.verify({ signature,
2370
+ // body })`. Since outbound headers are masked, a route that relied on
2371
+ // its own outbound `Bearer ${key}` to pass no longer does, and these
2372
+ // are what actually authenticate it.
2373
+ /\bverify\w{0,20}Signature\w{0,20}\s*\(/i,
2374
+ /\b\w{0,30}[Rr]eceiver\s*\.\s*verify\s*\(/,
1862
2375
  /supabase\.auth/i,
1863
2376
  /firebase\.auth/i,
1864
2377
  /\bclerk\b/i,
@@ -1897,16 +2410,17 @@ var missingAuthMiddleware = {
1897
2410
  const handlerAuthPatterns = authPatterns.filter(
1898
2411
  (p) => !APP_LEVEL_AUTH.some((a) => a.source === p.source)
1899
2412
  );
1900
- const maskedForScope = maskComments(content);
2413
+ const maskedForScope = maskOutboundAuthNoise(maskComments(content));
2414
+ const codeForAuth = maskOutboundAuthNoise(codeOnly);
1901
2415
  const handlerHasAuth = (index) => {
1902
2416
  const bodyStart = maskedForScope.indexOf("{", index);
1903
2417
  const probe = bodyStart === -1 ? index : bodyStart + 1;
1904
2418
  const scope = enclosingHandler(maskedForScope, probe);
1905
- if (scope === null) return handlerAuthPatterns.some((p) => p.test(codeOnly));
2419
+ if (scope === null) return handlerAuthPatterns.some((p) => p.test(codeForAuth));
1906
2420
  return handlerAuthPatterns.some((p) => p.test(scope));
1907
2421
  };
1908
2422
  const matches = [];
1909
- for (const pattern of routePatterns) {
2423
+ for (const pattern of serverSide ? routePatterns : []) {
1910
2424
  matches.push(
1911
2425
  ...findMatches(
1912
2426
  content,
@@ -1917,11 +2431,11 @@ var missingAuthMiddleware = {
1917
2431
  )
1918
2432
  );
1919
2433
  }
1920
- if (matches.length === 0 && SUPABASE_EDGE_FN_RE.test(filePath) && isDenoEdgeEntry(codeOnly) && !isPublicByDesignEdgePath(filePath)) {
2434
+ if (matches.length === 0 && serverSide && SUPABASE_EDGE_FN_RE.test(filePath) && isDenoEdgeEntry(codeOnly) && !isPublicByDesignEdgePath(filePath)) {
1921
2435
  const fnName = supabaseFunctionName(filePath);
1922
2436
  const verifyJwt = fnName && project?.supabaseEdgeVerifyJwt ? project.supabaseEdgeVerifyJwt.get(fnName) : void 0;
1923
2437
  if (verifyJwt !== true) {
1924
- const withoutCors = stripCorsHeaderList(codeOnly);
2438
+ const withoutCors = maskProseStrings(maskOutboundAuthNoise(stripCorsHeaderList(codeOnly)));
1925
2439
  const hasWeakHint = verifyJwt === false ? false : EDGE_WEAK_AUTH_HINTS.some((p) => p.test(withoutCors));
1926
2440
  if (!hasWeakHint) {
1927
2441
  matches.push(
@@ -1942,6 +2456,21 @@ var missingAuthMiddleware = {
1942
2456
  }
1943
2457
  const indexOfLine = (line) => lineStarts[Math.max(0, Math.min(line - 1, lineStarts.length - 1))];
1944
2458
  const unauthenticated = matches.filter((m) => !handlerHasAuth(indexOfLine(m.line)));
2459
+ if (serverSide || tanstackCandidate) {
2460
+ for (const idx of unauthenticatedTanStackHandlers(maskedForScope, filePath)) {
2461
+ const line = lineNumberAt(content, idx);
2462
+ unauthenticated.push({
2463
+ rule: "VC003",
2464
+ title: missingAuthMiddleware.title,
2465
+ severity: "high",
2466
+ category: missingAuthMiddleware.category,
2467
+ file: filePath,
2468
+ line,
2469
+ snippet: getSnippet(content, line),
2470
+ fix: "This TanStack Start handler changes data and is callable by anyone who can reach the app: server functions and server routes are public endpoints, and a route's beforeLoad guard does not protect them. Attach an auth middleware (`.middleware([requireSupabaseAuth])` in Lovable projects) and scope the write to the caller (`context.userId`), or verify the caller inside the handler and return 401. If it is public by design, add an inline `// VC003-OK: <reason>` comment above it."
2471
+ });
2472
+ }
2473
+ }
1945
2474
  return filterSilenced(unauthenticated, content, "VC003");
1946
2475
  }
1947
2476
  };
@@ -2236,7 +2765,8 @@ var noRateLimiting = {
2236
2765
  check(content, filePath) {
2237
2766
  const isEntryFile = /(?:server|app|index|main)\.[jt]sx?$/.test(filePath) || filePath.includes("middleware");
2238
2767
  if (!isEntryFile) return [];
2239
- const isServer = /(?:from\s+|require\s*\(\s*)["'`](?:express|hono|fastify|koa|@hono\/[\w-]+|next\/server|(?:node:)?https?)["'`]/.test(content) || /\b(?:express|fastify|createServer)\s*\(/.test(content) || /\bnew\s+(?:Hono|Koa)\s*\(/.test(content) || /\b(?:Deno|Bun)\.serve\s*\(/.test(content) || /\.listen\s*\(/.test(content);
2768
+ const isServer = /(?: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) || // Case-sensitive framework types — `adNext` and `nextLap` can't match.
2769
+ /\b(?:NextApiRequest|NextApiResponse|NextRequest|NextResponse)\b/.test(content) || /\b(?:express|fastify|createServer)\s*\(/.test(content) || /\bnew\s+(?:Hono|Koa)\s*\(/.test(content) || /\b(?:Deno|Bun)\.serve\s*\(/.test(content) || /\.listen\s*\(/.test(content);
2240
2770
  if (!isServer) return [];
2241
2771
  const hasRateLimit = /rate.?limit|throttle|express-rate-limit|@elysiajs\/rate-limit|hono.*limiter/i.test(content);
2242
2772
  if (hasRateLimit) return [];
@@ -2311,35 +2841,61 @@ var clientSideAuth = {
2311
2841
  return matches;
2312
2842
  }
2313
2843
  };
2844
+ var PUBLIC_ENV_FIX = {
2845
+ NEXT_PUBLIC_: "Remove the NEXT_PUBLIC_ prefix. Only use NEXT_PUBLIC_ for values safe to expose in the browser.",
2846
+ VITE_: "Vite inlines every VITE_ variable that client code reads into the JavaScript bundle each visitor downloads. Rename it without the VITE_ prefix and use it only in server code \u2014 an API route or edge function that makes the call for the browser \u2014 then rotate the key if a build has been deployed.",
2847
+ REACT_APP_: "Create React App inlines every REACT_APP_ variable into the JavaScript bundle each visitor downloads. Rename it without the REACT_APP_ prefix and use it only in server code \u2014 an API route or serverless function that makes the call for the browser \u2014 then rotate the key if a build has been deployed.",
2848
+ EXPO_PUBLIC_: "Expo inlines EXPO_PUBLIC_ variables into the app bundle, which anyone can unpack from the installed app. Rename it without the EXPO_PUBLIC_ prefix and make the call from your backend, then rotate the key if a build has shipped.",
2849
+ GATSBY_: "Gatsby inlines GATSBY_ variables into the JavaScript bundle each visitor downloads. Rename it without the GATSBY_ prefix and use it only in server code (a Gatsby Function or your API), then rotate the key if a build has been deployed.",
2850
+ PUBLIC_: "SvelteKit ($env/static/public) and Astro send PUBLIC_ variables to the browser. Rename it without the PUBLIC_ prefix and read it only in server code ($env/static/private, or a server endpoint), then rotate the key if a build has been deployed.",
2851
+ NUXT_PUBLIC_: "Nuxt copies NUXT_PUBLIC_ variables into runtimeConfig.public, which is sent to every client. Rename it to NUXT_<NAME> so it lands in the private runtimeConfig and use it only in server routes, then rotate the key if a build has been deployed."
2852
+ };
2853
+ var NEXT_PUBLIC_ASSIGN_RE = /(?:^|[^A-Za-z0-9_])(NEXT_PUBLIC_[A-Za-z0-9_]{1,128})\s*=\s*([^\r\n]*)/i;
2314
2854
  var nextPublicSecret = {
2315
2855
  id: "VC011",
2316
- title: "Secret in NEXT_PUBLIC_ Environment Variable",
2856
+ title: "Secret in Browser-Exposed Environment Variable",
2317
2857
  severity: "critical",
2318
2858
  category: "Secrets",
2319
- description: "NEXT_PUBLIC_ variables are exposed to the browser. Secrets placed here are visible to anyone.",
2859
+ description: "Variables with a browser-exposed prefix (NEXT_PUBLIC_, VITE_, REACT_APP_, EXPO_PUBLIC_, GATSBY_, PUBLIC_, NUXT_PUBLIC_) are built into code shipped to every visitor or app user. A secret placed in one is visible to anyone.",
2320
2860
  check(content, filePath) {
2321
- if (!filePath.match(/\.env/) && !filePath.match(/next\.config/)) return [];
2322
- const patterns = [
2323
- /NEXT_PUBLIC_[A-Z_]*(?:SECRET|KEY|TOKEN|PASSWORD|PRIVATE)[A-Z_]*\s*=\s*.+/gi,
2324
- /NEXT_PUBLIC_[A-Z_]*(?:SUPABASE_SERVICE|CLERK_SECRET|STRIPE_SECRET)[A-Z_]*\s*=\s*.+/gi
2325
- ];
2861
+ const legacyScope = /\.env/.test(filePath) || /next\.config/.test(filePath);
2862
+ const dotenvScope = isDotenvPath(filePath);
2863
+ if (!legacyScope && !dotenvScope) return [];
2864
+ if (!/(?:NEXT_PUBLIC_|NUXT_PUBLIC_|EXPO_PUBLIC_|REACT_APP_|GATSBY_|VITE_|PUBLIC_)/i.test(content)) return [];
2326
2865
  const matches = [];
2327
- for (const p of patterns) {
2328
- const raw = findMatches(
2329
- content,
2330
- p,
2331
- nextPublicSecret,
2332
- filePath,
2333
- () => "Remove the NEXT_PUBLIC_ prefix. Only use NEXT_PUBLIC_ for values safe to expose in the browser."
2334
- );
2335
- for (const m of raw) {
2336
- const lineText = content.split("\n")[m.line - 1] || "";
2337
- if (/PUBLISHABLE|ANON_KEY|PUBLIC_KEY/i.test(lineText)) continue;
2338
- if (/CLERK_PUBLISHABLE/i.test(lineText)) continue;
2339
- if (/STRIPE_PUBLISHABLE/i.test(lineText)) continue;
2340
- if (/=\s*["']?\s*$|=\s*["']?pk_(?:test|live)_["']?\s*$/.test(lineText)) continue;
2341
- matches.push(m);
2866
+ const lines = content.split("\n");
2867
+ for (let i = 0; i < lines.length; i++) {
2868
+ const line = lines[i];
2869
+ const trimmed = line.trimStart();
2870
+ if (/^(?:#|\/\/|\*|\/\*|<!--)/.test(trimmed)) continue;
2871
+ let name;
2872
+ let value = "";
2873
+ const a = dotenvScope ? DOTENV_ASSIGN_RE.exec(line) : null;
2874
+ if (a && PUBLIC_ENV_PREFIX_RE.test(a[1])) {
2875
+ name = a[1];
2876
+ value = a[2];
2877
+ } else if (legacyScope) {
2878
+ const n = NEXT_PUBLIC_ASSIGN_RE.exec(line);
2879
+ if (n) {
2880
+ name = n[1];
2881
+ value = n[2];
2882
+ }
2342
2883
  }
2884
+ if (!name) continue;
2885
+ const bare = dotenvValue(value);
2886
+ if (bare === "" || /^pk_(?:test|live)_$/.test(bare)) continue;
2887
+ const verdict = classifyPublicEnvVar(name, bare);
2888
+ if (!verdict || !verdict.secret) continue;
2889
+ matches.push({
2890
+ rule: "VC011",
2891
+ title: nextPublicSecret.title,
2892
+ severity: "critical",
2893
+ category: "Secrets",
2894
+ file: filePath,
2895
+ line: i + 1,
2896
+ snippet: getSnippet(content, i + 1),
2897
+ fix: PUBLIC_ENV_FIX[verdict.prefix] ?? PUBLIC_ENV_FIX.NEXT_PUBLIC_
2898
+ });
2343
2899
  }
2344
2900
  return matches;
2345
2901
  }
@@ -2515,12 +3071,32 @@ var exposedAuthSecret = {
2515
3071
  }
2516
3072
  };
2517
3073
  function cspFixFor(content) {
2518
- const origins = [
2519
- ...new Set(
2520
- [...content.slice(0, 2e5).matchAll(/<script\b[^>]{0,500}?\bsrc\s*=\s*["'](https?:\/\/[^/"'\s>]+)/gi)].map((m) => m[1])
2521
- )
2522
- ].slice(0, 10);
2523
- const inlineScripts = (content.slice(0, 2e5).match(/<script\b(?![^>]{0,500}\bsrc\s*=)[^>]{0,500}>\s*[^<\s]/gi) ?? []).length;
3074
+ const html = content.slice(0, 2e5);
3075
+ const origins = /* @__PURE__ */ new Set();
3076
+ const addOrigin = (url) => {
3077
+ const m2 = url.match(/^(https?:)?\/\/([^/"'`\s>?#]+)/i);
3078
+ if (m2 && origins.size < 10) origins.add(`${(m2[1] ?? "https:").toLowerCase()}//${m2[2].toLowerCase()}`);
3079
+ };
3080
+ let inlineScripts = 0;
3081
+ const openTag = /<script\b([^>]{0,500})>/gi;
3082
+ let m;
3083
+ for (let seen = 0; (m = openTag.exec(html)) && seen < 100; seen++) {
3084
+ const attrs = m[1];
3085
+ const src = attrs.match(/\bsrc\s*=\s*["']?((?:https?:)?\/\/[^"'\s>]+)/i);
3086
+ if (src) {
3087
+ addOrigin(src[1]);
3088
+ continue;
3089
+ }
3090
+ if (/\bsrc\s*=/i.test(attrs)) continue;
3091
+ const close = html.indexOf("</script", openTag.lastIndex);
3092
+ const body = html.slice(openTag.lastIndex, close < 0 ? openTag.lastIndex + 5e4 : close);
3093
+ const type = (attrs.match(/\btype\s*=\s*["']?([^"'\s>]+)/i)?.[1] ?? "").toLowerCase();
3094
+ const runs = type === "" || type === "module" || type === "importmap" || /^(?:text|application)\/(?:x-)?(?:java|ecma)script$/.test(type);
3095
+ if (!runs || !body.trim()) continue;
3096
+ inlineScripts++;
3097
+ const urls = type === "importmap" ? body.matchAll(/["']((?:https?:)?\/\/[^"'\s]+)["']/g) : type === "module" ? body.matchAll(/(?:\bfrom|\bimport\s*\(?)\s*["'`]((?:https?:)?\/\/[^"'`\s]+)["'`]/g) : [];
3098
+ for (const u of urls) addOrigin(u[1]);
3099
+ }
2524
3100
  const scriptSrc = ["'self'", ...origins].join(" ");
2525
3101
  return [
2526
3102
  `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.`,
@@ -3273,8 +3849,29 @@ var complianceMap = {
3273
3849
  // VC213–VC214: account state held in browser storage
3274
3850
  VC213: { owasp: "A01:2021", cwe: "CWE-602" },
3275
3851
  // entitlement from web storage (client-side enforcement)
3276
- VC214: { owasp: "A04:2021", cwe: "CWE-1188" }
3852
+ VC214: { owasp: "A04:2021", cwe: "CWE-1188" },
3277
3853
  // per-account state from web storage (insecure default state)
3854
+ // VC215: Supabase migration lint — RLS off, always-true write policy, user_metadata in a policy
3855
+ VC215: { owasp: "A01:2021", cwe: "CWE-732" },
3856
+ // incorrect permission assignment for a critical resource
3857
+ VC216: { owasp: "A01:2021", cwe: "CWE-732" },
3858
+ // Firebase rules: open, any-signed-in-user, or test mode
3859
+ // VC217: AI or secret key shipped to the browser
3860
+ VC217: { owasp: "A07:2021", cwe: "CWE-798" },
3861
+ // key inlined into the client bundle (as VC066 / VC149)
3862
+ VC220: { owasp: "A01:2021", cwe: "CWE-862" },
3863
+ // unauthenticated AI/LLM proxy (denial of wallet); same class as VC003
3864
+ // VC218–VC219: caller identity never checked, or checked against data the caller controls
3865
+ VC218: { owasp: "A01:2021", cwe: "CWE-862" },
3866
+ // Base44 asServiceRole with no caller check (missing authorization, as VC003)
3867
+ VC219: { owasp: "A01:2021", cwe: "CWE-269" },
3868
+ // role/plan from user_metadata / unsafeMetadata (improper privilege management)
3869
+ VC221: { owasp: "A07:2021", cwe: "CWE-347" },
3870
+ // server trusts unverified session / decoded JWT
3871
+ VC222: { owasp: "A05:2021", cwe: "CWE-942" },
3872
+ // Python CORS wildcard with credentials (origin echoed)
3873
+ VC223: { owasp: "A01:2021", cwe: "CWE-22" }
3874
+ // prefix-only path containment check (startsWith without separator)
3278
3875
  };
3279
3876
  var consoleLogProduction = {
3280
3877
  id: "VC097",
@@ -3459,15 +4056,15 @@ function runCustomRules(content, filePath, disabledRules = [], tier = "free", ex
3459
4056
 
3460
4057
  // src/rule-counts.ts
3461
4058
  var FREE_RULE_COUNT = 30;
3462
- var PRO_RULE_COUNT = 184;
3463
- var TOTAL_RULE_COUNT = 214;
4059
+ var PRO_RULE_COUNT = 193;
4060
+ var TOTAL_RULE_COUNT = 223;
3464
4061
 
3465
4062
  // src/ai-fp-filter.ts
3466
4063
  import Anthropic from "@anthropic-ai/sdk";
3467
4064
  var 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.
3468
4065
 
3469
4066
  Common false positive patterns you should catch:
3470
- - Auth check exists inside the function body (requireUser, requireUserForApi, getSession, etc.) but the scanner only checked the function signature
4067
+ - Auth check exists inside the function body (requireUser, requireUserForApi, supabase.auth.getUser, jwt.verify, etc.) but the scanner only checked the function signature. These are NOT auth checks in server code: supabase.auth.getSession() (it reads the cookie without verifying it), jwt.decode() / decodeJwt() / jwtDecode(), or PyJWT with verify_signature False. A finding that says the server trusts one of them is real unless the same code also verifies the token
3471
4068
  - The flagged pattern is in example/documentation/tutorial code, not production code
3472
4069
  - The variable is developer-controlled (constants, config values, static strings), not user input
3473
4070
  - The flagged function is a database method (conn.exec, db.exec, prisma.$executeRaw) not a shell command (child_process.exec)
@@ -3755,10 +4352,18 @@ var SAFE_PATTERNS = [
3755
4352
  // double-flag these. They are designed to ship to the browser.
3756
4353
  /^pk_(?:live|test|[a-z0-9]+)_/,
3757
4354
  // Stripe / Clerk publishable
4355
+ // A string that IS an env-var name — `required: ["VITE_SUPABASE_URL", …]`.
4356
+ // This tests the VALUE, never the variable it is assigned to: a secret held
4357
+ // in a public-prefixed variable is decided by classifyPublicEnvVar below.
3758
4358
  /^NEXT_PUBLIC_|^VITE_|^REACT_APP_/,
3759
- // Build-time public env vars
3760
4359
  /^pub_/,
3761
4360
  // Segment etc.
4361
+ // dotenvx ciphertext: `STRIPE_SECRET_KEY="encrypted:BE9Y…"`. dotenvx
4362
+ // encrypts each value to the file's public key (ECIES); the private key
4363
+ // stays in the git-ignored .env.keys, and committing the encrypted file is
4364
+ // the documented workflow (Supabase's own dotenvx example does). The value
4365
+ // is not usable without that key, so it is not a leaked secret.
4366
+ /^encrypted:[A-Za-z0-9+/=]{20,}$/,
3762
4367
  /^ey[A-Za-z0-9_-]+\.ey[A-Za-z0-9_-]+\./,
3763
4368
  // JWT header.payload prefix — don't flag solely on entropy
3764
4369
  // Content-Security-Policy hashes / nonces in HTML/JSON
@@ -3785,6 +4390,8 @@ var VERIFICATION_BLOCK_RE = /\bverification\s*:\s*\{/;
3785
4390
  var VERIFICATION_KEY_NAMES = /^(?: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;
3786
4391
  var VERIFICATION_META_RE = /<meta[^>]+name\s*=\s*["'][^"']*(?:site-verification|domain-verification|msvalidate|domain_verify)[^"']*["']/i;
3787
4392
  var 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;
4393
+ var DOTENV_EXAMPLE_RE = /\.(?:example|sample|template|dist|defaults?)$/i;
4394
+ var MAX_DOTENV_VALUE = 256;
3788
4395
  function getSnippet2(content, line) {
3789
4396
  const lines = content.split("\n");
3790
4397
  const start = Math.max(0, line - 2);
@@ -3807,6 +4414,7 @@ function scanEntropy(files) {
3807
4414
  if (/pro-rules-bundle|\.bundle\.|\.chunk\./i.test(filePath)) continue;
3808
4415
  if (/(?:\.test\.|\.spec\.|__tests__|__mocks__|fixtures?\/)/i.test(filePath)) continue;
3809
4416
  const vendored = isVendoredPath(filePath);
4417
+ const dotenv = isDotenvPath(filePath) && !DOTENV_EXAMPLE_RE.test(filePath);
3810
4418
  const lines = content.split("\n");
3811
4419
  let verificationDepth = -1;
3812
4420
  let braceDepth = 0;
@@ -3825,14 +4433,27 @@ function scanEntropy(files) {
3825
4433
  const inVerificationBlock = verificationDepth !== -1;
3826
4434
  const trimmed = line.trimStart();
3827
4435
  if (trimmed.startsWith("//") || trimmed.startsWith("#") || trimmed.startsWith("*") || trimmed.startsWith("/*")) continue;
3828
- const stringPattern = /(?:[:=]\s*)(["'`])([^"'`\n]{20,120})\1/g;
3829
- let match;
3830
- while ((match = stringPattern.exec(line)) !== null) {
3831
- const value = match[2];
4436
+ const candidates = [];
4437
+ const assign = dotenv ? DOTENV_ASSIGN_RE.exec(line) : null;
4438
+ const assignValue = assign ? dotenvValue(assign[2]) : "";
4439
+ const structured = assign !== null && (assignValue.length > MAX_DOTENV_VALUE || /^[{[]/.test(assignValue));
4440
+ if (assign && !structured) {
4441
+ if (assignValue.length >= 20) {
4442
+ candidates.push({ value: assignValue, beforeAssign: assign[1], dotenvName: assign[1] });
4443
+ }
4444
+ } else {
4445
+ const stringPattern = /(?:[:=]\s*)(["'`])([^"'`\n]{20,120})\1/g;
4446
+ let match;
4447
+ while ((match = stringPattern.exec(line)) !== null) {
4448
+ let beforeAssign = line.substring(0, match.index);
4449
+ if (structured) beforeAssign = beforeAssign.slice(Math.max(beforeAssign.lastIndexOf(","), beforeAssign.lastIndexOf("{")) + 1);
4450
+ candidates.push({ value: match[2], beforeAssign });
4451
+ }
4452
+ }
4453
+ for (const { value, beforeAssign, dotenvName } of candidates) {
3832
4454
  if (value.includes("${")) continue;
3833
4455
  if (SAFE_PATTERNS.some((p) => p.test(value))) continue;
3834
4456
  if (HASH_PREFIX_RE.test(value)) continue;
3835
- const beforeAssign = line.substring(0, match.index);
3836
4457
  if (SAFE_VAR_NAMES.test(beforeAssign)) continue;
3837
4458
  if (/^https?:\/\/[^:@]*$/.test(value)) continue;
3838
4459
  if ((value.match(/\s/g) || []).length > 2) continue;
@@ -3844,11 +4465,15 @@ function scanEntropy(files) {
3844
4465
  if (value.length < 20) continue;
3845
4466
  const entropy = shannonEntropy(value);
3846
4467
  if (entropy < threshold) continue;
3847
- const varName = beforeAssign.match(/["']([^"']+)["']\s*$/)?.[1] || beforeAssign.match(/([\w$-]+)\s*$/)?.[1] || "";
4468
+ const varName = dotenvName || beforeAssign.match(/["']([^"']+)["']\s*$/)?.[1] || beforeAssign.match(/([\w$-]+)\s*$/)?.[1] || "";
3848
4469
  if (inVerificationBlock && VERIFICATION_KEY_NAMES.test(varName)) continue;
3849
4470
  if (VERIFICATION_META_RE.test(line)) continue;
3850
4471
  if (HASH_LIKE_VAR_NAMES.test(varName) && (isHex || isBase64)) continue;
3851
- const isLikelySecret = SECRET_VAR_NAMES.test(varName);
4472
+ if (/^DOTENV_PUBLIC_KEY(?:_\w{1,60})?$/.test(varName) && /^0[23][0-9a-fA-F]{64}$/.test(value)) continue;
4473
+ const publicEnv = classifyPublicEnvVar(varName, value);
4474
+ if (publicEnv && publicEnv.publicByDesign) continue;
4475
+ if (dotenvName && /(?:^|_)IDS?$/i.test(dotenvName) && !SECRET_VAR_NAMES.test(dotenvName)) continue;
4476
+ const isLikelySecret = SECRET_VAR_NAMES.test(varName) || publicEnv?.secret === true;
3852
4477
  if (entropy < 4.5 && !isLikelySecret) continue;
3853
4478
  if (isLineSilenced(lines, i, "ENTROPY")) continue;
3854
4479
  const masked = value.substring(0, 6) + "..." + value.substring(value.length - 4);
@@ -3862,7 +4487,10 @@ function scanEntropy(files) {
3862
4487
  file: filePath,
3863
4488
  line: i + 1,
3864
4489
  snippet: getSnippet2(content, i + 1),
3865
- 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.",
4490
+ // The generic advice ("move it to an environment variable") is
4491
+ // wrong for a value that is already in one, so dotenv findings get
4492
+ // advice about the file, and public-prefixed ones about the prefix.
4493
+ fix: publicEnv?.secret ? `${varName} has a browser-exposed prefix (${publicEnv.prefix}), so the framework writes its value into any browser code that reads it. Rename it without the prefix, use it only in server code, and rotate the credential if a build has been deployed.` : dotenvName ? "If this is a live credential, keep this env file out of version control (add it to .gitignore and run `git rm --cached` on it) and rotate the credential if the file has been committed. If it's not a secret, add an inline `# ENTROPY-OK: <reason>` comment above the line." : "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.",
3866
4494
  category: "Secrets",
3867
4495
  source: "custom",
3868
4496
  owasp: "A02:2021",
@@ -7559,6 +8187,7 @@ function scanQuality(input, rules = qualityRules) {
7559
8187
  }
7560
8188
  export {
7561
8189
  CHECKABLE_CLAIMS,
8190
+ DOTENV_ASSIGN_RE,
7562
8191
  FREE_RULE_COUNT,
7563
8192
  INTENT_EXPECTATIONS,
7564
8193
  MODEL_ANALYSIS,
@@ -7568,6 +8197,7 @@ export {
7568
8197
  MODEL_TRIAGE,
7569
8198
  NON_APP_PATH_PATTERNS,
7570
8199
  PRO_RULE_COUNT,
8200
+ PUBLIC_ENV_PREFIX_RE,
7571
8201
  QUALITY_EXAMPLES,
7572
8202
  RULE_IMPACTS,
7573
8203
  TEST_FILE_PATTERN,
@@ -7582,6 +8212,7 @@ export {
7582
8212
  callSpreads,
7583
8213
  checkIntent,
7584
8214
  classifyExposure,
8215
+ classifyPublicEnvVar,
7585
8216
  classifyStatement,
7586
8217
  clientSideAuth,
7587
8218
  complianceMap,
@@ -7593,6 +8224,7 @@ export {
7593
8224
  detectFramework,
7594
8225
  detectPlatform,
7595
8226
  disabledTLSVerification,
8227
+ dotenvValue,
7596
8228
  emptyCatchBlock,
7597
8229
  enclosingHandler,
7598
8230
  envNotGitignored,
@@ -7618,6 +8250,7 @@ export {
7618
8250
  isCalleeNamed,
7619
8251
  isClientTarget,
7620
8252
  isCommentLine,
8253
+ isDotenvPath,
7621
8254
  isInlineSilenced,
7622
8255
  isInsideFixMessage,
7623
8256
  isLineSilenced,
@@ -7631,6 +8264,7 @@ export {
7631
8264
  lineNumberAt,
7632
8265
  lineTextAt,
7633
8266
  maskComments,
8267
+ maskOutboundAuthNoise,
7634
8268
  missingAuthMiddleware,
7635
8269
  missingCSP,
7636
8270
  missingErrorBoundary,
@@ -7643,6 +8277,7 @@ export {
7643
8277
  parseScanTarget,
7644
8278
  parseSupabaseConfig,
7645
8279
  qualityRules,
8280
+ replaceBlockComments,
7646
8281
  routeForFile,
7647
8282
  runCustomRules,
7648
8283
  scanEntropy,