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/README.md +3 -3
- package/dist/index.cjs +711 -69
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +125 -7
- package/dist/index.d.ts +125 -7
- package/dist/index.js +704 -69
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -31,6 +31,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
31
31
|
var index_exports = {};
|
|
32
32
|
__export(index_exports, {
|
|
33
33
|
CHECKABLE_CLAIMS: () => CHECKABLE_CLAIMS,
|
|
34
|
+
DOTENV_ASSIGN_RE: () => DOTENV_ASSIGN_RE,
|
|
34
35
|
FREE_RULE_COUNT: () => FREE_RULE_COUNT,
|
|
35
36
|
INTENT_EXPECTATIONS: () => INTENT_EXPECTATIONS,
|
|
36
37
|
MODEL_ANALYSIS: () => MODEL_ANALYSIS,
|
|
@@ -40,6 +41,7 @@ __export(index_exports, {
|
|
|
40
41
|
MODEL_TRIAGE: () => MODEL_TRIAGE,
|
|
41
42
|
NON_APP_PATH_PATTERNS: () => NON_APP_PATH_PATTERNS,
|
|
42
43
|
PRO_RULE_COUNT: () => PRO_RULE_COUNT,
|
|
44
|
+
PUBLIC_ENV_PREFIX_RE: () => PUBLIC_ENV_PREFIX_RE,
|
|
43
45
|
QUALITY_EXAMPLES: () => QUALITY_EXAMPLES,
|
|
44
46
|
RULE_IMPACTS: () => RULE_IMPACTS,
|
|
45
47
|
TEST_FILE_PATTERN: () => TEST_FILE_PATTERN,
|
|
@@ -54,6 +56,7 @@ __export(index_exports, {
|
|
|
54
56
|
callSpreads: () => callSpreads,
|
|
55
57
|
checkIntent: () => checkIntent,
|
|
56
58
|
classifyExposure: () => classifyExposure,
|
|
59
|
+
classifyPublicEnvVar: () => classifyPublicEnvVar,
|
|
57
60
|
classifyStatement: () => classifyStatement,
|
|
58
61
|
clientSideAuth: () => clientSideAuth,
|
|
59
62
|
complianceMap: () => complianceMap,
|
|
@@ -65,6 +68,7 @@ __export(index_exports, {
|
|
|
65
68
|
detectFramework: () => detectFramework,
|
|
66
69
|
detectPlatform: () => detectPlatform,
|
|
67
70
|
disabledTLSVerification: () => disabledTLSVerification,
|
|
71
|
+
dotenvValue: () => dotenvValue,
|
|
68
72
|
emptyCatchBlock: () => emptyCatchBlock,
|
|
69
73
|
enclosingHandler: () => enclosingHandler,
|
|
70
74
|
envNotGitignored: () => envNotGitignored,
|
|
@@ -90,6 +94,7 @@ __export(index_exports, {
|
|
|
90
94
|
isCalleeNamed: () => isCalleeNamed,
|
|
91
95
|
isClientTarget: () => isClientTarget,
|
|
92
96
|
isCommentLine: () => isCommentLine,
|
|
97
|
+
isDotenvPath: () => isDotenvPath,
|
|
93
98
|
isInlineSilenced: () => isInlineSilenced,
|
|
94
99
|
isInsideFixMessage: () => isInsideFixMessage,
|
|
95
100
|
isLineSilenced: () => isLineSilenced,
|
|
@@ -103,6 +108,7 @@ __export(index_exports, {
|
|
|
103
108
|
lineNumberAt: () => lineNumberAt,
|
|
104
109
|
lineTextAt: () => lineTextAt,
|
|
105
110
|
maskComments: () => maskComments,
|
|
111
|
+
maskOutboundAuthNoise: () => maskOutboundAuthNoise,
|
|
106
112
|
missingAuthMiddleware: () => missingAuthMiddleware,
|
|
107
113
|
missingCSP: () => missingCSP,
|
|
108
114
|
missingErrorBoundary: () => missingErrorBoundary,
|
|
@@ -115,6 +121,7 @@ __export(index_exports, {
|
|
|
115
121
|
parseScanTarget: () => parseScanTarget,
|
|
116
122
|
parseSupabaseConfig: () => parseSupabaseConfig,
|
|
117
123
|
qualityRules: () => qualityRules,
|
|
124
|
+
replaceBlockComments: () => replaceBlockComments,
|
|
118
125
|
routeForFile: () => routeForFile,
|
|
119
126
|
runCustomRules: () => runCustomRules,
|
|
120
127
|
scanEntropy: () => scanEntropy,
|
|
@@ -190,9 +197,9 @@ function isInlineSilenced(content, matchIndex, ruleId) {
|
|
|
190
197
|
}
|
|
191
198
|
function isLineSilenced(lines, lineIdx, ruleId) {
|
|
192
199
|
const matchLine = lines[lineIdx] ?? "";
|
|
193
|
-
const marker = new RegExp(`(
|
|
200
|
+
const marker = new RegExp(`(?://|/\\*|#|--)\\s*(?:${ruleId}|scanner)-OK\\b`, "i");
|
|
194
201
|
if (marker.test(matchLine)) return true;
|
|
195
|
-
const COMMENT_LINE = /^\s*[{(]?\s*(
|
|
202
|
+
const COMMENT_LINE = /^\s*[{(]?\s*(?:\/\/|#|\/\*|\*|--)/;
|
|
196
203
|
const MAX_BLOCK_LINES = 20;
|
|
197
204
|
for (let i = lineIdx - 1, seen = 0; i >= 0 && seen < MAX_BLOCK_LINES; i--, seen++) {
|
|
198
205
|
const line = lines[i] ?? "";
|
|
@@ -221,7 +228,7 @@ var RULE_IMPACTS = {
|
|
|
221
228
|
VC008: "Without rate limiting, an attacker can flood your API with requests causing denial of service, brute-force attacks, or excessive cloud billing.",
|
|
222
229
|
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.",
|
|
223
230
|
VC010: "Hiding UI elements without server-side checks means an attacker can call your API directly and bypass the restriction entirely.",
|
|
224
|
-
VC011: "
|
|
231
|
+
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.",
|
|
225
232
|
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.",
|
|
226
233
|
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.",
|
|
227
234
|
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.",
|
|
@@ -424,7 +431,16 @@ var RULE_IMPACTS = {
|
|
|
424
431
|
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.",
|
|
425
432
|
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.",
|
|
426
433
|
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.",
|
|
427
|
-
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."
|
|
434
|
+
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.",
|
|
435
|
+
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.",
|
|
436
|
+
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.",
|
|
437
|
+
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.",
|
|
438
|
+
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.",
|
|
439
|
+
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.",
|
|
440
|
+
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.",
|
|
441
|
+
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.",
|
|
442
|
+
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.",
|
|
443
|
+
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."
|
|
428
444
|
};
|
|
429
445
|
|
|
430
446
|
// src/exposure.ts
|
|
@@ -1003,6 +1019,77 @@ function checkIntent(files, findings) {
|
|
|
1003
1019
|
return { statements, mismatches, sources, unchallenged, uncheckable };
|
|
1004
1020
|
}
|
|
1005
1021
|
|
|
1022
|
+
// src/public-env.ts
|
|
1023
|
+
var PUBLIC_ENV_PREFIX_RE = /^(?:NEXT_PUBLIC_|NUXT_PUBLIC_|EXPO_PUBLIC_|REACT_APP_|GATSBY_|VITE_|PUBLIC_)/i;
|
|
1024
|
+
var STRONG_SECRET_ENV_WORD_RE = /SECRET|PASSWORD|PASSWD|SERVICE_?ROLE|SUPABASE_SERVICE/;
|
|
1025
|
+
var QUALIFIED_SECRET_ENV_WORD_RE = /PRIVATE|ADMIN|SERVER|SERVICE_?ACCOUNT|PERSONAL|MANAGEMENT|MASTER/;
|
|
1026
|
+
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";
|
|
1027
|
+
var KEY_SEGMENT_RE = new RegExp(
|
|
1028
|
+
`(?:^|_)(?:(?: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})?)?$`
|
|
1029
|
+
);
|
|
1030
|
+
var KEYISH_WORD_RE = /SECRET|PASSWORD|PASSWD|CREDENTIALS?$|(?:^|_)PRIVATE$/;
|
|
1031
|
+
var NON_SECRET_WORD_VALUE_RE = /^(?:true|false|yes|no|on|off|null|undefined)$/i;
|
|
1032
|
+
var NUMBER_VALUE_RE = /^-?\d+(?:\.\d+)?$/;
|
|
1033
|
+
var SECRET_TAIL_RE = /(?:SECRET|PASSWORD|PASSWD|PASSCODE|PIN)(?:_KEY)?$/;
|
|
1034
|
+
var NUMERIC_SECRET_VALUE_RE = /^\d{4,}$/;
|
|
1035
|
+
var PLAIN_URL_VALUE_RE = /^https?:\/\/[^\s@]+$/i;
|
|
1036
|
+
function urlCarriesToken(url) {
|
|
1037
|
+
const rest = url.replace(/^https?:\/\/[^/?#]*/i, "");
|
|
1038
|
+
for (const seg of rest.split(/[/?#&=.:;,]/)) {
|
|
1039
|
+
if (seg.length < 20 || !/^[A-Za-z0-9_-]+$/.test(seg)) continue;
|
|
1040
|
+
if (!/\d/.test(seg) || !/[A-Za-z]/.test(seg)) continue;
|
|
1041
|
+
if (seg.split(/[-_]/).some((run) => run.length >= 16)) return true;
|
|
1042
|
+
}
|
|
1043
|
+
return false;
|
|
1044
|
+
}
|
|
1045
|
+
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})?$/;
|
|
1046
|
+
var PUBLIC_VALUE_PREFIX_RE = /^(?:pk_(?:test|live)_|sb_publishable_|phc_|pk\.ey|(?:appl|goog|amzn|strp)_)/;
|
|
1047
|
+
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}-)/;
|
|
1048
|
+
function isAnonJwt(value) {
|
|
1049
|
+
const m = /^eyJ[A-Za-z0-9_-]{1,200}\.(eyJ[A-Za-z0-9_-]{1,2000})\./.exec(value);
|
|
1050
|
+
if (!m) return false;
|
|
1051
|
+
try {
|
|
1052
|
+
const b64 = m[1].replace(/-/g, "+").replace(/_/g, "/");
|
|
1053
|
+
const json = typeof atob === "function" ? atob(b64 + "=".repeat((4 - b64.length % 4) % 4)) : "";
|
|
1054
|
+
return /"role"\s*:\s*"anon"/.test(json);
|
|
1055
|
+
} catch {
|
|
1056
|
+
return false;
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
function classifyPublicEnvVar(name, value = "") {
|
|
1060
|
+
const m = PUBLIC_ENV_PREFIX_RE.exec(name);
|
|
1061
|
+
if (!m) return null;
|
|
1062
|
+
const prefix = m[0].toUpperCase();
|
|
1063
|
+
const upper = name.toUpperCase();
|
|
1064
|
+
const rest = upper.slice(prefix.length);
|
|
1065
|
+
const v = value.trim().replace(/^["'`]/, "");
|
|
1066
|
+
const notSecret = { prefix, secret: false, publicByDesign: true };
|
|
1067
|
+
if (PUBLIC_VALUE_PREFIX_RE.test(v) || NON_SECRET_WORD_VALUE_RE.test(v) || isAnonJwt(v)) return notSecret;
|
|
1068
|
+
if (NUMBER_VALUE_RE.test(v) && !(SECRET_TAIL_RE.test(rest) && NUMERIC_SECRET_VALUE_RE.test(v))) return notSecret;
|
|
1069
|
+
if (PLAIN_URL_VALUE_RE.test(v) && !urlCarriesToken(v)) return notSecret;
|
|
1070
|
+
if (SECRET_VALUE_PREFIX_RE.test(v)) return { prefix, secret: true, publicByDesign: false };
|
|
1071
|
+
const keyish = KEY_SEGMENT_RE.test(rest) || KEYISH_WORD_RE.test(rest);
|
|
1072
|
+
if (STRONG_SECRET_ENV_WORD_RE.test(rest)) return { prefix, secret: true, publicByDesign: false };
|
|
1073
|
+
if (QUALIFIED_SECRET_ENV_WORD_RE.test(rest) && keyish) return { prefix, secret: true, publicByDesign: false };
|
|
1074
|
+
if (PUBLIC_BY_DESIGN_ENV_RE.test(upper)) return notSecret;
|
|
1075
|
+
return { prefix, secret: keyish, publicByDesign: false };
|
|
1076
|
+
}
|
|
1077
|
+
var DOTENV_FILE_RE = /(?:^|\/)(?:\.env(?:\.[\w.-]+)?|[\w.-]+\.env)$/;
|
|
1078
|
+
function isDotenvPath(filePath) {
|
|
1079
|
+
return DOTENV_FILE_RE.test(filePath);
|
|
1080
|
+
}
|
|
1081
|
+
var DOTENV_ASSIGN_RE = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]{0,127})\s*=\s*([^\r\n]*)/;
|
|
1082
|
+
function dotenvValue(raw) {
|
|
1083
|
+
const v = raw.trim();
|
|
1084
|
+
const q = v[0];
|
|
1085
|
+
if (q === '"' || q === "'" || q === "`") {
|
|
1086
|
+
const end = v.indexOf(q, 1);
|
|
1087
|
+
return end === -1 ? v.slice(1) : v.slice(1, end);
|
|
1088
|
+
}
|
|
1089
|
+
const hash = v.search(/\s#/);
|
|
1090
|
+
return (hash === -1 ? v : v.slice(0, hash)).trim();
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1006
1093
|
// src/ast/parse.ts
|
|
1007
1094
|
var import_parser = require("@babel/parser");
|
|
1008
1095
|
var MAX_CACHE = 256;
|
|
@@ -1550,7 +1637,23 @@ function isTestFile(filePath) {
|
|
|
1550
1637
|
}
|
|
1551
1638
|
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;
|
|
1552
1639
|
function maskComments(content) {
|
|
1553
|
-
return content
|
|
1640
|
+
return replaceBlockComments(content, (c) => c.replace(/[^\n]/g, " ")).replace(/(^|[^:])\/\/[^\n]*/gm, (m, p1) => p1 + " ".repeat(m.length - p1.length));
|
|
1641
|
+
}
|
|
1642
|
+
function replaceBlockComments(content, replace) {
|
|
1643
|
+
let open = content.indexOf("/*");
|
|
1644
|
+
if (open === -1) return content;
|
|
1645
|
+
const parts = [];
|
|
1646
|
+
let copied = 0;
|
|
1647
|
+
while (open !== -1) {
|
|
1648
|
+
const close = content.indexOf("*/", open + 2);
|
|
1649
|
+
if (close === -1) break;
|
|
1650
|
+
parts.push(content.slice(copied, open), replace(content.slice(open, close + 2)));
|
|
1651
|
+
copied = close + 2;
|
|
1652
|
+
open = content.indexOf("/*", copied);
|
|
1653
|
+
}
|
|
1654
|
+
if (parts.length === 0) return content;
|
|
1655
|
+
parts.push(content.slice(copied));
|
|
1656
|
+
return parts.join("");
|
|
1554
1657
|
}
|
|
1555
1658
|
function enclosingHandler(content, index) {
|
|
1556
1659
|
const MAX_LEVELS = 6;
|
|
@@ -1623,10 +1726,11 @@ var SERVER_SIDE_PATH_RE = new RegExp(
|
|
|
1623
1726
|
"i"
|
|
1624
1727
|
);
|
|
1625
1728
|
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/;
|
|
1729
|
+
var USE_SERVER_DIRECTIVE_RE = /^[ \t\uFEFF]*["']use server["']/m;
|
|
1626
1730
|
function isServerSideFile(filePath, content) {
|
|
1627
1731
|
if (isTestFile(filePath)) return false;
|
|
1628
1732
|
if (SERVER_SIDE_PATH_RE.test(filePath)) return true;
|
|
1629
|
-
if (content &&
|
|
1733
|
+
if (content && USE_SERVER_DIRECTIVE_RE.test(content)) return true;
|
|
1630
1734
|
if (content && SERVER_SIDE_CONTENT_RE.test(content)) return true;
|
|
1631
1735
|
return false;
|
|
1632
1736
|
}
|
|
@@ -1726,12 +1830,37 @@ function tryParse(content, filePath) {
|
|
|
1726
1830
|
parseCacheValid = true;
|
|
1727
1831
|
return result;
|
|
1728
1832
|
}
|
|
1729
|
-
function isNamespacedSlotKey(value) {
|
|
1833
|
+
function isNamespacedSlotKey(name, value) {
|
|
1834
|
+
if (CREDENTIAL_NAME.test(name)) return false;
|
|
1730
1835
|
const words = value.split(/[.:/_-]/);
|
|
1731
1836
|
if (words[words.length - 1] === "") words.pop();
|
|
1732
1837
|
if (words.length < 2) return false;
|
|
1838
|
+
if (words.some((w) => CREDENTIAL_WORD.test(w))) return false;
|
|
1733
1839
|
return words.every((w) => /^[a-z]+[0-9]*(?:[A-Z][a-z]+[0-9]*)*$/.test(w));
|
|
1734
1840
|
}
|
|
1841
|
+
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/;
|
|
1842
|
+
var CREDENTIAL_WORD = /secret|passw|token|private|signing|apikey|credential/i;
|
|
1843
|
+
function isPlaceholderToken(token) {
|
|
1844
|
+
if (/(.)\1{7,}/.test(token)) return true;
|
|
1845
|
+
if (new Set(token).size < 8) return true;
|
|
1846
|
+
return /example|placeholder|redacted|your_?(?:api_?)?(?:key|token)|insert_?your|replace_?me/i.test(token);
|
|
1847
|
+
}
|
|
1848
|
+
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/;
|
|
1849
|
+
var GEMINI_NAME_RE = /gemini|generative/i;
|
|
1850
|
+
var PUBLIC_GOOGLE_KEY_NAME_RE = /firebase|maps?(?:\b|_)|places|recaptcha|youtube/i;
|
|
1851
|
+
var FIREBASE_CONFIG_FIELD_RE = /\b(?:authDomain|messagingSenderId|storageBucket)\b/;
|
|
1852
|
+
function isGeminiKeyContext(lines, line, fileIsGemini) {
|
|
1853
|
+
const lineText = lines[line - 1] ?? "";
|
|
1854
|
+
const keyAt = lineText.search(/AIza[\w-]{35}/);
|
|
1855
|
+
const before = keyAt === -1 ? lineText : lineText.slice(0, keyAt);
|
|
1856
|
+
if (PUBLIC_GOOGLE_KEY_NAME_RE.test(before)) return false;
|
|
1857
|
+
const from = Math.max(0, line - 4);
|
|
1858
|
+
const to = Math.min(lines.length, line + 3);
|
|
1859
|
+
for (let i = from; i < to; i++) {
|
|
1860
|
+
if (FIREBASE_CONFIG_FIELD_RE.test(lines[i])) return false;
|
|
1861
|
+
}
|
|
1862
|
+
return fileIsGemini || GEMINI_NAME_RE.test(before);
|
|
1863
|
+
}
|
|
1735
1864
|
var hardcodedSecrets = {
|
|
1736
1865
|
id: "VC001",
|
|
1737
1866
|
title: "Hardcoded API Key or Secret",
|
|
@@ -1751,8 +1880,16 @@ var hardcodedSecrets = {
|
|
|
1751
1880
|
/(?:sk_live|pk_live|sk_test|pk_test)_[a-zA-Z0-9]{20,}/g,
|
|
1752
1881
|
// Supabase anon/service keys (JWT format)
|
|
1753
1882
|
/(?:supabase[_-]?(?:anon|service)[_-]?key|SUPABASE_(?:ANON|SERVICE_ROLE)_KEY)\s*[:=]\s*["'`](eyJ[a-zA-Z0-9_-]{50,})["'`]/gi,
|
|
1754
|
-
// OpenAI keys
|
|
1755
|
-
|
|
1883
|
+
// OpenAI keys. Every OpenAI secret key carries `T3BlbkFJ` (base64 of
|
|
1884
|
+
// "OpenAI") in the middle, which is what keeps this near zero false
|
|
1885
|
+
// positives. This used to be `sk-[a-zA-Z0-9]{20,}T3BlbkFJ…`, the legacy
|
|
1886
|
+
// user-key shape: its character class has no `-`, so it could not get
|
|
1887
|
+
// past the second hyphen of `sk-proj-`, and every project, service
|
|
1888
|
+
// account and admin key OpenAI has issued since 2024 went unreported.
|
|
1889
|
+
// Prefixes and the `-`/`_` body follow gitleaks' openai-api-key rule.
|
|
1890
|
+
// Bounded on both sides so a hostile run of key characters cannot
|
|
1891
|
+
// backtrack a whole line.
|
|
1892
|
+
/sk-(?:(?:proj|svcacct|admin)-[A-Za-z0-9_-]{20,80}|[A-Za-z0-9]{20,80})T3BlbkFJ[A-Za-z0-9_-]{20,80}/g,
|
|
1756
1893
|
// Generic tokens in assignments — require standalone word and longer min length
|
|
1757
1894
|
/(?:^|[\s,({])(?:token|secret|password|passwd|pwd)\s*[:=]\s*["'`]([a-zA-Z0-9_\-!@#$%^&*]{20,})["'`]/gim,
|
|
1758
1895
|
// SCREAMING_CASE identifiers ending in SECRET/TOKEN/KEY/PASSWORD
|
|
@@ -1769,20 +1906,42 @@ var hardcodedSecrets = {
|
|
|
1769
1906
|
// Private keys
|
|
1770
1907
|
/-----BEGIN (?:RSA |EC |DSA )?PRIVATE KEY-----/g,
|
|
1771
1908
|
// Database URLs with credentials
|
|
1772
|
-
/(?:postgres|mysql|mongodb(?:\+srv)?):\/\/[^:]+:[^@]+@[^/\s"'`]+/gi
|
|
1909
|
+
/(?:postgres|mysql|mongodb(?:\+srv)?):\/\/[^:]+:[^@]+@[^/\s"'`]+/gi,
|
|
1910
|
+
// ── [11]–[14] Fixed-prefix AI-provider and payment keys ──
|
|
1911
|
+
// These match the token itself, so they fire whatever it is bound to:
|
|
1912
|
+
// `const k = "…"`, a positional `new OpenAI("…")`, an unquoted .env
|
|
1913
|
+
// value. The name-based patterns above only see a key that sits in a
|
|
1914
|
+
// slot called apiKey / token / *_KEY. Shapes follow gitleaks.
|
|
1915
|
+
// [11] Hugging Face user access token: `hf_` + 34 letters.
|
|
1916
|
+
/\bhf_[A-Za-z]{34}\b/g,
|
|
1917
|
+
// [12] OpenRouter: `sk-or-v1-` + 64 hex.
|
|
1918
|
+
/\bsk-or-v1-[a-f0-9]{64}\b/g,
|
|
1919
|
+
// [13] Stripe restricted key. `rk_` keys are scoped, but a live one can
|
|
1920
|
+
// still read customers or issue refunds, and [2] above only knows
|
|
1921
|
+
// `sk_`/`pk_`. No trailing anchor: Stripe keys run to ~100 characters
|
|
1922
|
+
// and the match only needs the prefix plus a real body.
|
|
1923
|
+
/\brk_(?:live|test)_[A-Za-z0-9]{20,200}/g,
|
|
1924
|
+
// [14] Google API key — reported only in a Gemini context, see
|
|
1925
|
+
// GEMINI_FILE_CONTEXT_RE. The lookahead stands in for `\b`, which the
|
|
1926
|
+
// `-` in the key alphabet would break.
|
|
1927
|
+
/AIza[\w-]{35}(?![\w-])/g
|
|
1773
1928
|
];
|
|
1774
1929
|
const fixMessages = [
|
|
1775
1930
|
"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.",
|
|
1776
1931
|
"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.",
|
|
1777
1932
|
"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.",
|
|
1778
1933
|
"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.",
|
|
1779
|
-
"OpenAI API key detected
|
|
1934
|
+
"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.",
|
|
1780
1935
|
"Hardcoded token or password detected. Move to an environment variable and rotate the credential if it has been committed to version control.",
|
|
1781
1936
|
"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.",
|
|
1782
1937
|
"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.",
|
|
1783
1938
|
"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.",
|
|
1784
1939
|
"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.",
|
|
1785
|
-
"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."
|
|
1940
|
+
"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.",
|
|
1941
|
+
"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.",
|
|
1942
|
+
"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.",
|
|
1943
|
+
"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.",
|
|
1944
|
+
"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."
|
|
1786
1945
|
];
|
|
1787
1946
|
const minLen = [
|
|
1788
1947
|
12,
|
|
@@ -1793,8 +1952,12 @@ var hardcodedSecrets = {
|
|
|
1793
1952
|
// [2] Stripe
|
|
1794
1953
|
50,
|
|
1795
1954
|
// [3] Supabase JWT
|
|
1796
|
-
|
|
1797
|
-
//
|
|
1955
|
+
// [4] OpenAI and [11]–[14] fixed-prefix tokens: the regex already
|
|
1956
|
+
// fixes the length. The floor check reads the FIRST quoted value on the
|
|
1957
|
+
// line, which in `a = "x"; key = "sk-proj-…"` is not the token, so it
|
|
1958
|
+
// must not run for them. ([4] was 40, which the regex's minimum of 48
|
|
1959
|
+
// made redundant everywhere except that misread.)
|
|
1960
|
+
0,
|
|
1798
1961
|
20,
|
|
1799
1962
|
// [5] generic tokens with {20,} in the regex
|
|
1800
1963
|
12,
|
|
@@ -1805,18 +1968,49 @@ var hardcodedSecrets = {
|
|
|
1805
1968
|
// [8] password: "..." — lower floor per the pattern comment above
|
|
1806
1969
|
0,
|
|
1807
1970
|
// [9] private keys — no length check
|
|
1808
|
-
0
|
|
1971
|
+
0,
|
|
1809
1972
|
// [10] DB URLs — no length check
|
|
1973
|
+
0,
|
|
1974
|
+
0,
|
|
1975
|
+
0,
|
|
1976
|
+
0
|
|
1977
|
+
// [11]–[14] see [4]
|
|
1810
1978
|
];
|
|
1979
|
+
const OPENAI_PI = 4;
|
|
1980
|
+
const FIRST_TOKEN_PI = 11;
|
|
1981
|
+
const STRIPE_RESTRICTED_PI = 13;
|
|
1982
|
+
const GOOGLE_PI = 14;
|
|
1983
|
+
const lines = content.split("\n");
|
|
1984
|
+
const fileIsGemini = GEMINI_FILE_CONTEXT_RE.test(content);
|
|
1811
1985
|
const matches = [];
|
|
1812
1986
|
for (let pi = 0; pi < patterns.length; pi++) {
|
|
1813
1987
|
const pattern = patterns[pi];
|
|
1814
|
-
|
|
1988
|
+
if (pi === GOOGLE_PI && !fileIsGemini && !GEMINI_NAME_RE.test(content)) continue;
|
|
1989
|
+
const matchedText = [];
|
|
1990
|
+
const rawMatches = findMatches(content, pattern, hardcodedSecrets, filePath, (m) => {
|
|
1991
|
+
matchedText.push(m[0]);
|
|
1992
|
+
return fixMessages[pi];
|
|
1993
|
+
});
|
|
1815
1994
|
const floor = minLen[pi] ?? 12;
|
|
1816
|
-
|
|
1817
|
-
|
|
1995
|
+
const isTokenPattern = pi === OPENAI_PI || pi >= FIRST_TOKEN_PI;
|
|
1996
|
+
for (let ri = 0; ri < rawMatches.length; ri++) {
|
|
1997
|
+
const rm = rawMatches[ri];
|
|
1998
|
+
const lineText = lines[rm.line - 1] || "";
|
|
1818
1999
|
const trimmed = lineText.trimStart();
|
|
1819
2000
|
if (trimmed.startsWith("//") || trimmed.startsWith("#")) continue;
|
|
2001
|
+
if (isTokenPattern) {
|
|
2002
|
+
const token = matchedText[ri] ?? "";
|
|
2003
|
+
if (isPlaceholderToken(token)) continue;
|
|
2004
|
+
if (pi === GOOGLE_PI) {
|
|
2005
|
+
if (!isGeminiKeyContext(lines, rm.line, fileIsGemini)) continue;
|
|
2006
|
+
matches.push({ ...rm, severity: "high" });
|
|
2007
|
+
continue;
|
|
2008
|
+
}
|
|
2009
|
+
if (pi === STRIPE_RESTRICTED_PI && !token.startsWith("rk_live_")) {
|
|
2010
|
+
matches.push({ ...rm, severity: "high" });
|
|
2011
|
+
continue;
|
|
2012
|
+
}
|
|
2013
|
+
}
|
|
1820
2014
|
if (floor > 0) {
|
|
1821
2015
|
const secretMatch = lineText.match(/[:=]\s*["'`]([^"'`]*)["'`]/);
|
|
1822
2016
|
if (secretMatch && secretMatch[1].length < floor) continue;
|
|
@@ -1827,7 +2021,7 @@ var hardcodedSecrets = {
|
|
|
1827
2021
|
if (valMatch && nameMatch) {
|
|
1828
2022
|
const value = valMatch[1];
|
|
1829
2023
|
const isKeySuffix = nameMatch[1].endsWith("_KEY");
|
|
1830
|
-
const isSlotIdentifier = value.length < 40 && (/^[a-z0-9]+([_-][a-z0-9]+)+$/.test(value) || isNamespacedSlotKey(value));
|
|
2024
|
+
const isSlotIdentifier = value.length < 40 && (/^[a-z0-9]+([_-][a-z0-9]+)+$/.test(value) || isNamespacedSlotKey(nameMatch[1], value));
|
|
1831
2025
|
if (isKeySuffix && isSlotIdentifier) continue;
|
|
1832
2026
|
}
|
|
1833
2027
|
}
|
|
@@ -1933,6 +2127,323 @@ function stripCorsHeaderList(codeOnly) {
|
|
|
1933
2127
|
""
|
|
1934
2128
|
);
|
|
1935
2129
|
}
|
|
2130
|
+
function blankKeepLines(s) {
|
|
2131
|
+
return s.replace(/[^\n]/g, " ");
|
|
2132
|
+
}
|
|
2133
|
+
function closingBrace(text, open, limit) {
|
|
2134
|
+
let depth = 0;
|
|
2135
|
+
const end = Math.min(text.length, open + limit);
|
|
2136
|
+
for (let i = open; i < end; i++) {
|
|
2137
|
+
const c = text.charCodeAt(i);
|
|
2138
|
+
if (c === 34 || c === 39) {
|
|
2139
|
+
let j = i + 1;
|
|
2140
|
+
while (j < end) {
|
|
2141
|
+
const d = text.charCodeAt(j);
|
|
2142
|
+
if (d === 92) {
|
|
2143
|
+
j += 2;
|
|
2144
|
+
continue;
|
|
2145
|
+
}
|
|
2146
|
+
if (d === c || d === 10) break;
|
|
2147
|
+
j++;
|
|
2148
|
+
}
|
|
2149
|
+
i = j;
|
|
2150
|
+
continue;
|
|
2151
|
+
}
|
|
2152
|
+
if (c === 123) depth++;
|
|
2153
|
+
else if (c === 125) {
|
|
2154
|
+
depth--;
|
|
2155
|
+
if (depth === 0) return i;
|
|
2156
|
+
}
|
|
2157
|
+
}
|
|
2158
|
+
return -1;
|
|
2159
|
+
}
|
|
2160
|
+
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;
|
|
2161
|
+
function forwardsCallerCredential(headersInner, readsCaller) {
|
|
2162
|
+
const CRED_ENTRY_RE = /["']?(?:authorization|x-api-key|api-key|apikey|x-auth-token|x-access-token|cookie)["']?\s*:\s*([^,\n}]{0,300})/gi;
|
|
2163
|
+
let e;
|
|
2164
|
+
while ((e = CRED_ENTRY_RE.exec(headersInner)) !== null) {
|
|
2165
|
+
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, "");
|
|
2166
|
+
if (/\b(?:token|accessToken|access_token|idToken|id_token|authToken|userToken|bearerToken|jwt|session|cookies?)\b/i.test(value)) {
|
|
2167
|
+
return true;
|
|
2168
|
+
}
|
|
2169
|
+
if (readsCaller?.(value)) return true;
|
|
2170
|
+
}
|
|
2171
|
+
return false;
|
|
2172
|
+
}
|
|
2173
|
+
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*[,)]/;
|
|
2174
|
+
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;
|
|
2175
|
+
var MAX_BINDINGS = 4096;
|
|
2176
|
+
function collectBindings(code) {
|
|
2177
|
+
const byName = /* @__PURE__ */ new Map();
|
|
2178
|
+
const add = (name, at, rhs) => {
|
|
2179
|
+
const list = byName.get(name);
|
|
2180
|
+
if (list) list.push({ at, rhs });
|
|
2181
|
+
else byName.set(name, [{ at, rhs }]);
|
|
2182
|
+
};
|
|
2183
|
+
let count = 0;
|
|
2184
|
+
let b;
|
|
2185
|
+
BINDING_RE.lastIndex = 0;
|
|
2186
|
+
while ((b = BINDING_RE.exec(code)) !== null && count < MAX_BINDINGS) {
|
|
2187
|
+
count++;
|
|
2188
|
+
if (b[1]) {
|
|
2189
|
+
add(b[1], b.index, b[3]);
|
|
2190
|
+
continue;
|
|
2191
|
+
}
|
|
2192
|
+
for (const part of b[2].split(",")) {
|
|
2193
|
+
const local = part.replace(/=[^]*$/, "").replace(/^[^:]*:/, "").trim().replace(/^\.\.\./, "");
|
|
2194
|
+
if (/^[A-Za-z_$][\w$]{0,60}$/.test(local)) add(local, b.index, b[3]);
|
|
2195
|
+
}
|
|
2196
|
+
}
|
|
2197
|
+
return byName;
|
|
2198
|
+
}
|
|
2199
|
+
function credentialValueReadsCaller(value, at, bindings) {
|
|
2200
|
+
if (INBOUND_CREDENTIAL_READ_RE.test(value) || INBOUND_REQUEST_READ_RE.test(value)) return true;
|
|
2201
|
+
const roots = /* @__PURE__ */ new Set();
|
|
2202
|
+
const INTERP_RE = /\$\{\s*([A-Za-z_$][\w$]{0,60})/g;
|
|
2203
|
+
const ROOT_RE = /(?<![\w$.])[A-Za-z_$][\w$]{0,60}/g;
|
|
2204
|
+
let r;
|
|
2205
|
+
while ((r = INTERP_RE.exec(value)) !== null && roots.size < 6) roots.add(r[1]);
|
|
2206
|
+
const bare = value.replace(/"[^"\n]{0,300}"|'[^'\n]{0,300}'|`[^`]{0,300}(?:`|$)/g, " ");
|
|
2207
|
+
while ((r = ROOT_RE.exec(bare)) !== null && roots.size < 6) roots.add(r[0]);
|
|
2208
|
+
for (const name of roots) {
|
|
2209
|
+
const list = bindings().get(name);
|
|
2210
|
+
if (!list || list[0].at >= at) continue;
|
|
2211
|
+
let lo = 0;
|
|
2212
|
+
let hi = list.length - 1;
|
|
2213
|
+
while (lo < hi) {
|
|
2214
|
+
const mid = lo + hi + 1 >> 1;
|
|
2215
|
+
if (list[mid].at < at) lo = mid;
|
|
2216
|
+
else hi = mid - 1;
|
|
2217
|
+
}
|
|
2218
|
+
if (INBOUND_REQUEST_READ_RE.test(list[lo].rhs)) return true;
|
|
2219
|
+
}
|
|
2220
|
+
return false;
|
|
2221
|
+
}
|
|
2222
|
+
function maskOutboundAuthNoise(code) {
|
|
2223
|
+
let out = code.replace(
|
|
2224
|
+
/(["']?)role\1\s{0,20}:\s{0,20}["'](?:user|assistant|system|developer|tool|model|function)["']/g,
|
|
2225
|
+
blankKeepLines
|
|
2226
|
+
);
|
|
2227
|
+
if (/["'`]assistant["'`]/.test(out)) {
|
|
2228
|
+
out = out.replace(/["'`](?:user|assistant|system|developer|tool)["'`]/g, blankKeepLines);
|
|
2229
|
+
}
|
|
2230
|
+
const envNames = /* @__PURE__ */ new Set();
|
|
2231
|
+
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;
|
|
2232
|
+
let b;
|
|
2233
|
+
while ((b = ENV_BIND_RE.exec(out)) !== null && envNames.size < 32) {
|
|
2234
|
+
if (!/secret|webhook|signing|cron|internal|admin|password|passwd/i.test(b[1])) envNames.add(b[1]);
|
|
2235
|
+
}
|
|
2236
|
+
if (envNames.size > 0) {
|
|
2237
|
+
const names = [...envNames].map((n) => n.replace(/\$/g, "\\$")).join("|");
|
|
2238
|
+
out = out.replace(new RegExp(`(?<![\\w$.])(?:${names})(?![\\w$])`, "g"), blankKeepLines);
|
|
2239
|
+
}
|
|
2240
|
+
out = out.replace(
|
|
2241
|
+
/\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,
|
|
2242
|
+
blankKeepLines
|
|
2243
|
+
);
|
|
2244
|
+
let bindingMap = null;
|
|
2245
|
+
const bindingSource = out;
|
|
2246
|
+
const bindings = () => bindingMap ??= collectBindings(bindingSource);
|
|
2247
|
+
out = out.replace(
|
|
2248
|
+
/\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,
|
|
2249
|
+
(call, value, at) => credentialValueReadsCaller(value, at, bindings) ? call : blankKeepLines(call)
|
|
2250
|
+
);
|
|
2251
|
+
const OPEN_RE = /\b(?:headers\s*[:=]|new\s+Headers\s*\()\s*\{/g;
|
|
2252
|
+
const MAX_OBJECTS = 64;
|
|
2253
|
+
const MAX_OBJECT_LEN = 3e3;
|
|
2254
|
+
let examined = 0;
|
|
2255
|
+
let m;
|
|
2256
|
+
const parts = [];
|
|
2257
|
+
let copied = 0;
|
|
2258
|
+
while ((m = OPEN_RE.exec(out)) !== null) {
|
|
2259
|
+
if (++examined > MAX_OBJECTS) break;
|
|
2260
|
+
const open = m.index + m[0].length - 1;
|
|
2261
|
+
const close = closingBrace(out, open, MAX_OBJECT_LEN);
|
|
2262
|
+
if (close === -1) continue;
|
|
2263
|
+
const inner = out.slice(open + 1, close);
|
|
2264
|
+
const readsCaller = (value) => credentialValueReadsCaller(value, open, bindings);
|
|
2265
|
+
if (!INBOUND_CREDENTIAL_READ_RE.test(inner) && !forwardsCallerCredential(inner, readsCaller)) {
|
|
2266
|
+
parts.push(out.slice(copied, open + 1), blankKeepLines(inner));
|
|
2267
|
+
copied = close;
|
|
2268
|
+
}
|
|
2269
|
+
OPEN_RE.lastIndex = close + 1;
|
|
2270
|
+
}
|
|
2271
|
+
if (parts.length === 0) return out;
|
|
2272
|
+
parts.push(out.slice(copied));
|
|
2273
|
+
return parts.join("");
|
|
2274
|
+
}
|
|
2275
|
+
function maskProseStrings(code) {
|
|
2276
|
+
return code.replace(
|
|
2277
|
+
/(?<!\\)"(?:[^"\\\n]|\\.){0,2000}"|(?<!\\)'(?:[^'\\\n]|\\.){0,2000}'|(?<!\\)`(?:[^`\\]|\\.){0,8000}`/g,
|
|
2278
|
+
(lit) => /\S\s+\S+\s+\S+\s+\S/.test(lit) ? blankKeepLines(lit) : lit
|
|
2279
|
+
);
|
|
2280
|
+
}
|
|
2281
|
+
var TANSTACK_START_IMPORT_RE = /["']@tanstack\/(?:(?:react|solid)-)?start(?:\/[\w-]{1,40})?["']/;
|
|
2282
|
+
var TANSTACK_ROUTER_IMPORT_RE = /["']@tanstack\/(?:react|solid)-router["']/;
|
|
2283
|
+
var TANSTACK_AUTH_MIDDLEWARE_RE = /\bmiddleware\s*[:(]\s*\[([^\]]{0,600})\]/g;
|
|
2284
|
+
var AUTH_MIDDLEWARE_NAME_RE = /auth|session|protect|require|guard|user|admin|clerk|signed|logged|login|member|owner|role|permission/i;
|
|
2285
|
+
var TANSTACK_HANDLER_AUTH_RE = [
|
|
2286
|
+
/\bget(?:User|Claims|Session|ServerSession|Auth|Token)\s*\(/,
|
|
2287
|
+
/\bget(?:Authed|Authenticated|Current|Signed\w{0,8}|Logged\w{0,8}|Session)\w{0,30}\s*\(/,
|
|
2288
|
+
/\bcurrentUser\b/,
|
|
2289
|
+
/\buse\w{0,30}Session\s*\(/,
|
|
2290
|
+
/\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,
|
|
2291
|
+
// `requireX()` / `assertX()` / `ensureX()` / `authorizeX()` is the
|
|
2292
|
+
// near-universal spelling of a bespoke gate — tanstack.com's own
|
|
2293
|
+
// `requireModerateShowcases()`, `requireCaller()`. Suppression only.
|
|
2294
|
+
/\b(?:require|assert|ensure|guard|protect|authori[sz]e)[A-Z]\w{0,40}\s*\(/,
|
|
2295
|
+
/\b(?:can|has)(?:Permission|Access|Role|Capability|Scope)\w{0,30}\s*\(/,
|
|
2296
|
+
/\bisAuthenticated\b/,
|
|
2297
|
+
/\bauth\s*\(\s*\)/,
|
|
2298
|
+
/\bauth\s*\.\s*api\s*\.\s*getSession\b/,
|
|
2299
|
+
/\.auth\s*\.\s*(?:getUser|getClaims|getSession)\b/,
|
|
2300
|
+
/\bcontext\s*\.\s*(?:user|userId|session|auth|claims|supabase)\b/,
|
|
2301
|
+
/\b(?:jwt\.verify|jwtVerify|verifyIdToken|verifyToken|timingSafeEqual|constructEvent\w{0,20}|createHmac)\s*\(/,
|
|
2302
|
+
/\bstatus(?:Code)?\s*[:(]\s*401\b/,
|
|
2303
|
+
/\bunauthori[sz]ed\b/i,
|
|
2304
|
+
/\bnot\s+(?:authenticated|authori[sz]ed|logged\s+in|signed\s+in)\b/i,
|
|
2305
|
+
// Reads the caller's credential. Forwarding it to a row-level-security
|
|
2306
|
+
// client scopes every query to the caller, which is the safe Supabase shape.
|
|
2307
|
+
/\bauthorization\b/i,
|
|
2308
|
+
// A capability-token lookup: the row is found by an unguessable value the
|
|
2309
|
+
// caller holds (`.eq("token", data.token)`, `.eq("id", body.session_id)`).
|
|
2310
|
+
// Share links, anonymous votes, guest chat sessions — the token in the
|
|
2311
|
+
// request IS the credential, the same family VC003 already accepts via a
|
|
2312
|
+
// 401 on the Next.js shapes. Calibration: every such handler in the sample
|
|
2313
|
+
// was public by design.
|
|
2314
|
+
/\.(?:eq|match)\(\s*["'`]\w{0,40}(?:token|secret|code|hash|key)["'`]/i,
|
|
2315
|
+
/\.eq\(\s*["'`]\w{1,40}["'`]\s*,\s*[\w$.]{0,60}(?:[Tt]oken|[Ss]ession_?(?:[Ii]d|[Kk]ey)|[Ss]ecret|[Hh]ash)\b/,
|
|
2316
|
+
// A shared-secret comparison (`data.password !== process.env.ADMIN_PASSWORD`).
|
|
2317
|
+
/[!=]==?\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}/
|
|
2318
|
+
];
|
|
2319
|
+
var TANSTACK_MUTATION_RE = [
|
|
2320
|
+
// Supabase: .from("orders").update(…) / .upsert(…) / .delete()
|
|
2321
|
+
/\.from\(\s*["'`][\w.-]{1,64}["'`]\s*\)\s*\.\s*(?:update|upsert|delete)\s*\(/,
|
|
2322
|
+
// Supabase admin auth API: listUsers, deleteUser, updateUserById, …
|
|
2323
|
+
/\.auth\s*\.\s*admin\s*\.\s*\w{1,40}\s*\(/,
|
|
2324
|
+
// Prisma: prisma.order.delete(…), db.user.updateMany(…)
|
|
2325
|
+
/\b(?:prisma|db|tx)\s*\.\s*\w{1,64}\s*\.\s*(?:update|upsert|delete|updateMany|deleteMany)\s*\(/,
|
|
2326
|
+
// Drizzle: db.update(orders) / db.delete(orders)
|
|
2327
|
+
/\b(?:db|tx)\s*\.\s*(?:update|delete)\s*\(\s*\w/,
|
|
2328
|
+
// Firestore admin: .doc(id).update(…) / .delete()
|
|
2329
|
+
/\.doc\([^()\n]{0,200}\)\s*\.\s*(?:update|delete|set)\s*\(/,
|
|
2330
|
+
// Raw SQL
|
|
2331
|
+
/\b(?:UPDATE\s+["`]?\w{1,64}["`]?\s+SET|DELETE\s+FROM)\b/
|
|
2332
|
+
];
|
|
2333
|
+
var SUPABASE_WRITE_TABLE_RE = /\.from\(\s*["'`]([\w.-]{1,64})["'`]\s*\)\s*\.\s*(?:update|upsert|delete)\s*\(/g;
|
|
2334
|
+
var ANALYTICS_TABLE_RE = /(?:^|[_.-])(?:page_?views?|views?|visits?|visitors?|analytics?|tracking|clicks?|impressions?|heartbeats?|presence|metrics?|stats?|counters?)(?:[_.-]|$)/i;
|
|
2335
|
+
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;
|
|
2336
|
+
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;
|
|
2337
|
+
function closingParen(text, open, limit) {
|
|
2338
|
+
let depth = 0;
|
|
2339
|
+
const end = Math.min(text.length, limit);
|
|
2340
|
+
for (let i = open; i < end; i++) {
|
|
2341
|
+
const c = text.charCodeAt(i);
|
|
2342
|
+
if (c === 34 || c === 39 || c === 96) {
|
|
2343
|
+
let j = i + 1;
|
|
2344
|
+
while (j < end) {
|
|
2345
|
+
const d = text.charCodeAt(j);
|
|
2346
|
+
if (d === 92) {
|
|
2347
|
+
j += 2;
|
|
2348
|
+
continue;
|
|
2349
|
+
}
|
|
2350
|
+
if (d === c || c !== 96 && d === 10) break;
|
|
2351
|
+
j++;
|
|
2352
|
+
}
|
|
2353
|
+
i = j;
|
|
2354
|
+
continue;
|
|
2355
|
+
}
|
|
2356
|
+
if (c === 40) depth++;
|
|
2357
|
+
else if (c === 41) {
|
|
2358
|
+
depth--;
|
|
2359
|
+
if (depth === 0) return i;
|
|
2360
|
+
}
|
|
2361
|
+
}
|
|
2362
|
+
return -1;
|
|
2363
|
+
}
|
|
2364
|
+
function hasAuthMiddleware(text) {
|
|
2365
|
+
TANSTACK_AUTH_MIDDLEWARE_RE.lastIndex = 0;
|
|
2366
|
+
let m;
|
|
2367
|
+
while ((m = TANSTACK_AUTH_MIDDLEWARE_RE.exec(text)) !== null) {
|
|
2368
|
+
if (AUTH_MIDDLEWARE_NAME_RE.test(m[1])) return true;
|
|
2369
|
+
}
|
|
2370
|
+
return false;
|
|
2371
|
+
}
|
|
2372
|
+
function unauthenticatedTanStackHandlers(masked, filePath) {
|
|
2373
|
+
const isStart = TANSTACK_START_IMPORT_RE.test(masked);
|
|
2374
|
+
const hasServerFn = /\bcreateServerFn\s*\(/.test(masked);
|
|
2375
|
+
const hasServerRoute = /\bcreateServerFileRoute\s*\(|\bcreateAPIFileRoute\s*\(/.test(masked) || /\bserver\s*:\s*\{/.test(masked) && /\bhandlers\s*:/.test(masked);
|
|
2376
|
+
if (!hasServerFn && !hasServerRoute) return [];
|
|
2377
|
+
if (!isStart && !(hasServerRoute && TANSTACK_ROUTER_IMPORT_RE.test(masked))) return [];
|
|
2378
|
+
if (TANSTACK_PUBLIC_ROUTE_PATH_RE.test(filePath)) return [];
|
|
2379
|
+
const hits = [];
|
|
2380
|
+
const touchesData = (body) => {
|
|
2381
|
+
const supabaseWrites = [...body.matchAll(SUPABASE_WRITE_TABLE_RE)].map((w) => w[1]);
|
|
2382
|
+
const otherWrites = TANSTACK_MUTATION_RE.slice(1).some((p) => p.test(body));
|
|
2383
|
+
if (otherWrites) return true;
|
|
2384
|
+
return supabaseWrites.some((t) => !ANALYTICS_TABLE_RE.test(t));
|
|
2385
|
+
};
|
|
2386
|
+
const establishesCaller = (body) => hasAuthMiddleware(body) || TANSTACK_HANDLER_AUTH_RE.some((p) => p.test(body));
|
|
2387
|
+
if (hasServerFn) {
|
|
2388
|
+
const starts = [];
|
|
2389
|
+
const FN_RE = /\bcreateServerFn\s*\(/g;
|
|
2390
|
+
let m;
|
|
2391
|
+
while ((m = FN_RE.exec(masked)) !== null && starts.length < 500) starts.push(m.index);
|
|
2392
|
+
for (let k = 0; k < starts.length; k++) {
|
|
2393
|
+
const start = starts[k];
|
|
2394
|
+
const limit = k + 1 < starts.length ? starts[k + 1] : Math.min(masked.length, start + 4e4);
|
|
2395
|
+
const h = /\.handler\s*\(/.exec(masked.slice(start, limit));
|
|
2396
|
+
if (!h) continue;
|
|
2397
|
+
const open = start + h.index + h[0].length - 1;
|
|
2398
|
+
const close = closingParen(masked, open, limit);
|
|
2399
|
+
const chain = masked.slice(start, close === -1 ? limit : close + 1);
|
|
2400
|
+
const header = masked.slice(start, open);
|
|
2401
|
+
const body = masked.slice(open, close === -1 ? limit : close + 1);
|
|
2402
|
+
const before = masked.slice(Math.max(0, start - 120), start);
|
|
2403
|
+
const nameMatch = before.match(/\b(?:const|let|var)\s+(\w{1,80})\s*(?::[^=\n]{0,80})?=\s*$/);
|
|
2404
|
+
if (nameMatch && TANSTACK_PUBLIC_FN_NAME_RE.test(nameMatch[1])) continue;
|
|
2405
|
+
if (hasAuthMiddleware(header)) continue;
|
|
2406
|
+
if (!touchesData(body)) continue;
|
|
2407
|
+
if (establishesCaller(chain)) continue;
|
|
2408
|
+
hits.push(nameMatch && nameMatch.index !== void 0 ? start - before.length + nameMatch.index : start);
|
|
2409
|
+
if (hits.length >= 50) return hits;
|
|
2410
|
+
}
|
|
2411
|
+
}
|
|
2412
|
+
if (hasServerRoute) {
|
|
2413
|
+
const serverBlock = /\bserver\s*:\s*\{/.exec(masked);
|
|
2414
|
+
const routeLevelAuth = serverBlock !== null && (() => {
|
|
2415
|
+
const close = closingBrace(masked, serverBlock.index + serverBlock[0].length - 1, 6e4);
|
|
2416
|
+
const block = masked.slice(serverBlock.index, close === -1 ? masked.length : close);
|
|
2417
|
+
const handlersAt = block.search(/\bhandlers\s*:/);
|
|
2418
|
+
return hasAuthMiddleware(handlersAt === -1 ? block : block.slice(0, handlersAt));
|
|
2419
|
+
})();
|
|
2420
|
+
if (!routeLevelAuth) {
|
|
2421
|
+
const METHOD_RE = /\b(GET|POST|PUT|PATCH|DELETE)\s*:\s*(?:async\s+)?(?:\(|function\b|\{|[A-Za-z_$][\w$]{0,40}\s*=>)/g;
|
|
2422
|
+
const methodStarts = [];
|
|
2423
|
+
let m;
|
|
2424
|
+
while ((m = METHOD_RE.exec(masked)) !== null && methodStarts.length < 200) methodStarts.push(m.index);
|
|
2425
|
+
for (let k = 0; k < methodStarts.length; k++) {
|
|
2426
|
+
const start = methodStarts[k];
|
|
2427
|
+
const limit = k + 1 < methodStarts.length ? methodStarts[k + 1] : Math.min(masked.length, start + 4e4);
|
|
2428
|
+
const head = masked.slice(start, Math.min(limit, start + 400));
|
|
2429
|
+
const opener = /^\w+\s*:\s*\{/.exec(head) ?? /=>\s*\{/.exec(head) ?? /\)\s*\{/.exec(head);
|
|
2430
|
+
let body;
|
|
2431
|
+
if (opener) {
|
|
2432
|
+
const braceAt = start + opener.index + opener[0].length - 1;
|
|
2433
|
+
const close = closingBrace(masked, braceAt, limit - braceAt);
|
|
2434
|
+
body = masked.slice(start, close === -1 ? limit : close + 1);
|
|
2435
|
+
} else {
|
|
2436
|
+
body = masked.slice(start, limit);
|
|
2437
|
+
}
|
|
2438
|
+
if (!touchesData(body)) continue;
|
|
2439
|
+
if (establishesCaller(body)) continue;
|
|
2440
|
+
hits.push(start);
|
|
2441
|
+
if (hits.length >= 50) return hits;
|
|
2442
|
+
}
|
|
2443
|
+
}
|
|
2444
|
+
}
|
|
2445
|
+
return hits;
|
|
2446
|
+
}
|
|
1936
2447
|
var missingAuthMiddleware = {
|
|
1937
2448
|
id: "VC003",
|
|
1938
2449
|
title: "API Route Missing Authentication",
|
|
@@ -1940,7 +2451,9 @@ var missingAuthMiddleware = {
|
|
|
1940
2451
|
category: "Authentication",
|
|
1941
2452
|
description: "API routes without authentication checks allow unauthorized access.",
|
|
1942
2453
|
check(content, filePath, project) {
|
|
1943
|
-
|
|
2454
|
+
const serverSide = isServerSideFile(filePath, content);
|
|
2455
|
+
const tanstackCandidate = !serverSide && !isTestFile(filePath) && /@tanstack\/(?:(?:react|solid)-)?(?:start|router)\b/.test(content);
|
|
2456
|
+
if (!serverSide && !tanstackCandidate) return [];
|
|
1944
2457
|
if (PUBLIC_BY_CONVENTION_ROUTE.test(routeSegmentName(filePath))) return [];
|
|
1945
2458
|
const routePatterns = [
|
|
1946
2459
|
// Express/Hono style
|
|
@@ -1956,7 +2469,7 @@ var missingAuthMiddleware = {
|
|
|
1956
2469
|
/module\.exports\s*=\s*(?:async\s+)?(?:function\b|\()/g
|
|
1957
2470
|
);
|
|
1958
2471
|
}
|
|
1959
|
-
if (
|
|
2472
|
+
if (USE_SERVER_DIRECTIVE_RE.test(content)) {
|
|
1960
2473
|
routePatterns.push(
|
|
1961
2474
|
/export\s+(?:async\s+)?function\s+\w+\s*\(/g,
|
|
1962
2475
|
/export\s+const\s+\w+\s*(?::[^=\n]{0,120})?=\s*(?:async\s*)?\(/g
|
|
@@ -1980,7 +2493,7 @@ var missingAuthMiddleware = {
|
|
|
1980
2493
|
if (isAuthRoute) return [];
|
|
1981
2494
|
const isWebhookRoute = /\/webhook/i.test(filePath) || /(?:^|[/_-])webhooks?(?:[/_.-]|$)/i.test(filePath);
|
|
1982
2495
|
if (isWebhookRoute) return [];
|
|
1983
|
-
const codeOnly = content
|
|
2496
|
+
const codeOnly = replaceBlockComments(content, () => "").replace(/(^|[^:])\/\/.*$/gm, "$1").replace(/^[ \t\uFEFF]*#.*$/gm, "");
|
|
1984
2497
|
const authPatterns = [
|
|
1985
2498
|
/\bgetUser\b/i,
|
|
1986
2499
|
/\bcurrentUser\b/i,
|
|
@@ -1996,6 +2509,13 @@ var missingAuthMiddleware = {
|
|
|
1996
2509
|
/\bcheckApiKey\b/i,
|
|
1997
2510
|
/\bverifyCronSecret\b/i,
|
|
1998
2511
|
/\bverifySecret\b/i,
|
|
2512
|
+
// Signed-request receivers: `await verifyQstashSignature({ req, rawBody })`,
|
|
2513
|
+
// `verifyWebhookSignature(…)`, Upstash's `receiver.verify({ signature,
|
|
2514
|
+
// body })`. Since outbound headers are masked, a route that relied on
|
|
2515
|
+
// its own outbound `Bearer ${key}` to pass no longer does, and these
|
|
2516
|
+
// are what actually authenticate it.
|
|
2517
|
+
/\bverify\w{0,20}Signature\w{0,20}\s*\(/i,
|
|
2518
|
+
/\b\w{0,30}[Rr]eceiver\s*\.\s*verify\s*\(/,
|
|
1999
2519
|
/supabase\.auth/i,
|
|
2000
2520
|
/firebase\.auth/i,
|
|
2001
2521
|
/\bclerk\b/i,
|
|
@@ -2034,16 +2554,17 @@ var missingAuthMiddleware = {
|
|
|
2034
2554
|
const handlerAuthPatterns = authPatterns.filter(
|
|
2035
2555
|
(p) => !APP_LEVEL_AUTH.some((a) => a.source === p.source)
|
|
2036
2556
|
);
|
|
2037
|
-
const maskedForScope = maskComments(content);
|
|
2557
|
+
const maskedForScope = maskOutboundAuthNoise(maskComments(content));
|
|
2558
|
+
const codeForAuth = maskOutboundAuthNoise(codeOnly);
|
|
2038
2559
|
const handlerHasAuth = (index) => {
|
|
2039
2560
|
const bodyStart = maskedForScope.indexOf("{", index);
|
|
2040
2561
|
const probe = bodyStart === -1 ? index : bodyStart + 1;
|
|
2041
2562
|
const scope = enclosingHandler(maskedForScope, probe);
|
|
2042
|
-
if (scope === null) return handlerAuthPatterns.some((p) => p.test(
|
|
2563
|
+
if (scope === null) return handlerAuthPatterns.some((p) => p.test(codeForAuth));
|
|
2043
2564
|
return handlerAuthPatterns.some((p) => p.test(scope));
|
|
2044
2565
|
};
|
|
2045
2566
|
const matches = [];
|
|
2046
|
-
for (const pattern of routePatterns) {
|
|
2567
|
+
for (const pattern of serverSide ? routePatterns : []) {
|
|
2047
2568
|
matches.push(
|
|
2048
2569
|
...findMatches(
|
|
2049
2570
|
content,
|
|
@@ -2054,11 +2575,11 @@ var missingAuthMiddleware = {
|
|
|
2054
2575
|
)
|
|
2055
2576
|
);
|
|
2056
2577
|
}
|
|
2057
|
-
if (matches.length === 0 && SUPABASE_EDGE_FN_RE.test(filePath) && isDenoEdgeEntry(codeOnly) && !isPublicByDesignEdgePath(filePath)) {
|
|
2578
|
+
if (matches.length === 0 && serverSide && SUPABASE_EDGE_FN_RE.test(filePath) && isDenoEdgeEntry(codeOnly) && !isPublicByDesignEdgePath(filePath)) {
|
|
2058
2579
|
const fnName = supabaseFunctionName(filePath);
|
|
2059
2580
|
const verifyJwt = fnName && project?.supabaseEdgeVerifyJwt ? project.supabaseEdgeVerifyJwt.get(fnName) : void 0;
|
|
2060
2581
|
if (verifyJwt !== true) {
|
|
2061
|
-
const withoutCors = stripCorsHeaderList(codeOnly);
|
|
2582
|
+
const withoutCors = maskProseStrings(maskOutboundAuthNoise(stripCorsHeaderList(codeOnly)));
|
|
2062
2583
|
const hasWeakHint = verifyJwt === false ? false : EDGE_WEAK_AUTH_HINTS.some((p) => p.test(withoutCors));
|
|
2063
2584
|
if (!hasWeakHint) {
|
|
2064
2585
|
matches.push(
|
|
@@ -2079,6 +2600,21 @@ var missingAuthMiddleware = {
|
|
|
2079
2600
|
}
|
|
2080
2601
|
const indexOfLine = (line) => lineStarts[Math.max(0, Math.min(line - 1, lineStarts.length - 1))];
|
|
2081
2602
|
const unauthenticated = matches.filter((m) => !handlerHasAuth(indexOfLine(m.line)));
|
|
2603
|
+
if (serverSide || tanstackCandidate) {
|
|
2604
|
+
for (const idx of unauthenticatedTanStackHandlers(maskedForScope, filePath)) {
|
|
2605
|
+
const line = lineNumberAt(content, idx);
|
|
2606
|
+
unauthenticated.push({
|
|
2607
|
+
rule: "VC003",
|
|
2608
|
+
title: missingAuthMiddleware.title,
|
|
2609
|
+
severity: "high",
|
|
2610
|
+
category: missingAuthMiddleware.category,
|
|
2611
|
+
file: filePath,
|
|
2612
|
+
line,
|
|
2613
|
+
snippet: getSnippet(content, line),
|
|
2614
|
+
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."
|
|
2615
|
+
});
|
|
2616
|
+
}
|
|
2617
|
+
}
|
|
2082
2618
|
return filterSilenced(unauthenticated, content, "VC003");
|
|
2083
2619
|
}
|
|
2084
2620
|
};
|
|
@@ -2373,7 +2909,8 @@ var noRateLimiting = {
|
|
|
2373
2909
|
check(content, filePath) {
|
|
2374
2910
|
const isEntryFile = /(?:server|app|index|main)\.[jt]sx?$/.test(filePath) || filePath.includes("middleware");
|
|
2375
2911
|
if (!isEntryFile) return [];
|
|
2376
|
-
const isServer = /(?:from\s+|require\s*\(\s*)["'`](?:express|hono|fastify|koa|@hono\/[\w-]+|next
|
|
2912
|
+
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.
|
|
2913
|
+
/\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);
|
|
2377
2914
|
if (!isServer) return [];
|
|
2378
2915
|
const hasRateLimit = /rate.?limit|throttle|express-rate-limit|@elysiajs\/rate-limit|hono.*limiter/i.test(content);
|
|
2379
2916
|
if (hasRateLimit) return [];
|
|
@@ -2448,35 +2985,61 @@ var clientSideAuth = {
|
|
|
2448
2985
|
return matches;
|
|
2449
2986
|
}
|
|
2450
2987
|
};
|
|
2988
|
+
var PUBLIC_ENV_FIX = {
|
|
2989
|
+
NEXT_PUBLIC_: "Remove the NEXT_PUBLIC_ prefix. Only use NEXT_PUBLIC_ for values safe to expose in the browser.",
|
|
2990
|
+
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.",
|
|
2991
|
+
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.",
|
|
2992
|
+
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.",
|
|
2993
|
+
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.",
|
|
2994
|
+
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.",
|
|
2995
|
+
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."
|
|
2996
|
+
};
|
|
2997
|
+
var NEXT_PUBLIC_ASSIGN_RE = /(?:^|[^A-Za-z0-9_])(NEXT_PUBLIC_[A-Za-z0-9_]{1,128})\s*=\s*([^\r\n]*)/i;
|
|
2451
2998
|
var nextPublicSecret = {
|
|
2452
2999
|
id: "VC011",
|
|
2453
|
-
title: "Secret in
|
|
3000
|
+
title: "Secret in Browser-Exposed Environment Variable",
|
|
2454
3001
|
severity: "critical",
|
|
2455
3002
|
category: "Secrets",
|
|
2456
|
-
description: "NEXT_PUBLIC_
|
|
3003
|
+
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.",
|
|
2457
3004
|
check(content, filePath) {
|
|
2458
|
-
|
|
2459
|
-
const
|
|
2460
|
-
|
|
2461
|
-
|
|
2462
|
-
];
|
|
3005
|
+
const legacyScope = /\.env/.test(filePath) || /next\.config/.test(filePath);
|
|
3006
|
+
const dotenvScope = isDotenvPath(filePath);
|
|
3007
|
+
if (!legacyScope && !dotenvScope) return [];
|
|
3008
|
+
if (!/(?:NEXT_PUBLIC_|NUXT_PUBLIC_|EXPO_PUBLIC_|REACT_APP_|GATSBY_|VITE_|PUBLIC_)/i.test(content)) return [];
|
|
2463
3009
|
const matches = [];
|
|
2464
|
-
|
|
2465
|
-
|
|
2466
|
-
|
|
2467
|
-
|
|
2468
|
-
|
|
2469
|
-
|
|
2470
|
-
|
|
2471
|
-
);
|
|
2472
|
-
|
|
2473
|
-
|
|
2474
|
-
|
|
2475
|
-
|
|
2476
|
-
|
|
2477
|
-
if (
|
|
2478
|
-
|
|
3010
|
+
const lines = content.split("\n");
|
|
3011
|
+
for (let i = 0; i < lines.length; i++) {
|
|
3012
|
+
const line = lines[i];
|
|
3013
|
+
const trimmed = line.trimStart();
|
|
3014
|
+
if (/^(?:#|\/\/|\*|\/\*|<!--)/.test(trimmed)) continue;
|
|
3015
|
+
let name;
|
|
3016
|
+
let value = "";
|
|
3017
|
+
const a = dotenvScope ? DOTENV_ASSIGN_RE.exec(line) : null;
|
|
3018
|
+
if (a && PUBLIC_ENV_PREFIX_RE.test(a[1])) {
|
|
3019
|
+
name = a[1];
|
|
3020
|
+
value = a[2];
|
|
3021
|
+
} else if (legacyScope) {
|
|
3022
|
+
const n = NEXT_PUBLIC_ASSIGN_RE.exec(line);
|
|
3023
|
+
if (n) {
|
|
3024
|
+
name = n[1];
|
|
3025
|
+
value = n[2];
|
|
3026
|
+
}
|
|
2479
3027
|
}
|
|
3028
|
+
if (!name) continue;
|
|
3029
|
+
const bare = dotenvValue(value);
|
|
3030
|
+
if (bare === "" || /^pk_(?:test|live)_$/.test(bare)) continue;
|
|
3031
|
+
const verdict = classifyPublicEnvVar(name, bare);
|
|
3032
|
+
if (!verdict || !verdict.secret) continue;
|
|
3033
|
+
matches.push({
|
|
3034
|
+
rule: "VC011",
|
|
3035
|
+
title: nextPublicSecret.title,
|
|
3036
|
+
severity: "critical",
|
|
3037
|
+
category: "Secrets",
|
|
3038
|
+
file: filePath,
|
|
3039
|
+
line: i + 1,
|
|
3040
|
+
snippet: getSnippet(content, i + 1),
|
|
3041
|
+
fix: PUBLIC_ENV_FIX[verdict.prefix] ?? PUBLIC_ENV_FIX.NEXT_PUBLIC_
|
|
3042
|
+
});
|
|
2480
3043
|
}
|
|
2481
3044
|
return matches;
|
|
2482
3045
|
}
|
|
@@ -2652,12 +3215,32 @@ var exposedAuthSecret = {
|
|
|
2652
3215
|
}
|
|
2653
3216
|
};
|
|
2654
3217
|
function cspFixFor(content) {
|
|
2655
|
-
const
|
|
2656
|
-
|
|
2657
|
-
|
|
2658
|
-
)
|
|
2659
|
-
|
|
2660
|
-
|
|
3218
|
+
const html = content.slice(0, 2e5);
|
|
3219
|
+
const origins = /* @__PURE__ */ new Set();
|
|
3220
|
+
const addOrigin = (url) => {
|
|
3221
|
+
const m2 = url.match(/^(https?:)?\/\/([^/"'`\s>?#]+)/i);
|
|
3222
|
+
if (m2 && origins.size < 10) origins.add(`${(m2[1] ?? "https:").toLowerCase()}//${m2[2].toLowerCase()}`);
|
|
3223
|
+
};
|
|
3224
|
+
let inlineScripts = 0;
|
|
3225
|
+
const openTag = /<script\b([^>]{0,500})>/gi;
|
|
3226
|
+
let m;
|
|
3227
|
+
for (let seen = 0; (m = openTag.exec(html)) && seen < 100; seen++) {
|
|
3228
|
+
const attrs = m[1];
|
|
3229
|
+
const src = attrs.match(/\bsrc\s*=\s*["']?((?:https?:)?\/\/[^"'\s>]+)/i);
|
|
3230
|
+
if (src) {
|
|
3231
|
+
addOrigin(src[1]);
|
|
3232
|
+
continue;
|
|
3233
|
+
}
|
|
3234
|
+
if (/\bsrc\s*=/i.test(attrs)) continue;
|
|
3235
|
+
const close = html.indexOf("</script", openTag.lastIndex);
|
|
3236
|
+
const body = html.slice(openTag.lastIndex, close < 0 ? openTag.lastIndex + 5e4 : close);
|
|
3237
|
+
const type = (attrs.match(/\btype\s*=\s*["']?([^"'\s>]+)/i)?.[1] ?? "").toLowerCase();
|
|
3238
|
+
const runs = type === "" || type === "module" || type === "importmap" || /^(?:text|application)\/(?:x-)?(?:java|ecma)script$/.test(type);
|
|
3239
|
+
if (!runs || !body.trim()) continue;
|
|
3240
|
+
inlineScripts++;
|
|
3241
|
+
const urls = type === "importmap" ? body.matchAll(/["']((?:https?:)?\/\/[^"'\s]+)["']/g) : type === "module" ? body.matchAll(/(?:\bfrom|\bimport\s*\(?)\s*["'`]((?:https?:)?\/\/[^"'`\s]+)["'`]/g) : [];
|
|
3242
|
+
for (const u of urls) addOrigin(u[1]);
|
|
3243
|
+
}
|
|
2661
3244
|
const scriptSrc = ["'self'", ...origins].join(" ");
|
|
2662
3245
|
return [
|
|
2663
3246
|
`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.`,
|
|
@@ -3410,8 +3993,29 @@ var complianceMap = {
|
|
|
3410
3993
|
// VC213–VC214: account state held in browser storage
|
|
3411
3994
|
VC213: { owasp: "A01:2021", cwe: "CWE-602" },
|
|
3412
3995
|
// entitlement from web storage (client-side enforcement)
|
|
3413
|
-
VC214: { owasp: "A04:2021", cwe: "CWE-1188" }
|
|
3996
|
+
VC214: { owasp: "A04:2021", cwe: "CWE-1188" },
|
|
3414
3997
|
// per-account state from web storage (insecure default state)
|
|
3998
|
+
// VC215: Supabase migration lint — RLS off, always-true write policy, user_metadata in a policy
|
|
3999
|
+
VC215: { owasp: "A01:2021", cwe: "CWE-732" },
|
|
4000
|
+
// incorrect permission assignment for a critical resource
|
|
4001
|
+
VC216: { owasp: "A01:2021", cwe: "CWE-732" },
|
|
4002
|
+
// Firebase rules: open, any-signed-in-user, or test mode
|
|
4003
|
+
// VC217: AI or secret key shipped to the browser
|
|
4004
|
+
VC217: { owasp: "A07:2021", cwe: "CWE-798" },
|
|
4005
|
+
// key inlined into the client bundle (as VC066 / VC149)
|
|
4006
|
+
VC220: { owasp: "A01:2021", cwe: "CWE-862" },
|
|
4007
|
+
// unauthenticated AI/LLM proxy (denial of wallet); same class as VC003
|
|
4008
|
+
// VC218–VC219: caller identity never checked, or checked against data the caller controls
|
|
4009
|
+
VC218: { owasp: "A01:2021", cwe: "CWE-862" },
|
|
4010
|
+
// Base44 asServiceRole with no caller check (missing authorization, as VC003)
|
|
4011
|
+
VC219: { owasp: "A01:2021", cwe: "CWE-269" },
|
|
4012
|
+
// role/plan from user_metadata / unsafeMetadata (improper privilege management)
|
|
4013
|
+
VC221: { owasp: "A07:2021", cwe: "CWE-347" },
|
|
4014
|
+
// server trusts unverified session / decoded JWT
|
|
4015
|
+
VC222: { owasp: "A05:2021", cwe: "CWE-942" },
|
|
4016
|
+
// Python CORS wildcard with credentials (origin echoed)
|
|
4017
|
+
VC223: { owasp: "A01:2021", cwe: "CWE-22" }
|
|
4018
|
+
// prefix-only path containment check (startsWith without separator)
|
|
3415
4019
|
};
|
|
3416
4020
|
var consoleLogProduction = {
|
|
3417
4021
|
id: "VC097",
|
|
@@ -3596,15 +4200,15 @@ function runCustomRules(content, filePath, disabledRules = [], tier = "free", ex
|
|
|
3596
4200
|
|
|
3597
4201
|
// src/rule-counts.ts
|
|
3598
4202
|
var FREE_RULE_COUNT = 30;
|
|
3599
|
-
var PRO_RULE_COUNT =
|
|
3600
|
-
var TOTAL_RULE_COUNT =
|
|
4203
|
+
var PRO_RULE_COUNT = 193;
|
|
4204
|
+
var TOTAL_RULE_COUNT = 223;
|
|
3601
4205
|
|
|
3602
4206
|
// src/ai-fp-filter.ts
|
|
3603
4207
|
var import_sdk = __toESM(require("@anthropic-ai/sdk"), 1);
|
|
3604
4208
|
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.
|
|
3605
4209
|
|
|
3606
4210
|
Common false positive patterns you should catch:
|
|
3607
|
-
- Auth check exists inside the function body (requireUser, requireUserForApi,
|
|
4211
|
+
- 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
|
|
3608
4212
|
- The flagged pattern is in example/documentation/tutorial code, not production code
|
|
3609
4213
|
- The variable is developer-controlled (constants, config values, static strings), not user input
|
|
3610
4214
|
- The flagged function is a database method (conn.exec, db.exec, prisma.$executeRaw) not a shell command (child_process.exec)
|
|
@@ -3892,10 +4496,18 @@ var SAFE_PATTERNS = [
|
|
|
3892
4496
|
// double-flag these. They are designed to ship to the browser.
|
|
3893
4497
|
/^pk_(?:live|test|[a-z0-9]+)_/,
|
|
3894
4498
|
// Stripe / Clerk publishable
|
|
4499
|
+
// A string that IS an env-var name — `required: ["VITE_SUPABASE_URL", …]`.
|
|
4500
|
+
// This tests the VALUE, never the variable it is assigned to: a secret held
|
|
4501
|
+
// in a public-prefixed variable is decided by classifyPublicEnvVar below.
|
|
3895
4502
|
/^NEXT_PUBLIC_|^VITE_|^REACT_APP_/,
|
|
3896
|
-
// Build-time public env vars
|
|
3897
4503
|
/^pub_/,
|
|
3898
4504
|
// Segment etc.
|
|
4505
|
+
// dotenvx ciphertext: `STRIPE_SECRET_KEY="encrypted:BE9Y…"`. dotenvx
|
|
4506
|
+
// encrypts each value to the file's public key (ECIES); the private key
|
|
4507
|
+
// stays in the git-ignored .env.keys, and committing the encrypted file is
|
|
4508
|
+
// the documented workflow (Supabase's own dotenvx example does). The value
|
|
4509
|
+
// is not usable without that key, so it is not a leaked secret.
|
|
4510
|
+
/^encrypted:[A-Za-z0-9+/=]{20,}$/,
|
|
3899
4511
|
/^ey[A-Za-z0-9_-]+\.ey[A-Za-z0-9_-]+\./,
|
|
3900
4512
|
// JWT header.payload prefix — don't flag solely on entropy
|
|
3901
4513
|
// Content-Security-Policy hashes / nonces in HTML/JSON
|
|
@@ -3922,6 +4534,8 @@ var VERIFICATION_BLOCK_RE = /\bverification\s*:\s*\{/;
|
|
|
3922
4534
|
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;
|
|
3923
4535
|
var VERIFICATION_META_RE = /<meta[^>]+name\s*=\s*["'][^"']*(?:site-verification|domain-verification|msvalidate|domain_verify)[^"']*["']/i;
|
|
3924
4536
|
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;
|
|
4537
|
+
var DOTENV_EXAMPLE_RE = /\.(?:example|sample|template|dist|defaults?)$/i;
|
|
4538
|
+
var MAX_DOTENV_VALUE = 256;
|
|
3925
4539
|
function getSnippet2(content, line) {
|
|
3926
4540
|
const lines = content.split("\n");
|
|
3927
4541
|
const start = Math.max(0, line - 2);
|
|
@@ -3944,6 +4558,7 @@ function scanEntropy(files) {
|
|
|
3944
4558
|
if (/pro-rules-bundle|\.bundle\.|\.chunk\./i.test(filePath)) continue;
|
|
3945
4559
|
if (/(?:\.test\.|\.spec\.|__tests__|__mocks__|fixtures?\/)/i.test(filePath)) continue;
|
|
3946
4560
|
const vendored = isVendoredPath(filePath);
|
|
4561
|
+
const dotenv = isDotenvPath(filePath) && !DOTENV_EXAMPLE_RE.test(filePath);
|
|
3947
4562
|
const lines = content.split("\n");
|
|
3948
4563
|
let verificationDepth = -1;
|
|
3949
4564
|
let braceDepth = 0;
|
|
@@ -3962,14 +4577,27 @@ function scanEntropy(files) {
|
|
|
3962
4577
|
const inVerificationBlock = verificationDepth !== -1;
|
|
3963
4578
|
const trimmed = line.trimStart();
|
|
3964
4579
|
if (trimmed.startsWith("//") || trimmed.startsWith("#") || trimmed.startsWith("*") || trimmed.startsWith("/*")) continue;
|
|
3965
|
-
const
|
|
3966
|
-
|
|
3967
|
-
|
|
3968
|
-
|
|
4580
|
+
const candidates = [];
|
|
4581
|
+
const assign = dotenv ? DOTENV_ASSIGN_RE.exec(line) : null;
|
|
4582
|
+
const assignValue = assign ? dotenvValue(assign[2]) : "";
|
|
4583
|
+
const structured = assign !== null && (assignValue.length > MAX_DOTENV_VALUE || /^[{[]/.test(assignValue));
|
|
4584
|
+
if (assign && !structured) {
|
|
4585
|
+
if (assignValue.length >= 20) {
|
|
4586
|
+
candidates.push({ value: assignValue, beforeAssign: assign[1], dotenvName: assign[1] });
|
|
4587
|
+
}
|
|
4588
|
+
} else {
|
|
4589
|
+
const stringPattern = /(?:[:=]\s*)(["'`])([^"'`\n]{20,120})\1/g;
|
|
4590
|
+
let match;
|
|
4591
|
+
while ((match = stringPattern.exec(line)) !== null) {
|
|
4592
|
+
let beforeAssign = line.substring(0, match.index);
|
|
4593
|
+
if (structured) beforeAssign = beforeAssign.slice(Math.max(beforeAssign.lastIndexOf(","), beforeAssign.lastIndexOf("{")) + 1);
|
|
4594
|
+
candidates.push({ value: match[2], beforeAssign });
|
|
4595
|
+
}
|
|
4596
|
+
}
|
|
4597
|
+
for (const { value, beforeAssign, dotenvName } of candidates) {
|
|
3969
4598
|
if (value.includes("${")) continue;
|
|
3970
4599
|
if (SAFE_PATTERNS.some((p) => p.test(value))) continue;
|
|
3971
4600
|
if (HASH_PREFIX_RE.test(value)) continue;
|
|
3972
|
-
const beforeAssign = line.substring(0, match.index);
|
|
3973
4601
|
if (SAFE_VAR_NAMES.test(beforeAssign)) continue;
|
|
3974
4602
|
if (/^https?:\/\/[^:@]*$/.test(value)) continue;
|
|
3975
4603
|
if ((value.match(/\s/g) || []).length > 2) continue;
|
|
@@ -3981,11 +4609,15 @@ function scanEntropy(files) {
|
|
|
3981
4609
|
if (value.length < 20) continue;
|
|
3982
4610
|
const entropy = shannonEntropy(value);
|
|
3983
4611
|
if (entropy < threshold) continue;
|
|
3984
|
-
const varName = beforeAssign.match(/["']([^"']+)["']\s*$/)?.[1] || beforeAssign.match(/([\w$-]+)\s*$/)?.[1] || "";
|
|
4612
|
+
const varName = dotenvName || beforeAssign.match(/["']([^"']+)["']\s*$/)?.[1] || beforeAssign.match(/([\w$-]+)\s*$/)?.[1] || "";
|
|
3985
4613
|
if (inVerificationBlock && VERIFICATION_KEY_NAMES.test(varName)) continue;
|
|
3986
4614
|
if (VERIFICATION_META_RE.test(line)) continue;
|
|
3987
4615
|
if (HASH_LIKE_VAR_NAMES.test(varName) && (isHex || isBase64)) continue;
|
|
3988
|
-
|
|
4616
|
+
if (/^DOTENV_PUBLIC_KEY(?:_\w{1,60})?$/.test(varName) && /^0[23][0-9a-fA-F]{64}$/.test(value)) continue;
|
|
4617
|
+
const publicEnv = classifyPublicEnvVar(varName, value);
|
|
4618
|
+
if (publicEnv && publicEnv.publicByDesign) continue;
|
|
4619
|
+
if (dotenvName && /(?:^|_)IDS?$/i.test(dotenvName) && !SECRET_VAR_NAMES.test(dotenvName)) continue;
|
|
4620
|
+
const isLikelySecret = SECRET_VAR_NAMES.test(varName) || publicEnv?.secret === true;
|
|
3989
4621
|
if (entropy < 4.5 && !isLikelySecret) continue;
|
|
3990
4622
|
if (isLineSilenced(lines, i, "ENTROPY")) continue;
|
|
3991
4623
|
const masked = value.substring(0, 6) + "..." + value.substring(value.length - 4);
|
|
@@ -3999,7 +4631,10 @@ function scanEntropy(files) {
|
|
|
3999
4631
|
file: filePath,
|
|
4000
4632
|
line: i + 1,
|
|
4001
4633
|
snippet: getSnippet2(content, i + 1),
|
|
4002
|
-
|
|
4634
|
+
// The generic advice ("move it to an environment variable") is
|
|
4635
|
+
// wrong for a value that is already in one, so dotenv findings get
|
|
4636
|
+
// advice about the file, and public-prefixed ones about the prefix.
|
|
4637
|
+
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.",
|
|
4003
4638
|
category: "Secrets",
|
|
4004
4639
|
source: "custom",
|
|
4005
4640
|
owasp: "A02:2021",
|
|
@@ -7697,6 +8332,7 @@ function scanQuality(input, rules = qualityRules) {
|
|
|
7697
8332
|
// Annotate the CommonJS export names for ESM import in node:
|
|
7698
8333
|
0 && (module.exports = {
|
|
7699
8334
|
CHECKABLE_CLAIMS,
|
|
8335
|
+
DOTENV_ASSIGN_RE,
|
|
7700
8336
|
FREE_RULE_COUNT,
|
|
7701
8337
|
INTENT_EXPECTATIONS,
|
|
7702
8338
|
MODEL_ANALYSIS,
|
|
@@ -7706,6 +8342,7 @@ function scanQuality(input, rules = qualityRules) {
|
|
|
7706
8342
|
MODEL_TRIAGE,
|
|
7707
8343
|
NON_APP_PATH_PATTERNS,
|
|
7708
8344
|
PRO_RULE_COUNT,
|
|
8345
|
+
PUBLIC_ENV_PREFIX_RE,
|
|
7709
8346
|
QUALITY_EXAMPLES,
|
|
7710
8347
|
RULE_IMPACTS,
|
|
7711
8348
|
TEST_FILE_PATTERN,
|
|
@@ -7720,6 +8357,7 @@ function scanQuality(input, rules = qualityRules) {
|
|
|
7720
8357
|
callSpreads,
|
|
7721
8358
|
checkIntent,
|
|
7722
8359
|
classifyExposure,
|
|
8360
|
+
classifyPublicEnvVar,
|
|
7723
8361
|
classifyStatement,
|
|
7724
8362
|
clientSideAuth,
|
|
7725
8363
|
complianceMap,
|
|
@@ -7731,6 +8369,7 @@ function scanQuality(input, rules = qualityRules) {
|
|
|
7731
8369
|
detectFramework,
|
|
7732
8370
|
detectPlatform,
|
|
7733
8371
|
disabledTLSVerification,
|
|
8372
|
+
dotenvValue,
|
|
7734
8373
|
emptyCatchBlock,
|
|
7735
8374
|
enclosingHandler,
|
|
7736
8375
|
envNotGitignored,
|
|
@@ -7756,6 +8395,7 @@ function scanQuality(input, rules = qualityRules) {
|
|
|
7756
8395
|
isCalleeNamed,
|
|
7757
8396
|
isClientTarget,
|
|
7758
8397
|
isCommentLine,
|
|
8398
|
+
isDotenvPath,
|
|
7759
8399
|
isInlineSilenced,
|
|
7760
8400
|
isInsideFixMessage,
|
|
7761
8401
|
isLineSilenced,
|
|
@@ -7769,6 +8409,7 @@ function scanQuality(input, rules = qualityRules) {
|
|
|
7769
8409
|
lineNumberAt,
|
|
7770
8410
|
lineTextAt,
|
|
7771
8411
|
maskComments,
|
|
8412
|
+
maskOutboundAuthNoise,
|
|
7772
8413
|
missingAuthMiddleware,
|
|
7773
8414
|
missingCSP,
|
|
7774
8415
|
missingErrorBoundary,
|
|
@@ -7781,6 +8422,7 @@ function scanQuality(input, rules = qualityRules) {
|
|
|
7781
8422
|
parseScanTarget,
|
|
7782
8423
|
parseSupabaseConfig,
|
|
7783
8424
|
qualityRules,
|
|
8425
|
+
replaceBlockComments,
|
|
7784
8426
|
routeForFile,
|
|
7785
8427
|
runCustomRules,
|
|
7786
8428
|
scanEntropy,
|