greenlitlab 0.4.4 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,6 +1,34 @@
1
1
  # Changelog
2
2
 
3
- ## 0.4.4 (unreleased)
3
+ ## 0.5.1 (unreleased)
4
+
5
+ Hand-checked against real public Lovable projects (25 November 2026). Each wrong answer became a test case.
6
+
7
+ - **Fewer false alarms:**
8
+ - Lovable's default `.env` (Supabase URL and publishable key) is fine. A tracked `.env` is flagged only when it holds a filled-in secret whose name doesn't ship to the browser anyway.
9
+ - Examples, fixtures and root `tests/` folders are skipped, because security tools plant leaks there on purpose. A key with a real key's shape still counts there.
10
+ - Row Level Security isn't expected of MySQL or SQLite migrations.
11
+ - These are no longer read as secrets: secret names in comments, in quoted lists of names, or held as JSON values, and Shopify storefront and EmailJS public keys.
12
+ - `verify_jwt = false` is fine when the function checks the signed-in user (`auth.getUser`, `getClaims`), a cron secret or an API key header in its own code.
13
+ - `with (security_invoker)` with no value counts as on.
14
+ - A tracked `.env` holding a database address with no password in it (a local SQLite file, `postgres://localhost/app`) isn't a secret.
15
+ - Firestore and Storage rules that let anyone read a collection are flagged only on catch-all paths (`/{document=**}`, not `/avatars/{path=**}`) or paths that look like people's data (users, messages, orders, uploads…). Public listings, posts and images are often meant to be readable. Open writes and test-mode rules are still always flagged.
16
+ - An AI SDK set to run in the browser (`dangerouslyAllowBrowser: true`) is flagged only when its key comes from the build environment or is written into the code, not when the visitor types in their own key.
17
+ - **Clearer findings:**
18
+ - A login secret used only as a fallback for a missing environment variable (`process.env.JWT_SECRET || "…"`, `os.getenv("SECRET_KEY", "…")`) is its own finding, `scan:auth-secret-fallback`.
19
+ - Login secrets passed straight to `jwt.sign`, express-session, cookieParser or Flask's config are caught.
20
+
21
+ ## 0.5.0 (23 November 2026)
22
+
23
+ `greenlit scan` was rebuilt after an adversarial audit of the project scan that Launch Blockers runs before deploys.
24
+
25
+ - **SQL is read statement by statement, in the order the migrations run.** Row Level Security switched off again, tables dropped or renamed, and policies altered, renamed or dropped are all followed, so a later migration that undoes a fix is caught. A rule that only asks whether someone is signed in (`auth.uid() is not null`) is treated like `true`: any account passes it. Restrictive policies and policies for the service role alone are left out.
26
+ - **New checks:** public storage buckets (from migrations and `supabase/config.toml`, critical when the name says IDs or documents), `storage.objects` policies with no owner check, views that skip Row Level Security or read `auth.users`, SECURITY DEFINER functions anyone can call (high when they run SQL built from text), rules that trust `user_metadata`, keys recognised by their shape (Stripe, OpenAI, Anthropic, AWS, GitHub and others; reported by kind and line, never the value), a Supabase key whose role is service_role written into code, `dangerouslyAllowBrowser: true`, login secrets written into code or used as a fallback, Google `AIza` keys in browser code of a project that uses Gemini, Firebase `request.auth != null` on a catch-all path and on a whole Realtime Database, and Stripe routes that act on a request body without a signature check, whatever the file is called.
27
+ - **Fewer misses:** a `.env` committed at the top of the repository is found when a subfolder is checked; symlinked folders are followed once; Firebase rules with no semicolon or with `true ||` are read; `verify_jwt` is read from TOML with comments and quoted names; table protection switched on by a fixed statement inside `execute` counts.
28
+ - **Fewer false alarms:** other checkouts inside the project (git worktrees, submodules) are skipped; files that run on a server (TanStack server functions, anything reading `process.env`, `.server`/`.nitro` files) aren't treated as browser code; a private-key header in a regex isn't a key.
29
+ - **It says what it couldn't read:** results include `truncated` (more than 20,000 files), `unread` (a rules or config file too big to read) and `gitUnavailable`. Firebase finding ids now come from the rule, not its line number, so an ignore entry survives edits above it.
30
+
31
+ ## 0.4.4 (20 November 2026)
4
32
 
5
33
  - `greenlit scan` no longer raises an alarm for `verify_jwt = false` on a webhook whose code verifies the sender's signature (Stripe, Svix, GitHub and others): it's reported as low, to confirm the check runs first.
6
34
  - `greenlit scan` reads Firebase rules: `firestore.rules`, `storage.rules` and `database.rules.json`. A rule of `if true`, or Firebase's test-mode date rule, is reported with a fix prompt (critical for database data and anything writable, high for a public read of files, which may be intended). Open Firebase rules are a common cause of leaks from mobile and AI apps.
package/package.json CHANGED
@@ -1,20 +1,48 @@
1
1
  {
2
2
  "name": "greenlitlab",
3
- "version": "0.4.4",
3
+ "version": "0.5.1",
4
4
  "description": "Is your AI-built app safe to launch? A grade from A to F for apps built with Lovable, Bolt, v0, Replit or Emergent, with a fix prompt for every problem. Checks leaks, open data and launch basics.",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "greenlit": "bin/greenlit.mjs",
8
8
  "greenlitlab": "bin/greenlit.mjs"
9
9
  },
10
- "files": ["bin", "src", "README.md", "CHANGELOG.md", "SECURITY.md", "LICENSE", "server.json"],
11
- "engines": { "node": ">=20" },
12
- "scripts": { "test": "node --test test/*.test.mjs" },
10
+ "files": [
11
+ "bin",
12
+ "src",
13
+ "README.md",
14
+ "CHANGELOG.md",
15
+ "SECURITY.md",
16
+ "LICENSE",
17
+ "server.json"
18
+ ],
19
+ "engines": {
20
+ "node": ">=20"
21
+ },
22
+ "scripts": {
23
+ "test": "node --test test/*.test.mjs"
24
+ },
13
25
  "license": "Apache-2.0",
14
- "keywords": ["lovable", "bolt", "v0", "replit", "supabase", "firebase", "vibe-coding", "security", "mcp", "ai-app-builder"],
26
+ "keywords": [
27
+ "lovable",
28
+ "bolt",
29
+ "v0",
30
+ "replit",
31
+ "supabase",
32
+ "firebase",
33
+ "vibe-coding",
34
+ "security",
35
+ "mcp",
36
+ "ai-app-builder"
37
+ ],
15
38
  "homepage": "https://greenlit.priberry.com",
16
- "bugs": { "url": "https://github.com/priberry-data/greenlitlab/issues" },
39
+ "bugs": {
40
+ "url": "https://github.com/priberry-data/greenlitlab/issues"
41
+ },
17
42
  "author": "Priberry",
18
- "repository": { "type": "git", "url": "git+https://github.com/priberry-data/greenlitlab.git" },
43
+ "repository": {
44
+ "type": "git",
45
+ "url": "git+https://github.com/priberry-data/greenlitlab.git"
46
+ },
19
47
  "mcpName": "io.github.priberry-data/greenlitlab"
20
48
  }
package/server.json CHANGED
@@ -5,12 +5,12 @@
5
5
  "description": "Grade apps built with Lovable, Bolt, v0 or Replit A to F, with a fix prompt for every problem.",
6
6
  "websiteUrl": "https://greenlit.priberry.com",
7
7
  "repository": { "url": "https://github.com/priberry-data/greenlitlab", "source": "github" },
8
- "version": "0.4.4",
8
+ "version": "0.5.0",
9
9
  "packages": [
10
10
  {
11
11
  "registryType": "npm",
12
12
  "identifier": "greenlitlab",
13
- "version": "0.4.4",
13
+ "version": "0.5.0",
14
14
  "transport": { "type": "stdio" },
15
15
  "packageArguments": [{ "type": "positional", "value": "mcp" }]
16
16
  }
package/src/scan.mjs CHANGED
@@ -1,49 +1,229 @@
1
1
  // greenlit scan [folder]: reads a project's own files, on your computer, for the launch mistakes that can't be
2
2
  // seen from outside: rules that let everyone in, functions that skip the sign-in check, payment messages nobody
3
- // verifies, secrets named so they ship to the browser. Node only. Reads names in .env files, never values.
3
+ // verifies, secrets that ship to the browser. Node only. Reads names in .env files, never values; a key found in
4
+ // code is reported by its kind and place, never by its value.
4
5
  import fs from "node:fs";
5
6
  import path from "node:path";
7
+ import crypto from "node:crypto";
6
8
  import { execFileSync } from "node:child_process";
7
9
 
8
- // Build output, dependencies, agents' working copies, and tests (whose made-up secrets and tables aren't the app's).
9
- const SKIP = new Set(["node_modules", ".claude", "worktrees", "__tests__", "__mocks__", "__fixtures__", "fixtures", "test", "tests", "e2e", "cypress", ".git", "dist", "build", ".next", ".vercel", ".netlify", ".wrangler", "coverage", ".turbo", ".cache", "vendor", "__pycache__", ".venv"]);
10
- const TEXT = /\.(sql|toml|json|js|jsx|ts|tsx|mjs|cjs|py|vue|svelte|rules)$|(^|\/)\.env[^/]*$/;
11
- const PUBLIC_PREFIX = "(?:VITE_|NEXT_PUBLIC_|REACT_APP_|EXPO_PUBLIC_|PUBLIC_|NUXT_PUBLIC_)";
12
- // The name must END in the secret word (or _KEY/_TOKEN after it): VITE_STRIPE_SECRET_KEY is a secret,
13
- // VITE_PASSWORD_MIN_LENGTH and VITE_WEBHOOK_URL are settings.
14
- const SECRET_NAME = new RegExp(`\\b(${PUBLIC_PREFIX}[A-Z0-9_]*?(?:SECRET(?:_KEY|_TOKEN)?|SERVICE_ROLE(?:_KEY)?|PRIVATE_KEY|PASSWORD|DATABASE_URL))(?![A-Z0-9_])`, "g");
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");
15
22
  // A key for a paid service behind a public prefix (VITE_OPENAI_API_KEY) is the same mistake under another name.
16
- const PAID_KEY_NAME = new RegExp(`\\b(${PUBLIC_PREFIX}[A-Z0-9_]*?(?:OPENAI|ANTHROPIC|CLAUDE|GEMINI|GROQ|OPENROUTER|MISTRAL|PERPLEXITY|REPLICATE|HUGGINGFACE|RESEND|SENDGRID|MAILGUN|TWILIO|GITHUB)[A-Z0-9_]*?(?:KEY|TOKEN))(?![A-Z0-9_])`, "g");
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 notPgDirs = new Map();
33
+ function notPostgres(dir) {
34
+ if (!notPgDirs.has(dir)) {
35
+ let hit = false;
36
+ try {
37
+ for (const f of fs.readdirSync(dir)) {
38
+ if (!f.endsWith(".sql")) continue;
39
+ const p = path.join(dir, f);
40
+ if (fs.statSync(p).size < 4 * 1024 * 1024 && NOT_PG.test(fs.readFileSync(p, "utf8"))) { hit = true; break; }
41
+ }
42
+ } catch {}
43
+ notPgDirs.set(dir, hit);
44
+ }
45
+ return notPgDirs.get(dir);
46
+ }
47
+ // A name written in a comment (a doc line, a commented-out example) ships nothing to the browser.
48
+ function inComment(text, index) {
49
+ const start = text.lastIndexOf("\n", index - 1) + 1;
50
+ const before = text.slice(start, index);
51
+ return /^\s*(\*|\/\*|\/\/|#|--|<!--)/.test(before) || /(^|[^:"'`])\/\/[^"'`]*$/.test(before);
52
+ }
53
+ // Keys recognised by their shape, wherever they're written. Only the kind and the place are ever reported.
54
+ const KEY_SHAPES = [
55
+ ["a live Stripe secret key", /\b[rs]k_live_[0-9A-Za-z]{10,}/g],
56
+ ["a Stripe webhook signing secret", /\bwhsec_[0-9A-Za-z]{20,}/g],
57
+ ["an OpenAI key", /\bsk-(?:proj|svcacct|admin)-[A-Za-z0-9_-]{16,}|\bsk-[A-Za-z0-9]{40,}\b/g],
58
+ ["an Anthropic key", /\bsk-ant-(?:api|admin)\d{2}-[A-Za-z0-9_-]{20,}/g],
59
+ ["an OpenRouter key", /\bsk-or-v1-[a-f0-9]{32,}/g],
60
+ ["a Groq key", /\bgsk_[A-Za-z0-9]{40,}/g],
61
+ ["an xAI key", /\bxai-[A-Za-z0-9]{40,}/g],
62
+ ["a Replicate token", /\br8_[A-Za-z0-9]{30,}/g],
63
+ ["a Hugging Face token", /\bhf_[A-Za-z0-9]{30,}/g],
64
+ ["an AWS access key", /\bAKIA[0-9A-Z]{16}\b/g],
65
+ ["a GitHub token", /\bgh[pousr]_[A-Za-z0-9]{36}\b|\bgithub_pat_[A-Za-z0-9_]{40,}/g],
66
+ ["a Slack token", /\bxox[baprs]-[A-Za-z0-9-]{10,}/g],
67
+ ["a SendGrid key", /\bSG\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}/g],
68
+ ["a Resend key", /\bre_[A-Za-z0-9]{8,}_[A-Za-z0-9]{16,}/g],
69
+ ["a Supabase access token", /\bsbp_[a-f0-9]{40}\b/g],
70
+ ["a private key", /-----BEGIN (?:RSA |EC |OPENSSH |DSA |ENCRYPTED )?PRIVATE KEY-----(?:\s|\\n|\\r)*[A-Za-z0-9+\/]{40,}/g],
71
+ ];
72
+ const PLACEHOLDER = /x{4,}|\.\.\.|your[_-]|example|placeholder|dummy|<|\*{3,}|changeme|replace/i;
17
73
  // A table or policy target the way SQL writes it: orders, public.orders, "public"."orders".
18
74
  const IDENT = String.raw`(?:"?(\w+)"?\s*\.\s*)?"?(\w+)"?`;
19
- // Comments blanked out, keeping every character's position so line numbers stay right.
20
- // Text inside single quotes is blanked too: it is data or SQL run later, not a statement in this file.
21
- // Double-quoted names are matched first and kept as they are, so an apostrophe in a policy's name ("Users can't …") starts nothing.
22
- const noComments = (sql) => sql.replace(/"(?:[^"]|"")*"|'(?:[^']|'')*'|\/\*[\s\S]*?\*\/|--[^\n]*/g, (m) => (m[0] === '"' ? m : m[0] === "'" ? `'${m.slice(1, -1).replace(/[^\n]/g, " ")}'` : m.replace(/[^\n]/g, " ")));
75
+ // A column name that says the table holds something about a person.
76
+ 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;
77
+ 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;
78
+
79
+ // Comments blanked out, keeping every character's position so line numbers stay right. With `strings`,
80
+ // text inside single quotes is blanked too: it is data or SQL run later, not a statement in this file.
81
+ // Double-quoted names are kept, so an apostrophe in a policy's name ("Users can't …") starts nothing.
82
+ const sqlBlank = (sql, strings = true) =>
83
+ 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, " ")));
84
+ const noComments = (sql) => sqlBlank(sql, true);
85
+ 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, " ")));
86
+ const shortHash = (s) => crypto.createHash("sha1").update(s).digest("hex").slice(0, 8);
87
+ const lineOf = (text, index) => text.slice(0, index).split("\n").length;
88
+
89
+ // Splits SQL into statements at semicolons, keeping $tag$ … $tag$ bodies whole. Linear in the file's length.
90
+ function statements(code) {
91
+ const out = [];
92
+ let start = 0;
93
+ let i = 0;
94
+ const n = code.length;
95
+ while (i < n) {
96
+ const c = code[i];
97
+ if (c === "$") {
98
+ const m = code.slice(i, i + 64).match(/^\$([A-Za-z_]\w*)?\$/);
99
+ if (m) {
100
+ const end = code.indexOf(m[0], i + m[0].length);
101
+ i = end < 0 ? n : end + m[0].length;
102
+ continue;
103
+ }
104
+ }
105
+ if (c === ";") {
106
+ out.push({ text: code.slice(start, i), index: start });
107
+ start = i + 1;
108
+ }
109
+ i++;
110
+ }
111
+ if (code.slice(start).trim()) out.push({ text: code.slice(start), index: start });
112
+ return out;
113
+ }
114
+ // The text inside the parentheses that open at `from` (which must point at "(").
115
+ function parens(s, from) {
116
+ let depth = 0;
117
+ for (let j = from; j < s.length && j < from + 20000; j++) {
118
+ if (s[j] === "(") depth++;
119
+ else if (s[j] === ")" && --depth === 0) return s.slice(from + 1, j);
120
+ }
121
+ return null;
122
+ }
123
+ const clause = (stmt, word) => {
124
+ const m = stmt.match(new RegExp(`\\b${word}\\s*\\(`, "i"));
125
+ return m ? parens(stmt, m.index + m[0].length - 1) : null;
126
+ };
127
+ // Splits a condition at top-level OR / ||.
128
+ function disjuncts(expr) {
129
+ const parts = [];
130
+ let depth = 0;
131
+ let last = 0;
132
+ for (let j = 0; j < expr.length; j++) {
133
+ const c = expr[j];
134
+ if (c === "(") depth++;
135
+ else if (c === ")") depth--;
136
+ else if (depth === 0) {
137
+ if (/^\s+or\s/i.test(expr.slice(j, j + 5)) || expr.slice(j, j + 2) === "||") {
138
+ parts.push(expr.slice(last, j));
139
+ j += expr.slice(j, j + 2) === "||" ? 1 : 3;
140
+ last = j + 1;
141
+ }
142
+ }
143
+ }
144
+ parts.push(expr.slice(last));
145
+ return parts.map((p) => p.trim().replace(/^\(+|\)+$/g, (x) => x).toLowerCase().replace(/\s+/g, " "));
146
+ }
147
+ const unwrapParens = (p) => {
148
+ let s = p.trim();
149
+ while (s.startsWith("(") && parens(s, 0) === s.slice(1, -1)) s = s.slice(1, -1).trim();
150
+ return s;
151
+ };
152
+ // "true", "1=1", "true or …": a condition that lets everyone through.
153
+ const ALWAYS = (d) => /^(true|'t'|'true'|1\s*=\s*1|true::bool(ean)?|not\s+false)$/.test(unwrapParens(d));
154
+ // A condition that only asks "is anyone signed in?": every signed-in user passes.
155
+ 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));
156
+
157
+ function isCheckout(dotGit) {
158
+ try {
159
+ const st = fs.statSync(dotGit);
160
+ if (st.isFile()) return /^gitdir:\s*\S/.test(fs.readFileSync(dotGit, "utf8").slice(0, 4096));
161
+ return st.isDirectory() && fs.existsSync(path.join(dotGit, "HEAD")) && fs.existsSync(path.join(dotGit, "objects"));
162
+ } catch {
163
+ return false;
164
+ }
165
+ }
23
166
 
24
- function walk(root, max = 5000) {
167
+ function walk(root) {
25
168
  const out = [];
169
+ const nested = [];
170
+ const seen = new Set();
26
171
  const stack = [root];
27
- while (stack.length && out.length < max) {
172
+ let truncated = false;
173
+ while (stack.length) {
28
174
  const dir = stack.pop();
175
+ let real;
176
+ try {
177
+ real = fs.realpathSync(dir);
178
+ } catch {
179
+ continue;
180
+ }
181
+ if (seen.has(real)) continue;
182
+ seen.add(real);
29
183
  let entries = [];
30
184
  try {
31
185
  entries = fs.readdirSync(dir, { withFileTypes: true });
32
186
  } catch {}
187
+ const later = [];
188
+ const first = [];
33
189
  for (const e of entries) {
34
190
  const full = path.join(dir, e.name);
35
- if (e.isDirectory()) !SKIP.has(e.name) && stack.push(full);
36
- else if (e.isFile() && TEXT.test(full.split(path.sep).join("/"))) out.push(full);
191
+ let isDir = e.isDirectory();
192
+ let isFile = e.isFile();
193
+ if (e.isSymbolicLink()) {
194
+ try {
195
+ const st = fs.statSync(full);
196
+ isDir = st.isDirectory();
197
+ isFile = st.isFile();
198
+ } catch {}
199
+ }
200
+ if (isDir) {
201
+ if (SKIP.has(e.name)) continue;
202
+ const relDir = path.relative(root, dir).split(path.sep).join("/");
203
+ if (TEST_DIRS.has(e.name) && !/(^|\/)(app|pages|routes)(\/|$)/.test(relDir)) continue;
204
+ // Another checkout inside this one (a git worktree, a submodule, a cloned repo) is a different project.
205
+ // Only a real one: an empty .git can't hide a folder. Every skipped folder is reported.
206
+ if (isCheckout(path.join(full, ".git"))) {
207
+ nested.push(path.relative(root, full).split(path.sep).join("/"));
208
+ continue;
209
+ }
210
+ (FIRST.has(e.name) ? first : later).push(full);
211
+ } else if (isFile && TEXT.test(full.split(path.sep).join("/"))) {
212
+ if (out.length >= MAX_FILES) {
213
+ truncated = true;
214
+ return { files: out, truncated, nested };
215
+ }
216
+ out.push(full);
217
+ }
37
218
  }
219
+ stack.push(...later, ...first); // the FIRST folders are popped first
38
220
  }
39
- return out;
221
+ return { files: out, truncated, nested };
40
222
  }
41
223
 
42
- const lineOf = (text, index) => text.slice(0, index).split("\n").length;
43
-
44
224
  // Whether a function's own code checks a webhook signature (Stripe, Svix/Resend/Clerk, GitHub, Lemon Squeezy, Paddle).
45
- const SIGNATURE = /constructEvent(?:Async)?\s*\(|webhooks?\.verify\s*\(|new\s+Webhook\s*\([\s\S]*?\.verify\s*\(|x-hub-signature|x-signature|paddle-signature|timingSafeEqual/i;
46
- function signsItself(dir) {
225
+ 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;
226
+ function signsItself(dir, re = SIGNATURE) {
47
227
  let found = false;
48
228
  const stack = [dir];
49
229
  while (stack.length && !found) {
@@ -57,7 +237,7 @@ function signsItself(dir) {
57
237
  if (e.isDirectory()) e.name !== "node_modules" && stack.push(full);
58
238
  else if (/\.(ts|js|mjs)$/.test(e.name)) {
59
239
  try {
60
- if (SIGNATURE.test(fs.readFileSync(full, "utf8"))) found = true;
240
+ if (re.test(jsNoComments(fs.readFileSync(full, "utf8")))) found = true;
61
241
  } catch {}
62
242
  }
63
243
  }
@@ -65,175 +245,577 @@ function signsItself(dir) {
65
245
  return found;
66
246
  }
67
247
 
248
+ // A function that checks the signed-in user in its own code (common when verify_jwt is off for the newer signing keys).
249
+ 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;
250
+
251
+ // Code that runs in the visitor's browser, judged by where it lives and what it says about itself.
252
+ function clientSide(name, text, project) {
253
+ 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;
254
+ if (/(^|\/)(route|middleware|\+server|\+page\.server|\+layout\.server|server)\.[jt]s$|\.(server|nitro|worker|cron|edge)\.[jt]sx?$/.test(name)) return false;
255
+ if (/^\s*["']use server["']/m.test(text)) return false;
256
+ if (/^\s*["']use client["']/m.test(text)) return true;
257
+ // Server functions (TanStack Start, SolidStart, Remix loaders) and anything reading process.env run on a server:
258
+ // a Vite build gives the browser import.meta.env, not process.env.
259
+ 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;
260
+ // Outside a single-page app, a file reading a non-public process.env value runs on a server. In a Vite or
261
+ // Create React App build it may still be bundled for the browser, so there it proves nothing.
262
+ if (!project.spa && /\bprocess\.env\.(?!NODE_ENV\b|REACT_APP_|NEXT_PUBLIC_|EXPO_PUBLIC_|VITE_|GATSBY_)[A-Z_]/.test(text)) return false;
263
+ if (/import\.meta\.env\b/.test(text)) return true;
264
+ if (/\.(vue|svelte|html)$/.test(name)) return true;
265
+ if (/\.astro$/.test(name)) return false; // frontmatter runs on the server
266
+ // In a single-page app (Vite, Create React App, Expo) everything under src/ or app/ ships to the browser or phone.
267
+ return project.spa && /^(src|app|components|pages|hooks|screens|public)\//.test(name);
268
+ }
269
+
68
270
  export function codeScan(dir = ".") {
69
271
  const root = path.resolve(dir);
70
272
  if (!fs.existsSync(root) || !fs.statSync(root).isDirectory()) throw new Error(`"${dir}" isn't a folder`);
71
273
  // In name order, which for migrations is the order they ran in: a later file can undo an earlier one.
72
- const files = walk(root).sort();
274
+ const walked = walk(root);
275
+ const files = walked.files.sort();
73
276
  const rel = (f) => path.relative(root, f).split(path.sep).join("/");
74
277
  const findings = [];
278
+ const unread = [];
75
279
  const add = (f) => findings.some((x) => x.id === f.id) || findings.push(f);
76
- const created = new Map(); // table -> where it was created
280
+ const exists = (p) => fs.existsSync(path.join(root, p));
281
+ let pkg = {};
282
+ try {
283
+ pkg = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8"));
284
+ } catch {}
285
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
286
+ const project = {
287
+ 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),
288
+ gemini: "@google/generative-ai" in deps || "@google/genai" in deps,
289
+ };
290
+ let usesSupabase = exists("supabase") || Object.keys(deps).some((d) => d.startsWith("@supabase/"));
291
+
292
+ // Database state across every migration, in order.
293
+ const created = new Map(); // table -> { where, people }
77
294
  const protectedTables = new Set();
295
+ const dynamic = []; // tables created before an EXECUTE … enable row level security we can't read
78
296
  const publicRead = { everyone: [], "every signed-in user": [] };
79
- let dynamicRls = false;
80
- // Open policies still standing after every migration: a later "drop policy" or "drop table" removes one.
81
- const openPolicies = new Map();
297
+ const policies = new Map(); // "schema.table|name" -> { action, roles, using, check, where, table, schema }
298
+ const buckets = new Map(); // bucket id -> { public, where }
299
+ const views = new Map(); // view -> { where, invoker, auth, revoked }
300
+ const definers = new Map(); // function -> { where, dynamicSql, revoked }
301
+ const keyFiles = [];
82
302
 
83
303
  for (const file of files) {
84
304
  const name = rel(file);
305
+ if (/\.(test|spec)\.[a-z]+$/i.test(name)) continue;
306
+ if (TEST_FILE.test(name)) continue;
307
+ // Examples, fixtures and tests aren't the app people use: security tools plant leaks there on purpose.
308
+ // Only a key with a real key's shape still counts there, since a real one works wherever it is written.
309
+ const sample = SAMPLE_PATH.test(name);
310
+ if (/(^|\/)(package-lock\.json|pnpm-lock\.yaml|yarn\.lock|bun\.lock|composer\.lock)$/.test(name)) continue;
85
311
  let text = "";
86
312
  try {
87
- if (fs.statSync(file).size > 1024 * 1024) continue;
313
+ const size = fs.statSync(file).size;
314
+ if (size > BIG && !(name.endsWith(".sql") && size < 16 * BIG)) {
315
+ if (/\.(sql|rules|toml)$|(^|\/)(firebase|database\.rules)\.json$/.test(name)) unread.push(name);
316
+ continue;
317
+ }
88
318
  text = fs.readFileSync(file, "utf8");
89
319
  } catch {
90
320
  continue;
91
321
  }
92
- if (/\.(test|spec)\.[a-z]+$/i.test(name)) continue;
93
- const isEnv = /(^|\/)\.env[^/]*$/.test(name);
322
+ if (text.includes("\0")) continue;
323
+ if (!usesSupabase && /@supabase\/(supabase-js|ssr|auth-helpers)/.test(text)) usesSupabase = true;
324
+ if (!project.gemini && /generativelanguage\.googleapis\.com|GoogleGenerativeAI|@google\/genai/.test(text)) project.gemini = true;
325
+ const isEnv = /(^|\/)(\.env[^/]*|\.dev\.vars)$/.test(name);
94
326
 
95
327
  // Names only: a secret behind a public prefix is copied into the code every visitor downloads.
96
- for (const m of [...text.matchAll(SECRET_NAME), ...text.matchAll(PAID_KEY_NAME)]) {
328
+ for (const m of sample ? [] : [...text.matchAll(SECRET_NAME), ...text.matchAll(PAID_KEY_NAME)]) {
97
329
  if (isEnv && !new RegExp(`^\\s*(?:export\\s+)?${m[1]}\\s*=`, "m").test(text)) continue;
330
+ if (!isEnv && inComment(text, m.index)) continue;
98
331
  add({ id: `scan:public-secret:${m[1]}`, severity: "critical", where: `${name}:${lineOf(text, 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.` });
99
332
  }
100
333
  if (isEnv) continue;
334
+ if (sample && (/\.(rules|sql)$/.test(name) || /(^|\/)(database\.rules\.json|supabase\/config\.toml)$/.test(name))) continue;
101
335
 
102
- // Firebase rules: "if true", or the test-mode date check, lets anyone on the internet in.
103
- // Open rules are a common cause of leaks from mobile and AI apps.
104
- const fb = name.match(/(?:^|\/)(firestore|storage)\.rules$/);
105
- if (fb) {
106
- const rules = text.replace(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, (m) => m.replace(/[^\n]/g, " "));
107
- const kind = fb[1] === "storage" ? "Storage" : "Firestore";
108
- for (const m of rules.matchAll(/allow\s+([a-z,\s]+?)\s*:\s*if\s+(true|request\.time\s*<\s*timestamp\.date\s*\([^)]*\))\s*;/g)) {
109
- const actions = m[1].replace(/\s+/g, "").split(",").filter(Boolean);
110
- const writes = actions.some((a) => ["write", "create", "update", "delete"].includes(a));
111
- const testMode = m[2] !== "true";
112
- const line = lineOf(rules, m.index);
113
- const what = writes ? (actions.some((a) => ["read", "get", "list"].includes(a)) ? "read and change" : "change") : "read";
114
- add({ id: `scan:firebase-open:${fb[1]}:${line}`, severity: writes || kind === "Firestore" ? "critical" : "high", where: `${name}:${line}`, title: `Your ${kind} rules let anyone ${what} this data${testMode ? " until a date" : ""}`, why: testMode ? `"${m[2].replace(/\s+/g, " ")}" 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.` : `"if true" 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} use "allow ${actions.join(", ")}: if ${testMode ? "request.time < timestamp.date(...)" : "true"}" at line ${line}, so anyone on the internet can ${what} the data. 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.` });
115
- }
336
+ // Firebase rules, wherever firebase.json says they are.
337
+ if (/\.rules$/.test(name) || (/(^|\/)database\.rules\.json$/.test(name))) {
338
+ scanFirebase(name, text, add);
116
339
  continue;
117
340
  }
118
- if (/(^|\/)database\.rules\.json$/.test(name)) {
119
- for (const m of text.matchAll(/"\.(read|write)"\s*:\s*(?:true|"true")/g)) {
120
- const line = lineOf(text, m.index);
121
- add({ id: `scan:firebase-open:database:${line}`, 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.` });
122
- }
341
+
342
+ if (name.endsWith(".sql")) {
343
+ // Row Level Security is a Postgres idea. A MySQL or SQLite schema, or SQL in an examples or fixtures
344
+ // folder, isn't the app's Supabase database. Anything under supabase/ always counts.
345
+ if (!/(^|\/)supabase\//.test(name) && notPostgres(path.dirname(file))) continue;
346
+ scanSql(name, text);
123
347
  continue;
124
348
  }
125
349
 
126
- if (name.endsWith(".sql")) {
127
- const sql = noComments(text);
128
- // What this file does, in the order it does it.
129
- const events = [];
130
- // Protection switched on in a loop: foreach t in array['a','b'] loop execute format('alter table … enable row level security', t).
131
- // The names are inside quotes, so they are read from the file as written.
132
- for (const m of text.matchAll(/foreach\s+\w+\s+in\s+array\s+(?:array\s*)?\[([^\]]*)\]\s*loop([\s\S]*?)end\s+loop/gi))
133
- if (/enable\s+row\s+level\s+security/i.test(m[2])) for (const n of m[1].matchAll(/'([\w.]+)'/g)) protectedTables.add(n[1].replace(/^public\./i, "").toLowerCase());
134
- // Any other statement built at run time that turns it on: the tables it covers can't be known from the file.
135
- if (/execute\b[\s\S]{0,300}?enable\s+row\s+level\s+security/i.test(text)) dynamicRls = true;
136
- for (const m of sql.matchAll(new RegExp(String.raw`create\s+(?:unlogged\s+)?table\s+(?:if\s+not\s+exists\s+)?${IDENT}`, "gi"))) {
137
- // Only the public schema is reachable with the app's public key.
138
- if ((m[1] || "public").toLowerCase() !== "public") continue;
350
+ if (/(^|\/)supabase\/config\.toml$/.test(name)) {
351
+ scanSupabaseConfig(name, text, file);
352
+ continue;
353
+ }
354
+
355
+ const code = /\.(js|jsx|ts|tsx|mjs|cjs|vue|svelte|astro)$/.test(name) ? jsNoComments(text) : text;
356
+ const client = clientSide(name, text, project);
357
+
358
+ if (sample && /\.(example|sample)\./.test(name)) continue;
359
+ // Keys written into the code itself, recognised by their shape.
360
+ if (!/\.(example|sample)\./.test(name)) {
361
+ for (const [kind, re] of KEY_SHAPES) {
362
+ for (const m of code.matchAll(re)) {
363
+ if (PLACEHOLDER.test(m[0].slice(6)) || /^(.)\1+$/.test(m[0].slice(-12))) continue;
364
+ const line = lineOf(code, m.index);
365
+ 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.` });
366
+ break;
367
+ }
368
+ }
369
+ if (sample) continue;
370
+ // A Supabase key whose role is service_role: it skips every Row Level Security rule.
371
+ for (const m of code.matchAll(/\beyJ[A-Za-z0-9_-]{10,}\.(eyJ[A-Za-z0-9_-]{10,})\.[A-Za-z0-9_-]{8,}/g)) {
372
+ let role = "";
373
+ try {
374
+ role = JSON.parse(Buffer.from(m[1], "base64url").toString("utf8")).role;
375
+ } catch {}
376
+ if (role !== "service_role") continue;
377
+ const line = lineOf(code, m.index);
378
+ 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.` });
379
+ }
380
+ // Google keys (AIza…) became Gemini keys on projects with the Generative Language API on.
381
+ for (const m of code.matchAll(/\bAIza[0-9A-Za-z_-]{35}\b/g)) keyFiles.push({ name, line: lineOf(code, m.index), client });
382
+ }
383
+ // The service_role key used in browser code, by name.
384
+ const SR_USE = /\benv(?:\.|\[\s*["'])[A-Z0-9_]*SERVICE_ROLE[A-Z0-9_]*|\b[A-Z0-9_]*SERVICE_ROLE_KEY\b(?!["'`]\s*[,\]])/;
385
+ if (client && SR_USE.test(code) && /\bcreateClient\s*\(/.test(code))
386
+ add({ id: `scan:service-role-client:${name}`, severity: "critical", where: `${name}:${lineOf(code, 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.` });
387
+ // An AI SDK told to run in the browser ships its key to every visitor.
388
+ // Bring-your-own-key apps (the visitor types their own key) are fine: flag only a key from the build env or written in.
389
+ 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)))
390
+ add({ id: `scan:ai-in-browser:${name}`, severity: "high", where: `${name}:${lineOf(code, 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.` });
391
+
392
+ // A login or session secret written into the code: anyone with the code can sign in as anyone.
393
+ if (!/\.(md|html)$/.test(name)) {
394
+ const yaml = /\.ya?ml$/.test(name);
395
+ const re = yaml
396
+ ? /\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
397
+ : /\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;
398
+ // The same secret passed straight to the code that uses it, with no variable name to go on:
399
+ // jwt.sign(user, "supersecretkey"), session({ secret: "keyboard cat" }), cookieParser("..."),
400
+ // Flask's app.config["SECRET_KEY"] = "...". The literal must end the argument, so a quoted key inside the payload doesn't count.
401
+ const direct = yaml ? [] : [
402
+ /\b(?:jwt|jsonwebtoken|JWT)\s*\.\s*(?:sign|verify)\s*\([^;]{0,300}?,\s*()["'`]([^"'`\s$]{1,200})["'`]\s*[,)]/g,
403
+ /\b(?:session|cookieSession|expressSession)\s*\(\s*\{[^}]{0,300}?\b(?:secret|keys)\s*:\s*\[?\s*()["'`]([^"'`$\n]{1,200})["'`]/g,
404
+ /\bcookieParser\s*\(\s*()["'`]([^"'`\s$]{1,200})["'`]/g,
405
+ /\bconfig\s*\[\s*["'](?:SECRET_KEY|JWT_SECRET_KEY)["']\s*\]\s*=\s*()["']([^"'\s]{1,200})["']/g,
406
+ ];
407
+ for (const m of [...code.matchAll(re), ...direct.flatMap((d) => [...code.matchAll(d)])]) {
408
+ const v = m[2] ?? m[3] ?? m[4] ?? "";
409
+ 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;
410
+ if (/\.(example|sample)\b/.test(name)) continue;
411
+ // A list of names, like ['publishableKey', 'secretKey', 'webhookSecret'], or a name held as a value
412
+ // ({ "env": "APP_SECRET", "bytes": 32 }) is not a secret.
413
+ if (/["'`]$/.test(code.slice(0, m.index)) && /[[,:]\s*["'`]$/.test(code.slice(Math.max(0, m.index - 40), m.index))) continue;
414
+ const line = lineOf(code, m.index);
415
+ // process.env.JWT_SECRET || "dev-secret", os.getenv("SECRET_KEY", "dev"): the literal is used only when
416
+ // the variable is missing. Still a blocker (that is how the Invicti admin takeover worked), named for what it is.
417
+ 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)));
418
+ if (fallback) {
419
+ 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.` });
420
+ break;
421
+ }
422
+ 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.` });
423
+ break;
424
+ }
425
+ }
426
+
427
+ // Payment webhooks that act on a message without checking who sent it.
428
+ if (/\.(js|ts|mjs|tsx|py)$/.test(name)) {
429
+ const stripe = !client && /from\s+["'](?:npm:|https?:\/\/[^"'\s]*\/)?stripe(?:@[^"'?\/\s]*)?(?:\?[^"'\s]*)?["']|require\(\s*["']stripe["']\)|^\s*import\s+stripe\b/m.test(code);
430
+ const events = /checkout\.session\.completed|invoice\.(?:paid|payment_succeeded)|customer\.subscription\.|payment_intent\.succeeded|event\.type\s*===?|event\[["']type["']\]/.test(code);
431
+ const named = /webhook/i.test(name);
432
+ // A route that takes a Stripe event as JSON, whatever the file is called (but not one that creates a checkout).
433
+ const takesEvent = /\b(?:const|let|var)\s+(?:event|evt)\s*=\s*(?:await\s+)?(?:req|request)\.json\(\)|\.data\.object\b/.test(code);
434
+ if (stripe && (named || events || takesEvent) && !/constructEvent|construct_event|stripe-signature|Stripe-Signature/i.test(code)) {
435
+ const trusts = /\b(req|request)\.json\(\)|JSON\.parse\(|\breq\.body\b|request\.get_json|await\s+request\.body/.test(code);
436
+ 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.` });
437
+ }
438
+ }
439
+
440
+ // Coding agents with a database connection that can write.
441
+ 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))))
442
+ 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.` });
443
+ }
444
+
445
+ // ---------- SQL: every statement, in the order the migrations run
446
+ function scanSql(name, text) {
447
+ const code = noComments(text); // strings blanked: for structure
448
+ const orig = sqlBlank(text, false); // comments blanked, strings kept: for names and conditions
449
+ const at = (i) => `${name}:${lineOf(code, i)}`;
450
+ const pkey = (schema, table, pol) => `${(schema || "public").toLowerCase()}.${table.toLowerCase()}|${pol.replace(/"/g, "").toLowerCase()}`;
451
+ for (const st of statements(code)) {
452
+ const s = st.text;
453
+ const o = orig.slice(st.index, st.index + s.length);
454
+ const lead = s.length - s.trimStart().length;
455
+ const i = st.index + lead;
456
+ const head = s.trimStart().slice(0, 200).toLowerCase().replace(/\s+/g, " ");
457
+ let m;
458
+ if ((m = s.match(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")))) {
459
+ if ((m[1] || "public").toLowerCase() !== "public" || /\btemp/i.test(m[0])) continue;
139
460
  const table = m[2].toLowerCase();
140
- const at = `${name}:${lineOf(sql, m.index)}`;
141
- events.push({ i: m.index, run: () => created.has(table) || created.set(table, at) });
142
- }
143
- for (const m of sql.matchAll(new RegExp(String.raw`alter\s+table\s+(?:if\s+exists\s+)?(?:only\s+)?${IDENT}\s+enable\s+row\s+level\s+security`, "gi"))) if ((m[1] || "public").toLowerCase() === "public") protectedTables.add(m[2].toLowerCase());
144
- // The policy's own name is skipped first: it is free text and often contains the word "on".
145
- const policyKey = (schema, table, policy) => `${(schema || "public").toLowerCase()}.${table.toLowerCase()}|${policy.replace(/"/g, "").toLowerCase()}`;
146
- for (const m of sql.matchAll(new RegExp(String.raw`(?:drop|alter)\s+policy\s+(?:if\s+exists\s+)?("[^"]*"|\w+)\s+on\s+${IDENT}`, "gi"))) {
147
- const key = policyKey(m[2], m[3], m[1]);
148
- events.push({ i: m.index, run: () => openPolicies.delete(key) });
149
- }
150
- for (const m of sql.matchAll(new RegExp(String.raw`drop\s+table\s+(?:if\s+exists\s+)?${IDENT}`, "gi"))) {
151
- const gone = `${(m[1] || "public").toLowerCase()}.${m[2].toLowerCase()}|`;
152
- events.push({ i: m.index, run: () => {
153
- if ((m[1] || "public").toLowerCase() === "public") created.delete(m[2].toLowerCase());
154
- for (const k of [...openPolicies.keys()]) if (k.startsWith(gone)) openPolicies.delete(k);
155
- } });
156
- }
157
- for (const full of sql.matchAll(new RegExp(String.raw`create\s+policy\s+("[^"]*"|\w+)\s+on\s+${IDENT}([^;]*);`, "gi"))) {
158
- const m = [full[0], full[2], full[3], full[4]];
159
- m.index = full.index;
160
- const key = policyKey(full[2], full[3], full[1]);
161
- const rest = m[3];
162
- if (!/(?:using|with\s+check)\s*\(+\s*true\s*\)+/i.test(rest)) continue;
163
- // Policies in a private schema open nothing to the app's public key; storage is named in full.
164
- const schema = (m[1] || "public").toLowerCase();
165
- if (schema !== "public" && schema !== "storage") continue;
166
- const roles = (rest.match(/\bto\s+([\w\s,"]+?)(?=\s+(?:using|with)\b|$)/i) || [, ""])[1].toLowerCase();
167
- // The service role skips every rule anyway; a policy for it alone opens nothing.
168
- if (/service_role/.test(roles) && !/anon|authenticated|public/.test(roles)) continue;
169
- const table = schema === "public" ? m[2].toLowerCase() : `${schema}.${m[2].toLowerCase()}`;
461
+ if (!created.has(table) || created.get(table).dropped) {
462
+ protectedTables.delete(table);
463
+ created.set(table, { where: at(i), people: PERSONAL_COLUMN.test(s) });
464
+ }
465
+ continue;
466
+ }
467
+ if ((m = s.match(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")))) {
468
+ if ((m[1] || "public").toLowerCase() !== "public") continue;
469
+ if (m[3].toLowerCase() === "enable") protectedTables.add(m[2].toLowerCase());
470
+ else protectedTables.delete(m[2].toLowerCase());
471
+ continue;
472
+ }
473
+ if ((m = s.match(new RegExp(String.raw`^\s*alter\s+table\s+(?:if\s+exists\s+)?(?:only\s+)?${IDENT}\s+rename\s+to\s+"?(\w+)"?`, "i")))) {
474
+ const [from, to] = [m[2].toLowerCase(), m[3].toLowerCase()];
475
+ if (created.has(from)) created.set(to, created.get(from)), created.delete(from);
476
+ if (protectedTables.delete(from)) protectedTables.add(to);
477
+ continue;
478
+ }
479
+ if (/^\s*drop\s+table\b/i.test(s)) {
480
+ for (const t of s.replace(/^\s*drop\s+table\s+(?:if\s+exists\s+)?/i, "").replace(/\b(cascade|restrict)\b/gi, "").split(",")) {
481
+ const mm = t.trim().match(new RegExp(`^${IDENT}`));
482
+ if (!mm) continue;
483
+ const table = mm[2].toLowerCase();
484
+ if ((mm[1] || "public").toLowerCase() === "public") {
485
+ created.delete(table);
486
+ protectedTables.delete(table);
487
+ }
488
+ for (const k of [...policies.keys()]) if (k.startsWith(`${(mm[1] || "public").toLowerCase()}.${table}|`)) policies.delete(k);
489
+ }
490
+ if (/(^|\/)migrations\//.test(name))
491
+ 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.` });
492
+ continue;
493
+ }
494
+ if (/^\s*truncate\b/i.test(s) && /(^|\/)migrations\//.test(name)) {
495
+ 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.` });
496
+ continue;
497
+ }
498
+ // Row Level Security switched on at run time.
499
+ // Only an anonymous DO block runs here; a function that does the same may never be called.
500
+ if (/^\s*do\b/i.test(o) && /\bexecute\b/i.test(o) && /enable\s+row\s+level\s+security/i.test(o)) {
501
+ const arr = o.match(/foreach\s+\w+\s+in\s+array\s+(?:array\s*)?\[([^\]]*)\]/i);
502
+ if (arr) for (const n of arr[1].matchAll(/'([\w.]+)'/g)) protectedTables.add(n[1].replace(/^public\./i, "").toLowerCase());
503
+ 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
504
+ else {
505
+ // A fixed statement in quotes names its table; one built from pieces (%I, ||, a variable) can't be read.
506
+ const literal = [...o.matchAll(/'\s*alter\s+table\s+(?:if\s+exists\s+)?(?:only\s+)?(?:"?public"?\s*\.\s*)?"?(\w+)"?\s+enable\s+row\s+level\s+security\s*;?\s*'/gi)];
507
+ for (const l of literal) protectedTables.add(l[1].toLowerCase());
508
+ if (/%I|%s|\|\||execute\s+(?!')\w/i.test(o)) for (const t of created.keys()) if (!protectedTables.has(t)) dynamic.push(t);
509
+ }
510
+ continue;
511
+ }
512
+ // Policies.
513
+ if ((m = s.match(new RegExp(String.raw`^\s*create\s+policy\s+("[^"]*"|\w+)\s+on\s+${IDENT}`, "i")))) {
514
+ const rest = o.slice(m[0].length);
515
+ if (/\bas\s+restrictive\b/i.test(rest)) continue; // narrows access, opens nothing
516
+ const roles = (rest.match(/\bto\s+([\w\s,"]+?)(?=\s+(?:using|with)\b|\s*$)/i) || [, "public"])[1].toLowerCase();
170
517
  const action = (rest.match(/\bfor\s+(select|insert|update|delete|all)\b/i) || [, "all"])[1].toLowerCase();
171
- const toAuthed = /authenticated/.test(roles) && !/anon|public/.test(roles);
172
- const who = toAuthed ? "every signed-in user" : "everyone";
173
- const where = `${name}:${lineOf(sql, m.index)}`;
174
- // Reading a whole table is often meant (products, courses), so those are gathered into one question below.
175
- if (action === "select") {
176
- events.push({ i: m.index, run: () => openPolicies.set(key, () => publicRead[who].some((t) => t.table === table) || publicRead[who].push({ table, where })) });
518
+ policies.set(pkey(m[2], m[3], m[1]), { schema: (m[2] || "public").toLowerCase(), table: m[3].toLowerCase(), roles, action, using: clause(rest, "using"), check: clause(rest, "with\\s+check"), where: at(i) });
519
+ continue;
520
+ }
521
+ if ((m = s.match(new RegExp(String.raw`^\s*alter\s+policy\s+("[^"]*"|\w+)\s+on\s+${IDENT}`, "i")))) {
522
+ const key = pkey(m[2], m[3], m[1]);
523
+ const p = policies.get(key);
524
+ const rest = o.slice(m[0].length);
525
+ const ren = rest.match(/^\s*rename\s+to\s+("[^"]*"|\w+)/i);
526
+ if (ren) {
527
+ if (p) policies.set(pkey(m[2], m[3], ren[1]), p), policies.delete(key);
177
528
  continue;
178
529
  }
179
- // Adding rows is right for a contact form, a waitlist or a log. Changing and deleting rarely is.
180
- const addOnly = action === "insert";
181
- const finding = { id: `scan:policy-true:${table}:${action}`, severity: addOnly ? "medium" : "high", where, title: `A rule lets ${who} ${action === "all" ? "read, change and delete" : addOnly ? "add" : action} rows in "${table}"`, why: `The policy's condition is simply "true", so Row Level Security is on but checks nothing for this action.${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 of using true.", first: null, prompt: `In my database, a Row Level Security policy on "${table}" for ${action} 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 ${action === "all" ? "reach" : 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.` };
182
- events.push({ i: m.index, run: () => openPolicies.set(key, () => add(finding)) });
530
+ if (!p) continue;
531
+ const roles = rest.match(/\bto\s+([\w\s,"]+?)(?=\s+(?:using|with)\b|\s*$)/i);
532
+ 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) });
533
+ continue;
534
+ }
535
+ if ((m = s.match(new RegExp(String.raw`^\s*drop\s+policy\s+(?:if\s+exists\s+)?("[^"]*"|\w+)\s+on\s+${IDENT}`, "i")))) {
536
+ policies.delete(pkey(m[2], m[3], m[1]));
537
+ continue;
538
+ }
539
+ // Storage buckets made public.
540
+ if (/^\s*insert\s+into\s+storage\.buckets\b/i.test(s)) {
541
+ const cols = (o.match(/storage\.buckets\s*\(([^)]*)\)/i) || [, ""])[1].split(",").map((c) => c.trim().replace(/"/g, "").toLowerCase());
542
+ const idIdx = cols.indexOf("id") >= 0 ? cols.indexOf("id") : cols.indexOf("name");
543
+ const pubIdx = cols.indexOf("public");
544
+ const valuesAt = o.search(/\bvalues\b/i);
545
+ if (valuesAt >= 0 && pubIdx >= 0) {
546
+ for (const tup of o.slice(valuesAt).matchAll(/\(([^()]*)\)/g)) {
547
+ const vals = tup[1].split(",").map((v) => v.trim());
548
+ const id = (vals[idIdx] || "").replace(/^'|'$/g, "");
549
+ if (/^(true|'t'|'true')$/i.test(vals[pubIdx] || "")) buckets.set(id, { public: true, where: at(i) });
550
+ else buckets.set(id, { public: false, where: at(i) });
551
+ }
552
+ }
553
+ continue;
554
+ }
555
+ 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))) {
556
+ buckets.set(m[2], { public: m[1].toLowerCase() === "true", where: at(i) });
557
+ continue;
558
+ }
559
+ // Views and functions that run with their owner's rights.
560
+ if ((m = s.match(new RegExp(String.raw`^\s*create\s+(?:or\s+replace\s+)?(?:materialized\s+)?view\s+(?:if\s+not\s+exists\s+)?${IDENT}`, "i")))) {
561
+ if ((m[1] || "public").toLowerCase() !== "public") continue;
562
+ const view = m[2].toLowerCase();
563
+ views.set(view, { where: at(i), invoker: INVOKER.test(s), auth: /\bauth\s*\.\s*users\b/i.test(s), materialized: /materialized/i.test(m[0]), revoked: false });
564
+ continue;
565
+ }
566
+ if ((m = s.match(new RegExp(String.raw`^\s*alter\s+view\s+(?:if\s+exists\s+)?${IDENT}\s+set\s*\(([^)]*)\)`, "i")))) {
567
+ const v = views.get(m[2].toLowerCase());
568
+ if (v && INVOKER.test(m[3])) v.invoker = true;
569
+ continue;
183
570
  }
184
- for (const e of events.sort((a, b) => a.i - b.i)) e.run();
185
- if (/(^|\/)migrations\//.test(name)) {
186
- const d = sql.match(/^\s*(drop\s+table|truncate)\b[^;]*;/im);
187
- if (d) add({ id: `scan:destructive:${name}`, severity: "low", where: `${name}:${lineOf(sql, d.index)}`, title: "A migration deletes data", why: `It contains "${d[0].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 (${d[1].toLowerCase()}). 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.` });
571
+ if ((m = s.match(/^\s*revoke\s+[\w\s,]*?\bon\s+(?:table\s+)?(?:"?public"?\s*\.\s*)?"?(\w+)"?\s+from\s+([\w\s,]+)/i))) {
572
+ const v = views.get(m[1].toLowerCase());
573
+ if (v && /anon|public/i.test(m[2])) v.revoked = true;
188
574
  }
575
+ if ((m = s.match(/^\s*revoke\s+(?:all|execute)[\s\S]*?\bon\s+function\s+(?:"?public"?\s*\.\s*)?"?(\w+)"?[\s\S]*?\bfrom\s+([\w\s,]+)/i))) {
576
+ const f = definers.get(m[1].toLowerCase());
577
+ if (f && /anon|public/i.test(m[2])) f.revoked = true;
578
+ continue;
579
+ }
580
+ if ((m = s.match(new RegExp(String.raw`^\s*create\s+(?:or\s+replace\s+)?function\s+${IDENT}`, "i")))) {
581
+ if ((m[1] || "public").toLowerCase() !== "public") continue;
582
+ if (!/\bsecurity\s+definer\b/i.test(s)) continue;
583
+ if (/\breturns\s+trigger\b/i.test(s)) continue; // triggers can't be called through the API
584
+ definers.set(m[2].toLowerCase(), { 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 });
585
+ continue;
586
+ }
587
+ void head;
189
588
  }
589
+ }
190
590
 
191
- if (/(^|\/)supabase\/config\.toml$/.test(name)) {
192
- for (const m of text.matchAll(/\[functions\.([\w-]+)\][^\[]*?verify_jwt\s*=\s*false/g)) {
193
- // A webhook that verifies its sender's signature itself is the one right use of verify_jwt = false.
194
- if (signsItself(path.join(path.dirname(file), "functions", m[1])))
195
- add({ id: `scan:verify-jwt:${m[1]}`, severity: "low", where: `${name}:${lineOf(text, m.index)}`, title: `The function "${m[1]}" 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 "${m[1]}" 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.` });
196
- else add({ id: `scan:verify-jwt:${m[1]}`, severity: "high", where: `${name}:${lineOf(text, m.index)}`, title: `The function "${m[1]}" 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 "${m[1]}" 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.` });
591
+ // ---------- Supabase config: functions without the sign-in check, public buckets
592
+ function scanSupabaseConfig(name, text, file) {
593
+ let section = null;
594
+ const lines = text.split("\n");
595
+ for (let k = 0; k < lines.length; k++) {
596
+ const line = lines[k].replace(/(^|[^"'])#.*$/, "$1");
597
+ const h = line.match(/^\s*\[\s*([^\]]+?)\s*\]\s*$/);
598
+ if (h) {
599
+ section = h[1].split(".").map((p) => p.trim().replace(/^["']|["']$/g, ""));
600
+ continue;
601
+ }
602
+ if (!section) continue;
603
+ if (section[0] === "functions" && section[1] && /^\s*verify_jwt\s*=\s*false\b/.test(line)) {
604
+ const fn = section[1];
605
+ const where = `${name}:${k + 1}`;
606
+ const fnDir = path.join(path.dirname(file), "functions", fn);
607
+ if (signsItself(fnDir, CHECKS_USER)) continue;
608
+ if (signsItself(fnDir))
609
+ 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.` });
610
+ 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.` });
197
611
  }
612
+ 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}` });
198
613
  }
614
+ }
199
615
 
200
- if (/webhook/i.test(name) && /\.(js|ts|mjs|tsx|py)$/.test(name) && /stripe/i.test(text) && !/constructEvent|construct_event|stripe-signature/i.test(text))
201
- add({ id: `scan:webhook:${name}`, severity: "medium", where: name, title: "Greenlit couldn't see a signature check in this payment webhook", why: "This file handles Stripe messages but never mentions the Stripe-Signature header or constructEvent. If the check isn't done in another file it calls, anyone can send a fake \"payment succeeded\" message.", 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.` });
616
+ // ---------- after every file: what's still open
617
+ if (usesSupabase || [...created.keys()].length)
618
+ for (const [table, info] of created) {
619
+ if (protectedTables.has(table) || !usesSupabase) continue;
620
+ const maybe = dynamic.includes(table);
621
+ 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.${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.` });
622
+ }
202
623
 
203
- if (/(^|\/)(\.mcp\.json|\.cursor\/mcp\.json|\.vscode\/mcp\.json)$/.test(name) && (/postgres(?:ql)?:\/\//i.test(text) || (/supabase/i.test(text) && !/read[-_]only/i.test(text))))
204
- 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.", fix: "Use the read-only mode, and point the agent at a development database.", 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.` });
624
+ for (const p of policies.values()) {
625
+ if (p.schema !== "public" && p.schema !== "storage") continue;
626
+ // The service role skips every rule anyway; a policy for it alone opens nothing.
627
+ if (/service_role/.test(p.roles) && !/anon|authenticated|public/.test(p.roles)) continue;
628
+ const conds = [p.using, p.check].filter((c) => c != null);
629
+ if (!conds.length) continue;
630
+ const parts = conds.flatMap(disjuncts);
631
+ const always = parts.some(ALWAYS);
632
+ const anySignedIn = !always && conds.every((c) => disjuncts(c).some((d) => ALWAYS(d) || ANY_SIGNED_IN(d)));
633
+ const meta = conds.some((c) => /user_metadata|raw_user_meta_data/i.test(c));
634
+ const table = p.schema === "public" ? p.table : `${p.schema}.${p.table}`;
635
+ if (meta)
636
+ 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.` });
637
+ if (!always && !anySignedIn) continue;
638
+ const toAuthed = anySignedIn || (/authenticated/.test(p.roles) && !/anon|public/.test(p.roles));
639
+ const who = toAuthed ? "every signed-in user" : "everyone";
640
+ if (p.schema === "storage") {
641
+ if (p.table !== "objects") continue;
642
+ const bucket = conds.join(" ").match(/bucket_id\s*=\s*'([^']+)'/i)?.[1];
643
+ if (p.action === "select" || p.action === "all") {
644
+ if (bucket && p.action === "select") continue; // a policy naming one bucket is judged with the bucket below
645
+ 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.` });
646
+ } 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.` });
647
+ continue;
648
+ }
649
+ // Reading a whole table is often meant (products, courses), so those are gathered into one question below.
650
+ if (p.action === "select") {
651
+ if (!publicRead[who].some((t) => t.table === table)) publicRead[who].push({ table, where: p.where, people: Boolean(created.get(p.table)?.people), known: created.has(p.table) });
652
+ continue;
653
+ }
654
+ // Adding rows is right for a contact form, a waitlist or a log. Changing and deleting rarely is.
655
+ const addOnly = p.action === "insert";
656
+ 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.` });
205
657
  }
206
658
 
207
- if (files.some((f) => /(^|\/)supabase\//.test(rel(f))))
208
- for (const [table, where] of created)
209
- if (!protectedTables.has(table) && dynamicRls)
210
- add({ id: `scan:no-rls:${table}`, severity: "medium", where, title: `Greenlit couldn't see Row Level Security being turned on for "${table}"`, why: "Your migrations switch it on for some tables with a statement built while it runs, and Greenlit can't tell which tables that covers. This one may be protected.", fix: "Check it in Supabase → Advisors → Security Advisor, or run npx greenlitlab <your app> --mine.", first: null, prompt: `Tell me whether Row Level Security is enabled on the table "${table}" in my database, and which statement enables it. Change nothing.` });
211
- else if (!protectedTables.has(table))
212
- add({ id: `scan:no-rls:${table}`, severity: "high", where, title: `The table "${table}" is created without Row Level Security`, why: "No migration turns Row Level Security on for it. 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.${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. 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.` });
659
+ // Buckets: public ones, judged by what their name says they hold.
660
+ const bucketPolicies = [...policies.values()].filter((p) => p.schema === "storage" && p.table === "objects" && p.action === "select");
661
+ for (const p of bucketPolicies) {
662
+ const conds = [p.using].filter(Boolean).join(" ");
663
+ const id = conds.match(/bucket_id\s*=\s*'([^']+)'/i)?.[1];
664
+ if (!id || /auth\.uid|auth\.jwt|storage\.foldername/i.test(conds)) continue;
665
+ if (/authenticated/.test(p.roles) && !/anon|public/.test(p.roles)) continue;
666
+ if (!buckets.has(id)) buckets.set(id, { public: true, where: p.where, viaPolicy: true });
667
+ }
668
+ for (const [id, b] of buckets) {
669
+ if (!b.public) continue;
670
+ const sensitive = SENSITIVE_BUCKET.test(id);
671
+ 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.` });
672
+ }
673
+
674
+ for (const [view, v] of views) {
675
+ if (v.revoked) continue;
676
+ if (v.auth)
677
+ 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.` });
678
+ else if (!v.invoker && !v.materialized)
679
+ 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.${view} set (security_invoker = on); then check the app still works for a signed-in user and tell me if any rule needs changing.` });
680
+ else if (v.materialized)
681
+ 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.` });
682
+ }
683
+ for (const [fn, f] of definers) {
684
+ if (f.revoked) continue;
685
+ 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.` });
686
+ }
213
687
 
688
+ // Firebase/Google keys in browser code that may now call Gemini.
689
+ if (keyFiles.length) {
690
+ const k = keyFiles.find((x) => x.client) ?? keyFiles[0];
691
+ 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.` });
692
+ }
693
+
694
+ let gitUnavailable = false;
214
695
  try {
215
- const tracked = execFileSync("git", ["-C", root, "ls-files"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).split("\n");
216
- const env = tracked.find((f) => /(^|\/)\.env(\.local|\.production)?$/.test(f));
217
- if (env) add({ id: "scan:env-tracked", severity: "high", where: env, title: `Your ${env} file is saved in version control`, why: "Everyone with access to the repository, now or later, has every key in it. If the repository is public, so does the world.", fix: "Remove it from git, add it to .gitignore, and replace the keys it held.", first: "Replace every key in that file: once committed, a key stays in the history.", prompt: `My ${env} file is tracked by git. 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 list every key that was in it so I can replace each one.` });
218
- } catch {}
696
+ // From the top of the repository: a .env committed above the folder being checked still ships with it.
697
+ const top = execFileSync("git", ["-C", root, "rev-parse", "--show-toplevel"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
698
+ const tracked = execFileSync("git", ["-C", top, "ls-files"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 64 * 1024 * 1024 }).split("\n");
699
+ const envs = tracked.filter((f) => /(^|\/)(\.env(\.[\w.-]+)?|\.dev\.vars)$/.test(f) && !/\.(example|sample|template|defaults?|dist|schema|fixture|test)$/.test(f) && !SAMPLE_PATH.test(f));
700
+ // Lovable and others commit a .env that holds only browser-safe values (the Supabase URL and
701
+ // publishable key). That is not a leak, so flag a tracked .env only when it holds a filled-in
702
+ // value whose name says it is secret. Values are read to see whether they are empty, never shown.
703
+ for (const env of envs) {
704
+ const secrets = trackedEnvSecrets(path.join(top, env));
705
+ if (secrets === null || !secrets.length) continue;
706
+ const shown = path.relative(fs.realpathSync(root), path.join(top, env)).split(path.sep).join("/") || env;
707
+ const list = secrets.slice(0, 8).join(", ") + (secrets.length > 8 ? ` and ${secrets.length - 8} more` : "");
708
+ 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.` });
709
+ break;
710
+ }
711
+ } catch {
712
+ gitUnavailable = true;
713
+ }
219
714
 
220
- for (const emit of openPolicies.values()) emit();
221
715
  for (const [who, list] of Object.entries(publicRead)) {
222
716
  if (!list.length) continue;
223
717
  const names = list.map((t) => t.table);
224
- add({ id: `scan:public-read:${who === "everyone" ? "everyone" : "signed-in"}`, severity: "medium", where: list[0].where, 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". 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 with the condition true, so ${who === "everyone" ? "anyone on the internet" : "any signed-in user"} can 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.` });
718
+ 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.` });
225
719
  }
226
720
 
227
721
  // A lockfile only matters when there is something to lock.
228
- let hasDeps = false;
229
- try {
230
- const pkg = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8"));
231
- hasDeps = Object.keys({ ...pkg.dependencies, ...pkg.devDependencies }).length > 0;
232
- } catch {}
722
+ const hasDeps = Object.keys(deps).length > 0;
233
723
  if (hasDeps && !["package-lock.json", "pnpm-lock.yaml", "yarn.lock", "bun.lockb", "bun.lock"].some((f) => fs.existsSync(path.join(root, f))))
234
724
  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." });
235
725
 
236
726
  const order = ["critical", "high", "medium", "low", "info"];
237
727
  findings.sort((a, b) => order.indexOf(a.severity) - order.indexOf(b.severity));
238
- return { source: "your project's files", dir: root, files: files.length, findings };
728
+ return { source: "your project's files", dir: root, files: files.length, findings, truncated: walked.truncated, unread, gitUnavailable, nested: walked.nested };
729
+ }
730
+
731
+ // ---------- Tracked .env files
732
+ // Names that are meant to reach the browser (and are safe there) never count as secrets.
733
+ 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;
734
+ 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;
735
+ // Returns the names of filled-in secret values in a .env file, or null if it can't be read.
736
+ export function trackedEnvSecrets(file) {
737
+ let text;
738
+ try { text = fs.readFileSync(file, "utf8"); } catch { return null; }
739
+ const out = [];
740
+ for (const raw of text.split(/\r?\n/)) {
741
+ const line = raw.trim();
742
+ if (!line || line.startsWith("#")) continue;
743
+ const m = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_.-]*)\s*=\s*(.*)$/.exec(line);
744
+ if (!m) continue;
745
+ const [, name, rawValue] = m;
746
+ const value = rawValue.replace(/\s+#.*$/, "").replace(/^(["'])(.*)\1$/, "$2").trim();
747
+ if (!value || /^(your|xxx|changeme|replace|<|\$\{|\{\{)|fake|dummy|placeholder/i.test(value)) continue;
748
+ if (BROWSER_SAFE_ENV.test(name) || !SECRET_ENV.test(name)) continue;
749
+ // A name with a public prefix ships to the browser anyway; if it's a secret, the public-secret check says so.
750
+ if (/^(VITE_|NEXT_PUBLIC_|PUBLIC_|EXPO_PUBLIC_|REACT_APP_|NUXT_PUBLIC_|GATSBY_)/.test(name)) continue;
751
+ // A database address with no password in it (a local SQLite file, postgres://localhost/app) is not a secret.
752
+ if (/^(sqlite|file)[:+]/i.test(value)) continue;
753
+ 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;
754
+ out.push(name);
755
+ }
756
+ return out;
757
+ }
758
+
759
+ // ---------- Firebase rules
760
+ // The match paths that enclose a position in a rules file, outermost first (siblings closed before it don't count).
761
+ function enclosingMatches(rules, at) {
762
+ const stack = [];
763
+ for (const m of rules.slice(0, at).matchAll(/match\s+(\/(?:\{[^}\s]*\}|[^\s{])*)\s*\{|\{|\}/g)) {
764
+ if (m[1] !== undefined) stack.push(m[1]);
765
+ else if (m[0] === "{") stack.push(null);
766
+ else stack.pop();
767
+ }
768
+ return stack.filter(Boolean);
769
+ }
770
+ 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;
771
+ function scanFirebase(name, text, add) {
772
+ if (/\.json$/.test(name)) {
773
+ // Realtime Database: ".read": true anywhere, or "auth != null" for the whole database.
774
+ for (const m of text.matchAll(/"\.(read|write)"\s*:\s*(?:true|"true")/g)) {
775
+ const line = lineOf(text, m.index);
776
+ 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.` });
777
+ }
778
+ let rules;
779
+ try {
780
+ rules = JSON.parse(text.replace(/\/\*[\s\S]*?\*\/|(^|[^:"])\/\/[^\n]*/g, "$1")).rules;
781
+ } catch {}
782
+ for (const op of ["read", "write"]) {
783
+ const v = rules?.[`.${op}`];
784
+ if (typeof v === "string" && /^\s*auth\s*!==?\s*null\s*$/.test(v))
785
+ 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.` });
786
+ }
787
+ return;
788
+ }
789
+ const rules = text.replace(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, (m) => m.replace(/[^\n]/g, " "));
790
+ const kind = /firebase\.storage/.test(rules) ? "Storage" : "Firestore";
791
+ const k = kind.toLowerCase();
792
+ // allow <ops>; allow <ops>: if <condition>; (the semicolon is optional before "}")
793
+ for (const m of rules.matchAll(/\ballow\s+([a-z]+(?:\s*,\s*[a-z]+){0,8})\s*(?::\s*if\b([^;{}]{0,2000}))?\s*(?:;|(?=\}))/g)) {
794
+ const actions = m[1].replace(/\s+/g, "").split(",").filter(Boolean);
795
+ const cond = m[2] == null ? null : m[2].trim();
796
+ const parts = cond == null ? ["true"] : disjuncts(cond);
797
+ const open = parts.some((p) => /^(true|\(?\s*true\s*\)?)$/.test(unwrapParens(p)));
798
+ const testMode = !open && parts.some((p) => /^request\.time\s*<\s*timestamp\.date\s*\(/.test(unwrapParens(p)));
799
+ const signedIn = !open && !testMode && parts.length === 1 && /^request\.auth\s*!=\s*null$|^request\.auth\.uid\s*!=\s*null$/.test(unwrapParens(parts[0]));
800
+ if (!open && !testMode && !signedIn) continue;
801
+ // The match path this rule sits under: the nearest "match /…" before it.
802
+ const before = rules.slice(0, m.index);
803
+ const paths = [...before.matchAll(/match\s+(\/(?:\{[^}\s]*\}|[^\s{])*)\s*\{/g)];
804
+ const matchPath = paths.length ? paths[paths.length - 1][1] : "";
805
+ const wildcard = /^\/\{\w+=\*\*\}$/.test(matchPath); // a catch-all for everything, not "/avatars/{path=**}"
806
+ if (signedIn && !wildcard) continue; // "signed in" on one collection is often meant; the agent reviews it
807
+ const writes = actions.some((a) => ["write", "create", "update", "delete"].includes(a));
808
+ // Anyone reading a collection is often meant (listings, posts, videos, images). Flag an open read only on a
809
+ // catch-all path or where the path looks like people's data; open writes and test mode are always flagged.
810
+ const near = enclosingMatches(rules, m.index).filter((p) => !/^\/(databases|b)\//.test(p)).join("");
811
+ if (!writes && !testMode && !wildcard && !PERSONAL_PATH.test(near)) continue;
812
+ const line = lineOf(rules, m.index);
813
+ const what = writes ? (actions.some((a) => ["read", "get", "list"].includes(a)) ? "read and change" : "change") : "read";
814
+ const id = `scan:firebase-open:${k}:${shortHash(`${matchPath}|${actions.join(",")}|${cond ?? ""}`)}`;
815
+ if (signedIn) {
816
+ 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.` });
817
+ continue;
818
+ }
819
+ 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.` });
820
+ }
239
821
  }