greenlitlab 0.5.4 → 0.6.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/CHANGELOG.md +20 -0
- package/README.md +4 -1
- package/bin/greenlit.mjs +8 -1
- package/package.json +2 -1
- package/server.json +2 -2
- package/src/plain.mjs +15 -2
- package/src/scan-files.mjs +1097 -0
- package/src/scan.mjs +97 -748
|
@@ -0,0 +1,1097 @@
|
|
|
1
|
+
// greenlitlab's project scan over files held in memory: scanFiles(files, opts).
|
|
2
|
+
// It looks in a project's own files for the launch mistakes that can't be seen from outside: rules that let everyone
|
|
3
|
+
// in, functions that skip the sign-in check, payment messages nobody verifies, secrets that ship to the browser. It
|
|
4
|
+
// reads no disk, runs no git and makes no network call, so it also runs where there is no filesystem (a Cloudflare
|
|
5
|
+
// Worker). Names in .env files are reported, never values; a key found in code is reported by its kind and place,
|
|
6
|
+
// never by its value. src/scan.mjs reads a folder on this computer into the same Map (readFolder) for the command line.
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import crypto from "node:crypto";
|
|
9
|
+
|
|
10
|
+
// Build output, dependencies and agents' working copies. Test folders are skipped too (their made-up secrets and
|
|
11
|
+
// tables aren't the app's), except a "test" folder inside a route tree, which is a real page.
|
|
12
|
+
const SKIP = new Set(["node_modules", ".claude", "worktrees", "__tests__", "__mocks__", "__fixtures__", "fixtures", "e2e", "cypress", ".git", "dist", "build", ".next", ".nuxt", ".svelte-kit", ".output", ".vercel", ".netlify", ".wrangler", "coverage", ".turbo", ".cache", "vendor", "__pycache__", ".venv", "venv", ".expo", "ios", "android", "Pods"]);
|
|
13
|
+
const TEST_DIRS = new Set(["test", "tests", "spec", "specs"]);
|
|
14
|
+
const TEXT = /\.(sql|toml|json|jsonc|js|jsx|ts|tsx|mjs|cjs|py|vue|svelte|astro|rules|ya?ml)$|(^|\/)(\.env[^/]*|\.dev\.vars)$/;
|
|
15
|
+
// Folders read first, so a cap never lands on the files that matter most.
|
|
16
|
+
const FIRST = new Set(["supabase", "migrations", "src", "app", "functions", "api", "server", "lib", "pages", "components", "db", "database", "firebase"]);
|
|
17
|
+
const MAX_FILES = 20000;
|
|
18
|
+
const BIG = 1024 * 1024;
|
|
19
|
+
const PUBLIC_PREFIX = "(?:VITE_|NEXT_PUBLIC_|REACT_APP_|EXPO_PUBLIC_|PUBLIC_|NUXT_PUBLIC_|GATSBY_|STORYBOOK_)";
|
|
20
|
+
// The name must END in the secret word: VITE_STRIPE_SECRET_KEY is a secret, VITE_PASSWORD_MIN_LENGTH is a setting.
|
|
21
|
+
const SECRET_NAME = new RegExp(`\\b(${PUBLIC_PREFIX}[A-Z0-9_]*?(?:SECRET(?:_ACCESS)?(?:_KEY|_TOKEN)?|SERVICE_ROLE(?:_KEY)?|SERVICE_KEY|PRIVATE_KEY|PASSWORD|DATABASE_URL|DB_URL|POSTGRES_URL))(?![A-Z0-9_])`, "g");
|
|
22
|
+
// A key for a paid service behind a public prefix (VITE_OPENAI_API_KEY) is the same mistake under another name.
|
|
23
|
+
// Keys made to be public (Stripe publishable, Supabase anon) are left out.
|
|
24
|
+
const PAID = "OPENAI|ANTHROPIC|CLAUDE|GEMINI|GOOGLE_AI|GOOGLE_GENAI|GROQ|OPENROUTER|MISTRAL|PERPLEXITY|REPLICATE|HUGGINGFACE|HF|DEEPSEEK|XAI|GROK|COHERE|TOGETHER|FIREWORKS|ELEVENLABS|DEEPGRAM|ASSEMBLYAI|PINECONE|VOYAGE|FAL|RUNWAY|STABILITY|TAVILY|SERPAPI|FIRECRAWL|EXA|RESEND|SENDGRID|MAILGUN|POSTMARK|BREVO|TWILIO|GITHUB|STRIPE|PAYPAL|RAZORPAY|LEMONSQUEEZY|LEMON_SQUEEZY|PADDLE|AWS|NOTION|AIRTABLE|SLACK|DISCORD|TELEGRAM|SHOPIFY|HUBSPOT|MAPBOX_SECRET|ALGOLIA_ADMIN|UPSTASH";
|
|
25
|
+
const PAID_KEY_NAME = new RegExp(`\\b(${PUBLIC_PREFIX}(?![A-Z0-9_]*(?:PUBLISHABLE|_PK(?:_|$)|PUBLIC_KEY|ANON|CLIENT_ID|SITE_KEY|APP_ID|PROJECT_ID|ACCOUNT_ID|MEASUREMENT|STOREFRONT))[A-Z0-9_]*?(?:${PAID})[A-Z0-9_]*?(?:KEY|TOKEN))(?![A-Z0-9_])`, "g");
|
|
26
|
+
const SAMPLE_PATH = /(^|\/)(examples?|fixtures?|__fixtures__|test-fixtures|testdata|__tests__)\/|^tests?\//i;
|
|
27
|
+
const TEST_FILE = /(^|\/)test_[^/]*\.py$|_test\.(py|go|rb)$/i;
|
|
28
|
+
// WITH (security_invoker) with no value means on, the same as security_invoker = true.
|
|
29
|
+
const INVOKER = /security_invoker\s*(=\s*(on|true|1|yes)\b|[,)])/i;
|
|
30
|
+
// A folder of SQL written for MySQL or SQLite: one file with their syntax marks the whole folder.
|
|
31
|
+
const NOT_PG = /\bAUTO_?INCREMENT\b|\bENGINE\s*=|\bPRAGMA\s|\bWITHOUT\s+ROWID\b|\bINSERT\s+OR\s+(IGNORE|REPLACE)\b|datetime\(\s*'now'|\bsqlite\b/i;
|
|
32
|
+
const LOCKFILE = /(^|\/)(package-lock\.json|pnpm-lock\.yaml|yarn\.lock|bun\.lock|composer\.lock)$/;
|
|
33
|
+
// Files that, left unread, leave a hole in the answer: a partial read is reported, never passed as clean.
|
|
34
|
+
const MATTERS = /\.(sql|rules|toml)$|(^|\/)(firebase|database\.rules)\.json$/;
|
|
35
|
+
// Committed .env files worth a look (examples, templates and test copies hold no real values).
|
|
36
|
+
const TRACKED_ENV = (f) => /(^|\/)(\.env(\.[\w.-]+)?|\.dev\.vars)$/.test(f) && !/\.(example|sample|template|defaults?|dist|schema|fixture|test)$/.test(f) && !SAMPLE_PATH.test(f);
|
|
37
|
+
// The build output folders, which hold what ships to every visitor.
|
|
38
|
+
const BUILT = ["dist", "build", "out", ".next/static"];
|
|
39
|
+
const BUNDLE_FILE = /\.(m?js|cjs|html|json)$/;
|
|
40
|
+
const BUNDLE_MAX_FILES = 2000;
|
|
41
|
+
const BUNDLE_MAX_BYTES = 8e6;
|
|
42
|
+
// Function code that might check a signature or the signed-in user itself.
|
|
43
|
+
const FUNCTION_FILE = /\.(ts|js|mjs)$/;
|
|
44
|
+
|
|
45
|
+
// What readFolder needs to read a folder the way scanFiles reads the Map: the same folders skipped, the same text
|
|
46
|
+
// files, the same caps. Not part of the public interface.
|
|
47
|
+
export const READ_RULES = Object.freeze({ SKIP, TEST_DIRS, TEXT, FIRST, MAX_FILES, BIG, LOCKFILE, TRACKED_ENV, BUILT, BUNDLE_FILE, BUNDLE_MAX_FILES, BUNDLE_MAX_BYTES, FUNCTION_FILE, LAZY: Symbol.for("greenlitlab.scanFiles.lazy") });
|
|
48
|
+
|
|
49
|
+
// ---------- Contents in the Map: a string, bytes, or null (the file is there but its content wasn't loaded)
|
|
50
|
+
const UTF8 = typeof TextDecoder === "undefined" ? null : new TextDecoder("utf-8", { ignoreBOM: true });
|
|
51
|
+
const textOf = (v) => (typeof v === "string" ? v : typeof Buffer !== "undefined" ? Buffer.from(v.buffer, v.byteOffset, v.byteLength).toString("utf8") : UTF8.decode(v));
|
|
52
|
+
const fromBase64url = (s) => (typeof Buffer !== "undefined" ? Buffer.from(s, "base64url").toString("utf8") : textOf(Uint8Array.from(atob(s.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(s.length / 4) * 4, "=")), (c) => c.charCodeAt(0))));
|
|
53
|
+
const sizeOf = (v) => (typeof v === "string" ? (typeof Buffer !== "undefined" ? Buffer.byteLength(v, "utf8") : new TextEncoder().encode(v).length) : v.byteLength);
|
|
54
|
+
// A name written in a comment (a doc line, a commented-out example) ships nothing to the browser.
|
|
55
|
+
function inComment(text, index) {
|
|
56
|
+
const start = text.lastIndexOf("\n", index - 1) + 1;
|
|
57
|
+
const before = text.slice(start, index);
|
|
58
|
+
return /^\s*(\*|\/\*|\/\/|#|--|<!--)/.test(before) || /(^|[^:"'`])\/\/[^"'`]*$/.test(before);
|
|
59
|
+
}
|
|
60
|
+
// Keys recognised by their shape, wherever they're written. Only the kind and the place are ever reported.
|
|
61
|
+
const KEY_SHAPES = [
|
|
62
|
+
["a live Stripe secret key", /\b[rs]k_live_[0-9A-Za-z]{10,}/g],
|
|
63
|
+
["a Stripe webhook signing secret", /\bwhsec_[0-9A-Za-z]{20,}/g],
|
|
64
|
+
["an OpenAI key", /\bsk-(?:proj|svcacct|admin)-[A-Za-z0-9_-]{16,}|\bsk-[A-Za-z0-9]{40,}\b/g],
|
|
65
|
+
["an Anthropic key", /\bsk-ant-(?:api|admin)\d{2}-[A-Za-z0-9_-]{20,}/g],
|
|
66
|
+
["an OpenRouter key", /\bsk-or-v1-[a-f0-9]{32,}/g],
|
|
67
|
+
["a Groq key", /\bgsk_[A-Za-z0-9]{40,}/g],
|
|
68
|
+
["an xAI key", /\bxai-[A-Za-z0-9]{40,}/g],
|
|
69
|
+
["a Replicate token", /\br8_[A-Za-z0-9]{30,}/g],
|
|
70
|
+
["a Hugging Face token", /\bhf_[A-Za-z0-9]{30,}/g],
|
|
71
|
+
["an AWS access key", /\bAKIA[0-9A-Z]{16}\b/g],
|
|
72
|
+
["a GitHub token", /\bgh[pousr]_[A-Za-z0-9]{36}\b|\bgithub_pat_[A-Za-z0-9_]{40,}/g],
|
|
73
|
+
["a Slack token", /\bxox[baprs]-[A-Za-z0-9-]{10,}/g],
|
|
74
|
+
["a SendGrid key", /\bSG\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}/g],
|
|
75
|
+
["a Resend key", /\bre_[A-Za-z0-9]{8,}_[A-Za-z0-9]{16,}/g],
|
|
76
|
+
["a Supabase access token", /\bsbp_[a-f0-9]{40}\b/g],
|
|
77
|
+
["a private key", /-----BEGIN (?:RSA |EC |OPENSSH |DSA |ENCRYPTED )?PRIVATE KEY-----(?:\s|\\n|\\r)*[A-Za-z0-9+\/]{40,}/g],
|
|
78
|
+
];
|
|
79
|
+
const PLACEHOLDER = /x{4,}|\.\.\.|your[_-]|example|placeholder|dummy|<|\*{3,}|changeme|replace/i;
|
|
80
|
+
// A table or policy target the way SQL writes it: orders, public.orders, "public"."orders".
|
|
81
|
+
// A quoted name keeps its case and may hold any character ("my-table", "Orders"); an unquoted one is folded to lower
|
|
82
|
+
// case, as Postgres does. Read the captured parts with ident().
|
|
83
|
+
const NAME = String.raw`(?:"(?:[^"]|"")+"|\w+)`;
|
|
84
|
+
const IDENT = String.raw`(?:(${NAME})\s*\.\s*)?(${NAME})`;
|
|
85
|
+
// Names are matched exactly as Postgres reads them: a quoted name as written ("orders " and "orders" are two tables),
|
|
86
|
+
// an unquoted one folded to lower case. Only the text shown is cleaned: shown() turns anything that could move the
|
|
87
|
+
// cursor, recolour a terminal or hide text (control characters, bidi and zero-width marks) into "?", so two different
|
|
88
|
+
// names never look the same, and shortens a long name with a hash of the whole so it stays distinct.
|
|
89
|
+
const UNSAFE = /[\u0000-\u001f\u007f-\u009f\u061c\u200b-\u200f\u2028-\u202e\u2060-\u2069\ufeff]/g;
|
|
90
|
+
const shown = (n) => {
|
|
91
|
+
const t = String(n).replace(UNSAFE, "?");
|
|
92
|
+
return t.length > 63 ? `${t.slice(0, 54)}…${crypto.createHash("sha1").update(String(n)).digest("hex").slice(0, 8)}` : t;
|
|
93
|
+
};
|
|
94
|
+
const ident = (raw) => (raw == null ? null : raw[0] === '"' ? raw.slice(1, -1).replace(/""/g, '"') : raw.toLowerCase());
|
|
95
|
+
const schemaOf = (raw) => (raw == null ? "public" : ident(raw));
|
|
96
|
+
// A table name written back into SQL in a fix: quoted when it has to be.
|
|
97
|
+
const sqlName = (n) => (/^[a-z_][a-z0-9_]*$/.test(n) ? n : `"${n.replace(/"/g, '""')}"`);
|
|
98
|
+
// The statements scanSql reads, built once. Each captures the schema and the name as IDENT does.
|
|
99
|
+
const SQL = {
|
|
100
|
+
createTable: new RegExp(String.raw`^\s*create\s+(?:(?:global|local)\s+)?(?:temp(?:orary)?\s+|unlogged\s+)?table\s+(?:if\s+not\s+exists\s+)?${IDENT}`, "i"),
|
|
101
|
+
alterRls: new RegExp(String.raw`^\s*alter\s+table\s+(?:if\s+exists\s+)?(?:only\s+)?${IDENT}\s+(enable|disable)\s+row\s+level\s+security`, "i"),
|
|
102
|
+
rename: new RegExp(String.raw`^\s*alter\s+table\s+(?:if\s+exists\s+)?(?:only\s+)?${IDENT}\s+rename\s+to\s+(${NAME})`, "i"),
|
|
103
|
+
identAtStart: new RegExp(`^${IDENT}`),
|
|
104
|
+
literalRls: new RegExp(String.raw`'\s*alter\s+table\s+(?:if\s+exists\s+)?(?:only\s+)?${IDENT}\s+enable\s+row\s+level\s+security\s*;?\s*'`, "gi"),
|
|
105
|
+
createPolicy: new RegExp(String.raw`^\s*create\s+policy\s+(${NAME}|"[^"]*")\s+on\s+${IDENT}`, "i"),
|
|
106
|
+
alterPolicy: new RegExp(String.raw`^\s*alter\s+policy\s+(${NAME}|"[^"]*")\s+on\s+${IDENT}`, "i"),
|
|
107
|
+
renameTo: new RegExp(String.raw`^\s*rename\s+to\s+(${NAME}|"[^"]*")`, "i"),
|
|
108
|
+
dropPolicy: new RegExp(String.raw`^\s*drop\s+policy\s+(?:if\s+exists\s+)?(${NAME}|"[^"]*")\s+on\s+${IDENT}`, "i"),
|
|
109
|
+
createView: new RegExp(String.raw`^\s*create\s+(?:or\s+replace\s+)?(?:materialized\s+)?view\s+(?:if\s+not\s+exists\s+)?${IDENT}`, "i"),
|
|
110
|
+
alterView: new RegExp(String.raw`^\s*alter\s+view\s+(?:if\s+exists\s+)?${IDENT}\s+set\s*\(([^)]*)\)`, "i"),
|
|
111
|
+
revokeTable: new RegExp(String.raw`^\s*revoke\s+[\w\s,]*?\bon\s+(?:table\s+)?${IDENT}\s+from\s+([\w\s,]+)`, "i"),
|
|
112
|
+
revokeHead: /^\s*revoke\s+(?:all|execute)\b/i,
|
|
113
|
+
onFunction: /\bon\s+function\s+/gi,
|
|
114
|
+
identHere: new RegExp(IDENT, "y"),
|
|
115
|
+
fromRoles: /\bfrom\s+([\w\s,]+)/gi,
|
|
116
|
+
createFunction: new RegExp(String.raw`^\s*create\s+(?:or\s+replace\s+)?function\s+${IDENT}`, "i"),
|
|
117
|
+
};
|
|
118
|
+
// revoke … on function <name> … from <roles>: [whole, schema, name, roles], or null. Each search starts where the
|
|
119
|
+
// last one ended, so a long statement is read once (one regex with two lazy gaps took seconds on a 1 MB statement).
|
|
120
|
+
function revokeFunction(s) {
|
|
121
|
+
if (!SQL.revokeHead.test(s)) return null;
|
|
122
|
+
SQL.onFunction.lastIndex = 0;
|
|
123
|
+
for (let on; (on = SQL.onFunction.exec(s)); ) {
|
|
124
|
+
SQL.identHere.lastIndex = on.index + on[0].length;
|
|
125
|
+
const id = SQL.identHere.exec(s);
|
|
126
|
+
if (!id) continue;
|
|
127
|
+
SQL.fromRoles.lastIndex = SQL.identHere.lastIndex;
|
|
128
|
+
const from = SQL.fromRoles.exec(s);
|
|
129
|
+
return from ? [s.slice(0, from.index + from[0].length), id[1], id[2], from[1]] : null;
|
|
130
|
+
}
|
|
131
|
+
return null;
|
|
132
|
+
}
|
|
133
|
+
// A column name that says the table holds something about a person.
|
|
134
|
+
const PERSONAL_COLUMN = /\b(e_?mail|phone|mobile|password|passwd|address|street|postcode|zip_?code|birth|dob|ssn|national_id|passport|full_name|first_name|last_name|ip_address|salary|iban|card_number|medical|diagnosis)\b/i;
|
|
135
|
+
const SENSITIVE_BUCKET = /(^|[-_])(ids?|identity|identities|kyc|verif\w*|documents?|docs|passports?|licen[cs]es?|selfies?|private|secure|medical|health|invoices?|receipts?|contracts?|statements?|tax|payslips?|resumes?|cvs?|uploads?|attachments?|records?|backups?)([-_]|$)/i;
|
|
136
|
+
|
|
137
|
+
// Comments blanked out, keeping every character's position so line numbers stay right. With `strings`,
|
|
138
|
+
// text inside single quotes is blanked too: it is data or SQL run later, not a statement in this file.
|
|
139
|
+
// Double-quoted names are kept, so an apostrophe in a policy's name ("Users can't …") starts nothing.
|
|
140
|
+
const sqlBlank = (sql, strings = true) =>
|
|
141
|
+
sql.replace(/"(?:[^"]|"")*"|'(?:[^']|'')*'|\/\*[\s\S]*?\*\/|--[^\n]*/g, (m) => (m[0] === '"' ? m : m[0] === "'" ? (strings ? `'${m.slice(1, -1).replace(/[^\n]/g, " ")}'` : m) : m.replace(/[^\n]/g, " ")));
|
|
142
|
+
const noComments = (sql) => sqlBlank(sql, true);
|
|
143
|
+
const jsNoComments = (t) => t.replace(/("(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'|`(?:[^`\\]|\\.)*`)|\/\*[\s\S]*?\*\/|(^|[^:\\])\/\/[^\n]*/g, (m, str, pre) => (str ? m : pre != null ? pre + m.slice(pre.length).replace(/[^\n]/g, " ") : m.replace(/[^\n]/g, " ")));
|
|
144
|
+
const shortHash = (s) => crypto.createHash("sha1").update(s).digest("hex").slice(0, 8);
|
|
145
|
+
// The line a position falls on. lineOf is for one-off lookups; linesOf(text) answers many lookups in the same text
|
|
146
|
+
// (or in a copy with comments blanked, which keeps every newline in place) without rescanning it each time.
|
|
147
|
+
const lineOf = (text, index) => text.slice(0, index).split("\n").length;
|
|
148
|
+
function linesOf(text) {
|
|
149
|
+
let starts = null;
|
|
150
|
+
return (index) => {
|
|
151
|
+
if (index < 0) return lineOf(text, index);
|
|
152
|
+
if (!starts) {
|
|
153
|
+
starts = [];
|
|
154
|
+
for (let j = text.indexOf("\n"); j >= 0; j = text.indexOf("\n", j + 1)) starts.push(j);
|
|
155
|
+
}
|
|
156
|
+
let lo = 0;
|
|
157
|
+
let hi = starts.length;
|
|
158
|
+
while (lo < hi) {
|
|
159
|
+
const mid = (lo + hi) >> 1;
|
|
160
|
+
if (starts[mid] < index) lo = mid + 1;
|
|
161
|
+
else hi = mid;
|
|
162
|
+
}
|
|
163
|
+
return lo + 1; // newlines before index, plus one
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// Splits SQL into statements at semicolons, keeping $tag$ … $tag$ bodies whole. Linear in the file's length.
|
|
168
|
+
function statements(code) {
|
|
169
|
+
const out = [];
|
|
170
|
+
let start = 0;
|
|
171
|
+
let i = 0;
|
|
172
|
+
const n = code.length;
|
|
173
|
+
while (i < n) {
|
|
174
|
+
const c = code[i];
|
|
175
|
+
if (c === "$") {
|
|
176
|
+
const m = code.slice(i, i + 64).match(/^\$([A-Za-z_]\w*)?\$/);
|
|
177
|
+
if (m) {
|
|
178
|
+
const end = code.indexOf(m[0], i + m[0].length);
|
|
179
|
+
i = end < 0 ? n : end + m[0].length;
|
|
180
|
+
continue;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
if (c === ";") {
|
|
184
|
+
out.push({ text: code.slice(start, i), index: start });
|
|
185
|
+
start = i + 1;
|
|
186
|
+
}
|
|
187
|
+
i++;
|
|
188
|
+
}
|
|
189
|
+
if (code.slice(start).trim()) out.push({ text: code.slice(start), index: start });
|
|
190
|
+
return out;
|
|
191
|
+
}
|
|
192
|
+
// The text inside the parentheses that open at `from` (which must point at "(").
|
|
193
|
+
function parens(s, from) {
|
|
194
|
+
let depth = 0;
|
|
195
|
+
for (let j = from; j < s.length && j < from + 20000; j++) {
|
|
196
|
+
if (s[j] === "(") depth++;
|
|
197
|
+
else if (s[j] === ")" && --depth === 0) return s.slice(from + 1, j);
|
|
198
|
+
}
|
|
199
|
+
return null;
|
|
200
|
+
}
|
|
201
|
+
const clause = (stmt, word) => {
|
|
202
|
+
const m = stmt.match(new RegExp(`\\b${word}\\s*\\(`, "i"));
|
|
203
|
+
return m ? parens(stmt, m.index + m[0].length - 1) : null;
|
|
204
|
+
};
|
|
205
|
+
// Splits a condition at top-level OR / ||.
|
|
206
|
+
function disjuncts(expr) {
|
|
207
|
+
const parts = [];
|
|
208
|
+
let depth = 0;
|
|
209
|
+
let last = 0;
|
|
210
|
+
for (let j = 0; j < expr.length; j++) {
|
|
211
|
+
const c = expr[j];
|
|
212
|
+
if (c === "(") depth++;
|
|
213
|
+
else if (c === ")") depth--;
|
|
214
|
+
else if (depth === 0) {
|
|
215
|
+
if (/^\s+or\s/i.test(expr.slice(j, j + 5)) || expr.slice(j, j + 2) === "||") {
|
|
216
|
+
parts.push(expr.slice(last, j));
|
|
217
|
+
j += expr.slice(j, j + 2) === "||" ? 1 : 3;
|
|
218
|
+
last = j + 1;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
parts.push(expr.slice(last));
|
|
223
|
+
return parts.map((p) => p.trim().replace(/^\(+|\)+$/g, (x) => x).toLowerCase().replace(/\s+/g, " "));
|
|
224
|
+
}
|
|
225
|
+
const unwrapParens = (p) => {
|
|
226
|
+
let s = p.trim();
|
|
227
|
+
while (s.startsWith("(") && parens(s, 0) === s.slice(1, -1)) s = s.slice(1, -1).trim();
|
|
228
|
+
return s;
|
|
229
|
+
};
|
|
230
|
+
// "true", "1=1", "true or …": a condition that lets everyone through.
|
|
231
|
+
const ALWAYS = (d) => /^(true|'t'|'true'|1\s*=\s*1|true::bool(ean)?|not\s+false)$/.test(unwrapParens(d));
|
|
232
|
+
// A condition that only asks "is anyone signed in?": every signed-in user passes.
|
|
233
|
+
const ANY_SIGNED_IN = (d) => /^(\(?\s*(select\s+)?auth\.uid\s*\(\s*\)\s*\)?\s+is\s+not\s+null|\(?\s*(select\s+)?auth\.role\s*\(\s*\)\s*\)?\s*=\s*'authenticated'|\(?\s*(select\s+)?auth\.jwt\s*\(\s*\)\s*\)?\s+is\s+not\s+null|auth\.uid\s*\(\s*\)\s*<>\s*null)$/.test(unwrapParens(d));
|
|
234
|
+
|
|
235
|
+
// Whether a function's own code checks a webhook signature (Stripe, Svix/Resend/Clerk, GitHub, Lemon Squeezy, Paddle).
|
|
236
|
+
const SIGNATURE = /constructEvent(?:Async)?\s*\(|webhooks?\.verify\s*\(|new\s+Webhook\s*\([\s\S]*?\.verify\s*\(|x-hub-signature|x-signature|paddle-signature|timingSafeEqual|construct_event\s*\(/i;
|
|
237
|
+
|
|
238
|
+
// A function that checks the signed-in user in its own code (common when verify_jwt is off for the newer signing keys).
|
|
239
|
+
const CHECKS_USER = /\bauth\s*\.\s*getUser\s*\(|\bgetClaims\s*\(|\bjwtVerify\s*\(|\bverify(?:JWT|Jwt|Token)\s*\(|headers\.get\(\s*["'`]x-(?:api-key|cron-secret|webhook-secret)["'`]\s*\)|\bCRON_SECRET\b/i;
|
|
240
|
+
|
|
241
|
+
// Code that runs in the visitor's browser, judged by where it lives and what it says about itself.
|
|
242
|
+
function clientSide(name, text, project) {
|
|
243
|
+
if (/(^|\/)(api|server|backend|functions|netlify\/functions|supabase\/functions|scripts|workers?|cron|jobs|lib\/server|routes\/api|app\/api|pages\/api)\//.test(name)) return false;
|
|
244
|
+
if (/(^|\/)(route|middleware|\+server|\+page\.server|\+layout\.server|server)\.[jt]s$|\.(server|nitro|worker|cron|edge)\.[jt]sx?$/.test(name)) return false;
|
|
245
|
+
if (/^\s*["']use server["']/m.test(text)) return false;
|
|
246
|
+
if (/^\s*["']use client["']/m.test(text)) return true;
|
|
247
|
+
// Server functions (TanStack Start, SolidStart, Remix loaders) and anything reading process.env run on a server:
|
|
248
|
+
// a Vite build gives the browser import.meta.env, not process.env.
|
|
249
|
+
if (/\bcreateServerFn\b|\bcreateServerAction\b|\bcreateMiddleware\b|["']server-only["']|["']@tanstack\/(?:react-)?start\/server["']|\bexport\s+(?:async\s+)?function\s+(?:loader|action)\b/.test(text)) return false;
|
|
250
|
+
// Outside a single-page app, a file reading a non-public process.env value runs on a server. In a Vite or
|
|
251
|
+
// Create React App build it may still be bundled for the browser, so there it proves nothing.
|
|
252
|
+
if (!project.spa && /\bprocess\.env\.(?!NODE_ENV\b|REACT_APP_|NEXT_PUBLIC_|EXPO_PUBLIC_|VITE_|GATSBY_)[A-Z_]/.test(text)) return false;
|
|
253
|
+
if (/import\.meta\.env\b/.test(text)) return true;
|
|
254
|
+
if (/\.(vue|svelte|html)$/.test(name)) return true;
|
|
255
|
+
if (/\.astro$/.test(name)) return false; // frontmatter runs on the server
|
|
256
|
+
// In a single-page app (Vite, Create React App, Expo) everything under src/ or app/ ships to the browser or phone.
|
|
257
|
+
return project.spa && /^(src|app|components|pages|hooks|screens|public)\//.test(name);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// ---------- Which paths in the Map the scan reads: the same choice the folder walk makes
|
|
261
|
+
// Skips the same folders as the folder walk in scan.mjs (build output, dependencies, tests outside a route tree, other checkouts) and
|
|
262
|
+
// keeps the same text files. Paths outside the project ("../") and folder markers ("x/") are never scanned.
|
|
263
|
+
function picked(name, nested) {
|
|
264
|
+
if (!name || name.endsWith("/") || name.startsWith("/") || name.startsWith("../")) return false;
|
|
265
|
+
const parts = name.split("/");
|
|
266
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
267
|
+
const seg = parts[i];
|
|
268
|
+
if (!seg || seg === "." || seg === ".." || SKIP.has(seg)) return false;
|
|
269
|
+
if (TEST_DIRS.has(seg) && !/(^|\/)(app|pages|routes)(\/|$)/.test(parts.slice(0, i).join("/"))) return false;
|
|
270
|
+
}
|
|
271
|
+
if (nested.some((n) => name.startsWith(`${n}/`))) return false;
|
|
272
|
+
return TEXT.test(name);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// Whether the folder walk reaches a folder (to report it as another checkout): no skipped folder on the way to it,
|
|
276
|
+
// and not inside another checkout.
|
|
277
|
+
function reachable(dir, nested) {
|
|
278
|
+
const parts = dir.split("/");
|
|
279
|
+
for (let i = 0; i < parts.length; i++) {
|
|
280
|
+
if (!parts[i] || parts[i] === "." || parts[i] === ".." || SKIP.has(parts[i])) return false;
|
|
281
|
+
if (TEST_DIRS.has(parts[i]) && !/(^|\/)(app|pages|routes)(\/|$)/.test(parts.slice(0, i).join("/"))) return false;
|
|
282
|
+
}
|
|
283
|
+
return !nested.some((n) => dir.startsWith(`${n}/`));
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// A folder tree built from paths, for walking them in the order a disk walk would (names in order, depth first).
|
|
287
|
+
function treeOf(names, strip = 0) {
|
|
288
|
+
const root = { dirs: new Map(), files: [] };
|
|
289
|
+
for (const n of names) {
|
|
290
|
+
const parts = n.slice(strip).split("/");
|
|
291
|
+
let node = root;
|
|
292
|
+
for (let i = 0; i < parts.length - 1; i++) {
|
|
293
|
+
if (!node.dirs.has(parts[i])) node.dirs.set(parts[i], { dirs: new Map(), files: [] });
|
|
294
|
+
node = node.dirs.get(parts[i]);
|
|
295
|
+
}
|
|
296
|
+
node.files.push([parts[parts.length - 1], n]);
|
|
297
|
+
}
|
|
298
|
+
return root;
|
|
299
|
+
}
|
|
300
|
+
const entriesOf = (node) => [...node.files, ...node.dirs].sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
|
|
301
|
+
|
|
302
|
+
// Over MAX_FILES, the files the folder walk would reach first: the FIRST folders before the rest, as on disk.
|
|
303
|
+
function firstFiles(names) {
|
|
304
|
+
const out = [];
|
|
305
|
+
const stack = [treeOf(names)];
|
|
306
|
+
while (stack.length) {
|
|
307
|
+
const later = [];
|
|
308
|
+
const first = [];
|
|
309
|
+
for (const [name, v] of entriesOf(stack.pop())) {
|
|
310
|
+
if (typeof v === "string") {
|
|
311
|
+
if (out.length >= MAX_FILES) return out;
|
|
312
|
+
out.push(v);
|
|
313
|
+
} else (FIRST.has(name) ? first : later).push(v);
|
|
314
|
+
}
|
|
315
|
+
stack.push(...later, ...first);
|
|
316
|
+
}
|
|
317
|
+
return out;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// ---------- What scanFiles accepts
|
|
321
|
+
// readFolder fills its Map with this marker instead of a file's bytes, plus a reader on the Map under the same symbol,
|
|
322
|
+
// so the command line holds one file at a time rather than the whole project. Not part of the public interface.
|
|
323
|
+
const LAZY = Symbol.for("greenlitlab.scanFiles.lazy");
|
|
324
|
+
// The limits a hosted check runs under unless the caller sets its own. readFolder (the command line) sets none.
|
|
325
|
+
// Bytes are counted rather than time because some hosts (a Cloudflare Worker) stop the clock while code runs.
|
|
326
|
+
export const HOSTED_LIMITS = Object.freeze({ maxFindings: 1000, maxBytes: 64 * 1024 * 1024, deadlineMs: 20000 });
|
|
327
|
+
|
|
328
|
+
// A file's content as the scan uses it: a string, bytes, or null. Anything else is the caller's mistake, reported
|
|
329
|
+
// before the scan starts and naming the file.
|
|
330
|
+
function contentOf(name, v, files) {
|
|
331
|
+
if (v == null || typeof v === "string" || v instanceof Uint8Array) return v ?? null;
|
|
332
|
+
if (v instanceof ArrayBuffer) return new Uint8Array(v);
|
|
333
|
+
if (ArrayBuffer.isView(v)) return new Uint8Array(v.buffer, v.byteOffset, v.byteLength);
|
|
334
|
+
if (v === LAZY && typeof files?.[LAZY] === "function") return v;
|
|
335
|
+
throw new TypeError(`scanFiles: the content of ${JSON.stringify(name)} must be a string, a Uint8Array, an ArrayBuffer or null, not ${v === null ? "null" : typeof v}`);
|
|
336
|
+
}
|
|
337
|
+
// A path as the scan uses it: "/" only, no leading "./", no control characters. A path that leaves the project
|
|
338
|
+
// (an absolute path, or ".." inside it) is dropped with the reason. Leading "../" is kept: that is how a tracked .env
|
|
339
|
+
// above the project folder is sent (see opts.prefix), and it is never scanned as code.
|
|
340
|
+
function pathOf(raw) {
|
|
341
|
+
if (typeof raw !== "string") return { reason: "the path isn't a string" };
|
|
342
|
+
if (raw.includes("\0")) return { reason: "the path holds a NUL character" };
|
|
343
|
+
let p = raw.replace(/\\/g, "/").replace(/[\u0001-\u001f\u007f]/g, "");
|
|
344
|
+
if (/^\/|^[A-Za-z]:(\/|$)/.test(p)) return { reason: "an absolute path, outside the project" };
|
|
345
|
+
const marker = p.endsWith("/");
|
|
346
|
+
const parts = p.split("/").filter((s) => s && s !== ".");
|
|
347
|
+
let up = 0;
|
|
348
|
+
while (parts[up] === "..") up++;
|
|
349
|
+
if (parts.slice(up).includes("..")) return { reason: "the path climbs out with \"..\"" };
|
|
350
|
+
if (parts.length === up) return { reason: "an empty path" };
|
|
351
|
+
p = parts.join("/") + (marker ? "/" : "");
|
|
352
|
+
return { key: p };
|
|
353
|
+
}
|
|
354
|
+
// The files as one Map with clean paths, plus the paths that were dropped and why.
|
|
355
|
+
function normalise(files) {
|
|
356
|
+
let entries;
|
|
357
|
+
if (files instanceof Map) entries = files.entries();
|
|
358
|
+
else if (files && typeof files === "object" && !Array.isArray(files) && !ArrayBuffer.isView(files)) entries = Object.entries(files);
|
|
359
|
+
else throw new TypeError("scanFiles: files must be a Map or a plain object of path -> content");
|
|
360
|
+
const out = new Map();
|
|
361
|
+
const skipped = [];
|
|
362
|
+
for (const [raw, v] of entries) {
|
|
363
|
+
const content = contentOf(raw, v, files);
|
|
364
|
+
const { key, reason } = pathOf(raw);
|
|
365
|
+
// Shown with "?" for each control character; judged by the path with them taken out, so "002.sql\0" is SQL.
|
|
366
|
+
const clean = String(raw).replace(/\\/g, "/").replace(/[\u0000-\u001f\u007f]/g, "");
|
|
367
|
+
if (!key) skipped.push({ path: String(raw).replace(/[\u0000-\u001f\u007f]/g, "?"), reason, matters: MATTERS.test(clean) });
|
|
368
|
+
else if (out.has(key)) skipped.push({ path: key, reason: "the same path as another file", matters: MATTERS.test(key) });
|
|
369
|
+
else out.set(key, content === LAZY ? () => files[LAZY](raw) : content);
|
|
370
|
+
}
|
|
371
|
+
return { map: out, skipped };
|
|
372
|
+
}
|
|
373
|
+
const cleanList = (list) => (Array.isArray(list) ? list.map((n) => String(n).replace(/\\/g, "/").replace(/^(\.\/)+/, "")) : list);
|
|
374
|
+
|
|
375
|
+
// scanFiles(files, opts): the whole scan over files held in memory.
|
|
376
|
+
// files a Map (or a plain object) of path -> content. Paths are relative to the project folder; "\" is read as
|
|
377
|
+
// "/" and a leading "./" is dropped. A path that leaves the project (absolute, or with ".." inside it) or
|
|
378
|
+
// holds a NUL character is not scanned and is listed in the result's skippedPaths. Content is a string,
|
|
379
|
+
// bytes (Uint8Array or ArrayBuffer), or null: the file exists but its content wasn't loaded (too big, a
|
|
380
|
+
// lockfile, unreadable, or a .env file whose values the caller doesn't send). A key ending in "/" marks a
|
|
381
|
+
// folder that exists with nothing in it worth sending. Any other content is a TypeError naming the path.
|
|
382
|
+
// opts.tracked the paths git tracks, relative to the top of the repository (what `git ls-files` lists there).
|
|
383
|
+
// Without it, committed .env files can't be looked for and the result says gitUnavailable.
|
|
384
|
+
// opts.prefix where the project folder sits in the repository ("" when the project is the whole repository).
|
|
385
|
+
// A tracked .env above the project folder is then found in `files` as "../.env".
|
|
386
|
+
// opts.nested folders that are other checkouts (submodules, worktrees): nothing under them is scanned.
|
|
387
|
+
// opts.built the build output folders to look in (default: dist, build, out and .next/static).
|
|
388
|
+
// opts.truncated the caller stopped listing files at a cap, so the result says truncated.
|
|
389
|
+
// opts.dir the folder name to put in the result.
|
|
390
|
+
// opts.maxFindings, opts.maxBytes, opts.deadlineMs when to stop (defaults: HOSTED_LIMITS; Infinity for none).
|
|
391
|
+
// A scan that stops early says so: truncated is true and stopped says which limit was reached,
|
|
392
|
+
// so it never reads as a clean result.
|
|
393
|
+
// A tracked .env file sent with no content is reported for review ("scan:env-review", medium), never as a blocker:
|
|
394
|
+
// without its values nobody can tell whether it holds a secret. readFolder always sends the values it can read.
|
|
395
|
+
export function scanFiles(input, opts = {}) {
|
|
396
|
+
const { map: files, skipped: skippedPaths } = normalise(input);
|
|
397
|
+
const nested = (cleanList(opts.nested) ?? []).map((n) => n.replace(/\/+$/, ""));
|
|
398
|
+
const tracked = cleanList(opts.tracked);
|
|
399
|
+
const keys = [...files.keys()];
|
|
400
|
+
// A file's content, read when it's needed (and, from readFolder, dropped again once used).
|
|
401
|
+
const get = (k) => {
|
|
402
|
+
const v = files.get(k);
|
|
403
|
+
if (typeof v !== "function") return v ?? null;
|
|
404
|
+
return contentOf(k, v(), null);
|
|
405
|
+
};
|
|
406
|
+
let chosen = keys.filter((k) => picked(k, nested));
|
|
407
|
+
let truncated = Boolean(opts.truncated);
|
|
408
|
+
if (chosen.length > MAX_FILES) {
|
|
409
|
+
chosen = firstFiles(chosen);
|
|
410
|
+
truncated = true;
|
|
411
|
+
}
|
|
412
|
+
// In name order, which for migrations is the order they ran in: a later file can undo an earlier one.
|
|
413
|
+
const list = chosen.sort();
|
|
414
|
+
const findings = [];
|
|
415
|
+
const unread = [];
|
|
416
|
+
// A path dropped for a NUL character may hide a file that matters: never a clean result over it.
|
|
417
|
+
// A dropped path that would have been SQL, rules or config is never passed over as clean, whatever the reason.
|
|
418
|
+
for (const s of skippedPaths) if (s.matters) unread.push(s.path);
|
|
419
|
+
for (const s of skippedPaths) delete s.matters;
|
|
420
|
+
|
|
421
|
+
// When to stop. Checked between files, every few hundred SQL statements, and on every finding.
|
|
422
|
+
const limit = (v, d) => (typeof v === "number" && v >= 0 ? v : d);
|
|
423
|
+
const maxFindings = limit(opts.maxFindings, HOSTED_LIMITS.maxFindings);
|
|
424
|
+
const maxBytes = limit(opts.maxBytes, HOSTED_LIMITS.maxBytes);
|
|
425
|
+
const deadlineMs = limit(opts.deadlineMs, HOSTED_LIMITS.deadlineMs);
|
|
426
|
+
const now = typeof opts.now === "function" ? opts.now : Date.now;
|
|
427
|
+
const started = deadlineMs === Infinity ? 0 : now();
|
|
428
|
+
let bytes = 0;
|
|
429
|
+
let stopped = null;
|
|
430
|
+
const stop = (reason, at) => {
|
|
431
|
+
stopped ??= { reason, limit: at };
|
|
432
|
+
return true;
|
|
433
|
+
};
|
|
434
|
+
const over = () => stopped != null || (bytes > maxBytes && stop("bytes", maxBytes)) || (deadlineMs !== Infinity && now() - started > deadlineMs && stop("time", deadlineMs));
|
|
435
|
+
const ids = new Set();
|
|
436
|
+
const add = (f) => {
|
|
437
|
+
if (ids.has(f.id) || stopped) return;
|
|
438
|
+
if (findings.length >= maxFindings) return void stop("findings", maxFindings);
|
|
439
|
+
ids.add(f.id);
|
|
440
|
+
findings.push(f);
|
|
441
|
+
};
|
|
442
|
+
const exists = (p) => files.has(p) || keys.some((k) => k.startsWith(`${p}/`));
|
|
443
|
+
let pkg = {};
|
|
444
|
+
try {
|
|
445
|
+
if (get("package.json") != null) pkg = JSON.parse(textOf(get("package.json")));
|
|
446
|
+
} catch {}
|
|
447
|
+
const deps = { ...pkg.dependencies, ...pkg.devDependencies };
|
|
448
|
+
const project = {
|
|
449
|
+
spa: !["@tanstack/react-start", "@tanstack/start", "@remix-run/node", "@react-router/node", "@sveltejs/kit", "nuxt", "astro", "@solidjs/start", "vinxi", "@builder.io/qwik-city"].some((d) => d in deps) && !exists("next.config.js") && !exists("next.config.mjs") && !exists("next.config.ts") && (["vite.config.ts", "vite.config.js", "vite.config.mjs"].some(exists) || "react-scripts" in deps || "expo" in deps),
|
|
450
|
+
gemini: "@google/generative-ai" in deps || "@google/genai" in deps,
|
|
451
|
+
};
|
|
452
|
+
let usesSupabase = exists("supabase") || Object.keys(deps).some((d) => d.startsWith("@supabase/"));
|
|
453
|
+
|
|
454
|
+
// Database state across every migration, in order.
|
|
455
|
+
const created = new Map(); // table -> { where, people }
|
|
456
|
+
const protectedTables = new Set();
|
|
457
|
+
const dynamic = new Set(); // tables created before an EXECUTE … enable row level security we can't read
|
|
458
|
+
const publicRead = { everyone: [], "every signed-in user": [] };
|
|
459
|
+
const publicReadSeen = { everyone: new Set(), "every signed-in user": new Set() };
|
|
460
|
+
const policies = new Map(); // "schema.table|name" -> { action, roles, using, check, where, table, schema }
|
|
461
|
+
const buckets = new Map(); // bucket id -> { public, where }
|
|
462
|
+
const views = new Map(); // view -> { where, invoker, auth, revoked }
|
|
463
|
+
const definers = new Map(); // function -> { where, dynamicSql, revoked }
|
|
464
|
+
const keyFiles = [];
|
|
465
|
+
|
|
466
|
+
// A folder of SQL written for MySQL or SQLite: one file with their syntax marks the whole folder.
|
|
467
|
+
const notPgDirs = new Map();
|
|
468
|
+
let sqlByDir = null;
|
|
469
|
+
const notPostgres = (dir) => {
|
|
470
|
+
if (!sqlByDir) {
|
|
471
|
+
sqlByDir = new Map();
|
|
472
|
+
for (const k of keys) if (k.endsWith(".sql")) sqlByDir.set(path.posix.dirname(k), [...(sqlByDir.get(path.posix.dirname(k)) ?? []), k]);
|
|
473
|
+
}
|
|
474
|
+
if (!notPgDirs.has(dir)) {
|
|
475
|
+
let hit = false;
|
|
476
|
+
for (const k of sqlByDir.get(dir) ?? []) {
|
|
477
|
+
const v = get(k);
|
|
478
|
+
if (v == null) continue;
|
|
479
|
+
if (sizeOf(v) < 4 * 1024 * 1024 && NOT_PG.test(textOf(v))) { hit = true; break; }
|
|
480
|
+
}
|
|
481
|
+
notPgDirs.set(dir, hit);
|
|
482
|
+
}
|
|
483
|
+
return notPgDirs.get(dir);
|
|
484
|
+
};
|
|
485
|
+
// Whether a function's own code (every .ts, .js and .mjs file in its folder, outside node_modules) matches.
|
|
486
|
+
const signsItself = (dir, re = SIGNATURE) => {
|
|
487
|
+
for (const k of keys) {
|
|
488
|
+
if (!k.startsWith(`${dir}/`) || !FUNCTION_FILE.test(k)) continue;
|
|
489
|
+
if (k.slice(dir.length + 1).split("/").slice(0, -1).includes("node_modules")) continue;
|
|
490
|
+
const v = get(k);
|
|
491
|
+
if (v != null && re.test(jsNoComments(textOf(v)))) return true;
|
|
492
|
+
}
|
|
493
|
+
return false;
|
|
494
|
+
};
|
|
495
|
+
|
|
496
|
+
for (const name of list) {
|
|
497
|
+
if (over()) break;
|
|
498
|
+
if (/\.(test|spec)\.[a-z]+$/i.test(name)) continue;
|
|
499
|
+
if (TEST_FILE.test(name)) continue;
|
|
500
|
+
// Examples, fixtures and tests aren't the app people use: security tools plant leaks there on purpose.
|
|
501
|
+
// Only a key with a real key's shape still counts there, since a real one works wherever it is written.
|
|
502
|
+
const sample = SAMPLE_PATH.test(name);
|
|
503
|
+
if (LOCKFILE.test(name)) continue;
|
|
504
|
+
const raw = get(name);
|
|
505
|
+
if (raw == null || (sizeOf(raw) > BIG && !(name.endsWith(".sql") && sizeOf(raw) < 16 * BIG))) {
|
|
506
|
+
if (MATTERS.test(name)) unread.push(name);
|
|
507
|
+
continue;
|
|
508
|
+
}
|
|
509
|
+
bytes += sizeOf(raw);
|
|
510
|
+
const text = textOf(raw);
|
|
511
|
+
if (text.includes("\0")) continue;
|
|
512
|
+
if (!usesSupabase && /@supabase\/(supabase-js|ssr|auth-helpers)/.test(text)) usesSupabase = true;
|
|
513
|
+
if (!project.gemini && /generativelanguage\.googleapis\.com|GoogleGenerativeAI|@google\/genai/.test(text)) project.gemini = true;
|
|
514
|
+
const isEnv = /(^|\/)(\.env[^/]*|\.dev\.vars)$/.test(name);
|
|
515
|
+
const lineAt = linesOf(text); // text and code below keep the same newlines
|
|
516
|
+
|
|
517
|
+
// Names only: a secret behind a public prefix is copied into the code every visitor downloads.
|
|
518
|
+
if (!sample) {
|
|
519
|
+
// In a .env file, only a name the file sets (NAME=…, at the start of a line) counts.
|
|
520
|
+
const defined = isEnv ? new Set(Array.from(text.matchAll(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/gm), (d) => d[1])) : null;
|
|
521
|
+
for (const re of [SECRET_NAME, PAID_KEY_NAME]) {
|
|
522
|
+
for (const m of text.matchAll(re)) {
|
|
523
|
+
if (stopped) break;
|
|
524
|
+
if (isEnv && !defined.has(m[1])) continue;
|
|
525
|
+
if (!isEnv && inComment(text, m.index)) continue;
|
|
526
|
+
if (ids.has(`scan:public-secret:${m[1]}`)) continue;
|
|
527
|
+
add({ id: `scan:public-secret:${m[1]}`, severity: "critical", where: `${name}:${lineAt(m.index)}`, title: `The secret ${m[1]} is named so it ships to the browser`, why: "Anything whose name starts with a public prefix (VITE_, NEXT_PUBLIC_ and the like) is copied into the JavaScript every visitor downloads. A secret there is public.", fix: "Rename it without the public prefix and use it only in backend code.", first: "Treat this key as leaked if the app has ever been deployed with it: revoke it and make a new one.", prompt: `My project has a secret named ${m[1]}. The public prefix means it is built into the frontend, where anyone can read it. Rename it without the prefix, move every use of it into backend code (an edge function or server route) that checks the user is signed in, and confirm it no longer appears anywhere in the frontend build. List the files you changed.` });
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
if (isEnv) continue;
|
|
532
|
+
if (sample && (/\.(rules|sql)$/.test(name) || /(^|\/)(database\.rules\.json|supabase\/config\.toml)$/.test(name))) continue;
|
|
533
|
+
|
|
534
|
+
// Firebase rules, wherever firebase.json says they are.
|
|
535
|
+
if (/\.rules$/.test(name) || (/(^|\/)database\.rules\.json$/.test(name))) {
|
|
536
|
+
scanFirebase(name, text, add);
|
|
537
|
+
continue;
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
if (name.endsWith(".sql")) {
|
|
541
|
+
// Row Level Security is a Postgres idea. A MySQL or SQLite schema, or SQL in an examples or fixtures
|
|
542
|
+
// folder, isn't the app's Supabase database. Anything under supabase/ always counts.
|
|
543
|
+
if (!/(^|\/)supabase\//.test(name) && notPostgres(path.posix.dirname(name))) continue;
|
|
544
|
+
scanSql(name, text);
|
|
545
|
+
continue;
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
if (/(^|\/)supabase\/config\.toml$/.test(name)) {
|
|
549
|
+
scanSupabaseConfig(name, text);
|
|
550
|
+
continue;
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
const code = /\.(js|jsx|ts|tsx|mjs|cjs|vue|svelte|astro)$/.test(name) ? jsNoComments(text) : text;
|
|
554
|
+
const client = clientSide(name, text, project);
|
|
555
|
+
|
|
556
|
+
if (sample && /\.(example|sample)\./.test(name)) continue;
|
|
557
|
+
// Keys written into the code itself, recognised by their shape.
|
|
558
|
+
if (!/\.(example|sample)\./.test(name)) {
|
|
559
|
+
for (const [kind, re] of KEY_SHAPES) {
|
|
560
|
+
for (const m of code.matchAll(re)) {
|
|
561
|
+
if (PLACEHOLDER.test(m[0].slice(6)) || /^(.)\1+$/.test(m[0].slice(-12))) continue;
|
|
562
|
+
const line = lineAt(m.index);
|
|
563
|
+
add({ id: `scan:key-in-code:${name}:${shortHash(kind)}`, severity: client ? "critical" : "high", where: `${name}:${line}`, title: `${kind[0].toUpperCase()}${kind.slice(1)} is written into ${client ? "code that ships to the browser" : "the code"}`, why: client ? "Anyone who opens the app can read it from the JavaScript they download." : "Everyone with access to the code, now or later, has this key. If the repository is ever public, so does the world.", fix: "Move it into a server-side secret and read it from there.", first: "Revoke this key and make a new one: it has been copied wherever this code has been.", prompt: `${name} line ${line} contains ${kind} written directly in the code. Don't show me the value. Move it into a server-side secret (an environment variable that never reaches the browser, or your platform's secret store), read it only in backend code, and remove it from this file. Then remind me to revoke the old key and make a new one.` });
|
|
564
|
+
break;
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
if (sample) continue;
|
|
568
|
+
// A Supabase key whose role is service_role: it skips every Row Level Security rule.
|
|
569
|
+
for (const m of code.matchAll(/\beyJ[A-Za-z0-9_-]{10,}\.(eyJ[A-Za-z0-9_-]{10,})\.[A-Za-z0-9_-]{8,}/g)) {
|
|
570
|
+
let role = "";
|
|
571
|
+
try {
|
|
572
|
+
role = JSON.parse(fromBase64url(m[1])).role;
|
|
573
|
+
} catch {}
|
|
574
|
+
if (role !== "service_role") continue;
|
|
575
|
+
const line = lineAt(m.index);
|
|
576
|
+
add({ id: `scan:service-role-literal:${name}`, severity: client ? "critical" : "high", where: `${name}:${line}`, title: `The Supabase service_role key is written into ${client ? "code that ships to the browser" : "the code"}`, why: "The service_role key skips every Row Level Security rule: whoever has it can read, change and delete every row in the database.", fix: "Use the anon (publishable) key in the app, and keep service_role only in server-side secrets.", first: "Rotate the service_role key in Supabase (Settings → API) now.", prompt: `${name} line ${line} contains my Supabase service_role key written into the code. Don't show me the value. Replace it with the anon (publishable) key if this code runs in the browser, or read it from a server-side secret if it runs on a server. Then tell me how to rotate the service_role key in the Supabase dashboard.` });
|
|
577
|
+
}
|
|
578
|
+
// Google keys (AIza…) became Gemini keys on projects with the Generative Language API on.
|
|
579
|
+
for (const m of code.matchAll(/\bAIza[0-9A-Za-z_-]{35}\b/g)) keyFiles.push({ name, line: lineAt(m.index), client });
|
|
580
|
+
}
|
|
581
|
+
// The service_role key used in browser code, by name.
|
|
582
|
+
const SR_USE = /\benv(?:\.|\[\s*["'])[A-Z0-9_]*SERVICE_ROLE[A-Z0-9_]*|\b[A-Z0-9_]*SERVICE_ROLE_KEY\b(?!["'`]\s*[,\]])/;
|
|
583
|
+
if (client && SR_USE.test(code) && /\bcreateClient\s*\(/.test(code))
|
|
584
|
+
add({ id: `scan:service-role-client:${name}`, severity: "critical", where: `${name}:${lineAt(code.search(SR_USE))}`, title: "Browser code uses the Supabase service_role key", why: "This file runs in the visitor's browser and builds a Supabase client with the service_role key, which skips every Row Level Security rule. Anyone can take it from the page.", fix: "Use the anon key here and move anything that needs service_role into an edge function.", first: "If this has been deployed, rotate the service_role key.", prompt: `${name} runs in the browser and uses my Supabase service_role key. Change it to use the anon (publishable) key, move anything that really needs service_role into a Supabase edge function or server route that checks the signed-in user, and confirm the service_role key appears nowhere in the frontend build.` });
|
|
585
|
+
// An AI SDK told to run in the browser ships its key to every visitor.
|
|
586
|
+
// Bring-your-own-key apps (the visitor types their own key) are fine: flag only a key from the build env or written in.
|
|
587
|
+
if (/[{,]\s*dangerouslyAllowBrowser\s*:\s*true/.test(code) && (/\b(import\.meta\.env|process\.env|Deno\.env)\b/.test(code) || /\bapiKey\s*:\s*["'`]((sk-|sk_|gsk_|xai-|pplx-|AIza)[A-Za-z0-9_-]{16,}|[A-Za-z0-9]{32,})["'`]/.test(code)))
|
|
588
|
+
add({ id: `scan:ai-in-browser:${name}`, severity: "high", where: `${name}:${lineAt(code.search(/dangerouslyAllowBrowser/))}`, title: "An AI SDK is set to run in the browser", why: "dangerouslyAllowBrowser: true means the AI provider's key is in the page. Anyone can copy it and run up your bill, as happened to thousands of sites with exposed ChatGPT keys.", fix: "Call the AI provider from a server route or edge function and keep the key there.", first: "Revoke the key this code uses and make a new one.", prompt: `${name} calls an AI provider from the browser with dangerouslyAllowBrowser: true, so the API key ships to every visitor. Move the call into a server route or edge function that checks the user is signed in and limits how often they can call it, keep the key in a server-side secret, and remove dangerouslyAllowBrowser. Show me the change.` });
|
|
589
|
+
|
|
590
|
+
// A login or session secret written into the code: anyone with the code can sign in as anyone.
|
|
591
|
+
if (!/\.(md|html)$/.test(name)) {
|
|
592
|
+
const yaml = /\.ya?ml$/.test(name);
|
|
593
|
+
const re = yaml
|
|
594
|
+
? /\b(JWT_SECRET|JWT_KEY|SECRET_KEY|SESSION_SECRET|NEXTAUTH_SECRET|AUTH_SECRET|TOKEN_SECRET|COOKIE_SECRET|APP_SECRET|SECRET_KEY_BASE)\s*[:=]\s*["']?([^"'\s#${}][^"'\s#]{0,200})/g
|
|
595
|
+
: /\b(JWT_SECRET|JWT_KEY|SECRET_KEY|SESSION_SECRET|NEXTAUTH_SECRET|AUTH_SECRET|TOKEN_SECRET|COOKIE_SECRET|APP_SECRET|jwtSecret|jwt_secret|sessionSecret|secretKey|secret_key)\b["']?\s*(?:[:=]|\|\||\?\?|,)\s*["'`]([^"'`\s$]{1,200})["'`]|\b(?:JWT_SECRET|SESSION_SECRET|SECRET_KEY|NEXTAUTH_SECRET|AUTH_SECRET)\b["']?\s*\)?\s*(?:\|\||\?\?|or)\s*["'`]([^"'`\s$]{1,200})["'`]|(?:environ\.get|getenv)\(\s*["'](?:JWT_SECRET|SECRET_KEY|SESSION_SECRET)["']\s*,\s*["']([^"'\s]{1,200})["']/g;
|
|
596
|
+
// The same secret passed straight to the code that uses it, with no variable name to go on:
|
|
597
|
+
// jwt.sign(user, "supersecretkey"), session({ secret: "keyboard cat" }), cookieParser("..."),
|
|
598
|
+
// Flask's app.config["SECRET_KEY"] = "...". The literal must end the argument, so a quoted key inside the payload doesn't count.
|
|
599
|
+
const direct = yaml ? [] : [
|
|
600
|
+
/\b(?:jwt|jsonwebtoken|JWT)\s*\.\s*(?:sign|verify)\s*\([^;]{0,300}?,\s*()["'`]([^"'`\s$]{1,200})["'`]\s*[,)]/g,
|
|
601
|
+
/\b(?:session|cookieSession|expressSession)\s*\(\s*\{[^}]{0,300}?\b(?:secret|keys)\s*:\s*\[?\s*()["'`]([^"'`$\n]{1,200})["'`]/g,
|
|
602
|
+
/\bcookieParser\s*\(\s*()["'`]([^"'`\s$]{1,200})["'`]/g,
|
|
603
|
+
/\bconfig\s*\[\s*["'](?:SECRET_KEY|JWT_SECRET_KEY)["']\s*\]\s*=\s*()["']([^"'\s]{1,200})["']/g,
|
|
604
|
+
];
|
|
605
|
+
for (const m of [...code.matchAll(re), ...direct.flatMap((d) => [...code.matchAll(d)])]) {
|
|
606
|
+
const v = m[2] ?? m[3] ?? m[4] ?? "";
|
|
607
|
+
if (!v || /^(process|import|os\.|env|config|settings|\$|\{|true|false|null|none|undefined)/i.test(v) || PLACEHOLDER.test(v) && !/secret|changeme/i.test(v)) continue;
|
|
608
|
+
if (/\.(example|sample)\b/.test(name)) continue;
|
|
609
|
+
// A list of names, like ['publishableKey', 'secretKey', 'webhookSecret'], or a name held as a value
|
|
610
|
+
// ({ "env": "APP_SECRET", "bytes": 32 }) is not a secret.
|
|
611
|
+
if (/["'`]$/.test(code.slice(0, m.index)) && /[[,:]\s*["'`]$/.test(code.slice(Math.max(0, m.index - 40), m.index))) continue;
|
|
612
|
+
const line = lineAt(m.index);
|
|
613
|
+
// process.env.JWT_SECRET || "dev-secret", os.getenv("SECRET_KEY", "dev"): the literal is used only when
|
|
614
|
+
// the variable is missing. Still a blocker (that is how the Invicti admin takeover worked), named for what it is.
|
|
615
|
+
const fallback = /\|\||\?\?|\bor\b/.test(m[0]) || /^(?:environ\.get|getenv)\(/.test(m[0]) || (/,/.test(m[0]) && /(getenv|environ\.get|env\.get|Deno\.env\.get|config\.get)\s*\(\s*["'`]?$/.test(code.slice(Math.max(0, m.index - 80), m.index)));
|
|
616
|
+
if (fallback) {
|
|
617
|
+
add({ id: `scan:auth-secret-fallback:${name}`, severity: "high", where: `${name}:${line}`, title: "If the login secret isn't set, the app signs logins with one written in the code", why: "The app reads its signing secret from an environment variable but falls back to a fixed value when it's missing. One forgotten variable on a new server and anyone who has read this code can make a valid login for any user. Invicti found the same few fallback values (like \"supersecretkey\") in over a thousand AI-generated apps.", fix: "Remove the fallback and make the app refuse to start without the variable.", first: "Check that production sets the variable. If it ever ran without it, change the secret.", prompt: `${name} line ${line} falls back to a fixed login secret when the environment variable is missing. Don't show me the value. Remove the fallback, make the app refuse to start if the variable isn't set, and tell me how to generate a long random one.` });
|
|
618
|
+
break;
|
|
619
|
+
}
|
|
620
|
+
add({ id: `scan:hardcoded-auth-secret:${name}`, severity: "high", where: `${name}:${line}`, title: "A login secret is written into the code", why: "The secret that signs login tokens or sessions is a fixed value in this file. Anyone who reads it can make a valid login for any user. Invicti found the same few values (like \"supersecretkey\") in over a thousand AI-generated apps.", fix: "Generate a long random secret, keep it in an environment variable, and fail to start if it's missing.", first: "Change the secret in production: every token signed with the old one stays valid until you do.", prompt: `${name} line ${line} sets the secret that signs logins or sessions to a fixed value (or falls back to one when the environment variable is missing). Don't show me the value. Make the app read it only from an environment variable, refuse to start if it isn't set, and tell me how to generate a long random one. Then remind me that changing it signs everyone out.` });
|
|
621
|
+
break;
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
// Payment webhooks that act on a message without checking who sent it.
|
|
626
|
+
if (/\.(js|ts|mjs|tsx|py)$/.test(name)) {
|
|
627
|
+
const stripe = !client && /from\s+["'](?:npm:|https?:\/\/[^"'\s]*\/)?stripe(?:@[^"'?\/\s]*)?(?:\?[^"'\s]*)?["']|require\(\s*["']stripe["']\)|^\s*import\s+stripe\b/m.test(code);
|
|
628
|
+
const events = /checkout\.session\.completed|invoice\.(?:paid|payment_succeeded)|customer\.subscription\.|payment_intent\.succeeded|event\.type\s*===?|event\[["']type["']\]/.test(code);
|
|
629
|
+
const named = /webhook/i.test(name);
|
|
630
|
+
// A route that takes a Stripe event as JSON, whatever the file is called (but not one that creates a checkout).
|
|
631
|
+
const takesEvent = /\b(?:const|let|var)\s+(?:event|evt)\s*=\s*(?:await\s+)?(?:req|request)\.json\(\)|\.data\.object\b/.test(code);
|
|
632
|
+
if (stripe && (named || events || takesEvent) && !/constructEvent|construct_event|stripe-signature|Stripe-Signature/i.test(code)) {
|
|
633
|
+
const trusts = /\b(req|request)\.json\(\)|JSON\.parse\(|\breq\.body\b|request\.get_json|await\s+request\.body/.test(code);
|
|
634
|
+
add({ id: `scan:webhook:${name}`, severity: trusts ? "high" : "medium", where: name, title: "Greenlit couldn't see a signature check in this payment webhook", why: "This file handles Stripe messages but never checks the Stripe-Signature header (constructEvent). If the check isn't done in another file it calls, anyone can send a fake \"payment succeeded\" message and get what was paid for.", fix: "Verify the signature with stripe.webhooks.constructEvent and the signing secret.", first: null, prompt: `My Stripe webhook handler in ${name} doesn't verify the Stripe-Signature header. Change it to read the raw request body and call stripe.webhooks.constructEvent (constructEventAsync on edge runtimes) with the signing secret from a server secret, reject anything that fails with a 400, and only then act on the event. Show me the change.` });
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
// Coding agents with a database connection that can write.
|
|
639
|
+
if (/(^|\/)(\.mcp\.json|\.cursor\/mcp\.json|\.vscode\/mcp\.json|\.windsurf\/mcp_config\.json|\.gemini\/settings\.json|claude_desktop_config\.json|\.roo\/mcp\.json|\.kiro\/settings\/mcp\.json)$/.test(name) && (/postgres(?:ql)?:\/\//i.test(text) || (/supabase/i.test(text) && !/read[-_]only/i.test(text))))
|
|
640
|
+
add({ id: `scan:agent-db:${name}`, severity: "medium", where: name, title: "Your coding agent can change your database", why: "This agent configuration gives the AI a database connection that isn't read-only. An agent has deleted a production database this way, and a support ticket with hidden instructions made an agent leak private tables through the Supabase MCP server.", fix: "Use the read-only mode, scope it to one development project, and keep user-written text away from the agent.", first: null, prompt: `My agent configuration in ${name} gives you a database connection that can write. Tell me how to change it to read-only and scoped to a development project (for the Supabase MCP server: the read-only and project-ref options), and whether the live database is reachable with it today. Change nothing until I confirm.` });
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
// ---------- SQL: every statement, in the order the migrations run
|
|
644
|
+
function scanSql(name, text) {
|
|
645
|
+
const code = noComments(text); // strings blanked: for structure
|
|
646
|
+
const orig = sqlBlank(text, false); // comments blanked, strings kept: for names and conditions
|
|
647
|
+
const lineAt = linesOf(code);
|
|
648
|
+
const at = (i) => `${name}:${lineAt(i)}`;
|
|
649
|
+
const pkey = (schema, table, pol) => `${schemaOf(schema)}.${ident(table)}|${ident(pol)}`;
|
|
650
|
+
let count = 0;
|
|
651
|
+
for (const st of statements(code)) {
|
|
652
|
+
if (++count % 256 === 0 && over()) return;
|
|
653
|
+
const s = st.text;
|
|
654
|
+
const o = orig.slice(st.index, st.index + s.length);
|
|
655
|
+
const lead = s.length - s.trimStart().length;
|
|
656
|
+
const i = st.index + lead;
|
|
657
|
+
let m;
|
|
658
|
+
if ((m = s.match(SQL.createTable))) {
|
|
659
|
+
if (schemaOf(m[1]) !== "public" || /\btemp/i.test(m[0])) continue;
|
|
660
|
+
const table = ident(m[2]);
|
|
661
|
+
if (!created.has(table) || created.get(table).dropped) {
|
|
662
|
+
protectedTables.delete(table);
|
|
663
|
+
created.set(table, { where: at(i), people: PERSONAL_COLUMN.test(s) });
|
|
664
|
+
}
|
|
665
|
+
continue;
|
|
666
|
+
}
|
|
667
|
+
if ((m = s.match(SQL.alterRls))) {
|
|
668
|
+
if (schemaOf(m[1]) !== "public") continue;
|
|
669
|
+
if (m[3].toLowerCase() === "enable") protectedTables.add(ident(m[2]));
|
|
670
|
+
else protectedTables.delete(ident(m[2]));
|
|
671
|
+
continue;
|
|
672
|
+
}
|
|
673
|
+
if ((m = s.match(SQL.rename))) {
|
|
674
|
+
const [from, to] = [ident(m[2]), ident(m[3])];
|
|
675
|
+
if (created.has(from)) created.set(to, created.get(from)), created.delete(from);
|
|
676
|
+
if (protectedTables.delete(from)) protectedTables.add(to);
|
|
677
|
+
continue;
|
|
678
|
+
}
|
|
679
|
+
if (/^\s*drop\s+table\b/i.test(s)) {
|
|
680
|
+
for (const t of s.replace(/^\s*drop\s+table\s+(?:if\s+exists\s+)?/i, "").replace(/\b(cascade|restrict)\b/gi, "").split(",")) {
|
|
681
|
+
const mm = t.trim().match(SQL.identAtStart);
|
|
682
|
+
if (!mm) continue;
|
|
683
|
+
const table = ident(mm[2]);
|
|
684
|
+
const schema = schemaOf(mm[1]);
|
|
685
|
+
if (schema === "public") {
|
|
686
|
+
created.delete(table);
|
|
687
|
+
protectedTables.delete(table);
|
|
688
|
+
}
|
|
689
|
+
for (const k of [...policies.keys()]) if (k.startsWith(`${schema}.${table}|`)) policies.delete(k);
|
|
690
|
+
}
|
|
691
|
+
if (/(^|\/)migrations\//.test(name))
|
|
692
|
+
add({ id: `scan:destructive:${name}`, severity: "low", where: at(i), title: "A migration deletes data", why: `It contains "${s.trim().slice(0, 60)}". Run against the live database, that data is gone unless you have a backup.`, fix: "Make sure a backup exists before this runs on the live database.", first: null, prompt: `My migration ${name} contains a statement that deletes data (drop table). Tell me exactly what would be lost if it runs on the live database, whether that is intended, and how to back up that data first. Change nothing.` });
|
|
693
|
+
continue;
|
|
694
|
+
}
|
|
695
|
+
if (/^\s*truncate\b/i.test(s) && /(^|\/)migrations\//.test(name)) {
|
|
696
|
+
add({ id: `scan:destructive:${name}`, severity: "low", where: at(i), title: "A migration deletes data", why: `It contains "${s.trim().slice(0, 60)}". Run against the live database, that data is gone unless you have a backup.`, fix: "Make sure a backup exists before this runs on the live database.", first: null, prompt: `My migration ${name} contains a statement that deletes data (truncate). Tell me exactly what would be lost if it runs on the live database, whether that is intended, and how to back up that data first. Change nothing.` });
|
|
697
|
+
continue;
|
|
698
|
+
}
|
|
699
|
+
// Row Level Security switched on at run time.
|
|
700
|
+
// Only an anonymous DO block runs here; a function that does the same may never be called.
|
|
701
|
+
if (/^\s*do\b/i.test(o) && /\bexecute\b/i.test(o) && /enable\s+row\s+level\s+security/i.test(o)) {
|
|
702
|
+
const arr = o.match(/foreach\s+\w+\s+in\s+array\s+(?:array\s*)?\[([^\]]*)\]/i);
|
|
703
|
+
if (arr) {
|
|
704
|
+
// Names in a list: format('%I') keeps their case, a plain || folds it, so both count.
|
|
705
|
+
for (const n of arr[1].matchAll(/'((?:[^']|'')+)'/g)) {
|
|
706
|
+
const t = n[1].replace(/''/g, "'").replace(/^"?public"?\./i, "").replace(/^"(.*)"$/, "$1");
|
|
707
|
+
protectedTables.add(t).add(t.toLowerCase());
|
|
708
|
+
}
|
|
709
|
+
} else if (/pg_tables|information_schema\.tables|pg_class|pg_catalog/i.test(o)) for (const t of created.keys()) protectedTables.add(t); // a loop over every table
|
|
710
|
+
else {
|
|
711
|
+
// A fixed statement in quotes names its table; one built from pieces (%I, ||, a variable) can't be read.
|
|
712
|
+
for (const l of o.matchAll(SQL.literalRls)) if (schemaOf(l[1]) === "public") protectedTables.add(ident(l[2]));
|
|
713
|
+
if (/%I|%s|\|\||execute\s+(?!')\w/i.test(o)) for (const t of created.keys()) if (!protectedTables.has(t)) dynamic.add(t);
|
|
714
|
+
}
|
|
715
|
+
continue;
|
|
716
|
+
}
|
|
717
|
+
// Policies.
|
|
718
|
+
if ((m = s.match(SQL.createPolicy))) {
|
|
719
|
+
const rest = o.slice(m[0].length);
|
|
720
|
+
if (/\bas\s+restrictive\b/i.test(rest)) continue; // narrows access, opens nothing
|
|
721
|
+
const roles = (rest.match(/\bto\s+([\w\s,"]+?)(?=\s+(?:using|with)\b|\s*$)/i) || [, "public"])[1].toLowerCase();
|
|
722
|
+
const action = (rest.match(/\bfor\s+(select|insert|update|delete|all)\b/i) || [, "all"])[1].toLowerCase();
|
|
723
|
+
policies.set(pkey(m[2], m[3], m[1]), { schema: schemaOf(m[2]), table: ident(m[3]), roles, action, using: clause(rest, "using"), check: clause(rest, "with\\s+check"), where: at(i) });
|
|
724
|
+
continue;
|
|
725
|
+
}
|
|
726
|
+
if ((m = s.match(SQL.alterPolicy))) {
|
|
727
|
+
const key = pkey(m[2], m[3], m[1]);
|
|
728
|
+
const p = policies.get(key);
|
|
729
|
+
const rest = o.slice(m[0].length);
|
|
730
|
+
const ren = rest.match(SQL.renameTo);
|
|
731
|
+
if (ren) {
|
|
732
|
+
if (p) policies.set(pkey(m[2], m[3], ren[1]), p), policies.delete(key);
|
|
733
|
+
continue;
|
|
734
|
+
}
|
|
735
|
+
if (!p) continue;
|
|
736
|
+
const roles = rest.match(/\bto\s+([\w\s,"]+?)(?=\s+(?:using|with)\b|\s*$)/i);
|
|
737
|
+
policies.set(key, { ...p, roles: roles ? roles[1].toLowerCase() : p.roles, using: clause(rest, "using") ?? p.using, check: clause(rest, "with\\s+check") ?? p.check, where: at(i) });
|
|
738
|
+
continue;
|
|
739
|
+
}
|
|
740
|
+
if ((m = s.match(SQL.dropPolicy))) {
|
|
741
|
+
policies.delete(pkey(m[2], m[3], m[1]));
|
|
742
|
+
continue;
|
|
743
|
+
}
|
|
744
|
+
// Storage buckets made public.
|
|
745
|
+
if (/^\s*insert\s+into\s+storage\.buckets\b/i.test(s)) {
|
|
746
|
+
const cols = (o.match(/storage\.buckets\s*\(([^)]*)\)/i) || [, ""])[1].split(",").map((c) => c.trim().replace(/"/g, "").toLowerCase());
|
|
747
|
+
const idIdx = cols.indexOf("id") >= 0 ? cols.indexOf("id") : cols.indexOf("name");
|
|
748
|
+
const pubIdx = cols.indexOf("public");
|
|
749
|
+
const valuesAt = o.search(/\bvalues\b/i);
|
|
750
|
+
if (valuesAt >= 0 && pubIdx >= 0) {
|
|
751
|
+
for (const tup of o.slice(valuesAt).matchAll(/\(([^()]*)\)/g)) {
|
|
752
|
+
const vals = tup[1].split(",").map((v) => v.trim());
|
|
753
|
+
const id = (vals[idIdx] || "").replace(/^'|'$/g, "");
|
|
754
|
+
if (/^(true|'t'|'true')$/i.test(vals[pubIdx] || "")) buckets.set(id, { public: true, where: at(i) });
|
|
755
|
+
else buckets.set(id, { public: false, where: at(i) });
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
continue;
|
|
759
|
+
}
|
|
760
|
+
if ((m = o.match(/^\s*update\s+storage\.buckets\s+set\s+public\s*=\s*(true|false)\b[\s\S]*?\bwhere\s+(?:id|name)\s*=\s*'([^']+)'/i))) {
|
|
761
|
+
buckets.set(m[2], { public: m[1].toLowerCase() === "true", where: at(i) });
|
|
762
|
+
continue;
|
|
763
|
+
}
|
|
764
|
+
// Views and functions that run with their owner's rights.
|
|
765
|
+
if ((m = s.match(SQL.createView))) {
|
|
766
|
+
if (schemaOf(m[1]) !== "public") continue;
|
|
767
|
+
views.set(ident(m[2]), { where: at(i), invoker: INVOKER.test(s), auth: /\bauth\s*\.\s*users\b/i.test(s), materialized: /materialized/i.test(m[0]), revoked: false });
|
|
768
|
+
continue;
|
|
769
|
+
}
|
|
770
|
+
if ((m = s.match(SQL.alterView))) {
|
|
771
|
+
const v = schemaOf(m[1]) === "public" ? views.get(ident(m[2])) : null;
|
|
772
|
+
if (v && INVOKER.test(m[3])) v.invoker = true;
|
|
773
|
+
continue;
|
|
774
|
+
}
|
|
775
|
+
if ((m = s.match(SQL.revokeTable))) {
|
|
776
|
+
const v = schemaOf(m[1]) === "public" ? views.get(ident(m[2])) : null;
|
|
777
|
+
if (v && /anon|public/i.test(m[3])) v.revoked = true;
|
|
778
|
+
}
|
|
779
|
+
if ((m = revokeFunction(s))) {
|
|
780
|
+
const f = schemaOf(m[1]) === "public" ? definers.get(ident(m[2])) : null;
|
|
781
|
+
if (f && /anon|public/i.test(m[3])) f.revoked = true;
|
|
782
|
+
continue;
|
|
783
|
+
}
|
|
784
|
+
if ((m = s.match(SQL.createFunction))) {
|
|
785
|
+
if (schemaOf(m[1]) !== "public") continue;
|
|
786
|
+
if (!/\bsecurity\s+definer\b/i.test(s)) continue;
|
|
787
|
+
if (/\breturns\s+trigger\b/i.test(s)) continue; // triggers can't be called through the API
|
|
788
|
+
definers.set(ident(m[2]), { where: at(i), dynamicSql: /\bexecute\s+(?:format\s*\(|'|\w+\s*\|\||\w+\s*;)/i.test(o) || /\bexecute\s+\w+/i.test(o.replace(/\bexecute\s+(procedure|function)\b/gi, "")), revoked: false });
|
|
789
|
+
continue;
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
// ---------- Supabase config: functions without the sign-in check, public buckets
|
|
795
|
+
function scanSupabaseConfig(name, text) {
|
|
796
|
+
let section = null;
|
|
797
|
+
const lines = text.split("\n");
|
|
798
|
+
for (let k = 0; k < lines.length; k++) {
|
|
799
|
+
const line = lines[k].replace(/(^|[^"'])#.*$/, "$1");
|
|
800
|
+
const h = line.match(/^\s*\[\s*([^\]]+?)\s*\]\s*$/);
|
|
801
|
+
if (h) {
|
|
802
|
+
section = h[1].split(".").map((p) => p.trim().replace(/^["']|["']$/g, ""));
|
|
803
|
+
continue;
|
|
804
|
+
}
|
|
805
|
+
if (!section) continue;
|
|
806
|
+
if (section[0] === "functions" && section[1] && /^\s*verify_jwt\s*=\s*false\b/.test(line)) {
|
|
807
|
+
const rawFn = section[1];
|
|
808
|
+
const fn = shown(rawFn);
|
|
809
|
+
const where = `${name}:${k + 1}`;
|
|
810
|
+
const fnDir = path.posix.join(path.posix.dirname(name), "functions", rawFn);
|
|
811
|
+
if (signsItself(fnDir, CHECKS_USER)) continue;
|
|
812
|
+
if (signsItself(fnDir))
|
|
813
|
+
add({ id: `scan:verify-jwt:${fn}`, severity: "low", where, title: `The function "${fn}" skips the sign-in check and verifies a signature instead`, why: "That is the right setup for a webhook. Greenlit saw a signature check in its code but can't confirm it runs before anything else.", fix: "Make sure the signature check is the first thing the function does.", first: null, prompt: `My Supabase edge function "${fn}" has verify_jwt = false and verifies a webhook signature. Confirm the signature check runs before the function reads or changes anything, and that a request with a missing or wrong signature gets a 400. Change nothing unless it doesn't.` });
|
|
814
|
+
else add({ id: `scan:verify-jwt:${fn}`, severity: "high", where, title: `The function "${fn}" skips the sign-in check`, why: "verify_jwt = false means anyone on the internet can call this function. That is right only for webhooks that check a signature themselves.", fix: "Remove verify_jwt = false, or verify a signature inside the function.", first: null, prompt: `My Supabase edge function "${fn}" has verify_jwt = false, so anyone can call it. If it is a webhook, make it verify the sender's signature before doing anything. Otherwise remove that setting and make the function check the signed-in user and what they are allowed to do. Show me what you changed.` });
|
|
815
|
+
}
|
|
816
|
+
if (section[0] === "storage" && section[1] === "buckets" && section[2] && /^\s*public\s*=\s*true\b/.test(line)) buckets.set(section[2], { public: true, where: `${name}:${k + 1}` });
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
// ---------- after every file: what's still open
|
|
821
|
+
// A scan that stopped early adds nothing more (add() is closed): a table whose Row Level Security is switched on in
|
|
822
|
+
// a file never read must not be reported open.
|
|
823
|
+
if (usesSupabase || [...created.keys()].length)
|
|
824
|
+
for (const [rawTable, info] of created) {
|
|
825
|
+
if (protectedTables.has(rawTable) || !usesSupabase) continue;
|
|
826
|
+
const maybe = dynamic.has(rawTable);
|
|
827
|
+
const table = shown(rawTable);
|
|
828
|
+
add({ id: `scan:no-rls:${table}`, severity: maybe ? "medium" : "high", where: info.where, title: maybe ? `Greenlit couldn't see Row Level Security switched on for "${table}"` : `The table "${table}" is created without Row Level Security`, why: `No migration turns Row Level Security on for it.${maybe ? " (A statement built at run time switches it on for some tables, and Greenlit can't tell whether this is one of them.)" : ""} If the app's public key can reach the table, every row is readable. (If you turned it on in the dashboard instead, the live database may be fine: check with npx greenlitlab <your app> --mine.)`, fix: `Add: alter table public.${sqlName(table)} enable row level security; plus a policy for the owner.`, first: null, prompt: `My migrations create the table "${table}" but never enable Row Level Security on it${maybe ? " in a statement I can read" : ""}. Write a new migration that enables it and adds policies so a signed-in user reaches only their own rows (auth.uid() = the owner column; add one if needed). If the table is meant to be public to read, say so and add a read-only policy. Show me the SQL.` });
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
for (const p of policies.values()) {
|
|
832
|
+
if (p.schema !== "public" && p.schema !== "storage") continue;
|
|
833
|
+
// The service role skips every rule anyway; a policy for it alone opens nothing.
|
|
834
|
+
if (/service_role/.test(p.roles) && !/anon|authenticated|public/.test(p.roles)) continue;
|
|
835
|
+
const conds = [p.using, p.check].filter((c) => c != null);
|
|
836
|
+
if (!conds.length) continue;
|
|
837
|
+
const parts = conds.flatMap(disjuncts);
|
|
838
|
+
const always = parts.some(ALWAYS);
|
|
839
|
+
const anySignedIn = !always && conds.every((c) => disjuncts(c).some((d) => ALWAYS(d) || ANY_SIGNED_IN(d)));
|
|
840
|
+
const meta = conds.some((c) => /user_metadata|raw_user_meta_data/i.test(c));
|
|
841
|
+
const table = shown(p.schema === "public" ? p.table : `${p.schema}.${p.table}`);
|
|
842
|
+
if (meta)
|
|
843
|
+
add({ id: `scan:policy-user-metadata:${table}`, severity: "high", where: p.where, title: `A rule on "${table}" trusts user_metadata, which users can change themselves`, why: "user_metadata is written by the user (supabase.auth.updateUser), so a rule that checks it can be passed by anyone who edits their own metadata. Supabase's own Security Advisor flags this as an error (lint 0015).", fix: "Check app_metadata (set only by the server) or a column in your own table instead.", first: null, prompt: `A Row Level Security policy on "${table}" checks user_metadata, which every user can change for themselves. Rewrite it to use app_metadata (which only the server can set) or a roles column in my own table that users can't write, as a new migration. Show me the SQL and how roles get assigned.` });
|
|
844
|
+
if (!always && !anySignedIn) continue;
|
|
845
|
+
const toAuthed = anySignedIn || (/authenticated/.test(p.roles) && !/anon|public/.test(p.roles));
|
|
846
|
+
const who = toAuthed ? "every signed-in user" : "everyone";
|
|
847
|
+
if (p.schema === "storage") {
|
|
848
|
+
if (p.table !== "objects") continue;
|
|
849
|
+
const bucket = conds.join(" ").match(/bucket_id\s*=\s*'([^']+)'/i)?.[1];
|
|
850
|
+
if (p.action === "select" || p.action === "all") {
|
|
851
|
+
if (bucket && p.action === "select") continue; // a policy naming one bucket is judged with the bucket below
|
|
852
|
+
add({ id: `scan:storage-open:${p.action}`, severity: toAuthed && p.action === "select" ? "medium" : "high", where: p.where, title: `${who === "everyone" ? "Anyone" : "Any signed-in user"} can ${p.action === "all" ? "read, replace and delete" : "read"} every file in storage`, why: "The policy on storage.objects lets this through with no condition on the bucket or the file's owner, so every uploaded file is reachable: profile photos, documents, ID scans. The Tea app leaked verification selfies and IDs this way.", fix: "Limit the policy to one bucket and to files under the user's own folder (auth.uid()).", first: null, prompt: `My storage.objects policy lets ${who} ${p.action === "all" ? "read, replace and delete" : "read"} every file in every bucket. Rewrite it as a new migration so each user reaches only files in their own folder (storage.foldername(name))[1] = auth.uid()::text, limited to the right bucket. Keep only truly public buckets (like avatars) readable by everyone, and tell me which you kept.` });
|
|
853
|
+
} else if (!bucket && p.action !== "insert") add({ id: `scan:storage-open:${p.action}`, severity: "high", where: p.where, title: `${who === "everyone" ? "Anyone" : "Any signed-in user"} can ${p.action} any file in storage`, why: "The policy on storage.objects has no condition on the bucket or the owner.", fix: "Limit it to the user's own folder.", first: null, prompt: `My storage.objects policy for ${p.action} lets ${who} through for any file. Rewrite it as a new migration so a user can ${p.action} only files in their own folder ((storage.foldername(name))[1] = auth.uid()::text). Show me the SQL.` });
|
|
854
|
+
continue;
|
|
855
|
+
}
|
|
856
|
+
// Reading a whole table is often meant (products, courses), so those are gathered into one question below.
|
|
857
|
+
if (p.action === "select") {
|
|
858
|
+
const key = `${p.schema}.${p.table}`;
|
|
859
|
+
if (!publicReadSeen[who].has(key) && publicReadSeen[who].add(key)) publicRead[who].push({ table, where: p.where, people: Boolean(created.get(p.table)?.people), known: created.has(p.table) });
|
|
860
|
+
continue;
|
|
861
|
+
}
|
|
862
|
+
// Adding rows is right for a contact form, a waitlist or a log. Changing and deleting rarely is.
|
|
863
|
+
const addOnly = p.action === "insert";
|
|
864
|
+
add({ id: `scan:policy-true:${table}:${p.action}`, severity: addOnly ? "medium" : "high", where: p.where, title: `A rule lets ${who} ${p.action === "all" ? "read, change and delete" : addOnly ? "add" : p.action} rows in "${table}"`, why: `${anySignedIn ? "The policy's condition only asks whether someone is signed in, so any account passes" : 'The policy\'s condition is simply "true"'}: Row Level Security is on but checks nothing about whose row it is.${addOnly ? " That is right for a contact form, a waitlist or a log, and a problem if anything in the app trusts what is in this table." : ""}`, fix: "Compare auth.uid() with the row's owner column instead.", first: null, prompt: `In my database, a Row Level Security policy on "${table}" for ${p.action} ${anySignedIn ? "only checks that the user is signed in" : "uses the condition true"}, so ${toAuthed ? "any signed-in user" : "anyone"} passes it. ${addOnly ? `Tell me first whether "${table}" is meant to take rows from ${toAuthed ? "any signed-in user" : "strangers"} (a form, a waitlist, a log). If it is, keep it but make sure the new row can't claim to belong to someone else (set the owner column from auth.uid(), never from the request) and can't be flooded. If it isn't, rewrite` : "Rewrite"} it so a user can only ${p.action === "all" ? "reach" : p.action} their own rows (auth.uid() = the owner column; add that column if it's missing). Write this as a new migration, don't edit old ones, and show me the SQL.` });
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
// Buckets: public ones, judged by what their name says they hold.
|
|
868
|
+
const bucketPolicies = [...policies.values()].filter((p) => p.schema === "storage" && p.table === "objects" && p.action === "select");
|
|
869
|
+
for (const p of bucketPolicies) {
|
|
870
|
+
const conds = [p.using].filter(Boolean).join(" ");
|
|
871
|
+
const id = conds.match(/bucket_id\s*=\s*'([^']+)'/i)?.[1];
|
|
872
|
+
if (!id || /auth\.uid|auth\.jwt|storage\.foldername/i.test(conds)) continue;
|
|
873
|
+
if (/authenticated/.test(p.roles) && !/anon|public/.test(p.roles)) continue;
|
|
874
|
+
if (!buckets.has(id)) buckets.set(id, { public: true, where: p.where, viaPolicy: true });
|
|
875
|
+
}
|
|
876
|
+
for (const [rawId, b] of buckets) {
|
|
877
|
+
const id = shown(rawId);
|
|
878
|
+
if (!b.public) continue;
|
|
879
|
+
const sensitive = SENSITIVE_BUCKET.test(rawId) || SENSITIVE_BUCKET.test(rawId.replace(UNSAFE, ""));
|
|
880
|
+
add({ id: `scan:public-bucket:${id}`, severity: sensitive ? "critical" : "medium", where: b.where, title: `The storage bucket "${id}" can be read by anyone`, why: `${b.viaPolicy ? "A policy lets everyone read every file in it" : "It is created as a public bucket"}: anyone with a file's address can download it, with no login.${sensitive ? " Its name says it holds documents or IDs. The Tea app leaked 72,000 images, including ID photos, from a bucket like this." : " That is fine for avatars or product photos, and a leak for anything private."}`, fix: "Make the bucket private and hand out short-lived signed URLs to the file's owner.", first: sensitive ? "Check the bucket's access logs: files may already have been downloaded." : null, prompt: `My Supabase storage bucket "${id}" is public, so anyone with a link can download its files. Tell me what it holds. If anything in it is private, write a migration that makes it private (public = false), add a storage.objects policy so users read only files under their own folder, and change the app to use createSignedUrl with a short expiry. Show me the changes.` });
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
for (const [rawView, v] of views) {
|
|
884
|
+
const view = shown(rawView);
|
|
885
|
+
if (v.revoked) continue;
|
|
886
|
+
if (v.auth)
|
|
887
|
+
add({ id: `scan:view-auth-users:${view}`, severity: "critical", where: v.where, title: `The view "${view}" exposes your users' accounts`, why: "It reads from auth.users (emails, phone numbers, sign-in details) and sits in the public schema, where the app's public key can reach it. Supabase's Security Advisor flags this as an error (lint 0002).", fix: "Move the view out of the public schema, or select only harmless columns from your own profiles table.", first: null, prompt: `My view "${view}" in the public schema reads from auth.users, so the app's public key may reach my users' emails and sign-in details. Replace it with a view over my own profiles table that has only the columns the app needs, created with (security_invoker = on), or move it to a private schema. Write it as a new migration and show me the SQL.` });
|
|
888
|
+
else if (!v.invoker && !v.materialized)
|
|
889
|
+
add({ id: `scan:view-definer:${view}`, severity: "high", where: v.where, title: `The view "${view}" skips Row Level Security`, why: "Views run with their creator's rights unless they're created with security_invoker = on, so this view returns rows the user's own rules would hide. Supabase's Security Advisor flags this as an error (lint 0010).", fix: "Recreate it with (security_invoker = on), or revoke access from anon and authenticated.", first: null, prompt: `My view "${view}" isn't created with security_invoker = on, so it ignores the Row Level Security on the tables it reads. Write a new migration: alter view public.${sqlName(view)} set (security_invoker = on); then check the app still works for a signed-in user and tell me if any rule needs changing.` });
|
|
890
|
+
else if (v.materialized)
|
|
891
|
+
add({ id: `scan:matview-exposed:${view}`, severity: "medium", where: v.where, title: `The materialized view "${view}" has no Row Level Security`, why: "Materialized views can't have Row Level Security. If it's in the public schema, the app's public key can read all of it (Supabase lint 0016).", fix: "Move it to a private schema, or revoke select from anon and authenticated.", first: null, prompt: `My materialized view "${view}" is in the public schema, and materialized views can't have Row Level Security. Tell me what it contains. If any of it is private, move it to a private schema or revoke select on it from anon and authenticated, in a new migration.` });
|
|
892
|
+
}
|
|
893
|
+
for (const [rawFn, f] of definers) {
|
|
894
|
+
const fn = shown(rawFn);
|
|
895
|
+
if (f.revoked) continue;
|
|
896
|
+
add({ id: `scan:definer-function:${fn}`, severity: f.dynamicSql ? "high" : "medium", where: f.where, title: `The function "${fn}" runs with full rights and anyone can call it`, why: `It's SECURITY DEFINER in the public schema, so it skips Row Level Security, and Supabase lets the public key call public functions unless execute is revoked (lint 0028).${f.dynamicSql ? " It also builds SQL from text at run time, so a caller may be able to run any query (lint 0031)." : ""}`, fix: "Revoke execute from anon (and public), or make it SECURITY INVOKER.", first: null, prompt: `My function "${fn}" is SECURITY DEFINER in the public schema, so anyone with the public key can call it and it ignores Row Level Security. Write a new migration that revokes execute on it from public and anon (grant it only to authenticated if needed), sets search_path = '', and makes it check auth.uid() itself${f.dynamicSql ? ". It also runs SQL built from text: rewrite that part without dynamic SQL, or with format('%I', …) and a fixed list of allowed names" : ""}. Show me the SQL.` });
|
|
897
|
+
}
|
|
898
|
+
|
|
899
|
+
// Firebase/Google keys in browser code that may now call Gemini.
|
|
900
|
+
if (keyFiles.length) {
|
|
901
|
+
const k = keyFiles.find((x) => x.client) ?? keyFiles[0];
|
|
902
|
+
add({ id: `scan:google-key:${k.name}`, severity: project.gemini && k.client ? "high" : "low", where: `${k.name}:${k.line}`, title: project.gemini && k.client ? "A Google API key in browser code, in a project that uses Gemini" : "A Google API key is in the code: make sure it can't call Gemini", why: "Google API keys (AIza…) used to be safe to publish, for Firebase or Maps. Since Gemini, the same key can call the Gemini API if the Generative Language API is switched on in its project, and run up your bill. Truffle Security found 2,863 live keys like this.", fix: "Restrict the key to the APIs and websites it needs, and keep Gemini calls on a server with its own key.", first: null, prompt: `My code has a Google API key (AIza…) at ${k.name}:${k.line}. Don't show me the value. Tell me how to check in Google Cloud whether this key can call the Generative Language (Gemini) API, how to restrict it to only the APIs and websites it needs, and, if the app calls Gemini, move those calls into a server route with a separate key kept in a server-side secret.` });
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
// From the top of the repository: a .env committed above the folder being checked still ships with it.
|
|
906
|
+
const gitUnavailable = !Array.isArray(tracked);
|
|
907
|
+
if (!gitUnavailable) {
|
|
908
|
+
const prefix = `/${String(opts.prefix ?? "").replace(/^\/+|\/+$/g, "")}`;
|
|
909
|
+
const notSent = [];
|
|
910
|
+
let found = false;
|
|
911
|
+
// Lovable and others commit a .env that holds only browser-safe values (the Supabase URL and
|
|
912
|
+
// publishable key). That is not a leak, so flag a tracked .env only when it holds a filled-in
|
|
913
|
+
// value whose name says it is secret. Values are read to see whether they are empty, never shown.
|
|
914
|
+
for (const env of tracked.filter(TRACKED_ENV)) {
|
|
915
|
+
const shown = path.posix.relative(prefix, `/${env}`) || env;
|
|
916
|
+
const raw = get(shown);
|
|
917
|
+
if (raw == null) {
|
|
918
|
+
notSent.push({ env, shown });
|
|
919
|
+
continue;
|
|
920
|
+
}
|
|
921
|
+
if (found) continue;
|
|
922
|
+
const secrets = envSecretNames(textOf(raw));
|
|
923
|
+
if (!secrets.length) continue;
|
|
924
|
+
const list = secrets.slice(0, 8).join(", ") + (secrets.length > 8 ? ` and ${secrets.length - 8} more` : "");
|
|
925
|
+
add({ id: "scan:env-tracked", severity: "high", where: shown, title: `Your ${env} file is saved in version control, with secrets in it`, why: `It holds ${list}. Everyone with access to the repository, now or later, has those values. If the repository is public, so does the world.`, fix: "Remove it from git, add it to .gitignore, and replace those keys.", first: "Replace each of those keys: once committed, a key stays in the history.", prompt: `My ${env} file is tracked by git and holds secrets (${list}). Remove it from version control without deleting my local copy (git rm --cached), add it to .gitignore, and give me an .env.example with the names only. Then tell me where to replace each of those keys.` });
|
|
926
|
+
found = true;
|
|
927
|
+
}
|
|
928
|
+
// Only when the caller didn't send a tracked .env's values (a hosted check never fetches them).
|
|
929
|
+
if (notSent.length) {
|
|
930
|
+
const names = notSent.map((n) => n.env);
|
|
931
|
+
const list = names.slice(0, 8).join(", ") + (names.length > 8 ? ` and ${names.length - 8} more` : "");
|
|
932
|
+
const one = names.length === 1;
|
|
933
|
+
add({ id: "scan:env-review", severity: "medium", where: notSent[0].shown, title: one ? `A .env file is in the repo (${names[0]}): check it holds no secret key` : `${names.length} .env files are in the repo: check they hold no secret key`, why: `${list} ${one ? "is" : "are"} saved in version control. Greenlit didn't read ${one ? "its" : "their"} values, so it can't tell whether ${one ? "it holds" : "they hold"} only values meant for the browser (the Supabase URL and publishable key are fine there) or a secret key, which everyone with access to the repository would have.`, fix: "Open it and check each value. If one is a secret key, remove the file from git, add it to .gitignore, and replace that key.", first: null, prompt: `My repository tracks ${list}. Without showing me any values, tell me for each name in ${one ? "it" : "them"} whether it is a secret (a service_role key, a payment or AI provider key, a database password) or a value meant for the browser (the Supabase URL and publishable key). If any is a secret, remove the file from version control without deleting my local copy (git rm --cached), add it to .gitignore, give me an .env.example with the names only, and tell me where to replace each secret.` });
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
for (const [who, list] of Object.entries(publicRead)) {
|
|
938
|
+
if (!list.length) continue;
|
|
939
|
+
const names = list.map((t) => t.table);
|
|
940
|
+
add({ id: `scan:public-read:${who === "everyone" ? "everyone" : "signed-in"}`, severity: "medium", where: list[0].where, tables: list, title: `${list.length} table${list.length > 1 ? "s" : ""} can be read in full by ${who}`, why: `${names.slice(0, 15).join(", ")}${names.length > 15 ? ` and ${names.length - 15} more` : ""}. Each has a policy whose condition is simply "true"${who === "everyone" ? "" : " or only asks whether someone is signed in"}. That is fine for a public list such as products or courses, and a leak for anything about people.`, fix: "Go through the list: keep the ones that are meant to be public, and limit the rest to the row's owner.", first: null, prompt: `These tables in my database have a read policy that lets ${who === "everyone" ? "anyone on the internet" : "any signed-in user"} read every row: ${names.join(", ")}. Go through them one by one and tell me, for each, whether it holds anything about a specific person (names, emails, messages, payments, activity). Change nothing yet. Then list the ones you would restrict to the row's owner, and wait for my OK.` });
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
// A lockfile only matters when there is something to lock.
|
|
944
|
+
const hasDeps = Object.keys(deps).length > 0;
|
|
945
|
+
if (hasDeps && !["package-lock.json", "pnpm-lock.yaml", "yarn.lock", "bun.lockb", "bun.lock"].some(exists))
|
|
946
|
+
add({ id: "scan:no-lockfile", severity: "low", where: "package.json", title: "No lockfile", why: "Without a lockfile every build may install different versions of your dependencies, so the app you tested isn't the app you ship.", fix: "Commit the lockfile your package manager creates.", first: null, prompt: "My project has no lockfile. Run the install for the package manager this project uses, commit the lockfile it creates, and make the build use it." });
|
|
947
|
+
|
|
948
|
+
// The built app (dist/, build/, out/, .next/static) is skipped above because it repeats the source. But it is what
|
|
949
|
+
// ships to every visitor, and it holds values the source only names: a VITE_ or NEXT_PUBLIC_ variable is replaced by
|
|
950
|
+
// its value at build time. Priberry's study found AI keys shipped this way in about 1 in 30 public Lovable apps.
|
|
951
|
+
// Only key shapes and service_role tokens are looked for here, never code patterns, and values are never shown.
|
|
952
|
+
const built = opts.built ?? BUILT;
|
|
953
|
+
for (const out of BUILT) {
|
|
954
|
+
if (!built.includes(out)) continue;
|
|
955
|
+
const inside = keys.filter((k) => k.startsWith(`${out}/`) && !k.endsWith("/"));
|
|
956
|
+
if (!inside.length) continue;
|
|
957
|
+
// Depth first in name order, as a disk walk goes, up to BUNDLE_MAX_FILES files read.
|
|
958
|
+
const stack = [treeOf(inside, out.length + 1)];
|
|
959
|
+
let read = 0;
|
|
960
|
+
while (stack.length && read < BUNDLE_MAX_FILES) {
|
|
961
|
+
const d = stack.pop();
|
|
962
|
+
for (const [entry, v] of entriesOf(d)) {
|
|
963
|
+
if (typeof v !== "string") {
|
|
964
|
+
stack.push(v);
|
|
965
|
+
continue;
|
|
966
|
+
}
|
|
967
|
+
if (!BUNDLE_FILE.test(entry)) continue;
|
|
968
|
+
if (over()) break;
|
|
969
|
+
const raw = get(v);
|
|
970
|
+
if (raw == null || sizeOf(raw) > BUNDLE_MAX_BYTES) continue;
|
|
971
|
+
bytes += sizeOf(raw);
|
|
972
|
+
const text = textOf(raw);
|
|
973
|
+
const lineAt = linesOf(text);
|
|
974
|
+
read++;
|
|
975
|
+
const name = v;
|
|
976
|
+
for (const [kind, re] of KEY_SHAPES) {
|
|
977
|
+
for (const m of text.matchAll(re)) {
|
|
978
|
+
if (PLACEHOLDER.test(m[0].slice(6)) || /^(.)\1+$/.test(m[0].slice(-12))) continue;
|
|
979
|
+
add({ id: `scan:key-in-bundle:${out}:${shortHash(kind)}`, severity: "critical", where: `${name}:${lineAt(m.index)}`, title: `${kind[0].toUpperCase()}${kind.slice(1)} is in the built app that ships to visitors`, why: `The ${out}/ folder is what gets deployed, and anyone who opens the app can read this key from its JavaScript. The source may only name it (a VITE_ or NEXT_PUBLIC_ variable is swapped for its value when the app is built), so the key can be missing from the code and still be public.`, fix: "Move the call that needs this key into a server function, read the key there from a secret, and rebuild.", first: "Rotate this key now: if the app was ever deployed with it, it is already public.", prompt: `My built app in ${out}/ contains ${kind}. Don't show me the value. First tell me where to rotate it. Then find which environment variable puts it into the browser build (a VITE_ or NEXT_PUBLIC_ prefix, or a define in the build config), move the code that uses it into a server function or Supabase edge function that reads it from a secret, rebuild, and confirm the key no longer appears anywhere in ${out}/.` });
|
|
980
|
+
break;
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
for (const m of text.matchAll(/\beyJ[A-Za-z0-9_-]{10,}\.(eyJ[A-Za-z0-9_-]{10,})\.[A-Za-z0-9_-]{8,}/g)) {
|
|
984
|
+
let role = "";
|
|
985
|
+
try {
|
|
986
|
+
role = JSON.parse(fromBase64url(m[1])).role;
|
|
987
|
+
} catch {}
|
|
988
|
+
if (role !== "service_role") continue;
|
|
989
|
+
add({ id: `scan:service-role-in-bundle:${out}`, severity: "critical", where: `${name}:${lineAt(m.index)}`, title: "The Supabase service_role key is in the built app that ships to visitors", why: "The service_role key skips every Row Level Security rule. It's in the deployed JavaScript, so anyone can read, change or delete everything in the database.", fix: "Use the publishable (anon) key in the browser and move admin work into an edge function that checks who's calling.", first: "Rotate the service_role key in the Supabase dashboard now, before anything else.", prompt: `My built app in ${out}/ contains my Supabase service_role key. Don't show me the value. First tell me how to rotate it in the Supabase dashboard. Then find what puts it into the browser build, replace it with the publishable key, move anything that needs admin rights into an edge function that checks the signed-in user, rebuild, and confirm the key no longer appears in ${out}/.` });
|
|
990
|
+
break;
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
const order = ["critical", "high", "medium", "low", "info"];
|
|
997
|
+
findings.sort((a, b) => order.indexOf(a.severity) - order.indexOf(b.severity));
|
|
998
|
+
// Nothing taken from the project's files reaches a terminal or a prompt with control or bidi characters in it
|
|
999
|
+
// (a quoted SQL snippet in a "why", a bucket id): each becomes a space.
|
|
1000
|
+
const safe = (v) => (typeof v === "string" ? v.replace(UNSAFE, " ") : Array.isArray(v) ? v.map(safe) : v && typeof v === "object" ? Object.fromEntries(Object.entries(v).map(([k, x]) => [k, safe(x)])) : v);
|
|
1001
|
+
for (let j = 0; j < findings.length; j++) findings[j] = safe(findings[j]);
|
|
1002
|
+
const result = { source: "your project's files", dir: opts.dir ?? null, files: list.length, findings, truncated: truncated || stopped != null, unread, gitUnavailable, nested: nested.filter((n) => reachable(n, nested)) };
|
|
1003
|
+
if (stopped) result.stopped = stopped;
|
|
1004
|
+
if (skippedPaths.length) result.skippedPaths = skippedPaths;
|
|
1005
|
+
return result;
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
// ---------- .env files
|
|
1009
|
+
// Names that are meant to reach the browser (and are safe there) never count as secrets.
|
|
1010
|
+
const BROWSER_SAFE_ENV = /(^|_)(SUPABASE_(URL|ANON_KEY|PUBLISHABLE_KEY|PUBLISHABLE_DEFAULT_KEY|PROJECT_ID|PROJECT_REF)|FIREBASE_(API_KEY|AUTH_DOMAIN|PROJECT_ID|STORAGE_BUCKET|MESSAGING_SENDER_ID|APP_ID|MEASUREMENT_ID|DATABASE_URL)|PUBLISHABLE_KEY|STRIPE_PUBLISHABLE_KEY|CLERK_PUBLISHABLE_KEY|POSTHOG_KEY|SENTRY_DSN|GA_MEASUREMENT_ID|MAPBOX_TOKEN)$/i;
|
|
1011
|
+
const SECRET_ENV = /(SECRET|PASSWORD|PASSWD|PRIVATE|CREDENTIAL|SERVICE_ROLE|SERVICE_KEY|TOKEN|API_KEY|ACCESS_KEY|_KEY$|^KEY$|DATABASE_URL|DB_URL|POSTGRES_URL|MONGODB_URI|REDIS_URL|DSN$|WEBHOOK)/i;
|
|
1012
|
+
// The names of filled-in secret values in the text of a .env file.
|
|
1013
|
+
export function envSecretNames(text) {
|
|
1014
|
+
const out = [];
|
|
1015
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
1016
|
+
const line = raw.trim();
|
|
1017
|
+
if (!line || line.startsWith("#")) continue;
|
|
1018
|
+
const m = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_.-]*)\s*=\s*(.*)$/.exec(line);
|
|
1019
|
+
if (!m) continue;
|
|
1020
|
+
const [, name, rawValue] = m;
|
|
1021
|
+
const value = rawValue.replace(/\s+#.*$/, "").replace(/^(["'])(.*)\1$/, "$2").trim();
|
|
1022
|
+
if (!value || /^(your|xxx|changeme|replace|<|\$\{|\{\{)|fake|dummy|placeholder/i.test(value)) continue;
|
|
1023
|
+
if (BROWSER_SAFE_ENV.test(name) || !SECRET_ENV.test(name)) continue;
|
|
1024
|
+
// A name with a public prefix ships to the browser anyway; if it's a secret, the public-secret check says so.
|
|
1025
|
+
if (/^(VITE_|NEXT_PUBLIC_|PUBLIC_|EXPO_PUBLIC_|REACT_APP_|NUXT_PUBLIC_|GATSBY_)/.test(name)) continue;
|
|
1026
|
+
// A database address with no password in it (a local SQLite file, postgres://localhost/app) is not a secret.
|
|
1027
|
+
if (/^(sqlite|file)[:+]/i.test(value)) continue;
|
|
1028
|
+
if (/^(postgres(ql)?|mysql|mariadb|mongodb(\+srv)?|redis|rediss|mssql)(\+\w+)?:\/\//i.test(value) && !/:\/\/[^/@\s]*:[^@\s]+@/.test(value) && !/[?&](password|pass|pwd|token|key|secret)=/i.test(value)) continue;
|
|
1029
|
+
out.push(name);
|
|
1030
|
+
}
|
|
1031
|
+
return out;
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
// ---------- Firebase rules
|
|
1035
|
+
// The match paths that enclose a position in a rules file, outermost first (siblings closed before it don't count).
|
|
1036
|
+
function enclosingMatches(rules, at) {
|
|
1037
|
+
const stack = [];
|
|
1038
|
+
for (const m of rules.slice(0, at).matchAll(/match\s+(\/(?:\{[^}\s]*\}|[^\s{])*)\s*\{|\{|\}/g)) {
|
|
1039
|
+
if (m[1] !== undefined) stack.push(m[1]);
|
|
1040
|
+
else if (m[0] === "{") stack.push(null);
|
|
1041
|
+
else stack.pop();
|
|
1042
|
+
}
|
|
1043
|
+
return stack.filter(Boolean);
|
|
1044
|
+
}
|
|
1045
|
+
const PERSONAL_PATH = /(^|\/)[a-z0-9_-]*(user|profile|account|customer|member|message|chat|conversation|order|payment|invoice|transaction|patient|medical|health|booking|appointment|address|contact|lead(?!er)|employee|student|applica|candidate|document|upload|private|secret|token|credential|session|wallet|notification|inbox|kyc|verif)/i;
|
|
1046
|
+
function scanFirebase(name, text, add) {
|
|
1047
|
+
const lineAt = linesOf(text); // the comment-blanked rules below keep the same newlines
|
|
1048
|
+
if (/\.json$/.test(name)) {
|
|
1049
|
+
// Realtime Database: ".read": true anywhere, or "auth != null" for the whole database.
|
|
1050
|
+
for (const m of text.matchAll(/"\.(read|write)"\s*:\s*(?:true|"true")/g)) {
|
|
1051
|
+
const line = lineAt(m.index);
|
|
1052
|
+
add({ id: `scan:firebase-open:database:${m[1]}:${shortHash(text.slice(Math.max(0, m.index - 200), m.index))}`, severity: "critical", where: `${name}:${line}`, title: `Your Realtime Database rules let anyone ${m[1]} this data`, why: `"${m[0]}" lets anyone on the internet ${m[1]} it, signed in or not.`, fix: 'Use "auth != null && auth.uid === $uid" under a per-user path instead of true.', first: m[1] === "write" ? "Look for data you didn't put there: anyone could have changed or deleted it." : null, prompt: `My Firebase Realtime Database rules in ${name} set ".${m[1]}": true at line ${line}, so anyone can ${m[1]} the data. Rewrite them so each user reaches only their own data (for example under users/$uid with auth != null && auth.uid === $uid), keep anything truly public read-only and say which it is, and show me the new rules.` });
|
|
1053
|
+
}
|
|
1054
|
+
let rules;
|
|
1055
|
+
try {
|
|
1056
|
+
rules = JSON.parse(text.replace(/\/\*[\s\S]*?\*\/|(^|[^:"])\/\/[^\n]*/g, "$1")).rules;
|
|
1057
|
+
} catch {}
|
|
1058
|
+
for (const op of ["read", "write"]) {
|
|
1059
|
+
const v = rules?.[`.${op}`];
|
|
1060
|
+
if (typeof v === "string" && /^\s*auth\s*!==?\s*null\s*$/.test(v))
|
|
1061
|
+
add({ id: `scan:firebase-signed-in:database:${op}`, severity: "high", where: name, title: `Any signed-in user can ${op} your whole Realtime Database`, why: `".${op}": "auth != null" at the top of the rules lets every account ${op} everything. Anyone can make an account.`, fix: "Scope rules to per-user paths: users/$uid with auth.uid === $uid.", first: null, prompt: `My Firebase Realtime Database rules give every signed-in user ".${op}" access to the whole database. Rewrite them so each user reaches only their own data under a path like users/$uid (auth.uid === $uid), with anything truly shared listed explicitly. Show me the new rules.` });
|
|
1062
|
+
}
|
|
1063
|
+
return;
|
|
1064
|
+
}
|
|
1065
|
+
const rules = text.replace(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, (m) => m.replace(/[^\n]/g, " "));
|
|
1066
|
+
const kind = /firebase\.storage/.test(rules) ? "Storage" : "Firestore";
|
|
1067
|
+
const k = kind.toLowerCase();
|
|
1068
|
+
// allow <ops>; allow <ops>: if <condition>; (the semicolon is optional before "}")
|
|
1069
|
+
for (const m of rules.matchAll(/\ballow\s+([a-z]+(?:\s*,\s*[a-z]+){0,8})\s*(?::\s*if\b([^;{}]{0,2000}))?\s*(?:;|(?=\}))/g)) {
|
|
1070
|
+
const actions = m[1].replace(/\s+/g, "").split(",").filter(Boolean);
|
|
1071
|
+
const cond = m[2] == null ? null : m[2].trim();
|
|
1072
|
+
const parts = cond == null ? ["true"] : disjuncts(cond);
|
|
1073
|
+
const open = parts.some((p) => /^(true|\(?\s*true\s*\)?)$/.test(unwrapParens(p)));
|
|
1074
|
+
const testMode = !open && parts.some((p) => /^request\.time\s*<\s*timestamp\.date\s*\(/.test(unwrapParens(p)));
|
|
1075
|
+
const signedIn = !open && !testMode && parts.length === 1 && /^request\.auth\s*!=\s*null$|^request\.auth\.uid\s*!=\s*null$/.test(unwrapParens(parts[0]));
|
|
1076
|
+
if (!open && !testMode && !signedIn) continue;
|
|
1077
|
+
// The match path this rule sits under: the nearest "match /…" before it.
|
|
1078
|
+
const before = rules.slice(0, m.index);
|
|
1079
|
+
const paths = [...before.matchAll(/match\s+(\/(?:\{[^}\s]*\}|[^\s{])*)\s*\{/g)];
|
|
1080
|
+
const matchPath = paths.length ? paths[paths.length - 1][1] : "";
|
|
1081
|
+
const wildcard = /^\/\{\w+=\*\*\}$/.test(matchPath); // a catch-all for everything, not "/avatars/{path=**}"
|
|
1082
|
+
if (signedIn && !wildcard) continue; // "signed in" on one collection is often meant; the agent reviews it
|
|
1083
|
+
const writes = actions.some((a) => ["write", "create", "update", "delete"].includes(a));
|
|
1084
|
+
// Anyone reading a collection is often meant (listings, posts, videos, images). Flag an open read only on a
|
|
1085
|
+
// catch-all path or where the path looks like people's data; open writes and test mode are always flagged.
|
|
1086
|
+
const near = enclosingMatches(rules, m.index).filter((p) => !/^\/(databases|b)\//.test(p)).join("");
|
|
1087
|
+
if (!writes && !testMode && !wildcard && !PERSONAL_PATH.test(near)) continue;
|
|
1088
|
+
const line = lineAt(m.index);
|
|
1089
|
+
const what = writes ? (actions.some((a) => ["read", "get", "list"].includes(a)) ? "read and change" : "change") : "read";
|
|
1090
|
+
const id = `scan:firebase-open:${k}:${shortHash(`${matchPath}|${actions.join(",")}|${cond ?? ""}`)}`;
|
|
1091
|
+
if (signedIn) {
|
|
1092
|
+
add({ id, severity: "high", where: `${name}:${line}`, title: `Any signed-in user can ${what} all of your ${kind} data`, why: `"allow ${actions.join(", ")}: if request.auth != null" on ${matchPath} lets every account ${what} every document, not just their own. Anyone can make an account.`, fix: "Check that the document belongs to request.auth.uid, collection by collection.", first: null, prompt: `My ${kind} rules in ${name} let any signed-in user ${what} everything under ${matchPath}. Replace that catch-all with rules per collection, so a user reaches only documents they own (request.auth.uid == resource.data.ownerId or the path's user id), with anything truly shared listed explicitly. Show me the new rules and how to test them with the emulator.` });
|
|
1093
|
+
continue;
|
|
1094
|
+
}
|
|
1095
|
+
add({ id, severity: writes || kind === "Firestore" ? "critical" : "high", where: `${name}:${line}`, title: `Your ${kind} rules let anyone ${what} this data${testMode ? " until a date" : ""}`, why: testMode ? "This is Firebase's test-mode rule: until that date, anyone on the internet passes it, signed in or not. Data is often left in test mode by accident." : `${cond == null ? `"allow ${actions.join(", ")}" with no condition` : `"if ${cond.replace(/\s+/g, " ").slice(0, 80)}"`} lets anyone on the internet ${what} it, signed in or not, with nothing but the project's public config.`, fix: "Allow access only when request.auth != null and the document belongs to request.auth.uid.", first: writes ? "Look for data you didn't put there: with write open, anyone could have changed or deleted it." : null, prompt: `My ${kind === "Storage" ? "Firebase Storage" : "Firestore"} security rules in ${name} at line ${line} let anyone on the internet ${what} the data under ${matchPath || "this path"}. Rewrite the rules so a signed-in user reaches only their own documents (request.auth != null && request.auth.uid == the owner field or path segment), keep anything truly public read-only and say which it is, and show me the new rules file. Then tell me how to test them with the Firebase emulator before deploying.` });
|
|
1096
|
+
}
|
|
1097
|
+
}
|