xploitscan-shared-rules 2.0.2 → 2.1.1
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 +2 -2
- package/dist/index.cjs +807 -94
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +135 -7
- package/dist/index.d.ts +135 -7
- package/dist/index.js +799 -94
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
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(`(
|
|
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: "
|
|
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
|
|
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 &&
|
|
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
|
}
|
|
@@ -1524,19 +1621,27 @@ function filterSilenced(matches, content, ruleId) {
|
|
|
1524
1621
|
return matches.filter((m) => !isInlineSilenced(content, lineStartIndex(m.line), ruleId));
|
|
1525
1622
|
}
|
|
1526
1623
|
function findMatches(content, pattern, rule, filePath, fixTemplate) {
|
|
1527
|
-
const matches = [];
|
|
1528
|
-
let m;
|
|
1529
1624
|
const re = new RegExp(pattern.source, pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`);
|
|
1625
|
+
function* execAll() {
|
|
1626
|
+
let m;
|
|
1627
|
+
let lastMatchIndex = -1;
|
|
1628
|
+
while ((m = re.exec(content)) !== null) {
|
|
1629
|
+
if (m.index === lastMatchIndex && m[0].length === 0) {
|
|
1630
|
+
re.lastIndex++;
|
|
1631
|
+
continue;
|
|
1632
|
+
}
|
|
1633
|
+
lastMatchIndex = m.index;
|
|
1634
|
+
yield m;
|
|
1635
|
+
}
|
|
1636
|
+
}
|
|
1637
|
+
return findMatchesAt(content, execAll(), rule, filePath, fixTemplate);
|
|
1638
|
+
}
|
|
1639
|
+
function findMatchesAt(content, found, rule, filePath, fixTemplate) {
|
|
1640
|
+
const matches = [];
|
|
1530
1641
|
let scanned = 0;
|
|
1531
1642
|
let lineNum = 1;
|
|
1532
|
-
let lastMatchIndex = -1;
|
|
1533
1643
|
const MAX_MATCHES = 500;
|
|
1534
|
-
|
|
1535
|
-
if (m.index === lastMatchIndex && m[0].length === 0) {
|
|
1536
|
-
re.lastIndex++;
|
|
1537
|
-
continue;
|
|
1538
|
-
}
|
|
1539
|
-
lastMatchIndex = m.index;
|
|
1644
|
+
for (const m of found) {
|
|
1540
1645
|
if (isCommentLine(content, m.index)) continue;
|
|
1541
1646
|
if (isInsideFixMessage(content, m.index)) continue;
|
|
1542
1647
|
for (; scanned < m.index; scanned++) {
|
|
@@ -1599,6 +1704,27 @@ function isNamespacedSlotKey(name, value) {
|
|
|
1599
1704
|
}
|
|
1600
1705
|
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/;
|
|
1601
1706
|
var CREDENTIAL_WORD = /secret|passw|token|private|signing|apikey|credential/i;
|
|
1707
|
+
function isPlaceholderToken(token) {
|
|
1708
|
+
if (/(.)\1{7,}/.test(token)) return true;
|
|
1709
|
+
if (new Set(token).size < 8) return true;
|
|
1710
|
+
return /example|placeholder|redacted|your_?(?:api_?)?(?:key|token)|insert_?your|replace_?me/i.test(token);
|
|
1711
|
+
}
|
|
1712
|
+
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/;
|
|
1713
|
+
var GEMINI_NAME_RE = /gemini|generative/i;
|
|
1714
|
+
var PUBLIC_GOOGLE_KEY_NAME_RE = /firebase|maps?(?:\b|_)|places|recaptcha|youtube/i;
|
|
1715
|
+
var FIREBASE_CONFIG_FIELD_RE = /\b(?:authDomain|messagingSenderId|storageBucket)\b/;
|
|
1716
|
+
function isGeminiKeyContext(lines, line, fileIsGemini) {
|
|
1717
|
+
const lineText = lines[line - 1] ?? "";
|
|
1718
|
+
const keyAt = lineText.search(/AIza[\w-]{35}/);
|
|
1719
|
+
const before = keyAt === -1 ? lineText : lineText.slice(0, keyAt);
|
|
1720
|
+
if (PUBLIC_GOOGLE_KEY_NAME_RE.test(before)) return false;
|
|
1721
|
+
const from = Math.max(0, line - 4);
|
|
1722
|
+
const to = Math.min(lines.length, line + 3);
|
|
1723
|
+
for (let i = from; i < to; i++) {
|
|
1724
|
+
if (FIREBASE_CONFIG_FIELD_RE.test(lines[i])) return false;
|
|
1725
|
+
}
|
|
1726
|
+
return fileIsGemini || GEMINI_NAME_RE.test(before);
|
|
1727
|
+
}
|
|
1602
1728
|
var hardcodedSecrets = {
|
|
1603
1729
|
id: "VC001",
|
|
1604
1730
|
title: "Hardcoded API Key or Secret",
|
|
@@ -1618,8 +1744,16 @@ var hardcodedSecrets = {
|
|
|
1618
1744
|
/(?:sk_live|pk_live|sk_test|pk_test)_[a-zA-Z0-9]{20,}/g,
|
|
1619
1745
|
// Supabase anon/service keys (JWT format)
|
|
1620
1746
|
/(?:supabase[_-]?(?:anon|service)[_-]?key|SUPABASE_(?:ANON|SERVICE_ROLE)_KEY)\s*[:=]\s*["'`](eyJ[a-zA-Z0-9_-]{50,})["'`]/gi,
|
|
1621
|
-
// OpenAI keys
|
|
1622
|
-
|
|
1747
|
+
// OpenAI keys. Every OpenAI secret key carries `T3BlbkFJ` (base64 of
|
|
1748
|
+
// "OpenAI") in the middle, which is what keeps this near zero false
|
|
1749
|
+
// positives. This used to be `sk-[a-zA-Z0-9]{20,}T3BlbkFJ…`, the legacy
|
|
1750
|
+
// user-key shape: its character class has no `-`, so it could not get
|
|
1751
|
+
// past the second hyphen of `sk-proj-`, and every project, service
|
|
1752
|
+
// account and admin key OpenAI has issued since 2024 went unreported.
|
|
1753
|
+
// Prefixes and the `-`/`_` body follow gitleaks' openai-api-key rule.
|
|
1754
|
+
// Bounded on both sides so a hostile run of key characters cannot
|
|
1755
|
+
// backtrack a whole line.
|
|
1756
|
+
/sk-(?:(?:proj|svcacct|admin)-[A-Za-z0-9_-]{20,80}|[A-Za-z0-9]{20,80})T3BlbkFJ[A-Za-z0-9_-]{20,80}/g,
|
|
1623
1757
|
// Generic tokens in assignments — require standalone word and longer min length
|
|
1624
1758
|
/(?:^|[\s,({])(?:token|secret|password|passwd|pwd)\s*[:=]\s*["'`]([a-zA-Z0-9_\-!@#$%^&*]{20,})["'`]/gim,
|
|
1625
1759
|
// SCREAMING_CASE identifiers ending in SECRET/TOKEN/KEY/PASSWORD
|
|
@@ -1636,20 +1770,42 @@ var hardcodedSecrets = {
|
|
|
1636
1770
|
// Private keys
|
|
1637
1771
|
/-----BEGIN (?:RSA |EC |DSA )?PRIVATE KEY-----/g,
|
|
1638
1772
|
// Database URLs with credentials
|
|
1639
|
-
/(?:postgres|mysql|mongodb(?:\+srv)?):\/\/[^:]+:[^@]+@[^/\s"'`]+/gi
|
|
1773
|
+
/(?:postgres|mysql|mongodb(?:\+srv)?):\/\/[^:]+:[^@]+@[^/\s"'`]+/gi,
|
|
1774
|
+
// ── [11]–[14] Fixed-prefix AI-provider and payment keys ──
|
|
1775
|
+
// These match the token itself, so they fire whatever it is bound to:
|
|
1776
|
+
// `const k = "…"`, a positional `new OpenAI("…")`, an unquoted .env
|
|
1777
|
+
// value. The name-based patterns above only see a key that sits in a
|
|
1778
|
+
// slot called apiKey / token / *_KEY. Shapes follow gitleaks.
|
|
1779
|
+
// [11] Hugging Face user access token: `hf_` + 34 letters.
|
|
1780
|
+
/\bhf_[A-Za-z]{34}\b/g,
|
|
1781
|
+
// [12] OpenRouter: `sk-or-v1-` + 64 hex.
|
|
1782
|
+
/\bsk-or-v1-[a-f0-9]{64}\b/g,
|
|
1783
|
+
// [13] Stripe restricted key. `rk_` keys are scoped, but a live one can
|
|
1784
|
+
// still read customers or issue refunds, and [2] above only knows
|
|
1785
|
+
// `sk_`/`pk_`. No trailing anchor: Stripe keys run to ~100 characters
|
|
1786
|
+
// and the match only needs the prefix plus a real body.
|
|
1787
|
+
/\brk_(?:live|test)_[A-Za-z0-9]{20,200}/g,
|
|
1788
|
+
// [14] Google API key — reported only in a Gemini context, see
|
|
1789
|
+
// GEMINI_FILE_CONTEXT_RE. The lookahead stands in for `\b`, which the
|
|
1790
|
+
// `-` in the key alphabet would break.
|
|
1791
|
+
/AIza[\w-]{35}(?![\w-])/g
|
|
1640
1792
|
];
|
|
1641
1793
|
const fixMessages = [
|
|
1642
1794
|
"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.",
|
|
1643
1795
|
"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.",
|
|
1644
1796
|
"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.",
|
|
1645
1797
|
"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.",
|
|
1646
|
-
"OpenAI API key detected
|
|
1798
|
+
"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.",
|
|
1647
1799
|
"Hardcoded token or password detected. Move to an environment variable and rotate the credential if it has been committed to version control.",
|
|
1648
1800
|
"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.",
|
|
1649
1801
|
"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.",
|
|
1650
1802
|
"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.",
|
|
1651
1803
|
"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.",
|
|
1652
|
-
"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."
|
|
1804
|
+
"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.",
|
|
1805
|
+
"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.",
|
|
1806
|
+
"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.",
|
|
1807
|
+
"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.",
|
|
1808
|
+
"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."
|
|
1653
1809
|
];
|
|
1654
1810
|
const minLen = [
|
|
1655
1811
|
12,
|
|
@@ -1660,8 +1816,12 @@ var hardcodedSecrets = {
|
|
|
1660
1816
|
// [2] Stripe
|
|
1661
1817
|
50,
|
|
1662
1818
|
// [3] Supabase JWT
|
|
1663
|
-
|
|
1664
|
-
//
|
|
1819
|
+
// [4] OpenAI and [11]–[14] fixed-prefix tokens: the regex already
|
|
1820
|
+
// fixes the length. The floor check reads the FIRST quoted value on the
|
|
1821
|
+
// line, which in `a = "x"; key = "sk-proj-…"` is not the token, so it
|
|
1822
|
+
// must not run for them. ([4] was 40, which the regex's minimum of 48
|
|
1823
|
+
// made redundant everywhere except that misread.)
|
|
1824
|
+
0,
|
|
1665
1825
|
20,
|
|
1666
1826
|
// [5] generic tokens with {20,} in the regex
|
|
1667
1827
|
12,
|
|
@@ -1672,18 +1832,49 @@ var hardcodedSecrets = {
|
|
|
1672
1832
|
// [8] password: "..." — lower floor per the pattern comment above
|
|
1673
1833
|
0,
|
|
1674
1834
|
// [9] private keys — no length check
|
|
1675
|
-
0
|
|
1835
|
+
0,
|
|
1676
1836
|
// [10] DB URLs — no length check
|
|
1837
|
+
0,
|
|
1838
|
+
0,
|
|
1839
|
+
0,
|
|
1840
|
+
0
|
|
1841
|
+
// [11]–[14] see [4]
|
|
1677
1842
|
];
|
|
1843
|
+
const OPENAI_PI = 4;
|
|
1844
|
+
const FIRST_TOKEN_PI = 11;
|
|
1845
|
+
const STRIPE_RESTRICTED_PI = 13;
|
|
1846
|
+
const GOOGLE_PI = 14;
|
|
1847
|
+
const lines = content.split("\n");
|
|
1848
|
+
const fileIsGemini = GEMINI_FILE_CONTEXT_RE.test(content);
|
|
1678
1849
|
const matches = [];
|
|
1679
1850
|
for (let pi = 0; pi < patterns.length; pi++) {
|
|
1680
1851
|
const pattern = patterns[pi];
|
|
1681
|
-
|
|
1852
|
+
if (pi === GOOGLE_PI && !fileIsGemini && !GEMINI_NAME_RE.test(content)) continue;
|
|
1853
|
+
const matchedText = [];
|
|
1854
|
+
const rawMatches = findMatches(content, pattern, hardcodedSecrets, filePath, (m) => {
|
|
1855
|
+
matchedText.push(m[0]);
|
|
1856
|
+
return fixMessages[pi];
|
|
1857
|
+
});
|
|
1682
1858
|
const floor = minLen[pi] ?? 12;
|
|
1683
|
-
|
|
1684
|
-
|
|
1859
|
+
const isTokenPattern = pi === OPENAI_PI || pi >= FIRST_TOKEN_PI;
|
|
1860
|
+
for (let ri = 0; ri < rawMatches.length; ri++) {
|
|
1861
|
+
const rm = rawMatches[ri];
|
|
1862
|
+
const lineText = lines[rm.line - 1] || "";
|
|
1685
1863
|
const trimmed = lineText.trimStart();
|
|
1686
1864
|
if (trimmed.startsWith("//") || trimmed.startsWith("#")) continue;
|
|
1865
|
+
if (isTokenPattern) {
|
|
1866
|
+
const token = matchedText[ri] ?? "";
|
|
1867
|
+
if (isPlaceholderToken(token)) continue;
|
|
1868
|
+
if (pi === GOOGLE_PI) {
|
|
1869
|
+
if (!isGeminiKeyContext(lines, rm.line, fileIsGemini)) continue;
|
|
1870
|
+
matches.push({ ...rm, severity: "high" });
|
|
1871
|
+
continue;
|
|
1872
|
+
}
|
|
1873
|
+
if (pi === STRIPE_RESTRICTED_PI && !token.startsWith("rk_live_")) {
|
|
1874
|
+
matches.push({ ...rm, severity: "high" });
|
|
1875
|
+
continue;
|
|
1876
|
+
}
|
|
1877
|
+
}
|
|
1687
1878
|
if (floor > 0) {
|
|
1688
1879
|
const secretMatch = lineText.match(/[:=]\s*["'`]([^"'`]*)["'`]/);
|
|
1689
1880
|
if (secretMatch && secretMatch[1].length < floor) continue;
|
|
@@ -1800,6 +1991,323 @@ function stripCorsHeaderList(codeOnly) {
|
|
|
1800
1991
|
""
|
|
1801
1992
|
);
|
|
1802
1993
|
}
|
|
1994
|
+
function blankKeepLines(s) {
|
|
1995
|
+
return s.replace(/[^\n]/g, " ");
|
|
1996
|
+
}
|
|
1997
|
+
function closingBrace(text, open, limit) {
|
|
1998
|
+
let depth = 0;
|
|
1999
|
+
const end = Math.min(text.length, open + limit);
|
|
2000
|
+
for (let i = open; i < end; i++) {
|
|
2001
|
+
const c = text.charCodeAt(i);
|
|
2002
|
+
if (c === 34 || c === 39) {
|
|
2003
|
+
let j = i + 1;
|
|
2004
|
+
while (j < end) {
|
|
2005
|
+
const d = text.charCodeAt(j);
|
|
2006
|
+
if (d === 92) {
|
|
2007
|
+
j += 2;
|
|
2008
|
+
continue;
|
|
2009
|
+
}
|
|
2010
|
+
if (d === c || d === 10) break;
|
|
2011
|
+
j++;
|
|
2012
|
+
}
|
|
2013
|
+
i = j;
|
|
2014
|
+
continue;
|
|
2015
|
+
}
|
|
2016
|
+
if (c === 123) depth++;
|
|
2017
|
+
else if (c === 125) {
|
|
2018
|
+
depth--;
|
|
2019
|
+
if (depth === 0) return i;
|
|
2020
|
+
}
|
|
2021
|
+
}
|
|
2022
|
+
return -1;
|
|
2023
|
+
}
|
|
2024
|
+
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;
|
|
2025
|
+
function forwardsCallerCredential(headersInner, readsCaller) {
|
|
2026
|
+
const CRED_ENTRY_RE = /["']?(?:authorization|x-api-key|api-key|apikey|x-auth-token|x-access-token|cookie)["']?\s*:\s*([^,\n}]{0,300})/gi;
|
|
2027
|
+
let e;
|
|
2028
|
+
while ((e = CRED_ENTRY_RE.exec(headersInner)) !== null) {
|
|
2029
|
+
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, "");
|
|
2030
|
+
if (/\b(?:token|accessToken|access_token|idToken|id_token|authToken|userToken|bearerToken|jwt|session|cookies?)\b/i.test(value)) {
|
|
2031
|
+
return true;
|
|
2032
|
+
}
|
|
2033
|
+
if (readsCaller?.(value)) return true;
|
|
2034
|
+
}
|
|
2035
|
+
return false;
|
|
2036
|
+
}
|
|
2037
|
+
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*[,)]/;
|
|
2038
|
+
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;
|
|
2039
|
+
var MAX_BINDINGS = 4096;
|
|
2040
|
+
function collectBindings(code) {
|
|
2041
|
+
const byName = /* @__PURE__ */ new Map();
|
|
2042
|
+
const add = (name, at, rhs) => {
|
|
2043
|
+
const list = byName.get(name);
|
|
2044
|
+
if (list) list.push({ at, rhs });
|
|
2045
|
+
else byName.set(name, [{ at, rhs }]);
|
|
2046
|
+
};
|
|
2047
|
+
let count = 0;
|
|
2048
|
+
let b;
|
|
2049
|
+
BINDING_RE.lastIndex = 0;
|
|
2050
|
+
while ((b = BINDING_RE.exec(code)) !== null && count < MAX_BINDINGS) {
|
|
2051
|
+
count++;
|
|
2052
|
+
if (b[1]) {
|
|
2053
|
+
add(b[1], b.index, b[3]);
|
|
2054
|
+
continue;
|
|
2055
|
+
}
|
|
2056
|
+
for (const part of b[2].split(",")) {
|
|
2057
|
+
const local = part.replace(/=[^]*$/, "").replace(/^[^:]*:/, "").trim().replace(/^\.\.\./, "");
|
|
2058
|
+
if (/^[A-Za-z_$][\w$]{0,60}$/.test(local)) add(local, b.index, b[3]);
|
|
2059
|
+
}
|
|
2060
|
+
}
|
|
2061
|
+
return byName;
|
|
2062
|
+
}
|
|
2063
|
+
function credentialValueReadsCaller(value, at, bindings) {
|
|
2064
|
+
if (INBOUND_CREDENTIAL_READ_RE.test(value) || INBOUND_REQUEST_READ_RE.test(value)) return true;
|
|
2065
|
+
const roots = /* @__PURE__ */ new Set();
|
|
2066
|
+
const INTERP_RE = /\$\{\s*([A-Za-z_$][\w$]{0,60})/g;
|
|
2067
|
+
const ROOT_RE = /(?<![\w$.])[A-Za-z_$][\w$]{0,60}/g;
|
|
2068
|
+
let r;
|
|
2069
|
+
while ((r = INTERP_RE.exec(value)) !== null && roots.size < 6) roots.add(r[1]);
|
|
2070
|
+
const bare = value.replace(/"[^"\n]{0,300}"|'[^'\n]{0,300}'|`[^`]{0,300}(?:`|$)/g, " ");
|
|
2071
|
+
while ((r = ROOT_RE.exec(bare)) !== null && roots.size < 6) roots.add(r[0]);
|
|
2072
|
+
for (const name of roots) {
|
|
2073
|
+
const list = bindings().get(name);
|
|
2074
|
+
if (!list || list[0].at >= at) continue;
|
|
2075
|
+
let lo = 0;
|
|
2076
|
+
let hi = list.length - 1;
|
|
2077
|
+
while (lo < hi) {
|
|
2078
|
+
const mid = lo + hi + 1 >> 1;
|
|
2079
|
+
if (list[mid].at < at) lo = mid;
|
|
2080
|
+
else hi = mid - 1;
|
|
2081
|
+
}
|
|
2082
|
+
if (INBOUND_REQUEST_READ_RE.test(list[lo].rhs)) return true;
|
|
2083
|
+
}
|
|
2084
|
+
return false;
|
|
2085
|
+
}
|
|
2086
|
+
function maskOutboundAuthNoise(code) {
|
|
2087
|
+
let out = code.replace(
|
|
2088
|
+
/(["']?)role\1\s{0,20}:\s{0,20}["'](?:user|assistant|system|developer|tool|model|function)["']/g,
|
|
2089
|
+
blankKeepLines
|
|
2090
|
+
);
|
|
2091
|
+
if (/["'`]assistant["'`]/.test(out)) {
|
|
2092
|
+
out = out.replace(/["'`](?:user|assistant|system|developer|tool)["'`]/g, blankKeepLines);
|
|
2093
|
+
}
|
|
2094
|
+
const envNames = /* @__PURE__ */ new Set();
|
|
2095
|
+
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;
|
|
2096
|
+
let b;
|
|
2097
|
+
while ((b = ENV_BIND_RE.exec(out)) !== null && envNames.size < 32) {
|
|
2098
|
+
if (!/secret|webhook|signing|cron|internal|admin|password|passwd/i.test(b[1])) envNames.add(b[1]);
|
|
2099
|
+
}
|
|
2100
|
+
if (envNames.size > 0) {
|
|
2101
|
+
const names = [...envNames].map((n) => n.replace(/\$/g, "\\$")).join("|");
|
|
2102
|
+
out = out.replace(new RegExp(`(?<![\\w$.])(?:${names})(?![\\w$])`, "g"), blankKeepLines);
|
|
2103
|
+
}
|
|
2104
|
+
out = out.replace(
|
|
2105
|
+
/\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,
|
|
2106
|
+
blankKeepLines
|
|
2107
|
+
);
|
|
2108
|
+
let bindingMap = null;
|
|
2109
|
+
const bindingSource = out;
|
|
2110
|
+
const bindings = () => bindingMap ??= collectBindings(bindingSource);
|
|
2111
|
+
out = out.replace(
|
|
2112
|
+
/\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,
|
|
2113
|
+
(call, value, at) => credentialValueReadsCaller(value, at, bindings) ? call : blankKeepLines(call)
|
|
2114
|
+
);
|
|
2115
|
+
const OPEN_RE = /\b(?:headers\s*[:=]|new\s+Headers\s*\()\s*\{/g;
|
|
2116
|
+
const MAX_OBJECTS = 64;
|
|
2117
|
+
const MAX_OBJECT_LEN = 3e3;
|
|
2118
|
+
let examined = 0;
|
|
2119
|
+
let m;
|
|
2120
|
+
const parts = [];
|
|
2121
|
+
let copied = 0;
|
|
2122
|
+
while ((m = OPEN_RE.exec(out)) !== null) {
|
|
2123
|
+
if (++examined > MAX_OBJECTS) break;
|
|
2124
|
+
const open = m.index + m[0].length - 1;
|
|
2125
|
+
const close = closingBrace(out, open, MAX_OBJECT_LEN);
|
|
2126
|
+
if (close === -1) continue;
|
|
2127
|
+
const inner = out.slice(open + 1, close);
|
|
2128
|
+
const readsCaller = (value) => credentialValueReadsCaller(value, open, bindings);
|
|
2129
|
+
if (!INBOUND_CREDENTIAL_READ_RE.test(inner) && !forwardsCallerCredential(inner, readsCaller)) {
|
|
2130
|
+
parts.push(out.slice(copied, open + 1), blankKeepLines(inner));
|
|
2131
|
+
copied = close;
|
|
2132
|
+
}
|
|
2133
|
+
OPEN_RE.lastIndex = close + 1;
|
|
2134
|
+
}
|
|
2135
|
+
if (parts.length === 0) return out;
|
|
2136
|
+
parts.push(out.slice(copied));
|
|
2137
|
+
return parts.join("");
|
|
2138
|
+
}
|
|
2139
|
+
function maskProseStrings(code) {
|
|
2140
|
+
return code.replace(
|
|
2141
|
+
/(?<!\\)"(?:[^"\\\n]|\\.){0,2000}"|(?<!\\)'(?:[^'\\\n]|\\.){0,2000}'|(?<!\\)`(?:[^`\\]|\\.){0,8000}`/g,
|
|
2142
|
+
(lit) => /\S\s+\S+\s+\S+\s+\S/.test(lit) ? blankKeepLines(lit) : lit
|
|
2143
|
+
);
|
|
2144
|
+
}
|
|
2145
|
+
var TANSTACK_START_IMPORT_RE = /["']@tanstack\/(?:(?:react|solid)-)?start(?:\/[\w-]{1,40})?["']/;
|
|
2146
|
+
var TANSTACK_ROUTER_IMPORT_RE = /["']@tanstack\/(?:react|solid)-router["']/;
|
|
2147
|
+
var TANSTACK_AUTH_MIDDLEWARE_RE = /\bmiddleware\s*[:(]\s*\[([^\]]{0,600})\]/g;
|
|
2148
|
+
var AUTH_MIDDLEWARE_NAME_RE = /auth|session|protect|require|guard|user|admin|clerk|signed|logged|login|member|owner|role|permission/i;
|
|
2149
|
+
var TANSTACK_HANDLER_AUTH_RE = [
|
|
2150
|
+
/\bget(?:User|Claims|Session|ServerSession|Auth|Token)\s*\(/,
|
|
2151
|
+
/\bget(?:Authed|Authenticated|Current|Signed\w{0,8}|Logged\w{0,8}|Session)\w{0,30}\s*\(/,
|
|
2152
|
+
/\bcurrentUser\b/,
|
|
2153
|
+
/\buse\w{0,30}Session\s*\(/,
|
|
2154
|
+
/\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,
|
|
2155
|
+
// `requireX()` / `assertX()` / `ensureX()` / `authorizeX()` is the
|
|
2156
|
+
// near-universal spelling of a bespoke gate — tanstack.com's own
|
|
2157
|
+
// `requireModerateShowcases()`, `requireCaller()`. Suppression only.
|
|
2158
|
+
/\b(?:require|assert|ensure|guard|protect|authori[sz]e)[A-Z]\w{0,40}\s*\(/,
|
|
2159
|
+
/\b(?:can|has)(?:Permission|Access|Role|Capability|Scope)\w{0,30}\s*\(/,
|
|
2160
|
+
/\bisAuthenticated\b/,
|
|
2161
|
+
/\bauth\s*\(\s*\)/,
|
|
2162
|
+
/\bauth\s*\.\s*api\s*\.\s*getSession\b/,
|
|
2163
|
+
/\.auth\s*\.\s*(?:getUser|getClaims|getSession)\b/,
|
|
2164
|
+
/\bcontext\s*\.\s*(?:user|userId|session|auth|claims|supabase)\b/,
|
|
2165
|
+
/\b(?:jwt\.verify|jwtVerify|verifyIdToken|verifyToken|timingSafeEqual|constructEvent\w{0,20}|createHmac)\s*\(/,
|
|
2166
|
+
/\bstatus(?:Code)?\s*[:(]\s*401\b/,
|
|
2167
|
+
/\bunauthori[sz]ed\b/i,
|
|
2168
|
+
/\bnot\s+(?:authenticated|authori[sz]ed|logged\s+in|signed\s+in)\b/i,
|
|
2169
|
+
// Reads the caller's credential. Forwarding it to a row-level-security
|
|
2170
|
+
// client scopes every query to the caller, which is the safe Supabase shape.
|
|
2171
|
+
/\bauthorization\b/i,
|
|
2172
|
+
// A capability-token lookup: the row is found by an unguessable value the
|
|
2173
|
+
// caller holds (`.eq("token", data.token)`, `.eq("id", body.session_id)`).
|
|
2174
|
+
// Share links, anonymous votes, guest chat sessions — the token in the
|
|
2175
|
+
// request IS the credential, the same family VC003 already accepts via a
|
|
2176
|
+
// 401 on the Next.js shapes. Calibration: every such handler in the sample
|
|
2177
|
+
// was public by design.
|
|
2178
|
+
/\.(?:eq|match)\(\s*["'`]\w{0,40}(?:token|secret|code|hash|key)["'`]/i,
|
|
2179
|
+
/\.eq\(\s*["'`]\w{1,40}["'`]\s*,\s*[\w$.]{0,60}(?:[Tt]oken|[Ss]ession_?(?:[Ii]d|[Kk]ey)|[Ss]ecret|[Hh]ash)\b/,
|
|
2180
|
+
// A shared-secret comparison (`data.password !== process.env.ADMIN_PASSWORD`).
|
|
2181
|
+
/[!=]==?\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}/
|
|
2182
|
+
];
|
|
2183
|
+
var TANSTACK_MUTATION_RE = [
|
|
2184
|
+
// Supabase: .from("orders").update(…) / .upsert(…) / .delete()
|
|
2185
|
+
/\.from\(\s*["'`][\w.-]{1,64}["'`]\s*\)\s*\.\s*(?:update|upsert|delete)\s*\(/,
|
|
2186
|
+
// Supabase admin auth API: listUsers, deleteUser, updateUserById, …
|
|
2187
|
+
/\.auth\s*\.\s*admin\s*\.\s*\w{1,40}\s*\(/,
|
|
2188
|
+
// Prisma: prisma.order.delete(…), db.user.updateMany(…)
|
|
2189
|
+
/\b(?:prisma|db|tx)\s*\.\s*\w{1,64}\s*\.\s*(?:update|upsert|delete|updateMany|deleteMany)\s*\(/,
|
|
2190
|
+
// Drizzle: db.update(orders) / db.delete(orders)
|
|
2191
|
+
/\b(?:db|tx)\s*\.\s*(?:update|delete)\s*\(\s*\w/,
|
|
2192
|
+
// Firestore admin: .doc(id).update(…) / .delete()
|
|
2193
|
+
/\.doc\([^()\n]{0,200}\)\s*\.\s*(?:update|delete|set)\s*\(/,
|
|
2194
|
+
// Raw SQL
|
|
2195
|
+
/\b(?:UPDATE\s+["`]?\w{1,64}["`]?\s+SET|DELETE\s+FROM)\b/
|
|
2196
|
+
];
|
|
2197
|
+
var SUPABASE_WRITE_TABLE_RE = /\.from\(\s*["'`]([\w.-]{1,64})["'`]\s*\)\s*\.\s*(?:update|upsert|delete)\s*\(/g;
|
|
2198
|
+
var ANALYTICS_TABLE_RE = /(?:^|[_.-])(?:page_?views?|views?|visits?|visitors?|analytics?|tracking|clicks?|impressions?|heartbeats?|presence|metrics?|stats?|counters?)(?:[_.-]|$)/i;
|
|
2199
|
+
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;
|
|
2200
|
+
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;
|
|
2201
|
+
function closingParen(text, open, limit) {
|
|
2202
|
+
let depth = 0;
|
|
2203
|
+
const end = Math.min(text.length, limit);
|
|
2204
|
+
for (let i = open; i < end; i++) {
|
|
2205
|
+
const c = text.charCodeAt(i);
|
|
2206
|
+
if (c === 34 || c === 39 || c === 96) {
|
|
2207
|
+
let j = i + 1;
|
|
2208
|
+
while (j < end) {
|
|
2209
|
+
const d = text.charCodeAt(j);
|
|
2210
|
+
if (d === 92) {
|
|
2211
|
+
j += 2;
|
|
2212
|
+
continue;
|
|
2213
|
+
}
|
|
2214
|
+
if (d === c || c !== 96 && d === 10) break;
|
|
2215
|
+
j++;
|
|
2216
|
+
}
|
|
2217
|
+
i = j;
|
|
2218
|
+
continue;
|
|
2219
|
+
}
|
|
2220
|
+
if (c === 40) depth++;
|
|
2221
|
+
else if (c === 41) {
|
|
2222
|
+
depth--;
|
|
2223
|
+
if (depth === 0) return i;
|
|
2224
|
+
}
|
|
2225
|
+
}
|
|
2226
|
+
return -1;
|
|
2227
|
+
}
|
|
2228
|
+
function hasAuthMiddleware(text) {
|
|
2229
|
+
TANSTACK_AUTH_MIDDLEWARE_RE.lastIndex = 0;
|
|
2230
|
+
let m;
|
|
2231
|
+
while ((m = TANSTACK_AUTH_MIDDLEWARE_RE.exec(text)) !== null) {
|
|
2232
|
+
if (AUTH_MIDDLEWARE_NAME_RE.test(m[1])) return true;
|
|
2233
|
+
}
|
|
2234
|
+
return false;
|
|
2235
|
+
}
|
|
2236
|
+
function unauthenticatedTanStackHandlers(masked, filePath) {
|
|
2237
|
+
const isStart = TANSTACK_START_IMPORT_RE.test(masked);
|
|
2238
|
+
const hasServerFn = /\bcreateServerFn\s*\(/.test(masked);
|
|
2239
|
+
const hasServerRoute = /\bcreateServerFileRoute\s*\(|\bcreateAPIFileRoute\s*\(/.test(masked) || /\bserver\s*:\s*\{/.test(masked) && /\bhandlers\s*:/.test(masked);
|
|
2240
|
+
if (!hasServerFn && !hasServerRoute) return [];
|
|
2241
|
+
if (!isStart && !(hasServerRoute && TANSTACK_ROUTER_IMPORT_RE.test(masked))) return [];
|
|
2242
|
+
if (TANSTACK_PUBLIC_ROUTE_PATH_RE.test(filePath)) return [];
|
|
2243
|
+
const hits = [];
|
|
2244
|
+
const touchesData = (body) => {
|
|
2245
|
+
const supabaseWrites = [...body.matchAll(SUPABASE_WRITE_TABLE_RE)].map((w) => w[1]);
|
|
2246
|
+
const otherWrites = TANSTACK_MUTATION_RE.slice(1).some((p) => p.test(body));
|
|
2247
|
+
if (otherWrites) return true;
|
|
2248
|
+
return supabaseWrites.some((t) => !ANALYTICS_TABLE_RE.test(t));
|
|
2249
|
+
};
|
|
2250
|
+
const establishesCaller = (body) => hasAuthMiddleware(body) || TANSTACK_HANDLER_AUTH_RE.some((p) => p.test(body));
|
|
2251
|
+
if (hasServerFn) {
|
|
2252
|
+
const starts = [];
|
|
2253
|
+
const FN_RE = /\bcreateServerFn\s*\(/g;
|
|
2254
|
+
let m;
|
|
2255
|
+
while ((m = FN_RE.exec(masked)) !== null && starts.length < 500) starts.push(m.index);
|
|
2256
|
+
for (let k = 0; k < starts.length; k++) {
|
|
2257
|
+
const start = starts[k];
|
|
2258
|
+
const limit = k + 1 < starts.length ? starts[k + 1] : Math.min(masked.length, start + 4e4);
|
|
2259
|
+
const h = /\.handler\s*\(/.exec(masked.slice(start, limit));
|
|
2260
|
+
if (!h) continue;
|
|
2261
|
+
const open = start + h.index + h[0].length - 1;
|
|
2262
|
+
const close = closingParen(masked, open, limit);
|
|
2263
|
+
const chain = masked.slice(start, close === -1 ? limit : close + 1);
|
|
2264
|
+
const header = masked.slice(start, open);
|
|
2265
|
+
const body = masked.slice(open, close === -1 ? limit : close + 1);
|
|
2266
|
+
const before = masked.slice(Math.max(0, start - 120), start);
|
|
2267
|
+
const nameMatch = before.match(/\b(?:const|let|var)\s+(\w{1,80})\s*(?::[^=\n]{0,80})?=\s*$/);
|
|
2268
|
+
if (nameMatch && TANSTACK_PUBLIC_FN_NAME_RE.test(nameMatch[1])) continue;
|
|
2269
|
+
if (hasAuthMiddleware(header)) continue;
|
|
2270
|
+
if (!touchesData(body)) continue;
|
|
2271
|
+
if (establishesCaller(chain)) continue;
|
|
2272
|
+
hits.push(nameMatch && nameMatch.index !== void 0 ? start - before.length + nameMatch.index : start);
|
|
2273
|
+
if (hits.length >= 50) return hits;
|
|
2274
|
+
}
|
|
2275
|
+
}
|
|
2276
|
+
if (hasServerRoute) {
|
|
2277
|
+
const serverBlock = /\bserver\s*:\s*\{/.exec(masked);
|
|
2278
|
+
const routeLevelAuth = serverBlock !== null && (() => {
|
|
2279
|
+
const close = closingBrace(masked, serverBlock.index + serverBlock[0].length - 1, 6e4);
|
|
2280
|
+
const block = masked.slice(serverBlock.index, close === -1 ? masked.length : close);
|
|
2281
|
+
const handlersAt = block.search(/\bhandlers\s*:/);
|
|
2282
|
+
return hasAuthMiddleware(handlersAt === -1 ? block : block.slice(0, handlersAt));
|
|
2283
|
+
})();
|
|
2284
|
+
if (!routeLevelAuth) {
|
|
2285
|
+
const METHOD_RE = /\b(GET|POST|PUT|PATCH|DELETE)\s*:\s*(?:async\s+)?(?:\(|function\b|\{|[A-Za-z_$][\w$]{0,40}\s*=>)/g;
|
|
2286
|
+
const methodStarts = [];
|
|
2287
|
+
let m;
|
|
2288
|
+
while ((m = METHOD_RE.exec(masked)) !== null && methodStarts.length < 200) methodStarts.push(m.index);
|
|
2289
|
+
for (let k = 0; k < methodStarts.length; k++) {
|
|
2290
|
+
const start = methodStarts[k];
|
|
2291
|
+
const limit = k + 1 < methodStarts.length ? methodStarts[k + 1] : Math.min(masked.length, start + 4e4);
|
|
2292
|
+
const head = masked.slice(start, Math.min(limit, start + 400));
|
|
2293
|
+
const opener = /^\w+\s*:\s*\{/.exec(head) ?? /=>\s*\{/.exec(head) ?? /\)\s*\{/.exec(head);
|
|
2294
|
+
let body;
|
|
2295
|
+
if (opener) {
|
|
2296
|
+
const braceAt = start + opener.index + opener[0].length - 1;
|
|
2297
|
+
const close = closingBrace(masked, braceAt, limit - braceAt);
|
|
2298
|
+
body = masked.slice(start, close === -1 ? limit : close + 1);
|
|
2299
|
+
} else {
|
|
2300
|
+
body = masked.slice(start, limit);
|
|
2301
|
+
}
|
|
2302
|
+
if (!touchesData(body)) continue;
|
|
2303
|
+
if (establishesCaller(body)) continue;
|
|
2304
|
+
hits.push(start);
|
|
2305
|
+
if (hits.length >= 50) return hits;
|
|
2306
|
+
}
|
|
2307
|
+
}
|
|
2308
|
+
}
|
|
2309
|
+
return hits;
|
|
2310
|
+
}
|
|
1803
2311
|
var missingAuthMiddleware = {
|
|
1804
2312
|
id: "VC003",
|
|
1805
2313
|
title: "API Route Missing Authentication",
|
|
@@ -1807,7 +2315,9 @@ var missingAuthMiddleware = {
|
|
|
1807
2315
|
category: "Authentication",
|
|
1808
2316
|
description: "API routes without authentication checks allow unauthorized access.",
|
|
1809
2317
|
check(content, filePath, project) {
|
|
1810
|
-
|
|
2318
|
+
const serverSide = isServerSideFile(filePath, content);
|
|
2319
|
+
const tanstackCandidate = !serverSide && !isTestFile(filePath) && /@tanstack\/(?:(?:react|solid)-)?(?:start|router)\b/.test(content);
|
|
2320
|
+
if (!serverSide && !tanstackCandidate) return [];
|
|
1811
2321
|
if (PUBLIC_BY_CONVENTION_ROUTE.test(routeSegmentName(filePath))) return [];
|
|
1812
2322
|
const routePatterns = [
|
|
1813
2323
|
// Express/Hono style
|
|
@@ -1823,7 +2333,7 @@ var missingAuthMiddleware = {
|
|
|
1823
2333
|
/module\.exports\s*=\s*(?:async\s+)?(?:function\b|\()/g
|
|
1824
2334
|
);
|
|
1825
2335
|
}
|
|
1826
|
-
if (
|
|
2336
|
+
if (USE_SERVER_DIRECTIVE_RE.test(content)) {
|
|
1827
2337
|
routePatterns.push(
|
|
1828
2338
|
/export\s+(?:async\s+)?function\s+\w+\s*\(/g,
|
|
1829
2339
|
/export\s+const\s+\w+\s*(?::[^=\n]{0,120})?=\s*(?:async\s*)?\(/g
|
|
@@ -1847,7 +2357,7 @@ var missingAuthMiddleware = {
|
|
|
1847
2357
|
if (isAuthRoute) return [];
|
|
1848
2358
|
const isWebhookRoute = /\/webhook/i.test(filePath) || /(?:^|[/_-])webhooks?(?:[/_.-]|$)/i.test(filePath);
|
|
1849
2359
|
if (isWebhookRoute) return [];
|
|
1850
|
-
const codeOnly = content
|
|
2360
|
+
const codeOnly = replaceBlockComments(content, () => "").replace(/(^|[^:])\/\/.*$/gm, "$1").replace(/^[ \t\uFEFF]*#.*$/gm, "");
|
|
1851
2361
|
const authPatterns = [
|
|
1852
2362
|
/\bgetUser\b/i,
|
|
1853
2363
|
/\bcurrentUser\b/i,
|
|
@@ -1863,6 +2373,13 @@ var missingAuthMiddleware = {
|
|
|
1863
2373
|
/\bcheckApiKey\b/i,
|
|
1864
2374
|
/\bverifyCronSecret\b/i,
|
|
1865
2375
|
/\bverifySecret\b/i,
|
|
2376
|
+
// Signed-request receivers: `await verifyQstashSignature({ req, rawBody })`,
|
|
2377
|
+
// `verifyWebhookSignature(…)`, Upstash's `receiver.verify({ signature,
|
|
2378
|
+
// body })`. Since outbound headers are masked, a route that relied on
|
|
2379
|
+
// its own outbound `Bearer ${key}` to pass no longer does, and these
|
|
2380
|
+
// are what actually authenticate it.
|
|
2381
|
+
/\bverify\w{0,20}Signature\w{0,20}\s*\(/i,
|
|
2382
|
+
/\b\w{0,30}[Rr]eceiver\s*\.\s*verify\s*\(/,
|
|
1866
2383
|
/supabase\.auth/i,
|
|
1867
2384
|
/firebase\.auth/i,
|
|
1868
2385
|
/\bclerk\b/i,
|
|
@@ -1901,16 +2418,17 @@ var missingAuthMiddleware = {
|
|
|
1901
2418
|
const handlerAuthPatterns = authPatterns.filter(
|
|
1902
2419
|
(p) => !APP_LEVEL_AUTH.some((a) => a.source === p.source)
|
|
1903
2420
|
);
|
|
1904
|
-
const maskedForScope = maskComments(content);
|
|
2421
|
+
const maskedForScope = maskOutboundAuthNoise(maskComments(content));
|
|
2422
|
+
const codeForAuth = maskOutboundAuthNoise(codeOnly);
|
|
1905
2423
|
const handlerHasAuth = (index) => {
|
|
1906
2424
|
const bodyStart = maskedForScope.indexOf("{", index);
|
|
1907
2425
|
const probe = bodyStart === -1 ? index : bodyStart + 1;
|
|
1908
2426
|
const scope = enclosingHandler(maskedForScope, probe);
|
|
1909
|
-
if (scope === null) return handlerAuthPatterns.some((p) => p.test(
|
|
2427
|
+
if (scope === null) return handlerAuthPatterns.some((p) => p.test(codeForAuth));
|
|
1910
2428
|
return handlerAuthPatterns.some((p) => p.test(scope));
|
|
1911
2429
|
};
|
|
1912
2430
|
const matches = [];
|
|
1913
|
-
for (const pattern of routePatterns) {
|
|
2431
|
+
for (const pattern of serverSide ? routePatterns : []) {
|
|
1914
2432
|
matches.push(
|
|
1915
2433
|
...findMatches(
|
|
1916
2434
|
content,
|
|
@@ -1921,11 +2439,11 @@ var missingAuthMiddleware = {
|
|
|
1921
2439
|
)
|
|
1922
2440
|
);
|
|
1923
2441
|
}
|
|
1924
|
-
if (matches.length === 0 && SUPABASE_EDGE_FN_RE.test(filePath) && isDenoEdgeEntry(codeOnly) && !isPublicByDesignEdgePath(filePath)) {
|
|
2442
|
+
if (matches.length === 0 && serverSide && SUPABASE_EDGE_FN_RE.test(filePath) && isDenoEdgeEntry(codeOnly) && !isPublicByDesignEdgePath(filePath)) {
|
|
1925
2443
|
const fnName = supabaseFunctionName(filePath);
|
|
1926
2444
|
const verifyJwt = fnName && project?.supabaseEdgeVerifyJwt ? project.supabaseEdgeVerifyJwt.get(fnName) : void 0;
|
|
1927
2445
|
if (verifyJwt !== true) {
|
|
1928
|
-
const withoutCors = stripCorsHeaderList(codeOnly);
|
|
2446
|
+
const withoutCors = maskProseStrings(maskOutboundAuthNoise(stripCorsHeaderList(codeOnly)));
|
|
1929
2447
|
const hasWeakHint = verifyJwt === false ? false : EDGE_WEAK_AUTH_HINTS.some((p) => p.test(withoutCors));
|
|
1930
2448
|
if (!hasWeakHint) {
|
|
1931
2449
|
matches.push(
|
|
@@ -1946,6 +2464,21 @@ var missingAuthMiddleware = {
|
|
|
1946
2464
|
}
|
|
1947
2465
|
const indexOfLine = (line) => lineStarts[Math.max(0, Math.min(line - 1, lineStarts.length - 1))];
|
|
1948
2466
|
const unauthenticated = matches.filter((m) => !handlerHasAuth(indexOfLine(m.line)));
|
|
2467
|
+
if (serverSide || tanstackCandidate) {
|
|
2468
|
+
for (const idx of unauthenticatedTanStackHandlers(maskedForScope, filePath)) {
|
|
2469
|
+
const line = lineNumberAt(content, idx);
|
|
2470
|
+
unauthenticated.push({
|
|
2471
|
+
rule: "VC003",
|
|
2472
|
+
title: missingAuthMiddleware.title,
|
|
2473
|
+
severity: "high",
|
|
2474
|
+
category: missingAuthMiddleware.category,
|
|
2475
|
+
file: filePath,
|
|
2476
|
+
line,
|
|
2477
|
+
snippet: getSnippet(content, line),
|
|
2478
|
+
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."
|
|
2479
|
+
});
|
|
2480
|
+
}
|
|
2481
|
+
}
|
|
1949
2482
|
return filterSilenced(unauthenticated, content, "VC003");
|
|
1950
2483
|
}
|
|
1951
2484
|
};
|
|
@@ -2050,6 +2583,105 @@ function namesPlaceholderRun(content) {
|
|
|
2050
2583
|
}
|
|
2051
2584
|
return false;
|
|
2052
2585
|
}
|
|
2586
|
+
function isLineTerminator(c) {
|
|
2587
|
+
return c === 10 || c === 13 || c === 8232 || c === 8233;
|
|
2588
|
+
}
|
|
2589
|
+
function quotedLiterals(content) {
|
|
2590
|
+
const literals = [];
|
|
2591
|
+
const failedUpTo = /* @__PURE__ */ new Map();
|
|
2592
|
+
for (let i = 0; i < content.length; i++) {
|
|
2593
|
+
const quote = content.charCodeAt(i);
|
|
2594
|
+
if (quote !== 39 && quote !== 34 && quote !== 96) continue;
|
|
2595
|
+
if (i < (failedUpTo.get(quote) ?? -1)) continue;
|
|
2596
|
+
let j = i + 1;
|
|
2597
|
+
let closed = false;
|
|
2598
|
+
while (j < content.length) {
|
|
2599
|
+
const c = content.charCodeAt(j);
|
|
2600
|
+
if (c === quote) {
|
|
2601
|
+
closed = true;
|
|
2602
|
+
break;
|
|
2603
|
+
}
|
|
2604
|
+
if (c === 92) {
|
|
2605
|
+
if (j + 1 >= content.length || isLineTerminator(content.charCodeAt(j + 1))) break;
|
|
2606
|
+
j += 2;
|
|
2607
|
+
continue;
|
|
2608
|
+
}
|
|
2609
|
+
if (c === 10 && quote !== 96) break;
|
|
2610
|
+
j++;
|
|
2611
|
+
}
|
|
2612
|
+
if (!closed) {
|
|
2613
|
+
failedUpTo.set(quote, j);
|
|
2614
|
+
continue;
|
|
2615
|
+
}
|
|
2616
|
+
literals.push(content.slice(i, j + 1));
|
|
2617
|
+
i = j;
|
|
2618
|
+
}
|
|
2619
|
+
return literals;
|
|
2620
|
+
}
|
|
2621
|
+
var SQL_VERB_RE = /\b(?:SELECT|INSERT|UPDATE|DELETE)\b/i;
|
|
2622
|
+
var SQL_CLAUSE_RE = /\b(?:FROM|INTO|SET|VALUES|WHERE)\b/gi;
|
|
2623
|
+
function isSqlStatement(lit) {
|
|
2624
|
+
const verb = SQL_VERB_RE.exec(lit);
|
|
2625
|
+
if (!verb) return false;
|
|
2626
|
+
SQL_CLAUSE_RE.lastIndex = verb.index + verb[0].length;
|
|
2627
|
+
return SQL_CLAUSE_RE.test(lit);
|
|
2628
|
+
}
|
|
2629
|
+
function* interpolatedSqlLiterals(content) {
|
|
2630
|
+
const opener = /["'`]\s*(?:SELECT|INSERT|UPDATE|DELETE)\b/gi;
|
|
2631
|
+
const literalBreak = /["'`\n]/g;
|
|
2632
|
+
const clauseRe = /\b(?:FROM|INTO|SET|VALUES|WHERE|JOIN|RETURNING)\b/i;
|
|
2633
|
+
let lineEnds = null;
|
|
2634
|
+
let lastOnLine = [];
|
|
2635
|
+
const parameterizedLater = (x) => {
|
|
2636
|
+
if (lineEnds === null) {
|
|
2637
|
+
const ends = [];
|
|
2638
|
+
for (let i = 0; i < content.length; i++) {
|
|
2639
|
+
if (isLineTerminator(content.charCodeAt(i))) ends.push(i);
|
|
2640
|
+
}
|
|
2641
|
+
ends.push(content.length);
|
|
2642
|
+
lastOnLine = new Array(ends.length).fill(-1);
|
|
2643
|
+
const word = /parameterized/gi;
|
|
2644
|
+
let line = 0;
|
|
2645
|
+
for (let w = word.exec(content); w !== null; w = word.exec(content)) {
|
|
2646
|
+
while (ends[line] < w.index) line++;
|
|
2647
|
+
lastOnLine[line] = w.index;
|
|
2648
|
+
}
|
|
2649
|
+
lineEnds = ends;
|
|
2650
|
+
}
|
|
2651
|
+
let lo = 0;
|
|
2652
|
+
let hi = lineEnds.length - 1;
|
|
2653
|
+
while (lo < hi) {
|
|
2654
|
+
const mid = lo + hi >> 1;
|
|
2655
|
+
if (lineEnds[mid] < x) lo = mid + 1;
|
|
2656
|
+
else hi = mid;
|
|
2657
|
+
}
|
|
2658
|
+
return lastOnLine[lo] >= x;
|
|
2659
|
+
};
|
|
2660
|
+
for (let m = opener.exec(content); m !== null; m = opener.exec(content)) {
|
|
2661
|
+
const start = m.index;
|
|
2662
|
+
const runStart = opener.lastIndex;
|
|
2663
|
+
literalBreak.lastIndex = runStart;
|
|
2664
|
+
const runEnd = literalBreak.exec(content)?.index ?? content.length;
|
|
2665
|
+
const run = content.slice(runStart, runEnd);
|
|
2666
|
+
const clause = clauseRe.exec(run);
|
|
2667
|
+
let matchEnd = -1;
|
|
2668
|
+
if (clause) {
|
|
2669
|
+
const clauseEnd = clause.index + clause[0].length;
|
|
2670
|
+
for (let d = run.lastIndexOf("${"); d >= clauseEnd; d = run.lastIndexOf("${", d - 1)) {
|
|
2671
|
+
if (!parameterizedLater(runStart + d + 2)) {
|
|
2672
|
+
matchEnd = runStart + d + 2;
|
|
2673
|
+
break;
|
|
2674
|
+
}
|
|
2675
|
+
}
|
|
2676
|
+
}
|
|
2677
|
+
if (matchEnd === -1) {
|
|
2678
|
+
opener.lastIndex = start + 1;
|
|
2679
|
+
continue;
|
|
2680
|
+
}
|
|
2681
|
+
yield { index: start };
|
|
2682
|
+
opener.lastIndex = matchEnd;
|
|
2683
|
+
}
|
|
2684
|
+
}
|
|
2053
2685
|
var sqlInjection = {
|
|
2054
2686
|
id: "VC006",
|
|
2055
2687
|
title: "Potential SQL Injection",
|
|
@@ -2072,35 +2704,22 @@ var sqlInjection = {
|
|
|
2072
2704
|
// allows the opposite quote type inside (common in SQL — "WHERE x = 'a'").
|
|
2073
2705
|
// The older `[^"']*` class bailed out at the first inner quote and
|
|
2074
2706
|
// missed every realistic SQL-containing concat.
|
|
2075
|
-
/(?:query|execute|raw|sql|queryRaw|queryRawUnsafe|executeRaw|executeRawUnsafe)\s*\(\s*(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')\s*\+/gi
|
|
2076
|
-
// Direct variable interpolation in a SQL string literal. Requires the
|
|
2077
|
-
// verb to START a quoted/backtick literal AND be followed — within the
|
|
2078
|
-
// same literal — by a SQL structural keyword (FROM/SET/WHERE/…), then a
|
|
2079
|
-
// `${` interpolation. The structural keyword is what distinguishes a
|
|
2080
|
-
// real query from ordinary prose: the previous pattern matched any
|
|
2081
|
-
// SELECT/UPDATE/… word anywhere on a line followed by `${`, so UI copy
|
|
2082
|
-
// like `UPDATE your profile settings ${name}` flagged as a CRITICAL SQL
|
|
2083
|
-
// injection. Real queries ("SELECT … FROM …", "UPDATE … SET …") always
|
|
2084
|
-
// carry a second structural keyword; sentences almost never do.
|
|
2085
|
-
/["'`]\s*(?:SELECT|INSERT|UPDATE|DELETE)\b[^"'`\n]*\b(?:FROM|INTO|SET|VALUES|WHERE|JOIN|RETURNING)\b[^"'`\n]*\$\{(?!.*parameterized)/gi
|
|
2707
|
+
/(?:query|execute|raw|sql|queryRaw|queryRawUnsafe|executeRaw|executeRawUnsafe)\s*\(\s*(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')\s*\+/gi
|
|
2086
2708
|
];
|
|
2087
2709
|
const matches = [];
|
|
2088
|
-
const sqlLiterals = (content
|
|
2089
|
-
(lit) => /\b(?:SELECT|INSERT|UPDATE|DELETE)\b[\s\S]*\b(?:FROM|INTO|SET|VALUES|WHERE)\b/i.test(lit)
|
|
2090
|
-
);
|
|
2710
|
+
const sqlLiterals = quotedLiterals(content).filter(isSqlStatement);
|
|
2091
2711
|
const usesParams = /\bprepare\b/i.test(content) || sqlLiterals.some((lit) => /\?\s*,|\?[^?,;]{1,20}\?|\$\d+|:[A-Za-z_]\w*|@[A-Za-z_]\w*|=\s*\?/.test(lit));
|
|
2092
|
-
const code = content
|
|
2712
|
+
const code = replaceBlockComments(content, () => " ").replace(/(^|[^:"'`\\])\/\/.*$/gm, "$1");
|
|
2093
2713
|
if (usesParams || namesPlaceholderRun(code)) return [];
|
|
2094
|
-
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
2101
|
-
);
|
|
2714
|
+
const fix = () => "Use parameterized queries or prepared statements instead of string interpolation. Example: db.query('SELECT * FROM users WHERE id = ?', [userId])";
|
|
2715
|
+
const raws = [
|
|
2716
|
+
...patterns.map((pattern) => findMatches(content, pattern, sqlInjection, filePath, fix)),
|
|
2717
|
+
findMatchesAt(content, interpolatedSqlLiterals(content), sqlInjection, filePath, fix)
|
|
2718
|
+
];
|
|
2719
|
+
let lines;
|
|
2720
|
+
for (const raw of raws) {
|
|
2102
2721
|
for (const m of raw) {
|
|
2103
|
-
const lineText = content.split("\n")[m.line - 1] || "";
|
|
2722
|
+
const lineText = (lines ??= content.split("\n"))[m.line - 1] || "";
|
|
2104
2723
|
if (/\bPrisma\.sql\s*`/.test(lineText)) continue;
|
|
2105
2724
|
if (/\bsql\s*`/.test(lineText) && !/\bsql\.raw\s*\(/.test(lineText)) continue;
|
|
2106
2725
|
if (/\$queryRaw\s*\(\s*Prisma\.sql|\$executeRaw\s*\(\s*Prisma\.sql/.test(lineText)) continue;
|
|
@@ -2316,35 +2935,61 @@ var clientSideAuth = {
|
|
|
2316
2935
|
return matches;
|
|
2317
2936
|
}
|
|
2318
2937
|
};
|
|
2938
|
+
var PUBLIC_ENV_FIX = {
|
|
2939
|
+
NEXT_PUBLIC_: "Remove the NEXT_PUBLIC_ prefix. Only use NEXT_PUBLIC_ for values safe to expose in the browser.",
|
|
2940
|
+
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.",
|
|
2941
|
+
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.",
|
|
2942
|
+
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.",
|
|
2943
|
+
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.",
|
|
2944
|
+
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.",
|
|
2945
|
+
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."
|
|
2946
|
+
};
|
|
2947
|
+
var NEXT_PUBLIC_ASSIGN_RE = /(?:^|[^A-Za-z0-9_])(NEXT_PUBLIC_[A-Za-z0-9_]{1,128})\s*=\s*([^\r\n]*)/i;
|
|
2319
2948
|
var nextPublicSecret = {
|
|
2320
2949
|
id: "VC011",
|
|
2321
|
-
title: "Secret in
|
|
2950
|
+
title: "Secret in Browser-Exposed Environment Variable",
|
|
2322
2951
|
severity: "critical",
|
|
2323
2952
|
category: "Secrets",
|
|
2324
|
-
description: "NEXT_PUBLIC_
|
|
2953
|
+
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.",
|
|
2325
2954
|
check(content, filePath) {
|
|
2326
|
-
|
|
2327
|
-
const
|
|
2328
|
-
|
|
2329
|
-
|
|
2330
|
-
];
|
|
2955
|
+
const legacyScope = /\.env/.test(filePath) || /next\.config/.test(filePath);
|
|
2956
|
+
const dotenvScope = isDotenvPath(filePath);
|
|
2957
|
+
if (!legacyScope && !dotenvScope) return [];
|
|
2958
|
+
if (!/(?:NEXT_PUBLIC_|NUXT_PUBLIC_|EXPO_PUBLIC_|REACT_APP_|GATSBY_|VITE_|PUBLIC_)/i.test(content)) return [];
|
|
2331
2959
|
const matches = [];
|
|
2332
|
-
|
|
2333
|
-
|
|
2334
|
-
|
|
2335
|
-
|
|
2336
|
-
|
|
2337
|
-
|
|
2338
|
-
|
|
2339
|
-
);
|
|
2340
|
-
|
|
2341
|
-
|
|
2342
|
-
|
|
2343
|
-
|
|
2344
|
-
|
|
2345
|
-
if (
|
|
2346
|
-
|
|
2960
|
+
const lines = content.split("\n");
|
|
2961
|
+
for (let i = 0; i < lines.length; i++) {
|
|
2962
|
+
const line = lines[i];
|
|
2963
|
+
const trimmed = line.trimStart();
|
|
2964
|
+
if (/^(?:#|\/\/|\*|\/\*|<!--)/.test(trimmed)) continue;
|
|
2965
|
+
let name;
|
|
2966
|
+
let value = "";
|
|
2967
|
+
const a = dotenvScope ? DOTENV_ASSIGN_RE.exec(line) : null;
|
|
2968
|
+
if (a && PUBLIC_ENV_PREFIX_RE.test(a[1])) {
|
|
2969
|
+
name = a[1];
|
|
2970
|
+
value = a[2];
|
|
2971
|
+
} else if (legacyScope) {
|
|
2972
|
+
const n = NEXT_PUBLIC_ASSIGN_RE.exec(line);
|
|
2973
|
+
if (n) {
|
|
2974
|
+
name = n[1];
|
|
2975
|
+
value = n[2];
|
|
2976
|
+
}
|
|
2347
2977
|
}
|
|
2978
|
+
if (!name) continue;
|
|
2979
|
+
const bare = dotenvValue(value);
|
|
2980
|
+
if (bare === "" || /^pk_(?:test|live)_$/.test(bare)) continue;
|
|
2981
|
+
const verdict = classifyPublicEnvVar(name, bare);
|
|
2982
|
+
if (!verdict || !verdict.secret) continue;
|
|
2983
|
+
matches.push({
|
|
2984
|
+
rule: "VC011",
|
|
2985
|
+
title: nextPublicSecret.title,
|
|
2986
|
+
severity: "critical",
|
|
2987
|
+
category: "Secrets",
|
|
2988
|
+
file: filePath,
|
|
2989
|
+
line: i + 1,
|
|
2990
|
+
snippet: getSnippet(content, i + 1),
|
|
2991
|
+
fix: PUBLIC_ENV_FIX[verdict.prefix] ?? PUBLIC_ENV_FIX.NEXT_PUBLIC_
|
|
2992
|
+
});
|
|
2348
2993
|
}
|
|
2349
2994
|
return matches;
|
|
2350
2995
|
}
|
|
@@ -2884,7 +3529,7 @@ var dangerousInnerHTML = {
|
|
|
2884
3529
|
if (!filePath.match(/\.(jsx|tsx)$/)) return [];
|
|
2885
3530
|
if (isTestFile(filePath)) return [];
|
|
2886
3531
|
if (!/dangerouslySetInnerHTML/i.test(content)) return [];
|
|
2887
|
-
const codeOnly = content
|
|
3532
|
+
const codeOnly = replaceBlockComments(content, () => "").replace(/(^|[^:])\/\/.*$/gm, "$1").replace(/\{\s*\/\*[\s\S]*?\*\/\s*\}/g, "");
|
|
2888
3533
|
const hasSanitize = /\b(?:DOMPurify|sanitizeHtml|sanitize-html|isomorphic-dompurify)\b|\b(?:sanitize|purify|xss)\s*\(/i.test(codeOnly);
|
|
2889
3534
|
if (hasSanitize) return [];
|
|
2890
3535
|
const findings = [];
|
|
@@ -3298,8 +3943,29 @@ var complianceMap = {
|
|
|
3298
3943
|
// VC213–VC214: account state held in browser storage
|
|
3299
3944
|
VC213: { owasp: "A01:2021", cwe: "CWE-602" },
|
|
3300
3945
|
// entitlement from web storage (client-side enforcement)
|
|
3301
|
-
VC214: { owasp: "A04:2021", cwe: "CWE-1188" }
|
|
3946
|
+
VC214: { owasp: "A04:2021", cwe: "CWE-1188" },
|
|
3302
3947
|
// per-account state from web storage (insecure default state)
|
|
3948
|
+
// VC215: Supabase migration lint — RLS off, always-true write policy, user_metadata in a policy
|
|
3949
|
+
VC215: { owasp: "A01:2021", cwe: "CWE-732" },
|
|
3950
|
+
// incorrect permission assignment for a critical resource
|
|
3951
|
+
VC216: { owasp: "A01:2021", cwe: "CWE-732" },
|
|
3952
|
+
// Firebase rules: open, any-signed-in-user, or test mode
|
|
3953
|
+
// VC217: AI or secret key shipped to the browser
|
|
3954
|
+
VC217: { owasp: "A07:2021", cwe: "CWE-798" },
|
|
3955
|
+
// key inlined into the client bundle (as VC066 / VC149)
|
|
3956
|
+
VC220: { owasp: "A01:2021", cwe: "CWE-862" },
|
|
3957
|
+
// unauthenticated AI/LLM proxy (denial of wallet); same class as VC003
|
|
3958
|
+
// VC218–VC219: caller identity never checked, or checked against data the caller controls
|
|
3959
|
+
VC218: { owasp: "A01:2021", cwe: "CWE-862" },
|
|
3960
|
+
// Base44 asServiceRole with no caller check (missing authorization, as VC003)
|
|
3961
|
+
VC219: { owasp: "A01:2021", cwe: "CWE-269" },
|
|
3962
|
+
// role/plan from user_metadata / unsafeMetadata (improper privilege management)
|
|
3963
|
+
VC221: { owasp: "A07:2021", cwe: "CWE-347" },
|
|
3964
|
+
// server trusts unverified session / decoded JWT
|
|
3965
|
+
VC222: { owasp: "A05:2021", cwe: "CWE-942" },
|
|
3966
|
+
// Python CORS wildcard with credentials (origin echoed)
|
|
3967
|
+
VC223: { owasp: "A01:2021", cwe: "CWE-22" }
|
|
3968
|
+
// prefix-only path containment check (startsWith without separator)
|
|
3303
3969
|
};
|
|
3304
3970
|
var consoleLogProduction = {
|
|
3305
3971
|
id: "VC097",
|
|
@@ -3484,15 +4150,15 @@ function runCustomRules(content, filePath, disabledRules = [], tier = "free", ex
|
|
|
3484
4150
|
|
|
3485
4151
|
// src/rule-counts.ts
|
|
3486
4152
|
var FREE_RULE_COUNT = 30;
|
|
3487
|
-
var PRO_RULE_COUNT =
|
|
3488
|
-
var TOTAL_RULE_COUNT =
|
|
4153
|
+
var PRO_RULE_COUNT = 193;
|
|
4154
|
+
var TOTAL_RULE_COUNT = 223;
|
|
3489
4155
|
|
|
3490
4156
|
// src/ai-fp-filter.ts
|
|
3491
4157
|
import Anthropic from "@anthropic-ai/sdk";
|
|
3492
4158
|
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.
|
|
3493
4159
|
|
|
3494
4160
|
Common false positive patterns you should catch:
|
|
3495
|
-
- Auth check exists inside the function body (requireUser, requireUserForApi,
|
|
4161
|
+
- 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
|
|
3496
4162
|
- The flagged pattern is in example/documentation/tutorial code, not production code
|
|
3497
4163
|
- The variable is developer-controlled (constants, config values, static strings), not user input
|
|
3498
4164
|
- The flagged function is a database method (conn.exec, db.exec, prisma.$executeRaw) not a shell command (child_process.exec)
|
|
@@ -3780,10 +4446,18 @@ var SAFE_PATTERNS = [
|
|
|
3780
4446
|
// double-flag these. They are designed to ship to the browser.
|
|
3781
4447
|
/^pk_(?:live|test|[a-z0-9]+)_/,
|
|
3782
4448
|
// Stripe / Clerk publishable
|
|
4449
|
+
// A string that IS an env-var name — `required: ["VITE_SUPABASE_URL", …]`.
|
|
4450
|
+
// This tests the VALUE, never the variable it is assigned to: a secret held
|
|
4451
|
+
// in a public-prefixed variable is decided by classifyPublicEnvVar below.
|
|
3783
4452
|
/^NEXT_PUBLIC_|^VITE_|^REACT_APP_/,
|
|
3784
|
-
// Build-time public env vars
|
|
3785
4453
|
/^pub_/,
|
|
3786
4454
|
// Segment etc.
|
|
4455
|
+
// dotenvx ciphertext: `STRIPE_SECRET_KEY="encrypted:BE9Y…"`. dotenvx
|
|
4456
|
+
// encrypts each value to the file's public key (ECIES); the private key
|
|
4457
|
+
// stays in the git-ignored .env.keys, and committing the encrypted file is
|
|
4458
|
+
// the documented workflow (Supabase's own dotenvx example does). The value
|
|
4459
|
+
// is not usable without that key, so it is not a leaked secret.
|
|
4460
|
+
/^encrypted:[A-Za-z0-9+/=]{20,}$/,
|
|
3787
4461
|
/^ey[A-Za-z0-9_-]+\.ey[A-Za-z0-9_-]+\./,
|
|
3788
4462
|
// JWT header.payload prefix — don't flag solely on entropy
|
|
3789
4463
|
// Content-Security-Policy hashes / nonces in HTML/JSON
|
|
@@ -3810,6 +4484,8 @@ var VERIFICATION_BLOCK_RE = /\bverification\s*:\s*\{/;
|
|
|
3810
4484
|
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;
|
|
3811
4485
|
var VERIFICATION_META_RE = /<meta[^>]+name\s*=\s*["'][^"']*(?:site-verification|domain-verification|msvalidate|domain_verify)[^"']*["']/i;
|
|
3812
4486
|
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;
|
|
4487
|
+
var DOTENV_EXAMPLE_RE = /\.(?:example|sample|template|dist|defaults?)$/i;
|
|
4488
|
+
var MAX_DOTENV_VALUE = 256;
|
|
3813
4489
|
function getSnippet2(content, line) {
|
|
3814
4490
|
const lines = content.split("\n");
|
|
3815
4491
|
const start = Math.max(0, line - 2);
|
|
@@ -3832,6 +4508,7 @@ function scanEntropy(files) {
|
|
|
3832
4508
|
if (/pro-rules-bundle|\.bundle\.|\.chunk\./i.test(filePath)) continue;
|
|
3833
4509
|
if (/(?:\.test\.|\.spec\.|__tests__|__mocks__|fixtures?\/)/i.test(filePath)) continue;
|
|
3834
4510
|
const vendored = isVendoredPath(filePath);
|
|
4511
|
+
const dotenv = isDotenvPath(filePath) && !DOTENV_EXAMPLE_RE.test(filePath);
|
|
3835
4512
|
const lines = content.split("\n");
|
|
3836
4513
|
let verificationDepth = -1;
|
|
3837
4514
|
let braceDepth = 0;
|
|
@@ -3850,14 +4527,27 @@ function scanEntropy(files) {
|
|
|
3850
4527
|
const inVerificationBlock = verificationDepth !== -1;
|
|
3851
4528
|
const trimmed = line.trimStart();
|
|
3852
4529
|
if (trimmed.startsWith("//") || trimmed.startsWith("#") || trimmed.startsWith("*") || trimmed.startsWith("/*")) continue;
|
|
3853
|
-
const
|
|
3854
|
-
|
|
3855
|
-
|
|
3856
|
-
|
|
4530
|
+
const candidates = [];
|
|
4531
|
+
const assign = dotenv ? DOTENV_ASSIGN_RE.exec(line) : null;
|
|
4532
|
+
const assignValue = assign ? dotenvValue(assign[2]) : "";
|
|
4533
|
+
const structured = assign !== null && (assignValue.length > MAX_DOTENV_VALUE || /^[{[]/.test(assignValue));
|
|
4534
|
+
if (assign && !structured) {
|
|
4535
|
+
if (assignValue.length >= 20) {
|
|
4536
|
+
candidates.push({ value: assignValue, beforeAssign: assign[1], dotenvName: assign[1] });
|
|
4537
|
+
}
|
|
4538
|
+
} else {
|
|
4539
|
+
const stringPattern = /(?:[:=]\s*)(["'`])([^"'`\n]{20,120})\1/g;
|
|
4540
|
+
let match;
|
|
4541
|
+
while ((match = stringPattern.exec(line)) !== null) {
|
|
4542
|
+
let beforeAssign = line.substring(0, match.index);
|
|
4543
|
+
if (structured) beforeAssign = beforeAssign.slice(Math.max(beforeAssign.lastIndexOf(","), beforeAssign.lastIndexOf("{")) + 1);
|
|
4544
|
+
candidates.push({ value: match[2], beforeAssign });
|
|
4545
|
+
}
|
|
4546
|
+
}
|
|
4547
|
+
for (const { value, beforeAssign, dotenvName } of candidates) {
|
|
3857
4548
|
if (value.includes("${")) continue;
|
|
3858
4549
|
if (SAFE_PATTERNS.some((p) => p.test(value))) continue;
|
|
3859
4550
|
if (HASH_PREFIX_RE.test(value)) continue;
|
|
3860
|
-
const beforeAssign = line.substring(0, match.index);
|
|
3861
4551
|
if (SAFE_VAR_NAMES.test(beforeAssign)) continue;
|
|
3862
4552
|
if (/^https?:\/\/[^:@]*$/.test(value)) continue;
|
|
3863
4553
|
if ((value.match(/\s/g) || []).length > 2) continue;
|
|
@@ -3869,11 +4559,15 @@ function scanEntropy(files) {
|
|
|
3869
4559
|
if (value.length < 20) continue;
|
|
3870
4560
|
const entropy = shannonEntropy(value);
|
|
3871
4561
|
if (entropy < threshold) continue;
|
|
3872
|
-
const varName = beforeAssign.match(/["']([^"']+)["']\s*$/)?.[1] || beforeAssign.match(/([\w$-]+)\s*$/)?.[1] || "";
|
|
4562
|
+
const varName = dotenvName || beforeAssign.match(/["']([^"']+)["']\s*$/)?.[1] || beforeAssign.match(/([\w$-]+)\s*$/)?.[1] || "";
|
|
3873
4563
|
if (inVerificationBlock && VERIFICATION_KEY_NAMES.test(varName)) continue;
|
|
3874
4564
|
if (VERIFICATION_META_RE.test(line)) continue;
|
|
3875
4565
|
if (HASH_LIKE_VAR_NAMES.test(varName) && (isHex || isBase64)) continue;
|
|
3876
|
-
|
|
4566
|
+
if (/^DOTENV_PUBLIC_KEY(?:_\w{1,60})?$/.test(varName) && /^0[23][0-9a-fA-F]{64}$/.test(value)) continue;
|
|
4567
|
+
const publicEnv = classifyPublicEnvVar(varName, value);
|
|
4568
|
+
if (publicEnv && publicEnv.publicByDesign) continue;
|
|
4569
|
+
if (dotenvName && /(?:^|_)IDS?$/i.test(dotenvName) && !SECRET_VAR_NAMES.test(dotenvName)) continue;
|
|
4570
|
+
const isLikelySecret = SECRET_VAR_NAMES.test(varName) || publicEnv?.secret === true;
|
|
3877
4571
|
if (entropy < 4.5 && !isLikelySecret) continue;
|
|
3878
4572
|
if (isLineSilenced(lines, i, "ENTROPY")) continue;
|
|
3879
4573
|
const masked = value.substring(0, 6) + "..." + value.substring(value.length - 4);
|
|
@@ -3887,7 +4581,10 @@ function scanEntropy(files) {
|
|
|
3887
4581
|
file: filePath,
|
|
3888
4582
|
line: i + 1,
|
|
3889
4583
|
snippet: getSnippet2(content, i + 1),
|
|
3890
|
-
|
|
4584
|
+
// The generic advice ("move it to an environment variable") is
|
|
4585
|
+
// wrong for a value that is already in one, so dotenv findings get
|
|
4586
|
+
// advice about the file, and public-prefixed ones about the prefix.
|
|
4587
|
+
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.",
|
|
3891
4588
|
category: "Secrets",
|
|
3892
4589
|
source: "custom",
|
|
3893
4590
|
owasp: "A02:2021",
|
|
@@ -7584,6 +8281,7 @@ function scanQuality(input, rules = qualityRules) {
|
|
|
7584
8281
|
}
|
|
7585
8282
|
export {
|
|
7586
8283
|
CHECKABLE_CLAIMS,
|
|
8284
|
+
DOTENV_ASSIGN_RE,
|
|
7587
8285
|
FREE_RULE_COUNT,
|
|
7588
8286
|
INTENT_EXPECTATIONS,
|
|
7589
8287
|
MODEL_ANALYSIS,
|
|
@@ -7593,6 +8291,7 @@ export {
|
|
|
7593
8291
|
MODEL_TRIAGE,
|
|
7594
8292
|
NON_APP_PATH_PATTERNS,
|
|
7595
8293
|
PRO_RULE_COUNT,
|
|
8294
|
+
PUBLIC_ENV_PREFIX_RE,
|
|
7596
8295
|
QUALITY_EXAMPLES,
|
|
7597
8296
|
RULE_IMPACTS,
|
|
7598
8297
|
TEST_FILE_PATTERN,
|
|
@@ -7607,6 +8306,7 @@ export {
|
|
|
7607
8306
|
callSpreads,
|
|
7608
8307
|
checkIntent,
|
|
7609
8308
|
classifyExposure,
|
|
8309
|
+
classifyPublicEnvVar,
|
|
7610
8310
|
classifyStatement,
|
|
7611
8311
|
clientSideAuth,
|
|
7612
8312
|
complianceMap,
|
|
@@ -7618,6 +8318,7 @@ export {
|
|
|
7618
8318
|
detectFramework,
|
|
7619
8319
|
detectPlatform,
|
|
7620
8320
|
disabledTLSVerification,
|
|
8321
|
+
dotenvValue,
|
|
7621
8322
|
emptyCatchBlock,
|
|
7622
8323
|
enclosingHandler,
|
|
7623
8324
|
envNotGitignored,
|
|
@@ -7631,6 +8332,7 @@ export {
|
|
|
7631
8332
|
filterFalsePositives,
|
|
7632
8333
|
filterSilenced,
|
|
7633
8334
|
findMatches,
|
|
8335
|
+
findMatchesAt,
|
|
7634
8336
|
findSourceMapRefs,
|
|
7635
8337
|
freeRules,
|
|
7636
8338
|
getObjectProperty,
|
|
@@ -7643,6 +8345,7 @@ export {
|
|
|
7643
8345
|
isCalleeNamed,
|
|
7644
8346
|
isClientTarget,
|
|
7645
8347
|
isCommentLine,
|
|
8348
|
+
isDotenvPath,
|
|
7646
8349
|
isInlineSilenced,
|
|
7647
8350
|
isInsideFixMessage,
|
|
7648
8351
|
isLineSilenced,
|
|
@@ -7656,6 +8359,7 @@ export {
|
|
|
7656
8359
|
lineNumberAt,
|
|
7657
8360
|
lineTextAt,
|
|
7658
8361
|
maskComments,
|
|
8362
|
+
maskOutboundAuthNoise,
|
|
7659
8363
|
missingAuthMiddleware,
|
|
7660
8364
|
missingCSP,
|
|
7661
8365
|
missingErrorBoundary,
|
|
@@ -7668,6 +8372,7 @@ export {
|
|
|
7668
8372
|
parseScanTarget,
|
|
7669
8373
|
parseSupabaseConfig,
|
|
7670
8374
|
qualityRules,
|
|
8375
|
+
replaceBlockComments,
|
|
7671
8376
|
routeForFile,
|
|
7672
8377
|
runCustomRules,
|
|
7673
8378
|
scanEntropy,
|