greenlitlab 0.4.2 → 0.4.3
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 +9 -0
- package/README.md +11 -7
- package/package.json +1 -1
- package/server.json +2 -2
- package/src/grade.mjs +322 -162
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.4.3 (19 November 2026)
|
|
4
|
+
|
|
5
|
+
- A passing grade now ends with what to check next: `--mine` (when the app has a database), `scan` and `questions`, the parts no outside check can see.
|
|
6
|
+
- The website's database check is paused. The owner's tag proved control of the web page, but the database to check was read from that same page, so it could be pointed at another app's database. `--mine` on your own computer is unchanged. It returns once the owner can prove control of the database itself.
|
|
7
|
+
- Crafted pages can no longer make a check slow: Supabase keys are found with a linear scan, the tag patterns stop at the next `<`, and the owner tag is read in one pass.
|
|
8
|
+
- The web check follows redirects one hop at a time and checks each address (and every script and source map) against the same rules as the address typed in. A trailing dot (`localhost.`) no longer slips past those rules.
|
|
9
|
+
- The website's APIs answer only this site's own JSON calls, so another site's page can't make its visitors fire checks.
|
|
10
|
+
- Cookie names from a scanned site are kept short and plain before they reach a report title.
|
|
11
|
+
|
|
3
12
|
## 0.4.2 (10 November 2026)
|
|
4
13
|
|
|
5
14
|
- A welcome screen: `npx greenlitlab` on its own, in a wide terminal, now shows a pixel-art signal on green and the four commands that matter. `--help` still prints the full reference, and pipes, CI, `NO_COLOR` and narrow windows get it too.
|
package/README.md
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
**Is your AI-built app safe to launch?** Greenlit grades a deployed app from A to F for what a stranger can use against it. It explains each problem in plain words and gives you a prompt to paste back into Lovable, Bolt, v0, Replit or Emergent that fixes it. Run it again after the fix, and it shows what got fixed.
|
|
4
4
|
|
|
5
|
+
<p><img src="https://raw.githubusercontent.com/priberry-data/greenlitlab/main/docs/demo.gif" alt="Greenlit checks a Lovable app: grade F with a leaked Stripe key, then a fix prompt to paste back" width="720"></p>
|
|
6
|
+
|
|
5
7
|
**In the browser:** [greenlit.priberry.com](https://greenlit.priberry.com). Paste your app's address. Nothing to install.
|
|
6
8
|
|
|
7
9
|
**On your computer:**
|
|
@@ -18,15 +20,17 @@ npx greenlitlab myapp.lovable.app
|
|
|
18
20
|
| A Supabase `service_role` key in the browser | everywhere |
|
|
19
21
|
| Source maps that hand out your source code | everywhere |
|
|
20
22
|
| Clickjacking (no `frame-ancestors` or `X-Frame-Options`) and no Content-Security-Policy | everywhere |
|
|
21
|
-
| Supabase tables anyone can read with the public key | your own app
|
|
22
|
-
| Supabase storage buckets that list their files to anyone | your own app
|
|
23
|
-
| Supabase sign-up open to anyone without email confirmation | your own app
|
|
24
|
-
| A public `.env` file or `.git` folder | your own app
|
|
25
|
-
| Firebase Realtime Database and Firestore open to everyone | your own app
|
|
23
|
+
| Supabase tables anyone can read with the public key | your own app: `--mine` |
|
|
24
|
+
| Supabase storage buckets that list their files to anyone | your own app: `--mine` |
|
|
25
|
+
| Supabase sign-up open to anyone without email confirmation | your own app: `--mine` |
|
|
26
|
+
| A public `.env` file or `.git` folder | your own app: `--mine` |
|
|
27
|
+
| Firebase Realtime Database and Firestore open to everyone | your own app: `--mine` |
|
|
26
28
|
|
|
27
29
|
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
30
|
|
|
29
|
-
|
|
31
|
+
The database checks run on your own computer. (The website version is paused until it can confirm you control the database itself, not only the web page.)
|
|
32
|
+
|
|
33
|
+
Supabase no longer lists a project's tables for the public key, so the database check tests the tables your app's code names, tells you how many it tested, and says so plainly when it could test none.
|
|
30
34
|
|
|
31
35
|
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.
|
|
32
36
|
|
|
@@ -37,7 +41,7 @@ The owner-only checks ask for a row count (Supabase), one file or document name
|
|
|
37
41
|
| A page that loads from a developer-only address, plain-http content, Stripe in test mode, a default title, "noindex", AI calls from the browser, a test email sender, unlocked sign-in cookies | everywhere |
|
|
38
42
|
| Plain http that doesn't redirect to https; an app that lets any website read a signed-in visitor's data | everywhere |
|
|
39
43
|
| No DMARC record or a broken SPF record on your own domain | everywhere, custom domains only |
|
|
40
|
-
| Personal columns (email, phone, password…) in tables strangers can read; backend functions listed for review | your own app
|
|
44
|
+
| Personal columns (email, phone, password…) in tables strangers can read; backend functions listed for review | your own app: `--mine` |
|
|
41
45
|
| Rules that are too loose, tables strangers can change: Supabase's Security Advisor in plain words | `advisor`, with your advisor results |
|
|
42
46
|
| Always-true policies, tables without Row Level Security, unverified payment webhooks, secrets behind a public prefix | `scan`, on your project's files |
|
|
43
47
|
| Backups, spending limits, a separate test database, outage alerts | `questions`: only you know, never graded |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "greenlitlab",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.3",
|
|
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": {
|
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.
|
|
8
|
+
"version": "0.4.3",
|
|
9
9
|
"packages": [
|
|
10
10
|
{
|
|
11
11
|
"registryType": "npm",
|
|
12
12
|
"identifier": "greenlitlab",
|
|
13
|
-
"version": "0.4.
|
|
13
|
+
"version": "0.4.3",
|
|
14
14
|
"transport": { "type": "stdio" },
|
|
15
15
|
"packageArguments": [{ "type": "positional", "value": "mcp" }]
|
|
16
16
|
}
|
package/src/grade.mjs
CHANGED
|
@@ -80,7 +80,31 @@ export function looksReal(found, kind = "") {
|
|
|
80
80
|
if (kind !== "twilio" && (/your[-_]|example|placeholder|replace|insert|[-_]here\b|goeshere|keyhere|tokenhere|api[-_]key$/i.test(found) || /[Yy]our[A-Z]/.test(found) || countsUpward(found))) return false;
|
|
81
81
|
return new Set(found.replace(/[^A-Za-z0-9]/g, "").slice(-16)).size >= 4;
|
|
82
82
|
}
|
|
83
|
-
const
|
|
83
|
+
const isTok = (c) => (c >= 48 && c <= 57) || (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c === 95 || c === 45;
|
|
84
|
+
const isWord = (c) => isTok(c) && c !== 45;
|
|
85
|
+
// JWTs (header.payload.signature, base64url), found from each ".eyJ" in one linear pass. The regex version
|
|
86
|
+
// backtracked on input like "-eyJ-eyJ…" (seconds per megabyte).
|
|
87
|
+
function findJwts(text) {
|
|
88
|
+
const out = [];
|
|
89
|
+
let from = 0;
|
|
90
|
+
let i;
|
|
91
|
+
while ((i = text.indexOf(".eyJ", from)) !== -1) {
|
|
92
|
+
let a = i;
|
|
93
|
+
while (a > from && i - a < 2003 && isTok(text.charCodeAt(a - 1))) a--;
|
|
94
|
+
let h = text.indexOf("eyJ", a);
|
|
95
|
+
while (h !== -1 && h < i && h > 0 && isWord(text.charCodeAt(h - 1))) h = text.indexOf("eyJ", h + 1);
|
|
96
|
+
const p = i + 1;
|
|
97
|
+
let e = p;
|
|
98
|
+
while (e < text.length && e - p <= 4003 && isTok(text.charCodeAt(e))) e++;
|
|
99
|
+
let s = e + 1;
|
|
100
|
+
while (s < text.length && s - e - 1 < 1000 && isTok(text.charCodeAt(s))) s++;
|
|
101
|
+
if (h !== -1 && h < i && i - h >= 13 && i - h <= 2003 && e - p >= 13 && e - p <= 4003 && text[e] === "." && s - e - 1 >= 10) {
|
|
102
|
+
out.push(text.slice(h, s));
|
|
103
|
+
from = s;
|
|
104
|
+
} else from = i + 1;
|
|
105
|
+
}
|
|
106
|
+
return out;
|
|
107
|
+
}
|
|
84
108
|
const SUPABASE_URL = /https:\/\/([a-z0-9]{20})\.supabase\.co/g;
|
|
85
109
|
const FB_PROJECT = /projectId["']?\s*:\s*["']([a-z0-9-]{4,40})["']/;
|
|
86
110
|
const FB_DB = /["'](https:\/\/[a-z0-9-]+(?:\.[a-z0-9-]+)*\.(?:firebaseio\.com|firebasedatabase\.app))\/?["']/;
|
|
@@ -166,13 +190,24 @@ const safeUrl = (u, base) => {
|
|
|
166
190
|
}
|
|
167
191
|
};
|
|
168
192
|
|
|
169
|
-
|
|
193
|
+
// With `allowUrl` (the website passes its address rules), every address is checked first, and redirects are followed
|
|
194
|
+
// one hop at a time so each hop is checked too: a public page can't redirect the check to a private address.
|
|
195
|
+
async function get(url, { timeout = 15000, headers = {}, method = "GET", body = null, max = 8 * 1024 * 1024, fetcher = fetch, allowUrl = null } = {}) {
|
|
170
196
|
const ctl = new AbortController();
|
|
171
197
|
const t = setTimeout(() => ctl.abort(), timeout);
|
|
172
198
|
try {
|
|
173
|
-
|
|
199
|
+
let at = url;
|
|
200
|
+
let r;
|
|
201
|
+
for (let hop = 0; ; hop++) {
|
|
202
|
+
if (allowUrl && !allowUrl(at)) return { status: 0, error: "blocked address", text: "" };
|
|
203
|
+
r = await fetcher(at, { method, headers: { "user-agent": "greenlit (+https://greenlit.priberry.com)", ...headers }, ...(body != null && { body }), signal: ctl.signal, redirect: allowUrl ? "manual" : "follow" });
|
|
204
|
+
const loc = allowUrl && r.status >= 300 && r.status < 400 ? r.headers?.get("location") : null;
|
|
205
|
+
if (!loc) break;
|
|
206
|
+
if (hop >= 5) return { status: 0, error: "too many redirects", text: "" };
|
|
207
|
+
at = new URL(loc, at).href;
|
|
208
|
+
}
|
|
174
209
|
const text = method === "HEAD" ? "" : await readCapped(r, max);
|
|
175
|
-
return { status: r.status, headers: r.headers, text, url: r.url };
|
|
210
|
+
return { status: r.status, headers: r.headers, text, url: allowUrl ? at : r.url };
|
|
176
211
|
} catch (e) {
|
|
177
212
|
return { status: 0, error: e.name === "AbortError" ? "timed out" : e.message, text: "" };
|
|
178
213
|
} finally {
|
|
@@ -180,9 +215,22 @@ async function get(url, { timeout = 15000, headers = {}, method = "GET", body =
|
|
|
180
215
|
}
|
|
181
216
|
}
|
|
182
217
|
|
|
218
|
+
// People often paste the link to their builder's editor or private preview, not the live app.
|
|
219
|
+
// Those pages are the builder's own (often a sign-in or upgrade screen), so say what to paste instead.
|
|
220
|
+
export function editorLink(u) {
|
|
221
|
+
const h = u.hostname.toLowerCase();
|
|
222
|
+
if (h === "lovable.dev" || h.endsWith(".lovable.dev")) return "That's your Lovable editor, not your app. In Lovable, click Publish (top right) and paste the address it gives you, like myapp.lovable.app.";
|
|
223
|
+
if (/^(id-)?preview--/.test(h) || h.endsWith(".lovableproject.com")) return "That's a private preview link, which only you can open. In Lovable, click Publish and paste the published address, like myapp.lovable.app.";
|
|
224
|
+
if (h === "bolt.new" || h.endsWith("stackblitz.com") || h.endsWith(".webcontainer.io") || h.endsWith(".webcontainer-api.io")) return "That's your Bolt editor, not your app. In Bolt, click Deploy and paste the address it gives you (it usually ends in .bolt.host or .netlify.app).";
|
|
225
|
+
if (h === "v0.dev" || h === "v0.app" || h === "www.v0.dev" || h === "www.v0.app") return "That's your v0 chat, not your app. In v0, click Publish and paste the address it gives you (it ends in .vercel.app).";
|
|
226
|
+
if (h === "replit.com" || h.endsWith(".replit.dev") || h.endsWith(".repl.co")) return "That's the Replit editor or a development link. In Replit, click Deploy and paste the address it gives you (it ends in .replit.app).";
|
|
227
|
+
return null;
|
|
228
|
+
}
|
|
229
|
+
|
|
183
230
|
// What went wrong, in words a non-developer can act on. Shared by the web check and the CLI.
|
|
184
231
|
export function explainError(message) {
|
|
185
232
|
const m = String(message);
|
|
233
|
+
if (m.startsWith("editor link: ")) return m.slice(13);
|
|
186
234
|
const code = Number((m.match(/\((\d{3})\)$/) || [])[1]);
|
|
187
235
|
if (/look like a web address/.test(m)) return "That doesn't look like a web address. Try something like myapp.lovable.app.";
|
|
188
236
|
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.";
|
|
@@ -306,11 +354,13 @@ const P = {
|
|
|
306
354
|
};
|
|
307
355
|
|
|
308
356
|
// --- the check -----------------------------------------------------------------------------------
|
|
309
|
-
export async function siteScan(target, { mine = false, fetcher = fetch, maxScripts = 400, maxBytes = 8 * 1024 * 1024, maxTotalBytes = 200 * 1024 * 1024, deadlineMs = 120000, scriptTimeoutMs = 15000, pageTimeoutMs = 15000, tailMs = 20000, httpProbe = null, wantPage = false } = {}) {
|
|
357
|
+
export async function siteScan(target, { mine = false, fetcher = fetch, allowUrl = null, maxScripts = 400, maxBytes = 8 * 1024 * 1024, maxTotalBytes = 200 * 1024 * 1024, deadlineMs = 120000, scriptTimeoutMs = 15000, pageTimeoutMs = 15000, tailMs = 20000, httpProbe = null, wantPage = false, wantPlan = false } = {}) {
|
|
310
358
|
const deadline = Date.now() + deadlineMs;
|
|
311
|
-
const fetchOpts = (o = {}) => ({ max: maxBytes, ...o, fetcher });
|
|
359
|
+
const fetchOpts = (o = {}) => ({ max: maxBytes, ...o, fetcher, allowUrl });
|
|
312
360
|
const url = safeUrl(/^https?:\/\//i.test(String(target).trim()) ? String(target).trim() : `https://${String(target).trim()}`);
|
|
313
361
|
if (!url || !/^https?:$/.test(url.protocol) || !url.hostname.includes(".")) throw new Error(`"${target}" doesn't look like a web address`);
|
|
362
|
+
const editor = editorLink(url);
|
|
363
|
+
if (editor) throw new Error(`editor link: ${editor}`);
|
|
314
364
|
const findings = [];
|
|
315
365
|
const add = (f) => findings.push(f);
|
|
316
366
|
|
|
@@ -338,8 +388,8 @@ export async function siteScan(target, { mine = false, fetcher = fetch, maxScrip
|
|
|
338
388
|
if (u && /^https?:$/.test(u.protocol)) srcs.add(u.href);
|
|
339
389
|
}
|
|
340
390
|
};
|
|
341
|
-
for (const m of page.text.matchAll(/<script[
|
|
342
|
-
for (const m of page.text.matchAll(/<link[
|
|
391
|
+
for (const m of page.text.matchAll(/<script[^<>]+src=["']([^"']+)["']/gi)) safeUrl(m[1], pageUrl) && srcs.add(safeUrl(m[1], pageUrl).href);
|
|
392
|
+
for (const m of page.text.matchAll(/<link[^<>]+href=["']([^"']+\.m?js(?:\?[^"']*)?)["']/gi)) safeUrl(m[1], pageUrl) && srcs.add(safeUrl(m[1], pageUrl).href);
|
|
343
393
|
collect(page.text, pageUrl);
|
|
344
394
|
|
|
345
395
|
const bundles = [{ where: "the page itself", text: page.text }];
|
|
@@ -382,7 +432,7 @@ export async function siteScan(target, { mine = false, fetcher = fetch, maxScrip
|
|
|
382
432
|
}
|
|
383
433
|
}
|
|
384
434
|
const unread = [...srcs].filter((src) => !seen.has(src) && isOwn(src)).length + failed.size;
|
|
385
|
-
const scriptTags = [...page.text.matchAll(/<script[
|
|
435
|
+
const scriptTags = [...page.text.matchAll(/<script[^<>]+src=["']([^"']+)["']/gi)].map((m) => safeUrl(m[1], pageUrl)).filter((u) => u && /^https?:$/.test(u.protocol));
|
|
386
436
|
const elsewhere = scriptTags.filter((u) => !isOwn(u.href)).length;
|
|
387
437
|
// The page has scripts, but all of them live on another site, so its real code was never read.
|
|
388
438
|
const noCodeRead = bundles.length === 1 && elsewhere > 0;
|
|
@@ -408,7 +458,7 @@ export async function siteScan(target, { mine = false, fetcher = fetch, maxScrip
|
|
|
408
458
|
add({ id: `secret:${id}`, severity: "critical", where: b.where, title: `${title} is in code every visitor downloads`, why: `${why} Found: ${m[0].slice(0, 8)}…`, fix: "Revoke this key now, make a new one, and call that service only from your backend (an edge function or server route), never from the browser.", ...P.secret(title, revoke, env) });
|
|
409
459
|
}
|
|
410
460
|
}
|
|
411
|
-
for (const t of b.text
|
|
461
|
+
for (const t of findJwts(b.text)) {
|
|
412
462
|
const p = decodeJwt(t);
|
|
413
463
|
if (!p) continue;
|
|
414
464
|
if (p.role === "service_role" && !keysSeen.has(t)) {
|
|
@@ -456,7 +506,7 @@ export async function siteScan(target, { mine = false, fetcher = fetch, maxScrip
|
|
|
456
506
|
add({ id: "db:several-projects", severity: "info", where: "Supabase", title: `Your code mentions ${supabaseRefs.size} Supabase projects`, why: `Greenlit looked at the one whose key comes first in your code (${supabase.ref}). The others (${[...supabaseRefs].filter((r) => r !== supabase.ref).slice(0, 4).join(", ")}) weren't checked. If one of them is the live database, this result doesn't cover it.`, fix: "Remove old project addresses and keys from the app, then check again.", first: null, prompt: null });
|
|
457
507
|
const database = supabase?.url && supabase.anon ? "Supabase" : firebase?.project ? "Firebase" : null;
|
|
458
508
|
if (database && !mine)
|
|
459
|
-
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) });
|
|
509
|
+
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 for an app you own: on greenlit.priberry.com after adding a tag, or 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) });
|
|
460
510
|
if (unread || cut)
|
|
461
511
|
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 });
|
|
462
512
|
if (noCodeRead)
|
|
@@ -469,7 +519,6 @@ export async function siteScan(target, { mine = false, fetcher = fetch, maxScrip
|
|
|
469
519
|
let tablesListed = false;
|
|
470
520
|
let tablesUntested = 0;
|
|
471
521
|
let keyRejected = false;
|
|
472
|
-
let authSettings = null;
|
|
473
522
|
// Database functions the app calls. Listed for the owner, never called: calling one runs it.
|
|
474
523
|
const functions = new Set();
|
|
475
524
|
const bucketsInCode = new Set();
|
|
@@ -487,140 +536,13 @@ export async function siteScan(target, { mine = false, fetcher = fetch, maxScrip
|
|
|
487
536
|
const supabasePartial = Boolean(supabase && !(supabase.url && supabase.anon) && !firebase?.project);
|
|
488
537
|
if (supabasePartial)
|
|
489
538
|
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") });
|
|
490
|
-
|
|
491
|
-
// The newer sb_publishable_ keys aren't JWTs and go in the apikey header only.
|
|
492
|
-
const h = { apikey: supabase.anon, ...(supabase.anon.startsWith("eyJ") && { authorization: `Bearer ${supabase.anon}` }) };
|
|
493
|
-
const names = new Set();
|
|
494
|
-
// Older projects still answer this with the list of tables; newer ones refuse the public key.
|
|
495
|
-
const api = await get(`${supabase.url}/rest/v1/`, fetchOpts({ headers: h }));
|
|
496
|
-
try {
|
|
497
|
-
for (const p of Object.keys(JSON.parse(api.text).paths || {})) if (p.slice(1) && !p.startsWith("/rpc/")) names.add(p.slice(1));
|
|
498
|
-
} catch {}
|
|
499
|
-
tablesListed = names.size > 0;
|
|
500
|
-
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]);
|
|
501
|
-
tables = [];
|
|
502
|
-
// Does Supabase accept this key at all? If not, every table would answer "no access" and look tested.
|
|
503
|
-
authSettings = await get(`${supabase.url}/auth/v1/settings`, fetchOpts({ headers: h, max: 65536 }));
|
|
504
|
-
keyRejected = authSettings.status === 401 || authSettings.status === 403;
|
|
505
|
-
const untested = [];
|
|
506
|
-
const head = (t, prefer) => get(`${supabase.url}/rest/v1/${encodeURIComponent(t)}?select=*`, fetchOpts({ method: "HEAD", headers: { ...h, range: "0-0", ...(prefer && { prefer }) } }));
|
|
507
|
-
for (const t of keyRejected ? [] : [...names].slice(0, 120)) {
|
|
508
|
-
// A HEAD request with a count returns how many rows are visible, and no rows. An exact count can time out on a
|
|
509
|
-
// big table, so an estimate is asked for next: the biggest tables are the ones that matter most.
|
|
510
|
-
let r = await head(t, "count=exact");
|
|
511
|
-
const estimated = !r.status || r.status >= 500;
|
|
512
|
-
if (estimated) r = await head(t, "count=planned");
|
|
513
|
-
// "Not found" means the name wasn't a table. No answer means it wasn't tested, and is said so below.
|
|
514
|
-
if (r.status === 404) continue;
|
|
515
|
-
if (!r.status || r.status >= 500) {
|
|
516
|
-
untested.push(t);
|
|
517
|
-
continue;
|
|
518
|
-
}
|
|
519
|
-
tablesTested++;
|
|
520
|
-
const range = r.headers?.get("content-range") || "";
|
|
521
|
-
const n = Number(range.split("/")[1]);
|
|
522
|
-
// An exact count above zero means rows are visible. An estimate is only the database's guess at the table's size,
|
|
523
|
-
// so there the proof is a returned row: a range like "0-0/…", not "*/…".
|
|
524
|
-
const rowCame = /^\d+-\d+\//.test(range);
|
|
525
|
-
if (r.status < 300 && (estimated ? rowCame : n > 0 || rowCame)) tables.push({ table: t, rows: !estimated && n > 0 ? n : null });
|
|
526
|
-
}
|
|
527
|
-
if (names.size > 120) untested.push(`${names.size - 120} more names`);
|
|
528
|
-
tablesUntested = untested.length;
|
|
529
|
-
// A check that tested no tables must say so, not report "nothing open".
|
|
530
|
-
dbBlind = tablesTested === 0;
|
|
531
|
-
if (keyRejected)
|
|
532
|
-
add({ id: "db:key-rejected", severity: "info", where: "Supabase", title: "Supabase turned down the public key Greenlit found, so the database wasn't checked", why: "The key in your app's code was refused. It may be an old key, or belong to a different project than the address next to it. Nothing about your tables, storage or sign-up could be tested.", fix: "Check that the live app uses your current Supabase address and publishable key, then run this again.", first: null, prompt: null, checkPrompt: P.dbCheck("Supabase") });
|
|
533
|
-
else if (dbBlind && !untested.length)
|
|
534
|
-
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") });
|
|
535
|
-
if (untested.length)
|
|
536
|
-
add({ id: "db:tables-untested", severity: "info", where: "Supabase", title: `${untested.length} table${untested.length > 1 ? "s" : ""} couldn't be tested`, why: `Supabase didn't answer for: ${untested.slice(0, 12).join(", ")}${untested.length > 12 ? " and more" : ""}. A very large table can time out when counted, and those are the ones that matter most, so don't read this as "closed".`, fix: "Open Supabase → Advisors → Security Advisor to see whether these tables are protected.", first: null, prompt: null, checkPrompt: P.dbCheck("Supabase") });
|
|
537
|
-
// For tables strangers can read: which hold personal or secret data? Asks whether a column exists, never for its values.
|
|
538
|
-
for (const t of tables.slice(0, 40)) {
|
|
539
|
-
t.sensitive = [];
|
|
540
|
-
for (const c of [...SECRET_COLUMNS, ...CONTACT_COLUMNS]) {
|
|
541
|
-
const r = await get(`${supabase.url}/rest/v1/${encodeURIComponent(t.table)}?select=${c}`, fetchOpts({ method: "HEAD", headers: { ...h, range: "0-0" } }));
|
|
542
|
-
if (r.status === 200 || r.status === 206) t.sensitive.push(c);
|
|
543
|
-
}
|
|
544
|
-
}
|
|
545
|
-
for (const { table, rows, sensitive = [] } of tables) {
|
|
546
|
-
// Critical when the name or a secret column says it's about people or credentials; an email column alone is serious
|
|
547
|
-
// but can be a public directory; anything else may be meant to be public.
|
|
548
|
-
const personal = isPersonal(table) || sensitive.some((c) => SECRET_COLUMNS.includes(c));
|
|
549
|
-
const level = personal ? "critical" : sensitive.includes("email") ? "high" : "medium";
|
|
550
|
-
const count = rows ? `${rows.toLocaleString("en-US")} row${rows > 1 ? "s" : ""}` : "rows";
|
|
551
|
-
const why = personal
|
|
552
|
-
? "The anon key is public (it ships in your app), so a table without Row Level Security is readable by everyone. This is how most vibe-coded apps have leaked data."
|
|
553
|
-
: "The anon key is public (it ships in your app). If this table is meant to be public, like a product list, reading it is fine, but make sure strangers can't change it. If it isn't, it's leaking.";
|
|
554
|
-
add({ id: `supabase:table:${table}`, severity: level, where: `Supabase table "${table}"`, title: `Anyone on the internet can read ${count} of "${table}"${sensitive.length ? `, including ${sensitive.slice(0, 4).join(", ")}` : ""}`, why, fix: `In Supabase, open Table Editor → ${table} → turn on RLS, then add a policy so people read only their own rows (for example: auth.uid() = user_id).`, ...P.rls(table, personal) });
|
|
555
|
-
}
|
|
556
|
-
}
|
|
557
|
-
|
|
558
|
-
// Your own app only: files that should never be on a live site. A real .env has KEY=value lines; a real .git
|
|
559
|
-
// folder has a config file with [core]. Anything else (often the home page served for every path) doesn't count.
|
|
560
|
-
if (mine) {
|
|
561
|
-
for (const path of ["/.env", "/.env.local", "/.env.production"]) {
|
|
562
|
-
const r = await get(new URL(path, origin).href, fetchOpts({ max: 4096 }));
|
|
563
|
-
if (r.status === 200 && !/^\s*</.test(r.text) && /^[A-Z][A-Z0-9_]*=/m.test(r.text)) {
|
|
564
|
-
add({ id: `exposed:${path}`, severity: "critical", where: path, title: `Your ${path} file is public`, why: "This file usually holds every secret key the app uses, and anyone can download it.", fix: `Stop deploying ${path}, then revoke every key it contained.`, ...P.envFile(path) });
|
|
565
|
-
break;
|
|
566
|
-
}
|
|
567
|
-
}
|
|
568
|
-
const g = await get(new URL("/.git/config", origin).href, fetchOpts({ max: 4096 }));
|
|
569
|
-
if (g.status === 200 && /\[core\]/.test(g.text))
|
|
570
|
-
add({ id: "exposed:git", severity: "high", where: "/.git/", title: "Your code history (.git folder) is public", why: "Anyone can download your full source code and every past version of it, including keys that were committed once and later removed.", fix: "Deploy only the build output, never the .git folder.", ...P.gitDir() });
|
|
571
|
-
}
|
|
572
|
-
|
|
573
|
-
// Your own app only: Supabase settings that quietly make "signed-in users only" mean "anyone".
|
|
574
|
-
if (mine && supabase?.url && supabase.anon && !keyRejected) {
|
|
575
|
-
const h = { apikey: supabase.anon, ...(supabase.anon.startsWith("eyJ") && { authorization: `Bearer ${supabase.anon}` }) };
|
|
576
|
-
const st = authSettings;
|
|
577
|
-
try {
|
|
578
|
-
const cfg = JSON.parse(st.text);
|
|
579
|
-
if (st.status === 200 && cfg.disable_signup === false && cfg.mailer_autoconfirm === true)
|
|
580
|
-
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() });
|
|
581
|
-
} catch {}
|
|
582
|
-
// Storage: which common buckets list their files to anyone? Asks for one file name, never the file.
|
|
583
|
-
for (const bucket of [...new Set(["avatars", "uploads", "files", "documents", "images", "attachments", "receipts", "invoices", "private", ...bucketsInCode])].slice(0, 24)) {
|
|
584
|
-
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 }));
|
|
585
|
-
let n = 0;
|
|
586
|
-
try {
|
|
587
|
-
n = Array.isArray(JSON.parse(r.text)) ? JSON.parse(r.text).length : 0;
|
|
588
|
-
} catch {}
|
|
589
|
-
if (r.status === 200 && n > 0)
|
|
590
|
-
add({ id: `supabase:storage:${bucket}`, severity: /receipt|invoice|document|private|attachment/.test(bucket) ? "critical" : "high", where: `Supabase storage bucket "${bucket}"`, title: `Anyone can list the files in the storage bucket "${bucket}"`, why: "Strangers can see every file name in it and, if the files are readable too, download them. Greenlit asked for one file name and opened nothing.", fix: `In Supabase → Storage → Policies, limit "${bucket}" so users list and read only their own files.`, ...P.storage(bucket) });
|
|
591
|
-
}
|
|
592
|
-
}
|
|
593
|
-
|
|
594
|
-
// Firebase: is the Realtime Database or a common Firestore collection open to anyone?
|
|
539
|
+
// The database checks live in dbScan below, so the website can run them in rounds (see functions/api/owner.js).
|
|
595
540
|
let firebaseOpen = null;
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
let keys = 0;
|
|
602
|
-
try {
|
|
603
|
-
const v = JSON.parse(r.text);
|
|
604
|
-
keys = v && typeof v === "object" ? Object.keys(v).length : v != null ? 1 : 0;
|
|
605
|
-
} catch {}
|
|
606
|
-
if (r.status === 200 && keys > 0) {
|
|
607
|
-
firebaseOpen.push({ where: "Realtime Database", keys });
|
|
608
|
-
add({ id: "firebase:rtdb", severity: "critical", where: "Firebase Realtime Database", title: "Anyone on the internet can read your Firebase Realtime Database", why: `Its rules let visitors who aren't signed in read it (${keys} top-level ${keys > 1 ? "branches" : "branch"} visible). Everything under them is open.`, fix: "In Firebase → Realtime Database → Rules, require sign-in and limit each user to their own data.", ...P.rtdb() });
|
|
609
|
-
}
|
|
610
|
-
}
|
|
611
|
-
for (const coll of FIRESTORE_GUESSES) {
|
|
612
|
-
// pageSize=1 and a mask on a field that doesn't exist: at most one document name comes back, no fields.
|
|
613
|
-
const q = `pageSize=1&mask.fieldPaths=__greenlit_none${firebase.key ? `&key=${firebase.key}` : ""}`;
|
|
614
|
-
const r = await get(`https://firestore.googleapis.com/v1/projects/${firebase.project}/databases/(default)/documents/${coll}?${q}`, fetchOpts());
|
|
615
|
-
let n = 0;
|
|
616
|
-
try {
|
|
617
|
-
n = (JSON.parse(r.text).documents || []).length;
|
|
618
|
-
} catch {}
|
|
619
|
-
if (r.status === 200 && n > 0) {
|
|
620
|
-
firebaseOpen.push({ where: `Firestore "${coll}"` });
|
|
621
|
-
add({ id: `firebase:firestore:${coll}`, severity: isPersonal(coll) ? "critical" : "high", where: `Firestore collection "${coll}"`, title: `Anyone on the internet can read the Firestore collection "${coll}"`, why: "Your Firestore rules let visitors who aren't signed in read it. Greenlit asked for one document name and no fields; a stranger would take everything.", fix: `In Firebase → Firestore → Rules, close "${coll}" to everyone except its owner.`, ...P.firestore(coll) });
|
|
622
|
-
}
|
|
623
|
-
}
|
|
541
|
+
const plan = dbPlan({ origin, supabase, firebase, bundles, bucketsInCode });
|
|
542
|
+
if (mine) {
|
|
543
|
+
const d = await dbScan(plan, { fetcher, maxBytes });
|
|
544
|
+
for (const f of d.findings) add(f);
|
|
545
|
+
({ tables, tablesTested, dbBlind, tablesListed, tablesUntested, keyRejected, firebaseOpen } = d.stats);
|
|
624
546
|
}
|
|
625
547
|
|
|
626
548
|
// --- launch basics: things that stop a live app working, read from what was already downloaded ---
|
|
@@ -630,7 +552,7 @@ export async function siteScan(target, { mine = false, fetcher = fetch, maxScrip
|
|
|
630
552
|
const scripts = bundles.slice(1);
|
|
631
553
|
const inScripts = (re) => scripts.map((b) => b.text.match(re)).find(Boolean);
|
|
632
554
|
// Only what the page loads or submits to: scripts, styles, frames, images and forms. A plain link loads nothing.
|
|
633
|
-
const loaded = [...page.text.matchAll(/<(?:script|img|iframe|source|embed)\b[
|
|
555
|
+
const loaded = [...page.text.matchAll(/<(?:script|img|iframe|source|embed)\b[^<>]*?\bsrc=["']([^"']+)["']|<form\b[^<>]*?\baction=["']([^"']+)["']|<link\b(?=[^<>]*\brel=["']?(?:stylesheet|preload|modulepreload|icon|manifest)\b)[^<>]*?\bhref=["']([^"']+)["']/gi)].map((m) => m[1] || m[2] || m[3]);
|
|
634
556
|
if (!isLocal) {
|
|
635
557
|
const inPage = loaded.find((u) => /^https?:\/\/(?:localhost|127\.0\.0\.1)(?=[:\/]|$)/i.test(u));
|
|
636
558
|
// A bare http://localhost:3000 in a list is usually an allow-list (Lovable's own preview code has one), so only an address
|
|
@@ -649,14 +571,15 @@ export async function siteScan(target, { mine = false, fetcher = fetch, maxScrip
|
|
|
649
571
|
const title = (page.text.match(/<title[^>]*>([^<]{0,120})<\/title>/i) || [])[1];
|
|
650
572
|
if (title && DEFAULT_TITLE.test(title))
|
|
651
573
|
add({ id: "launch:default-title", severity: "low", where: "the page itself", title: `Your app still has its default title, "${title.trim()}"`, why: "This is what shows in the browser tab, in Google and when someone shares your link.", fix: "Give the app a real title and description.", ...P.title(title.trim()) });
|
|
652
|
-
if (/<meta[
|
|
574
|
+
if (/<meta[^<>]+name=["']robots["'][^<>]+content=["'][^"']*noindex/i.test(page.text) || /noindex/i.test(page.headers?.get("x-robots-tag") || ""))
|
|
653
575
|
add({ id: "launch:noindex", severity: "low", where: "the page itself", title: "Your app tells Google not to list it", why: "A \"noindex\" setting is on. That's right for a private tool, and a problem if you want people to find the app by searching.", fix: "Remove the noindex setting if the app should be found.", ...P.noindex() });
|
|
654
576
|
if (inScripts(AI_DIRECT))
|
|
655
577
|
add({ id: "launch:ai-direct", severity: "low", where: "your app's scripts", title: "Your app seems to call an AI provider straight from the browser", why: "Calls made from the browser need the secret key in the browser, where anyone can copy it and run up your bill. If these calls really go through your own backend, this is fine.", fix: "Send AI calls through a backend function that checks the user and limits use.", ...P.aiDirect() });
|
|
656
578
|
if (allCode.some((t) => /onboarding@resend\.dev/i.test(t)))
|
|
657
579
|
add({ id: "launch:test-sender", severity: "low", where: "your app's scripts", title: "Your app's email still uses a test sender", why: "The code mentions onboarding@resend.dev, Resend's test address. Email from it reaches only your own inbox, so real users won't get sign-up or reset emails.", fix: "Send from an address on your own verified domain.", ...P.testSender() });
|
|
658
580
|
for (const c of page.headers?.getSetCookie?.() || []) {
|
|
659
|
-
|
|
581
|
+
// The name comes from the scanned site and can end up in a public report title: keep it short and plain.
|
|
582
|
+
const name = c.split("=")[0].trim().replace(/[^\w.-]/g, "").slice(0, 40);
|
|
660
583
|
// Sign-in cookies only. Anti-forgery cookies (csrf, xsrf) must stay readable by the page's own script.
|
|
661
584
|
if (!secure || PLATFORM_COOKIE.test(name) || /csrf|xsrf/i.test(name) || !/(^|[_.-])(session|sess|sid|auth|token|jwt|login)([_.-]|$)/i.test(name)) continue;
|
|
662
585
|
if (/;\s*secure/i.test(c) && /;\s*httponly/i.test(c)) continue;
|
|
@@ -737,6 +660,31 @@ export async function siteScan(target, { mine = false, fetcher = fetch, maxScrip
|
|
|
737
660
|
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() });
|
|
738
661
|
}
|
|
739
662
|
|
|
663
|
+
const flags = { noCodeRead, unread, cut, tablesUntested, dbBlind, supabasePartial, database, mine };
|
|
664
|
+
const { score, grade, verdict } = gradeOf(findings, flags);
|
|
665
|
+
return {
|
|
666
|
+
url: origin,
|
|
667
|
+
builder,
|
|
668
|
+
score,
|
|
669
|
+
grade,
|
|
670
|
+
verdict,
|
|
671
|
+
mine,
|
|
672
|
+
scripts: bundles.length - 1,
|
|
673
|
+
scriptsUnread: unread,
|
|
674
|
+
supabase: supabase ? { project: supabase.ref, checked: Boolean(mine && tables && !dbBlind && !keyRejected), tablesTested, tablesUntested, tablesListed, readable: tables, functions: [...functions].slice(0, 50), edgeFunctions: [...edge].slice(0, 50) } : null,
|
|
675
|
+
firebase: firebase ? { project: firebase.project, checked: mine, readable: firebaseOpen } : null,
|
|
676
|
+
findings,
|
|
677
|
+
pasteInto: builder || "your AI app builder or coding agent",
|
|
678
|
+
// Only for the web endpoints, which look for the owner's tag in the page and run the database checks in rounds.
|
|
679
|
+
...(wantPage && { page: page.text.slice(0, 200000) }),
|
|
680
|
+
...(wantPlan && { plan, flags }),
|
|
681
|
+
};
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
// --- the grade -------------------------------------------------------------------------------------
|
|
685
|
+
// Shared by siteScan and the website's owner check, which adds database findings to a public result and grades again.
|
|
686
|
+
// Sorts `findings` worst first, in place.
|
|
687
|
+
export function gradeOf(findings, { noCodeRead = false, unread = 0, cut = 0, tablesUntested = 0, dbBlind = false, supabasePartial = false, database = null, mine = false } = {}) {
|
|
740
688
|
// Small things add up to 20 points at most, so missing headers alone can never fail an app.
|
|
741
689
|
// One critical problem is an F whatever else is right: it can't be averaged away.
|
|
742
690
|
const sum = (kinds) => findings.reduce((a, f) => a + (kinds.includes(f.severity) ? SEVERITY[f.severity] : 0), 0);
|
|
@@ -762,22 +710,227 @@ export async function siteScan(target, { mine = false, fetcher = fetch, maxScrip
|
|
|
762
710
|
: VERDICT[grade];
|
|
763
711
|
const order = ["critical", "high", "medium", "low", "info"];
|
|
764
712
|
findings.sort((a, b) => order.indexOf(a.severity) - order.indexOf(b.severity));
|
|
713
|
+
return { score: ungraded ? null : score, grade, verdict };
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
// --- the database checks, for an app's owner ----------------------------------------------------------
|
|
717
|
+
// What the database checks need, taken from the app's own code. Plain data, so the website can keep it between rounds.
|
|
718
|
+
export function dbPlan({ origin, supabase, firebase, bundles = [], bucketsInCode = new Set() }) {
|
|
719
|
+
const codeNames = new Set();
|
|
720
|
+
if (supabase?.url && supabase.anon) for (const b of bundles) for (const m of b.text.matchAll(TABLE_REF)) (m[1] || m[2]) !== "rpc" && codeNames.add(m[1] || m[2]);
|
|
765
721
|
return {
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
722
|
+
origin,
|
|
723
|
+
supabase: supabase?.url && supabase.anon ? { url: supabase.url, anon: supabase.anon } : null,
|
|
724
|
+
firebase: firebase?.project ? { project: firebase.project, db: firebase.db || null, key: firebase.key || null } : null,
|
|
725
|
+
codeNames: [...codeNames],
|
|
726
|
+
buckets: [...new Set(["avatars", "uploads", "files", "documents", "images", "attachments", "receipts", "invoices", "private", ...bucketsInCode])].slice(0, 24),
|
|
727
|
+
};
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
// Which of the owner's data anyone on the internet can read with the app's public key, plus files that should never be
|
|
731
|
+
// online. Counts and names only, never data. `maxFetches` stops a round early; pass the returned `state` back to carry on
|
|
732
|
+
// (the website does this, because one request there may make only about 50 fetches). With no limit it runs to the end.
|
|
733
|
+
export async function dbScan(plan, { fetcher = fetch, maxBytes = 8 * 1024 * 1024, maxFetches = Infinity, state = null } = {}) {
|
|
734
|
+
const fetchOpts = (o = {}) => ({ max: maxBytes, ...o, fetcher });
|
|
735
|
+
const s = state || { step: 0, i: 0, names: null, listed: false, keyRejected: false, auth: null, tables: [], tested: 0, untested: [], open: [], findings: [], firebaseOpen: null };
|
|
736
|
+
const add = (f) => s.findings.push(f);
|
|
737
|
+
let used = 0;
|
|
738
|
+
// Each step starts only when its fetches fit in this round; a step never runs twice.
|
|
739
|
+
const room = (n) => used + n <= maxFetches;
|
|
740
|
+
const get2 = (url, o) => {
|
|
741
|
+
used++;
|
|
742
|
+
return get(url, fetchOpts(o));
|
|
743
|
+
};
|
|
744
|
+
const sb = plan.supabase;
|
|
745
|
+
const h = sb ? { apikey: sb.anon, ...(sb.anon.startsWith("eyJ") && { authorization: `Bearer ${sb.anon}` }) } : null;
|
|
746
|
+
const pause = () => ({ done: false, state: s, findings: s.findings, stats: null });
|
|
747
|
+
|
|
748
|
+
// 0: the table list (older projects still give it to the public key; newer ones refuse) and whether the key works at all.
|
|
749
|
+
if (s.step === 0) {
|
|
750
|
+
if (sb) {
|
|
751
|
+
if (!room(2)) return pause();
|
|
752
|
+
const names = new Set();
|
|
753
|
+
const api = await get2(`${sb.url}/rest/v1/`, { headers: h });
|
|
754
|
+
try {
|
|
755
|
+
for (const p of Object.keys(JSON.parse(api.text).paths || {})) if (p.slice(1) && !p.startsWith("/rpc/")) names.add(p.slice(1));
|
|
756
|
+
} catch {}
|
|
757
|
+
s.listed = names.size > 0;
|
|
758
|
+
for (const n of plan.codeNames) names.add(n);
|
|
759
|
+
s.names = [...names];
|
|
760
|
+
// Does Supabase accept this key at all? If not, every table would answer "no access" and look tested.
|
|
761
|
+
const auth = await get2(`${sb.url}/auth/v1/settings`, { headers: h, max: 65536 });
|
|
762
|
+
s.keyRejected = auth.status === 401 || auth.status === 403;
|
|
763
|
+
try {
|
|
764
|
+
const cfg = JSON.parse(auth.text);
|
|
765
|
+
s.auth = { ok: auth.status === 200, disable_signup: cfg.disable_signup, mailer_autoconfirm: cfg.mailer_autoconfirm };
|
|
766
|
+
} catch {
|
|
767
|
+
s.auth = { ok: false };
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
s.step = 1;
|
|
771
|
+
s.i = 0;
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
// 1: a HEAD request with a count for each table: how many rows a stranger sees, and no rows.
|
|
775
|
+
if (s.step === 1) {
|
|
776
|
+
const list = sb && !s.keyRejected ? s.names.slice(0, 120) : [];
|
|
777
|
+
const head = (t, prefer) => get2(`${sb.url}/rest/v1/${encodeURIComponent(t)}?select=*`, { method: "HEAD", headers: { ...h, range: "0-0", ...(prefer && { prefer }) } });
|
|
778
|
+
while (s.i < list.length) {
|
|
779
|
+
if (!room(2)) return pause();
|
|
780
|
+
const t = list[s.i++];
|
|
781
|
+
// An exact count can time out on a big table, so an estimate is asked for next: the biggest tables matter most.
|
|
782
|
+
let r = await head(t, "count=exact");
|
|
783
|
+
const estimated = !r.status || r.status >= 500;
|
|
784
|
+
if (estimated) r = await head(t, "count=planned");
|
|
785
|
+
// "Not found" means the name wasn't a table. No answer means it wasn't tested, and is said so below.
|
|
786
|
+
if (r.status === 404) continue;
|
|
787
|
+
if (!r.status || r.status >= 500) {
|
|
788
|
+
s.untested.push(t);
|
|
789
|
+
continue;
|
|
790
|
+
}
|
|
791
|
+
s.tested++;
|
|
792
|
+
const range = r.headers?.get("content-range") || "";
|
|
793
|
+
const n = Number(range.split("/")[1]);
|
|
794
|
+
// An exact count above zero means rows are visible. An estimate is only the database's guess at the table's size,
|
|
795
|
+
// so there the proof is a returned row: a range like "0-0/…", not "*/…".
|
|
796
|
+
const rowCame = /^\d+-\d+\//.test(range);
|
|
797
|
+
if (r.status < 300 && (estimated ? rowCame : n > 0 || rowCame)) s.tables.push({ table: t, rows: !estimated && n > 0 ? n : null, sensitive: [] });
|
|
798
|
+
}
|
|
799
|
+
if (sb && !s.keyRejected && s.names.length > 120) s.untested.push(`${s.names.length - 120} more names`);
|
|
800
|
+
if (sb) {
|
|
801
|
+
const blind = s.tested === 0;
|
|
802
|
+
if (s.keyRejected)
|
|
803
|
+
add({ id: "db:key-rejected", severity: "info", where: "Supabase", title: "Supabase turned down the public key Greenlit found, so the database wasn't checked", why: "The key in your app's code was refused. It may be an old key, or belong to a different project than the address next to it. Nothing about your tables, storage or sign-up could be tested.", fix: "Check that the live app uses your current Supabase address and publishable key, then run this again.", first: null, prompt: null, checkPrompt: P.dbCheck("Supabase") });
|
|
804
|
+
else if (blind && !s.untested.length)
|
|
805
|
+
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") });
|
|
806
|
+
if (s.untested.length)
|
|
807
|
+
add({ id: "db:tables-untested", severity: "info", where: "Supabase", title: `${s.untested.length} table${s.untested.length > 1 ? "s" : ""} couldn't be tested`, why: `Supabase didn't answer for: ${s.untested.slice(0, 12).join(", ")}${s.untested.length > 12 ? " and more" : ""}. A very large table can time out when counted, and those are the ones that matter most, so don't read this as "closed".`, fix: "Open Supabase → Advisors → Security Advisor to see whether these tables are protected.", first: null, prompt: null, checkPrompt: P.dbCheck("Supabase") });
|
|
808
|
+
}
|
|
809
|
+
s.step = 2;
|
|
810
|
+
s.i = 0;
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
// 2: for tables strangers can read, which hold personal or secret data? Asks whether a column exists, never for its values.
|
|
814
|
+
if (s.step === 2) {
|
|
815
|
+
const cols = [...SECRET_COLUMNS, ...CONTACT_COLUMNS];
|
|
816
|
+
const jobs = s.tables.slice(0, 40).length * cols.length;
|
|
817
|
+
while (s.i < jobs) {
|
|
818
|
+
if (!room(1)) return pause();
|
|
819
|
+
const t = s.tables[Math.floor(s.i / cols.length)];
|
|
820
|
+
const c = cols[s.i++ % cols.length];
|
|
821
|
+
const r = await get2(`${sb.url}/rest/v1/${encodeURIComponent(t.table)}?select=${c}`, { method: "HEAD", headers: { ...h, range: "0-0" } });
|
|
822
|
+
if (r.status === 200 || r.status === 206) t.sensitive.push(c);
|
|
823
|
+
}
|
|
824
|
+
for (const { table, rows, sensitive = [] } of s.tables) {
|
|
825
|
+
// Critical when the name or a secret column says it's about people or credentials; an email column alone is serious
|
|
826
|
+
// but can be a public directory; anything else may be meant to be public.
|
|
827
|
+
const personal = isPersonal(table) || sensitive.some((c) => SECRET_COLUMNS.includes(c));
|
|
828
|
+
const level = personal ? "critical" : sensitive.includes("email") ? "high" : "medium";
|
|
829
|
+
const count = rows ? `${rows.toLocaleString("en-US")} row${rows > 1 ? "s" : ""}` : "rows";
|
|
830
|
+
const why = personal
|
|
831
|
+
? "The anon key is public (it ships in your app), so a table without Row Level Security is readable by everyone. This is how most vibe-coded apps have leaked data."
|
|
832
|
+
: "The anon key is public (it ships in your app). If this table is meant to be public, like a product list, reading it is fine, but make sure strangers can't change it. If it isn't, it's leaking.";
|
|
833
|
+
add({ id: `supabase:table:${table}`, severity: level, where: `Supabase table "${table}"`, title: `Anyone on the internet can read ${count} of "${table}"${sensitive.length ? `, including ${sensitive.slice(0, 4).join(", ")}` : ""}`, why, fix: `In Supabase, open Table Editor → ${table} → turn on RLS, then add a policy so people read only their own rows (for example: auth.uid() = user_id).`, ...P.rls(table, personal) });
|
|
834
|
+
}
|
|
835
|
+
s.step = 3;
|
|
836
|
+
s.i = 0;
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
// 3: files that should never be on a live site. A real .env has KEY=value lines; a real .git folder has a config file
|
|
840
|
+
// with [core]. Anything else (often the home page served for every path) doesn't count.
|
|
841
|
+
if (s.step === 3) {
|
|
842
|
+
const envs = ["/.env", "/.env.local", "/.env.production"];
|
|
843
|
+
while (s.i < envs.length) {
|
|
844
|
+
if (!room(1)) return pause();
|
|
845
|
+
const path = envs[s.i++];
|
|
846
|
+
const r = await get2(new URL(path, plan.origin).href, { max: 4096 });
|
|
847
|
+
if (r.status === 200 && !/^\s*</.test(r.text) && /^[A-Z][A-Z0-9_]*=/m.test(r.text)) {
|
|
848
|
+
add({ id: `exposed:${path}`, severity: "critical", where: path, title: `Your ${path} file is public`, why: "This file usually holds every secret key the app uses, and anyone can download it.", fix: `Stop deploying ${path}, then revoke every key it contained.`, ...P.envFile(path) });
|
|
849
|
+
s.i = envs.length;
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
if (!room(1)) return pause();
|
|
853
|
+
const g = await get2(new URL("/.git/config", plan.origin).href, { max: 4096 });
|
|
854
|
+
if (g.status === 200 && /\[core\]/.test(g.text))
|
|
855
|
+
add({ id: "exposed:git", severity: "high", where: "/.git/", title: "Your code history (.git folder) is public", why: "Anyone can download your full source code and every past version of it, including keys that were committed once and later removed.", fix: "Deploy only the build output, never the .git folder.", ...P.gitDir() });
|
|
856
|
+
s.step = 4;
|
|
857
|
+
s.i = 0;
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
// 4: Supabase settings that quietly make "signed-in users only" mean "anyone", then which storage buckets list their files.
|
|
861
|
+
if (s.step === 4) {
|
|
862
|
+
if (sb && !s.keyRejected) {
|
|
863
|
+
if (s.i === 0 && s.auth?.ok && s.auth.disable_signup === false && s.auth.mailer_autoconfirm === true)
|
|
864
|
+
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() });
|
|
865
|
+
// Asks for one file name, never the file. s.i counts from 1 so the sign-up finding above is added once.
|
|
866
|
+
if (s.i === 0) s.i = 1;
|
|
867
|
+
while (s.i - 1 < plan.buckets.length) {
|
|
868
|
+
if (!room(1)) return pause();
|
|
869
|
+
const bucket = plan.buckets[s.i++ - 1];
|
|
870
|
+
const r = await get2(`${sb.url}/storage/v1/object/list/${encodeURIComponent(bucket)}`, { method: "POST", headers: { ...h, "content-type": "application/json" }, body: JSON.stringify({ prefix: "", limit: 1, offset: 0 }), max: 65536 });
|
|
871
|
+
let n = 0;
|
|
872
|
+
try {
|
|
873
|
+
n = Array.isArray(JSON.parse(r.text)) ? JSON.parse(r.text).length : 0;
|
|
874
|
+
} catch {}
|
|
875
|
+
if (r.status === 200 && n > 0)
|
|
876
|
+
add({ id: `supabase:storage:${bucket}`, severity: /receipt|invoice|document|private|attachment/.test(bucket) ? "critical" : "high", where: `Supabase storage bucket "${bucket}"`, title: `Anyone can list the files in the storage bucket "${bucket}"`, why: "Strangers can see every file name in it and, if the files are readable too, download them. Greenlit asked for one file name and opened nothing.", fix: `In Supabase → Storage → Policies, limit "${bucket}" so users list and read only their own files.`, ...P.storage(bucket) });
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
s.step = 5;
|
|
880
|
+
s.i = 0;
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
// 5: Firebase: is the Realtime Database or a common Firestore collection open to anyone?
|
|
884
|
+
if (s.step === 5) {
|
|
885
|
+
const fb = plan.firebase;
|
|
886
|
+
if (fb) {
|
|
887
|
+
s.firebaseOpen = s.firebaseOpen || [];
|
|
888
|
+
if (s.i === 0) {
|
|
889
|
+
if (fb.db) {
|
|
890
|
+
if (!room(1)) return pause();
|
|
891
|
+
// shallow=true returns only the top-level key names, each mapped to true; we count them and drop them.
|
|
892
|
+
const r = await get2(`${fb.db}/.json?shallow=true`, {});
|
|
893
|
+
let keys = 0;
|
|
894
|
+
try {
|
|
895
|
+
const v = JSON.parse(r.text);
|
|
896
|
+
keys = v && typeof v === "object" ? Object.keys(v).length : v != null ? 1 : 0;
|
|
897
|
+
} catch {}
|
|
898
|
+
if (r.status === 200 && keys > 0) {
|
|
899
|
+
s.firebaseOpen.push({ where: "Realtime Database", keys });
|
|
900
|
+
add({ id: "firebase:rtdb", severity: "critical", where: "Firebase Realtime Database", title: "Anyone on the internet can read your Firebase Realtime Database", why: `Its rules let visitors who aren't signed in read it (${keys} top-level ${keys > 1 ? "branches" : "branch"} visible). Everything under them is open.`, fix: "In Firebase → Realtime Database → Rules, require sign-in and limit each user to their own data.", ...P.rtdb() });
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
s.i = 1;
|
|
904
|
+
}
|
|
905
|
+
while (s.i - 1 < FIRESTORE_GUESSES.length) {
|
|
906
|
+
if (!room(1)) return pause();
|
|
907
|
+
const coll = FIRESTORE_GUESSES[s.i++ - 1];
|
|
908
|
+
// pageSize=1 and a mask on a field that doesn't exist: at most one document name comes back, no fields.
|
|
909
|
+
const q = `pageSize=1&mask.fieldPaths=__greenlit_none${fb.key ? `&key=${fb.key}` : ""}`;
|
|
910
|
+
const r = await get2(`https://firestore.googleapis.com/v1/projects/${fb.project}/databases/(default)/documents/${coll}?${q}`, {});
|
|
911
|
+
let n = 0;
|
|
912
|
+
try {
|
|
913
|
+
n = (JSON.parse(r.text).documents || []).length;
|
|
914
|
+
} catch {}
|
|
915
|
+
if (r.status === 200 && n > 0) {
|
|
916
|
+
s.firebaseOpen.push({ where: `Firestore "${coll}"` });
|
|
917
|
+
add({ id: `firebase:firestore:${coll}`, severity: isPersonal(coll) ? "critical" : "high", where: `Firestore collection "${coll}"`, title: `Anyone on the internet can read the Firestore collection "${coll}"`, why: "Your Firestore rules let visitors who aren't signed in read it. Greenlit asked for one document name and no fields; a stranger would take everything.", fix: `In Firebase → Firestore → Rules, close "${coll}" to everyone except its owner.`, ...P.firestore(coll) });
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
s.step = 6;
|
|
922
|
+
}
|
|
923
|
+
|
|
924
|
+
const stats = {
|
|
925
|
+
tables: sb ? s.tables.map(({ table, rows, sensitive }) => ({ table, rows, sensitive })) : null,
|
|
926
|
+
tablesTested: s.tested,
|
|
927
|
+
tablesUntested: s.untested.length,
|
|
928
|
+
tablesListed: s.listed,
|
|
929
|
+
dbBlind: Boolean(sb && s.tested === 0),
|
|
930
|
+
keyRejected: s.keyRejected,
|
|
931
|
+
firebaseOpen: s.firebaseOpen,
|
|
780
932
|
};
|
|
933
|
+
return { done: true, state: s, findings: s.findings, stats };
|
|
781
934
|
}
|
|
782
935
|
|
|
783
936
|
// Every fix prompt in one, worst first, for people who'd rather paste once. The builder still gets one
|
|
@@ -868,6 +1021,13 @@ export function renderSite(r, change, { color = true, mine = r.mine } = {}) {
|
|
|
868
1021
|
if (n) {
|
|
869
1022
|
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)`));
|
|
870
1023
|
L.push(dim("After the fixes are live, run this same command again: it shows what got fixed."));
|
|
1024
|
+
} else if (r.grade === "A" || r.grade === "B") {
|
|
1025
|
+
// A pass from outside isn't the whole answer: say where to look next.
|
|
1026
|
+
const host = new URL(r.url).host;
|
|
1027
|
+
L.push("", bold(" Next, the parts no outside check can see:"));
|
|
1028
|
+
if ((r.supabase || r.firebase) && !mine) L.push(` ${green("›")} npx greenlitlab ${host} --mine ${dim("your own app: which database tables anyone can read")}`);
|
|
1029
|
+
L.push(` ${green("›")} npx greenlitlab scan ${dim("in your project folder: rules that let everyone in")}`);
|
|
1030
|
+
L.push(` ${green("›")} npx greenlitlab questions ${dim("seven things only you know, like backups and spending limits")}`);
|
|
871
1031
|
}
|
|
872
1032
|
return L.join("\n");
|
|
873
1033
|
}
|