greenlitlab 0.5.0 → 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.
Files changed (3) hide show
  1. package/CHANGELOG.md +19 -1
  2. package/package.json +35 -7
  3. package/src/scan.mjs +128 -15
package/CHANGELOG.md CHANGED
@@ -1,6 +1,24 @@
1
1
  # Changelog
2
2
 
3
- ## 0.5.0 (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)
4
22
 
5
23
  `greenlit scan` was rebuilt after an adversarial audit of the project scan that Launch Blockers runs before deploys.
6
24
 
package/package.json CHANGED
@@ -1,20 +1,48 @@
1
1
  {
2
2
  "name": "greenlitlab",
3
- "version": "0.5.0",
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/src/scan.mjs CHANGED
@@ -22,7 +22,34 @@ const SECRET_NAME = new RegExp(`\\b(${PUBLIC_PREFIX}[A-Z0-9_]*?(?:SECRET(?:_ACCE
22
22
  // A key for a paid service behind a public prefix (VITE_OPENAI_API_KEY) is the same mistake under another name.
23
23
  // Keys made to be public (Stripe publishable, Supabase anon) are left out.
24
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))[A-Z0-9_]*?(?:${PAID})[A-Z0-9_]*?(?:KEY|TOKEN))(?![A-Z0-9_])`, "g");
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
+ }
26
53
  // Keys recognised by their shape, wherever they're written. Only the kind and the place are ever reported.
27
54
  const KEY_SHAPES = [
28
55
  ["a live Stripe secret key", /\b[rs]k_live_[0-9A-Za-z]{10,}/g],
@@ -196,7 +223,7 @@ function walk(root) {
196
223
 
197
224
  // Whether a function's own code checks a webhook signature (Stripe, Svix/Resend/Clerk, GitHub, Lemon Squeezy, Paddle).
198
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;
199
- function signsItself(dir) {
226
+ function signsItself(dir, re = SIGNATURE) {
200
227
  let found = false;
201
228
  const stack = [dir];
202
229
  while (stack.length && !found) {
@@ -210,7 +237,7 @@ function signsItself(dir) {
210
237
  if (e.isDirectory()) e.name !== "node_modules" && stack.push(full);
211
238
  else if (/\.(ts|js|mjs)$/.test(e.name)) {
212
239
  try {
213
- if (SIGNATURE.test(jsNoComments(fs.readFileSync(full, "utf8")))) found = true;
240
+ if (re.test(jsNoComments(fs.readFileSync(full, "utf8")))) found = true;
214
241
  } catch {}
215
242
  }
216
243
  }
@@ -218,6 +245,9 @@ function signsItself(dir) {
218
245
  return found;
219
246
  }
220
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
+
221
251
  // Code that runs in the visitor's browser, judged by where it lives and what it says about itself.
222
252
  function clientSide(name, text, project) {
223
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;
@@ -273,6 +303,10 @@ export function codeScan(dir = ".") {
273
303
  for (const file of files) {
274
304
  const name = rel(file);
275
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);
276
310
  if (/(^|\/)(package-lock\.json|pnpm-lock\.yaml|yarn\.lock|bun\.lock|composer\.lock)$/.test(name)) continue;
277
311
  let text = "";
278
312
  try {
@@ -291,11 +325,13 @@ export function codeScan(dir = ".") {
291
325
  const isEnv = /(^|\/)(\.env[^/]*|\.dev\.vars)$/.test(name);
292
326
 
293
327
  // Names only: a secret behind a public prefix is copied into the code every visitor downloads.
294
- 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)]) {
295
329
  if (isEnv && !new RegExp(`^\\s*(?:export\\s+)?${m[1]}\\s*=`, "m").test(text)) continue;
330
+ if (!isEnv && inComment(text, m.index)) continue;
296
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.` });
297
332
  }
298
333
  if (isEnv) continue;
334
+ if (sample && (/\.(rules|sql)$/.test(name) || /(^|\/)(database\.rules\.json|supabase\/config\.toml)$/.test(name))) continue;
299
335
 
300
336
  // Firebase rules, wherever firebase.json says they are.
301
337
  if (/\.rules$/.test(name) || (/(^|\/)database\.rules\.json$/.test(name))) {
@@ -304,6 +340,9 @@ export function codeScan(dir = ".") {
304
340
  }
305
341
 
306
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;
307
346
  scanSql(name, text);
308
347
  continue;
309
348
  }
@@ -316,6 +355,7 @@ export function codeScan(dir = ".") {
316
355
  const code = /\.(js|jsx|ts|tsx|mjs|cjs|vue|svelte|astro)$/.test(name) ? jsNoComments(text) : text;
317
356
  const client = clientSide(name, text, project);
318
357
 
358
+ if (sample && /\.(example|sample)\./.test(name)) continue;
319
359
  // Keys written into the code itself, recognised by their shape.
320
360
  if (!/\.(example|sample)\./.test(name)) {
321
361
  for (const [kind, re] of KEY_SHAPES) {
@@ -326,6 +366,7 @@ export function codeScan(dir = ".") {
326
366
  break;
327
367
  }
328
368
  }
369
+ if (sample) continue;
329
370
  // A Supabase key whose role is service_role: it skips every Row Level Security rule.
330
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)) {
331
372
  let role = "";
@@ -344,7 +385,8 @@ export function codeScan(dir = ".") {
344
385
  if (client && SR_USE.test(code) && /\bcreateClient\s*\(/.test(code))
345
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.` });
346
387
  // An AI SDK told to run in the browser ships its key to every visitor.
347
- if (/[{,]\s*dangerouslyAllowBrowser\s*:\s*true/.test(code))
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)))
348
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.` });
349
391
 
350
392
  // A login or session secret written into the code: anyone with the code can sign in as anyone.
@@ -353,11 +395,30 @@ export function codeScan(dir = ".") {
353
395
  const re = yaml
354
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
355
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;
356
- for (const m of code.matchAll(re)) {
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)])]) {
357
408
  const v = m[2] ?? m[3] ?? m[4] ?? "";
358
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;
359
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;
360
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
+ }
361
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.` });
362
423
  break;
363
424
  }
@@ -499,12 +560,12 @@ export function codeScan(dir = ".") {
499
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")))) {
500
561
  if ((m[1] || "public").toLowerCase() !== "public") continue;
501
562
  const view = m[2].toLowerCase();
502
- views.set(view, { where: at(i), invoker: /security_invoker\s*=\s*(on|true|1|yes)/i.test(s), auth: /\bauth\s*\.\s*users\b/i.test(s), materialized: /materialized/i.test(m[0]), revoked: false });
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 });
503
564
  continue;
504
565
  }
505
566
  if ((m = s.match(new RegExp(String.raw`^\s*alter\s+view\s+(?:if\s+exists\s+)?${IDENT}\s+set\s*\(([^)]*)\)`, "i")))) {
506
567
  const v = views.get(m[2].toLowerCase());
507
- if (v && /security_invoker\s*=\s*(on|true|1|yes)/i.test(m[3])) v.invoker = true;
568
+ if (v && INVOKER.test(m[3])) v.invoker = true;
508
569
  continue;
509
570
  }
510
571
  if ((m = s.match(/^\s*revoke\s+[\w\s,]*?\bon\s+(?:table\s+)?(?:"?public"?\s*\.\s*)?"?(\w+)"?\s+from\s+([\w\s,]+)/i))) {
@@ -542,7 +603,9 @@ export function codeScan(dir = ".") {
542
603
  if (section[0] === "functions" && section[1] && /^\s*verify_jwt\s*=\s*false\b/.test(line)) {
543
604
  const fn = section[1];
544
605
  const where = `${name}:${k + 1}`;
545
- if (signsItself(path.join(path.dirname(file), "functions", fn)))
606
+ const fnDir = path.join(path.dirname(file), "functions", fn);
607
+ if (signsItself(fnDir, CHECKS_USER)) continue;
608
+ if (signsItself(fnDir))
546
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.` });
547
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.` });
548
611
  }
@@ -585,7 +648,7 @@ export function codeScan(dir = ".") {
585
648
  }
586
649
  // Reading a whole table is often meant (products, courses), so those are gathered into one question below.
587
650
  if (p.action === "select") {
588
- if (!publicRead[who].some((t) => t.table === table)) publicRead[who].push({ table, where: p.where, people: Boolean(created.get(p.table)?.people) });
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) });
589
652
  continue;
590
653
  }
591
654
  // Adding rows is right for a contact form, a waitlist or a log. Changing and deleting rarely is.
@@ -633,10 +696,17 @@ export function codeScan(dir = ".") {
633
696
  // From the top of the repository: a .env committed above the folder being checked still ships with it.
634
697
  const top = execFileSync("git", ["-C", root, "rev-parse", "--show-toplevel"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
635
698
  const tracked = execFileSync("git", ["-C", top, "ls-files"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 64 * 1024 * 1024 }).split("\n");
636
- const env = tracked.find((f) => /(^|\/)(\.env(\.[\w.-]+)?|\.dev\.vars)$/.test(f) && !/\.(example|sample|template|defaults?|dist|schema)$/.test(f));
637
- if (env) {
638
- const shown = path.relative(root, path.join(top, env)).split(path.sep).join("/") || env;
639
- add({ id: "scan:env-tracked", severity: "high", where: shown, 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.` });
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;
640
710
  }
641
711
  } catch {
642
712
  gitUnavailable = true;
@@ -658,7 +728,46 @@ export function codeScan(dir = ".") {
658
728
  return { source: "your project's files", dir: root, files: files.length, findings, truncated: walked.truncated, unread, gitUnavailable, nested: walked.nested };
659
729
  }
660
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
+
661
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;
662
771
  function scanFirebase(name, text, add) {
663
772
  if (/\.json$/.test(name)) {
664
773
  // Realtime Database: ".read": true anywhere, or "auth != null" for the whole database.
@@ -693,9 +802,13 @@ function scanFirebase(name, text, add) {
693
802
  const before = rules.slice(0, m.index);
694
803
  const paths = [...before.matchAll(/match\s+(\/(?:\{[^}\s]*\}|[^\s{])*)\s*\{/g)];
695
804
  const matchPath = paths.length ? paths[paths.length - 1][1] : "";
696
- const wildcard = /\{\w+=\*\*\}/.test(matchPath);
805
+ const wildcard = /^\/\{\w+=\*\*\}$/.test(matchPath); // a catch-all for everything, not "/avatars/{path=**}"
697
806
  if (signedIn && !wildcard) continue; // "signed in" on one collection is often meant; the agent reviews it
698
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;
699
812
  const line = lineOf(rules, m.index);
700
813
  const what = writes ? (actions.some((a) => ["read", "get", "list"].includes(a)) ? "read and change" : "change") : "read";
701
814
  const id = `scan:firebase-open:${k}:${shortHash(`${matchPath}|${actions.join(",")}|${cond ?? ""}`)}`;