greenlitlab 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,24 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.0 (10 November 2026)
4
+
5
+ - Fixed: `--mine` was reporting nothing open when it had tested nothing. Supabase stopped listing a project's tables for the public key in 2026, and Greenlit relied on that list. It now takes table names from the app's own code, reports how many tables it tested, and says plainly when it could test none.
6
+ - Storage buckets named in the app's code are checked too, not only the nine common names. Database functions the app calls are listed in the JSON result and never called.
7
+ - An app that shows signs of Supabase without both its address and public key is reported as "database not checked" instead of nothing.
8
+ - Grades: one critical problem is now an F whatever else is right. Medium and low findings together take 20 points at most, so missing headers alone can never fail an app.
9
+ - Fairness: on a lovable.app address, missing frame protection is shown but costs no points, because the host sets those headers.
10
+
11
+ ## 0.2.1 (9 November 2026)
12
+
13
+ - Reads all of an app's code: lazy-loaded pages (Vite and Next.js chunk lists), every import form, chains of any depth, scripts with `?v=` addresses, and scripts on the app's own CDN. It used to stop after two rounds, so most code in larger apps went unread.
14
+ - Says what it didn't read. If a check runs out of room it reports how many scripts were left. If none of the app's code could be read, it gives no grade instead of an A.
15
+ - Grades match the danger: one critical problem means D at best, one high problem means C at best (a leaked master key used to earn a C, and a public `.git` folder a B).
16
+ - An A or B no longer sounds like an all-clear when the database wasn't checked, and there's now a prompt that has your builder check the database, for people without a terminal.
17
+ - A builder's "website not found" page, served with status 200, is now reported as not found instead of graded A.
18
+ - Clear errors in the CLI too, including for an address that doesn't exist.
19
+ - Web: the script and stylesheet addresses carry the version, because the 4-hour browser cache otherwise left returning visitors on old code after a deploy.
20
+ - Web: progress and errors now appear under the box instead of off screen. Results refresh after 2 minutes instead of 10, and the limit is 30 checks an hour.
21
+
3
22
  ## 0.2.0 (8 November 2026)
4
23
 
5
24
  - 18 more kinds of leaked keys: Supabase secret keys (sb_secret_) and access tokens, OpenRouter, xAI, Perplexity, Hugging Face, Replicate, Pinecone, GitLab, npm, Shopify, Brevo, Mailchimp, Mailgun, Telegram bots, secret Mapbox tokens, private keys and Google service-account JSON. `sk_live_` keys are named for Stripe, Clerk and similar.
package/README.md CHANGED
@@ -24,6 +24,10 @@ npx greenlitlab myapp.lovable.app
24
24
  | A public `.env` file or `.git` folder | your own app, `--mine` |
25
25
  | Firebase Realtime Database and Firestore open to everyone | your own app, `--mine` |
26
26
 
27
+ Greenlit reads all of the app's own scripts, including lazy-loaded pages and the app's own CDN, and tells you if a check ran out of room or couldn't read the code. Grades follow the danger: one critical problem is an F whatever else is right, one high problem means C at best, and small things such as missing headers take 20 points at most. What your host controls and you can't change is shown but costs nothing.
28
+
29
+ Supabase no longer lists a project's tables for the public key, so `--mine` tests the tables your app's code names, tells you how many it tested, and says so plainly when it could test none.
30
+
27
31
  The owner-only checks ask for a row count (Supabase), one file or document name (storage, Firebase), or the sign-up settings, never for data, and never write anything. They run only when you say the app is yours, because testing someone else's database without permission isn't OK.
28
32
 
29
33
  ## Commands
package/bin/greenlit.mjs CHANGED
@@ -8,7 +8,7 @@ import fs from "node:fs";
8
8
  import path from "node:path";
9
9
  import { parseArgs } from "node:util";
10
10
  import { fileURLToPath } from "node:url";
11
- import { siteScan, compare, renderSite, allPrompts } from "../src/grade.mjs";
11
+ import { siteScan, compare, renderSite, allPrompts, explainError } from "../src/grade.mjs";
12
12
  import { SEVERITY } from "../src/severity.mjs";
13
13
  import { loadLast, saveRun } from "../src/history.mjs";
14
14
 
@@ -67,7 +67,7 @@ if (opt.version) {
67
67
  result = await siteScan(target, { mine: opt.mine });
68
68
  } catch (e) {
69
69
  if (timer) (clearInterval(timer), process.stderr.write("\r\x1b[K"));
70
- console.error(`greenlit: ${e.message}`);
70
+ console.error(`greenlit: ${explainError(e.message)}`);
71
71
  process.exit(1);
72
72
  }
73
73
  if (timer) (clearInterval(timer), process.stderr.write("\r\x1b[K"));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "greenlitlab",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
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.",
5
5
  "type": "module",
6
6
  "bin": {
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.2.0",
8
+ "version": "0.3.0",
9
9
  "packages": [
10
10
  {
11
11
  "registryType": "npm",
12
12
  "identifier": "greenlitlab",
13
- "version": "0.2.0",
13
+ "version": "0.3.0",
14
14
  "transport": { "type": "stdio" },
15
15
  "packageArguments": [{ "type": "positional", "value": "mcp" }]
16
16
  }
package/src/grade.mjs CHANGED
@@ -51,6 +51,11 @@ const FB_DB = /["'](https:\/\/[a-z0-9-]+(?:\.[a-z0-9-]+)*\.(?:firebaseio\.com|fi
51
51
  const FB_KEY = /apiKey["']?\s*:\s*["'](AIza[0-9A-Za-z_-]{35})["']/;
52
52
  // Firestore can't list its collections without admin rights, so try the names apps use for people and money.
53
53
  const FIRESTORE_GUESSES = ["users", "profiles", "customers", "accounts", "orders", "payments", "messages", "chats", "leads", "contacts", "posts"];
54
+ // Supabase stopped listing tables for the public key in 2026, so table names come from the app's own code:
55
+ // supabase.from("orders") calls and /rest/v1/orders addresses. Names that aren't tables answer "not found" and are dropped.
56
+ const TABLE_REF = /\.from\(\s*["'`]([A-Za-z_][A-Za-z0-9_]{1,62})["'`]\s*\)|\/rest\/v1\/([A-Za-z_][A-Za-z0-9_]{1,62})(?![A-Za-z0-9_])/g;
57
+ const RPC_REF = /\.rpc\(\s*["'`]([A-Za-z_][A-Za-z0-9_]{1,62})["'`]|\/rest\/v1\/rpc\/([A-Za-z_][A-Za-z0-9_]{1,62})/g;
58
+ const BUCKET_REF = /storage\s*\.from\(\s*["'`]([A-Za-z0-9_.-]{1,63})["'`]/g;
54
59
  const PERSONAL = /user|profile|customer|account|order|payment|message|chat|contact|lead|email|subscri|invoice/i;
55
60
 
56
61
  // Which app builder made this, so the fix prompt can say where to paste it.
@@ -120,6 +125,37 @@ async function get(url, { timeout = 15000, headers = {}, method = "GET", body =
120
125
  }
121
126
  }
122
127
 
128
+ // What went wrong, in words a non-developer can act on. Shared by the web check and the CLI.
129
+ export function explainError(message) {
130
+ const m = String(message);
131
+ const code = Number((m.match(/\((\d{3})\)$/) || [])[1]);
132
+ if (/look like a web address/.test(m)) return "That doesn't look like a web address. Try something like myapp.lovable.app.";
133
+ if (/isn't a web page/.test(m)) return "That address isn't a web page. Enter the address people open to use your app.";
134
+ if (code === 404) return "That address answered \"not found\". Check it's the live address of your app (open it in your browser first).";
135
+ if (code === 530) return "Nothing answers at that address. Check the spelling, and that the app is published.";
136
+ if (code === 401 || code === 403 || code === 429) return "That site turned the check away. It may be private, password-protected, or blocking automated visitors, so Greenlit can't grade it from here.";
137
+ if (code >= 500) return `That site had an error of its own (${code}). Open it in your browser to see if it's up, then try again.`;
138
+ if (/timed out/.test(m)) return "That site took too long to answer. Try again in a minute.";
139
+ return "Couldn't reach that site. Check the spelling, and that the app is published.";
140
+ }
141
+
142
+ // A script belongs to the app if it's on the same site (static.myapp.com for myapp.com) or on a hosting CDN.
143
+ // Scripts on anyone else's site (Stripe, analytics) are that company's code, not the app's.
144
+ const siteKey = (host) => {
145
+ const parts = host.toLowerCase().split(".");
146
+ const short = parts.length > 2 && parts.at(-1).length === 2 && /^(co|com|org|net|ac|gov|edu)$/.test(parts.at(-2));
147
+ return parts.slice(short ? -3 : -2).join(".");
148
+ };
149
+ const HOSTING_CDN = /(^|\.)(cloudfront\.net|azureedge\.net|b-cdn\.net|r2\.dev|fastly\.net|akamaized\.net|amazonaws\.com|storage\.googleapis\.com)$/i;
150
+
151
+ // Paths to other scripts mentioned inside a script or page: imports of every form, and the lists of lazy-loaded
152
+ // pages that Vite and Next.js keep ("assets/Page-abc.js", "static/chunks/abc.js"). This is where most of an app's code is.
153
+ const SCRIPT_REF = /["'`]((?:\.{0,2}\/|assets\/|_next\/|static\/chunks\/)[\w@.~\/-]+\.m?js(?:\?[^"'`\s]*)?)["'`]/g;
154
+ const resolveRef = (ref, from, origin) => (/^(assets|_next)\//.test(ref) ? safeUrl(ref, `${origin}/`) : ref.startsWith("static/chunks/") ? safeUrl(`/_next/${ref}`, origin) : safeUrl(ref, from));
155
+
156
+ // Builders and hosts often answer an address with nothing on it with a normal-looking page and status 200.
157
+ const DEAD_PAGE = /<title[^>]*>[^<]*(?:(?:website|site|page|project|app|application|deployment)\s+(?:was\s+|is\s+)?not\s+found|\b404\b)[^<]*<\/title>/i;
158
+
123
159
  // --- fix prompts ---------------------------------------------------------------------------------
124
160
  // Written for someone who can't read the code: what to do by hand first (revoking a key is something
125
161
  // no AI builder can do for you), then one prompt to paste into the builder's chat.
@@ -167,8 +203,12 @@ const P = {
167
203
  }),
168
204
  framing: () => ({
169
205
  first: null,
170
- prompt: "Any other website can show my app inside a hidden frame and trick my users into clicking things (clickjacking). Add the response header `Content-Security-Policy: frame-ancestors 'self'` (or `X-Frame-Options: DENY`) in my host's header settings, redeploy, and confirm the header is there.",
206
+ prompt: "Any other website can show my app inside a hidden frame and trick my users into clicking things (clickjacking). Add the response header `Content-Security-Policy: frame-ancestors 'self'` (or `X-Frame-Options: DENY`) in my host's header settings, redeploy, and confirm the header is there. If this host doesn't let me set response headers, say so plainly instead of adding a meta tag, because a meta tag can't do this. Then tell me what my options are.",
171
207
  }),
208
+ dbCheck: (db) =>
209
+ db === "Supabase"
210
+ ? "Check my Supabase database and change nothing yet. For every table, tell me whether Row Level Security is on, and which policies let someone read or change rows without signing in, or read rows that aren't theirs. Do the same for my storage buckets. Also tell me whether anyone can sign up without confirming their email. End with a plain list of what is open to strangers, worst first."
211
+ : "Check my Firebase security rules and change nothing yet. For Firestore, Realtime Database and Storage, tell me which paths someone can read or change without signing in, or read when the data isn't theirs. End with a plain list of what is open to strangers, worst first.",
172
212
  sourceMaps: () => ({
173
213
  first: null,
174
214
  prompt: "My production build publishes source maps, so anyone can read my app's original source code. Turn them off for production builds only (for Vite: build.sourcemap = false in vite.config), rebuild and redeploy. Don't change anything else.",
@@ -180,7 +220,8 @@ const P = {
180
220
  };
181
221
 
182
222
  // --- the check -----------------------------------------------------------------------------------
183
- export async function siteScan(target, { mine = false, fetcher = fetch, maxScripts = 40, maxBytes = 8 * 1024 * 1024 } = {}) {
223
+ export async function siteScan(target, { mine = false, fetcher = fetch, maxScripts = 400, maxBytes = 8 * 1024 * 1024, maxTotalBytes = 200 * 1024 * 1024, deadlineMs = 120000, scriptTimeoutMs = 15000 } = {}) {
224
+ const deadline = Date.now() + deadlineMs;
184
225
  const fetchOpts = (o = {}) => ({ max: maxBytes, ...o, fetcher });
185
226
  const url = safeUrl(/^https?:\/\//i.test(String(target).trim()) ? String(target).trim() : `https://${String(target).trim()}`);
186
227
  if (!url || !/^https?:$/.test(url.protocol) || !url.hostname.includes(".")) throw new Error(`"${target}" doesn't look like a web address`);
@@ -189,33 +230,76 @@ export async function siteScan(target, { mine = false, fetcher = fetch, maxScrip
189
230
 
190
231
  const page = await get(url.href, fetchOpts());
191
232
  if (!page.status || page.status >= 400) throw new Error(`could not load ${url.href} (${page.error || page.status})`);
192
- const origin = new URL(page.url || url.href).origin;
233
+ const pageType = page.headers?.get("content-type") || "";
234
+ if (pageType && !/html/i.test(pageType)) throw new Error(`${url.href} isn't a web page`);
235
+ if (DEAD_PAGE.test(page.text)) throw new Error(`could not load ${url.href} (404)`);
236
+ const pageUrl = page.url || url.href;
237
+ const origin = new URL(pageUrl).origin;
238
+ const site = siteKey(new URL(origin).hostname);
193
239
  const builder = detectBuilder(new URL(origin).host, page.text);
240
+ const isOwn = (href) => {
241
+ const h = new URL(href).hostname;
242
+ return siteKey(h) === site || HOSTING_CDN.test(h);
243
+ };
194
244
 
195
- // Every script the page loads from its own site, plus the scripts those import.
245
+ // Every script that belongs to the app: the ones the page loads, then whatever those mention, until none are left.
196
246
  const srcs = new Set();
197
- const collect = (html, base) => {
198
- for (const m of html.matchAll(/<script[^>]+src=["']([^"']+)["']/gi)) safeUrl(m[1], base) && srcs.add(safeUrl(m[1], base).href);
199
- for (const m of html.matchAll(/<link[^>]+href=["']([^"']+\.m?js)["']/gi)) safeUrl(m[1], base) && srcs.add(safeUrl(m[1], base).href);
247
+ const collect = (text, base) => {
248
+ for (const m of text.matchAll(SCRIPT_REF)) {
249
+ const u = resolveRef(m[1], base, origin);
250
+ if (u && /^https?:$/.test(u.protocol)) srcs.add(u.href);
251
+ }
200
252
  };
201
- collect(page.text, origin);
253
+ for (const m of page.text.matchAll(/<script[^>]+src=["']([^"']+)["']/gi)) safeUrl(m[1], pageUrl) && srcs.add(safeUrl(m[1], pageUrl).href);
254
+ for (const m of page.text.matchAll(/<link[^>]+href=["']([^"']+\.m?js(?:\?[^"']*)?)["']/gi)) safeUrl(m[1], pageUrl) && srcs.add(safeUrl(m[1], pageUrl).href);
255
+ collect(page.text, pageUrl);
256
+
202
257
  const bundles = [{ where: "the page itself", text: page.text }];
203
258
  const seen = new Set();
204
- // Two rounds: the scripts the page names, then the scripts those import. Six at a time.
205
- for (let pass = 0; pass < 2; pass++) {
206
- const batch = [...srcs].filter((src) => !seen.has(src) && new URL(src).origin === origin).slice(0, Math.max(0, maxScripts - seen.size));
259
+ let total = page.text.length;
260
+ let stopped = false;
261
+ let cut = 0;
262
+ let fetched = 0;
263
+ const retried = new Set();
264
+ const failed = new Set();
265
+ for (;;) {
266
+ const waiting = [...srcs].filter((src) => !seen.has(src) && isOwn(src));
267
+ if (!waiting.length) break;
268
+ const room = maxScripts - fetched;
269
+ if (room <= 0 || total >= maxTotalBytes || Date.now() > deadline) {
270
+ stopped = true;
271
+ break;
272
+ }
273
+ // Six at a time.
274
+ const batch = waiting.slice(0, Math.min(6, room));
207
275
  for (const src of batch) seen.add(src);
208
- for (let i = 0; i < batch.length; i += 6) {
209
- const got = await Promise.all(batch.slice(i, i + 6).map((src) => get(src, fetchOpts()).then((r) => ({ src, r }))));
210
- for (const { src, r } of got) {
211
- // Many hosts answer a missing file with the home page; that isn't a script.
212
- if (r.status !== 200 || /text\/html/i.test(r.headers?.get("content-type") || "")) continue;
213
- bundles.push({ where: new URL(src).pathname, text: r.text, url: src });
214
- for (const m of r.text.matchAll(/(?:import\(|from\s*)["'](\.{0,2}\/[^"']+\.m?js)["']/g)) safeUrl(m[1], src) && srcs.add(safeUrl(m[1], src).href);
276
+ fetched += batch.length;
277
+ const got = await Promise.all(batch.map((src) => get(src, fetchOpts({ timeout: scriptTimeoutMs })).then((r) => ({ src, r }))));
278
+ for (const { src, r } of got) {
279
+ // A file that wouldn't load isn't the same as a file that doesn't exist: try once more, then count it as unread.
280
+ if (r.status === 0 || r.status === 429 || r.status >= 500) {
281
+ if (retried.has(src)) failed.add(src);
282
+ else {
283
+ retried.add(src);
284
+ seen.delete(src);
285
+ }
286
+ continue;
215
287
  }
288
+ // Many hosts answer a missing file with the home page; that isn't a script.
289
+ if (r.status !== 200 || /text\/html/i.test(r.headers?.get("content-type") || "")) continue;
290
+ if (r.text.length >= maxBytes) cut++;
291
+ total += r.text.length;
292
+ bundles.push({ where: new URL(src).pathname, text: r.text, url: src });
293
+ collect(r.text, src);
216
294
  }
217
295
  }
296
+ const unread = [...srcs].filter((src) => !seen.has(src) && isOwn(src)).length + failed.size;
297
+ const scriptTags = [...page.text.matchAll(/<script[^>]+src=["']([^"']+)["']/gi)].map((m) => safeUrl(m[1], pageUrl)).filter((u) => u && /^https?:$/.test(u.protocol));
298
+ const elsewhere = scriptTags.filter((u) => !isOwn(u.href)).length;
299
+ // The page has scripts, but all of them live on another site, so its real code was never read.
300
+ const noCodeRead = bundles.length === 1 && elsewhere > 0;
218
301
 
302
+ let mapTries = 0;
219
303
  let supabase = null;
220
304
  let firebase = null;
221
305
  const keysSeen = new Set();
@@ -256,7 +340,9 @@ export async function siteScan(target, { mine = false, fetcher = fetch, maxScrip
256
340
  }
257
341
  const sm = b.url && b.text.match(/sourceMappingURL=([^\s'"]+\.map)/);
258
342
  const mapUrl = sm && safeUrl(sm[1], b.url)?.href;
259
- if (mapUrl && safeUrl(mapUrl).origin === origin && !findings.some((f) => f.id === "sourcemaps")) {
343
+ // A few tries are enough: an app either publishes its maps or it doesn't.
344
+ if (mapUrl && isOwn(mapUrl) && mapTries < 3 && !findings.some((f) => f.id === "sourcemaps")) {
345
+ mapTries++;
260
346
  // Check what comes back: hosts that answer every missing file with the home page would look "public" otherwise.
261
347
  const r = await get(mapUrl, fetchOpts({ max: 4096 }));
262
348
  if (r.status === 200 && /^\s*\{[\s\S]*"(version|mappings|sources)"/.test(r.text))
@@ -266,25 +352,54 @@ export async function siteScan(target, { mine = false, fetcher = fetch, maxScrip
266
352
 
267
353
  const database = supabase?.url && supabase.anon ? "Supabase" : firebase?.project ? "Firebase" : null;
268
354
  if (database && !mine)
269
- add({ id: "db:skipped", severity: "info", where: database, title: `Your ${database} database wasn't checked`, why: `This app uses ${database}. Greenlit can check which of its data anyone on the internet can read, but only on your own computer, for an app you own.`, fix: `Run \`npx greenlitlab ${url.host} --mine\` if this is your app.`, first: null, prompt: null });
355
+ add({ id: "db:skipped", severity: "info", where: database, title: `Your ${database} database wasn't checked`, why: `This app uses ${database}. Greenlit can check which of its data anyone on the internet can read, but only on your own computer, for an app you own.`, fix: `Run \`npx greenlitlab ${url.host} --mine\` if this is your app.`, first: null, prompt: null, checkPrompt: P.dbCheck(database) });
356
+ if (unread || cut)
357
+ add({ id: "coverage:partial", severity: "info", where: "your app's scripts", title: unread ? `${unread} of this app's scripts weren't read` : "Some of this app's scripts were too big to read to the end", why: `Greenlit read ${bundles.length - 1} scripts, but couldn't get through the rest in one check. A problem in those wouldn't show up here.`, fix: `Run \`npx greenlitlab ${url.host}\` on your computer, which reads them all.`, first: null, prompt: null });
358
+ if (noCodeRead)
359
+ add({ id: "coverage:none", severity: "info", where: "your app's scripts", title: "This app's code wasn't read", why: `All ${elsewhere} of its scripts load from other sites, and Greenlit can't tell which of them are yours. Only the page itself and its settings were checked.`, fix: "If your app loads its code from a site of its own, check that site's address too.", first: null, prompt: null });
270
360
 
271
361
  // Supabase: with the public anon key, which tables can anyone read?
272
362
  let tables = null;
363
+ let tablesTested = 0;
364
+ let dbBlind = false;
365
+ let tablesListed = false;
366
+ // Database functions the app calls. Listed for the owner, never called: calling one runs it.
367
+ const functions = new Set();
368
+ const bucketsInCode = new Set();
369
+ if (supabase)
370
+ for (const b of bundles) {
371
+ for (const m of b.text.matchAll(RPC_REF)) functions.add(m[1] || m[2]);
372
+ for (const m of b.text.matchAll(BUCKET_REF)) bucketsInCode.add(m[1]);
373
+ }
374
+ // Signs of Supabase, but not both its address and its public key: nothing can be tested.
375
+ const supabasePartial = Boolean(supabase && !(supabase.url && supabase.anon) && !firebase?.project);
376
+ if (supabasePartial)
377
+ add({ id: "db:not-found", severity: "info", where: "Supabase", title: "This app seems to use Supabase, but its database wasn't checked", why: "Greenlit found signs of Supabase but not both its address and its public key in the code it read, so it couldn't test anything. The app may reach its database through its own server, which is the safer design, or the key may be in code that wasn't read.", fix: "Open Supabase → Advisors → Security Advisor: it lists every table and function that strangers can reach.", first: null, prompt: null, checkPrompt: P.dbCheck("Supabase") });
273
378
  if (mine && supabase?.url && supabase.anon) {
274
379
  // The newer sb_publishable_ keys aren't JWTs and go in the apikey header only.
275
380
  const h = { apikey: supabase.anon, ...(supabase.anon.startsWith("eyJ") && { authorization: `Bearer ${supabase.anon}` }) };
381
+ const names = new Set();
382
+ // Older projects still answer this with the list of tables; newer ones refuse the public key.
276
383
  const api = await get(`${supabase.url}/rest/v1/`, fetchOpts({ headers: h }));
277
- let names = [];
278
384
  try {
279
- names = Object.keys(JSON.parse(api.text).paths || {}).map((p) => p.slice(1)).filter((p) => p && !p.startsWith("rpc/"));
385
+ for (const p of Object.keys(JSON.parse(api.text).paths || {})) if (p.slice(1) && !p.startsWith("/rpc/")) names.add(p.slice(1));
280
386
  } catch {}
387
+ tablesListed = names.size > 0;
388
+ for (const b of bundles) for (const m of b.text.matchAll(TABLE_REF)) (m[1] || m[2]) !== "rpc" && names.add(m[1] || m[2]);
281
389
  tables = [];
282
- for (const t of names.slice(0, 60)) {
390
+ for (const t of [...names].slice(0, 80)) {
283
391
  // A HEAD request with count=exact returns how many rows are visible, and no rows.
284
392
  const r = await get(`${supabase.url}/rest/v1/${encodeURIComponent(t)}?select=*`, fetchOpts({ method: "HEAD", headers: { ...h, prefer: "count=exact", range: "0-0" } }));
393
+ // "Not found" means the name wasn't a table; no answer means it wasn't tested. Neither counts.
394
+ if (!r.status || r.status === 404 || r.status >= 500) continue;
395
+ tablesTested++;
285
396
  const n = Number((r.headers?.get("content-range") || "").split("/")[1]);
286
397
  if (r.status < 300 && n > 0) tables.push({ table: t, rows: n });
287
398
  }
399
+ // A check that tested no tables must say so, not report "nothing open".
400
+ dbBlind = tablesTested === 0;
401
+ if (dbBlind)
402
+ add({ id: "db:no-tables", severity: "info", where: "Supabase", title: "Your database tables weren't checked", why: "Greenlit couldn't find any of your table names in the code it read, and Supabase no longer lists them for the public key. So it couldn't test which tables strangers can read. Storage and sign-up settings were still checked.", fix: "Open Supabase → Advisors → Security Advisor: it lists every table that strangers can reach.", first: null, prompt: null, checkPrompt: P.dbCheck("Supabase") });
288
403
  for (const { table, rows } of tables) {
289
404
  const personal = PERSONAL.test(table);
290
405
  const why = personal
@@ -319,8 +434,8 @@ export async function siteScan(target, { mine = false, fetcher = fetch, maxScrip
319
434
  add({ id: "supabase:open-signup", severity: "high", where: "Supabase Auth settings", title: "Anyone can sign up with any email, without confirming it", why: "Rules that only check \"is the user signed in?\" protect nothing: a stranger can make an account in seconds, even with someone else's email address.", fix: "Turn on email confirmation in Supabase Auth, and make every policy check who owns the row, not just that someone is signed in.", ...P.signup() });
320
435
  } catch {}
321
436
  // Storage: which common buckets list their files to anyone? Asks for one file name, never the file.
322
- for (const bucket of ["avatars", "uploads", "files", "documents", "images", "attachments", "receipts", "invoices", "private"]) {
323
- const r = await get(`${supabase.url}/storage/v1/object/list/${bucket}`, fetchOpts({ method: "POST", headers: { ...h, "content-type": "application/json" }, body: JSON.stringify({ prefix: "", limit: 1, offset: 0 }), max: 65536 }));
437
+ for (const bucket of [...new Set(["avatars", "uploads", "files", "documents", "images", "attachments", "receipts", "invoices", "private", ...bucketsInCode])].slice(0, 24)) {
438
+ const r = await get(`${supabase.url}/storage/v1/object/list/${encodeURIComponent(bucket)}`, fetchOpts({ method: "POST", headers: { ...h, "content-type": "application/json" }, body: JSON.stringify({ prefix: "", limit: 1, offset: 0 }), max: 65536 }));
324
439
  let n = 0;
325
440
  try {
326
441
  n = Array.isArray(JSON.parse(r.text)) ? JSON.parse(r.text).length : 0;
@@ -366,23 +481,49 @@ export async function siteScan(target, { mine = false, fetcher = fetch, maxScrip
366
481
  add({ id: "csp", severity: "low", where: "response headers", title: "No Content-Security-Policy", why: "If an attacker gets a script into the page (through a comment, a profile field or a dependency), nothing stops it from sending your users' data out.", fix: "Add a Content-Security-Policy header in your host's settings.", ...P.csp([...thirdParty].slice(0, 6)) });
367
482
 
368
483
  const csp = page.headers?.get("content-security-policy") || "";
369
- if (!page.headers?.get("x-frame-options") && !/frame-ancestors/i.test(csp))
370
- add({ id: "framing", severity: "low", where: "response headers", title: "Other sites can put your app in a frame", why: "A malicious page can show your app inside an invisible frame and trick your users into clicking buttons they can't see (clickjacking).", fix: "Add the header Content-Security-Policy: frame-ancestors 'self' (or X-Frame-Options: DENY).", ...P.framing() });
484
+ // Lovable's own hosting sets the response headers, and this protection can't be added from inside an app
485
+ // (a meta tag can't do it). What the owner can't change is shown, and costs no points.
486
+ const hostSetsHeaders = /\.lovable\.app$/i.test(new URL(origin).hostname);
487
+ if (!page.headers?.get("x-frame-options") && !/frame-ancestors/i.test(csp)) {
488
+ if (hostSetsHeaders)
489
+ add({ id: "framing", severity: "info", where: "response headers", title: "Your host decides whether other sites can frame your app", why: "Other sites can show this app inside a frame, which can be used to trick people into clicks (clickjacking). On a lovable.app address the host sets these headers and we found no way for you to change them, so this costs you no points.", fix: "Nothing to do here. If you move to your own domain on a host that lets you set headers, add Content-Security-Policy: frame-ancestors 'self'.", first: null, prompt: null });
490
+ else
491
+ add({ id: "framing", severity: "low", where: "response headers", title: "Other sites can put your app in a frame", why: "A malicious page can show your app inside an invisible frame and trick your users into clicking buttons they can't see (clickjacking).", fix: "Add the header Content-Security-Policy: frame-ancestors 'self' (or X-Frame-Options: DENY).", ...P.framing() });
492
+ }
371
493
 
372
- const penalty = findings.reduce((a, f) => a + SEVERITY[f.severity], 0);
373
- const score = Math.max(0, 100 - penalty);
374
- const grade = score >= 90 ? "A" : score >= 75 ? "B" : score >= 60 ? "C" : score >= 40 ? "D" : "F";
494
+ // Small things add up to 20 points at most, so missing headers alone can never fail an app.
495
+ // One critical problem is an F whatever else is right: it can't be averaged away.
496
+ const sum = (kinds) => findings.reduce((a, f) => a + (kinds.includes(f.severity) ? SEVERITY[f.severity] : 0), 0);
497
+ const penalty = sum(["critical", "high"]) + Math.min(20, sum(["medium", "low"]));
498
+ const blocker = findings.some((f) => f.severity === "critical");
499
+ const score = Math.min(Math.max(0, 100 - penalty), blocker ? 39 : 100);
500
+ // With none of the app's code read and nothing serious seen, there's no honest grade to give.
501
+ const ungraded = noCodeRead && penalty < SEVERITY.high;
502
+ const grade = ungraded ? "?" : blocker ? "F" : score >= 90 ? "A" : score >= 75 ? "B" : score >= 60 ? "C" : score >= 40 ? "D" : "F";
503
+ // A good grade says only what was looked at, so it can't be read as "the database is safe too".
504
+ const good = grade === "A" || grade === "B";
505
+ const incomplete = unread > 0 || cut > 0;
506
+ const verdict = ungraded
507
+ ? "Not graded: Greenlit couldn't read this app's code."
508
+ : good && (dbBlind || supabasePartial)
509
+ ? `Nothing serious in the ${incomplete ? "code Greenlit read" : "code"}. Your database tables weren't checked.`
510
+ : good && database && !mine
511
+ ? `Nothing serious in the ${incomplete ? "code Greenlit read" : "code"}. Your database still needs checking.`
512
+ : good && incomplete
513
+ ? "Nothing serious in the code Greenlit read. Some of it wasn't read."
514
+ : VERDICT[grade];
375
515
  const order = ["critical", "high", "medium", "low", "info"];
376
516
  findings.sort((a, b) => order.indexOf(a.severity) - order.indexOf(b.severity));
377
517
  return {
378
518
  url: origin,
379
519
  builder,
380
- score,
520
+ score: ungraded ? null : score,
381
521
  grade,
382
- verdict: VERDICT[grade],
522
+ verdict,
383
523
  mine,
384
524
  scripts: bundles.length - 1,
385
- supabase: supabase ? { project: supabase.ref, checked: mine, readable: tables } : null,
525
+ scriptsUnread: unread,
526
+ supabase: supabase ? { project: supabase.ref, checked: Boolean(mine && tables && !dbBlind), tablesTested, tablesListed, readable: tables, functions: [...functions].slice(0, 50) } : null,
386
527
  firebase: firebase ? { project: firebase.project, checked: mine, readable: firebaseOpen } : null,
387
528
  findings,
388
529
  pasteInto: builder || "your AI app builder or coding agent",
@@ -440,10 +581,10 @@ export function renderSite(r, change, { color = true, mine = r.mine } = {}) {
440
581
  const k = (code) => (s) => (color ? `\x1b[${code}m${s}\x1b[0m` : s);
441
582
  const red = k("31"), green = k("32"), yellow = k("33"), dim = k("2"), bold = k("1"), cyan = k("36");
442
583
  const col = { critical: red, high: red, medium: yellow, low: dim, info: dim };
443
- const gcol = r.score >= 75 ? green : r.score >= 55 ? yellow : red;
584
+ const gcol = r.grade === "A" || r.grade === "B" ? green : r.grade === "C" || r.grade === "?" ? yellow : red;
444
585
  const L = [];
445
586
  L.push("", `${bold("Greenlit check")} · ${r.url}${r.builder ? ` · built with ${r.builder}` : ""} · ${r.scripts} scripts read${r.supabase ? " · Supabase" : ""}${r.firebase ? " · Firebase" : ""}`, "");
446
- L.push(` Grade ${gcol(bold(r.grade))} ${gcol(`${r.score}/100`)} ${r.verdict}`);
587
+ L.push(` Grade ${gcol(bold(r.grade))} ${r.score == null ? "" : `${gcol(`${r.score}/100`)} `}${r.verdict}`);
447
588
  if (change) {
448
589
  const arrow = change.after.score > change.before.score ? green : change.after.score < change.before.score ? red : dim;
449
590
  L.push(` ${arrow(`Was ${change.before.grade} (${change.before.score}) on ${change.since.slice(0, 10)}, now ${change.after.grade} (${change.after.score}).`)}`);
@@ -462,9 +603,17 @@ export function renderSite(r, change, { color = true, mine = r.mine } = {}) {
462
603
  if (f.prompt) {
463
604
  L.push(` ${cyan(`Then paste this into ${r.pasteInto}:`)}`);
464
605
  L.push(wrap(f.prompt, 84, ` ${dim("│")} `));
465
- } else L.push(wrap(`${green("Next:")} ${f.fix}`, 88, " "));
606
+ } else {
607
+ L.push(wrap(`${green("Next:")} ${f.fix}`, 88, " "));
608
+ if (f.checkPrompt) {
609
+ L.push(` ${cyan(`Or paste this into ${r.pasteInto} to have it check:`)}`);
610
+ L.push(wrap(f.checkPrompt, 84, ` ${dim("│")} `));
611
+ }
612
+ }
466
613
  L.push("");
467
614
  }
615
+ if (r.supabase?.checked) L.push(dim(`Supabase: ${r.supabase.tablesTested} table${r.supabase.tablesTested === 1 ? "" : "s"} tested with the public key, ${r.supabase.readable.length} readable by anyone.${r.supabase.tablesListed ? "" : " Only tables named in your app's code could be tested; Supabase's Security Advisor lists them all."}`));
616
+ else if (mine && r.supabase) L.push(dim("Supabase: no tables were tested. See the note above."));
468
617
  L.push(dim(`Read only what the site serves to every visitor${mine ? "; database checked with counts and names only, never data" : ""}.`));
469
618
  if (n) {
470
619
  L.push(dim(`Fix the red items first, one prompt at a time. Copy one prompt: npx greenlitlab ${new URL(r.url).host}${mine ? " --mine" : ""} --prompt 1 | pbcopy (or --prompt all for every fix in one)`));
package/src/severity.mjs CHANGED
@@ -1,2 +1,3 @@
1
- // How much each finding takes off a 100-point score. "info" is a note, not a problem: it costs nothing.
2
- export const SEVERITY = { critical: 40, high: 15, medium: 5, low: 1, info: 0 };
1
+ // How much each finding takes off a 100-point score. One critical problem is an F whatever else is right, and
2
+ // one high means C at best. Medium and low together take 20 points at most. "info" is a note: it costs nothing.
3
+ export const SEVERITY = { critical: 45, high: 30, medium: 5, low: 1, info: 0 };