greenlitlab 0.3.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +28 -0
- package/README.md +18 -1
- package/bin/greenlit.mjs +65 -1
- package/package.json +2 -2
- package/server.json +2 -2
- package/src/advisor.mjs +73 -0
- package/src/grade.mjs +287 -37
- package/src/mcp.mjs +30 -2
- package/src/node-probe.mjs +14 -0
- package/src/plain.mjs +34 -0
- package/src/questions.mjs +73 -0
- package/src/scan.mjs +187 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,33 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.4.1 (10 November 2026)
|
|
4
|
+
|
|
5
|
+
`scan`, after running it on real projects:
|
|
6
|
+
|
|
7
|
+
- Row Level Security switched on in a loop (`foreach t in array[…] loop execute format('alter table … enable row level security', t)`) is now seen. Where it is switched on by a statement Greenlit can't follow, an unmatched table is a question ("couldn't see"), not an alarm.
|
|
8
|
+
- Test files, test folders and agents' working copies (`.claude`, `worktrees`) are no longer read: their made-up secrets and tables aren't the app's.
|
|
9
|
+
- Tables that everyone may read are gathered into one finding with the list, instead of one finding per table.
|
|
10
|
+
- A policy that lets anyone add rows is a question (right for a form, a waitlist or a log), not a high finding. Changing and deleting still are.
|
|
11
|
+
- "No lockfile" is only reported for a project that has dependencies.
|
|
12
|
+
- Migrations are read in order, and a rule or table that a later migration removes (`drop policy`, `alter policy`, `drop table`) is no longer reported.
|
|
13
|
+
|
|
14
|
+
## 0.4.0 (10 November 2026)
|
|
15
|
+
|
|
16
|
+
Greenlit now checks launch readiness, not only leaks. Only things it confirmed move the grade; what it couldn't see is said, and what only you know is asked.
|
|
17
|
+
|
|
18
|
+
- Launch basics, read from what is already downloaded: a page that loads from a developer-only address, plain-http content on an https page, Stripe still in test mode, a default page title, an accidental "noindex", AI calls made straight from the browser, a test email sender, sign-in cookies without Secure and HttpOnly, and no privacy policy in sight. Two single requests check that plain http redirects to https and that the app doesn't hand a signed-in visitor's data to any website.
|
|
19
|
+
- Two more secret shapes: database addresses with a password, and Stripe webhook signing secrets (32 kinds in all).
|
|
20
|
+
- Your own domain: no DMARC record, or a broken SPF record, found through public DNS. Skipped on a builder's address, where it says so.
|
|
21
|
+
- `--mine`: for tables strangers can read, asks whether personal columns (email, phone, password and the like) exist, never for their values, and names them. Backend functions the app calls are listed with a prompt to check each; Greenlit never calls them.
|
|
22
|
+
- `greenlit advisor results.json`: Supabase's own Security Advisor in plain words with a fix prompt for each result. This is how to find rules that are too loose, and tables strangers can change, without Greenlit ever writing to a database.
|
|
23
|
+
- `greenlit scan [folder]`: reads your project's files for always-true policies, tables created without Row Level Security, functions with the sign-in check off, unverified Stripe webhooks, secrets behind a public prefix, a tracked .env file and a writable database connection in an agent's config. Reads names in .env files, never values.
|
|
24
|
+
- `greenlit questions`: seven things only you know (backups, a separate test database, spending limits, payment checks, outage alerts, email sender, database plan). Never graded. Also on the web result.
|
|
25
|
+
- Web: an owner can publish a dated report page and a badge for their own app, after adding a tag that proves it is theirs. Both show the date and expire after 30 days.
|
|
26
|
+
- The MCP server has three new tools: `greenlit_scan`, `greenlit_advisor`, `greenlit_questions`.
|
|
27
|
+
- After an independent review of this release, before it reached npm: example values in library text (placeholder passwords, `whsec_xxxx…`) are never reported as leaks; a table is "about people" only by whole words in its name, so `leaderboard` and `border_styles` are not; only secret columns make a readable table critical on their own; the public key now names the real Supabase project when the code mentions several; a refused key and a table that times out are said, not counted as closed; the owner's domain is found on country domains such as `.ne.jp` and `.me.uk`; shared hosts such as `herokuapp.com` are nobody's to fix; plain links and canonical tags load nothing; CSRF cookies are left alone; an app served only over http is said to be; checks that got no answer are listed; `--fail-on` exits 3 when the code couldn't be read; `scan` reads Supabase's `"public"."table"` form, skips comments, private schemas and service-role policies, and only names ending in a secret word are secrets; `advisor` refuses an error message instead of calling it clean.
|
|
28
|
+
- Reports: nothing is stored until a tagged page has been seen; the tag must be in the page's `<head>`; a report is removed when the tag is gone and kept 90 days at most; the page says anyone can refresh it.
|
|
29
|
+
- The CLI asks for the plain-http address the way a browser does, because some sites answer Node's own fetch differently.
|
|
30
|
+
|
|
3
31
|
## 0.3.0 (10 November 2026)
|
|
4
32
|
|
|
5
33
|
- 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.
|
package/README.md
CHANGED
|
@@ -14,7 +14,7 @@ npx greenlitlab myapp.lovable.app
|
|
|
14
14
|
|
|
15
15
|
| Check | Where it runs |
|
|
16
16
|
|---|---|
|
|
17
|
-
| Secret keys in the JavaScript every visitor downloads:
|
|
17
|
+
| Secret keys in the JavaScript every visitor downloads: 32 kinds, including Stripe, OpenAI, Anthropic, OpenRouter, Gemini, AWS, GitHub, Supabase secret keys, Telegram bots, private keys and service-account JSON | everywhere |
|
|
18
18
|
| A Supabase `service_role` key in the browser | everywhere |
|
|
19
19
|
| Source maps that hand out your source code | everywhere |
|
|
20
20
|
| Clickjacking (no `frame-ancestors` or `X-Frame-Options`) and no Content-Security-Policy | everywhere |
|
|
@@ -30,6 +30,20 @@ Supabase no longer lists a project's tables for the public key, so `--mine` test
|
|
|
30
30
|
|
|
31
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.
|
|
32
32
|
|
|
33
|
+
## Launch readiness, beyond leaks
|
|
34
|
+
|
|
35
|
+
| Check | Where it runs |
|
|
36
|
+
|---|---|
|
|
37
|
+
| 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
|
+
| Plain http that doesn't redirect to https; an app that lets any website read a signed-in visitor's data | everywhere |
|
|
39
|
+
| 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, `--mine` |
|
|
41
|
+
| Rules that are too loose, tables strangers can change: Supabase's Security Advisor in plain words | `advisor`, with your advisor results |
|
|
42
|
+
| Always-true policies, tables without Row Level Security, unverified payment webhooks, secrets behind a public prefix | `scan`, on your project's files |
|
|
43
|
+
| Backups, spending limits, a separate test database, outage alerts | `questions`: only you know, never graded |
|
|
44
|
+
|
|
45
|
+
Only what Greenlit confirmed moves the grade. What it couldn't see is said out loud, and what only you know is asked. Greenlit never signs in, never reads your users' data and never writes to your database.
|
|
46
|
+
|
|
33
47
|
## Commands
|
|
34
48
|
|
|
35
49
|
```bash
|
|
@@ -39,6 +53,9 @@ npx greenlitlab <url> --prompt 1 # print fix prompt 1 only (pipe it to pbco
|
|
|
39
53
|
npx greenlitlab <url> --prompt all # every fix in one prompt, worst first
|
|
40
54
|
npx greenlitlab <url> --json # the full result
|
|
41
55
|
npx greenlitlab <url> --fail-on high # exit 1 if anything this serious is found, for CI
|
|
56
|
+
npx greenlitlab questions # seven things only you know, with a fix for each gap
|
|
57
|
+
npx greenlitlab scan [folder] # read your project's files before you deploy
|
|
58
|
+
npx greenlitlab advisor results.json # Supabase's Security Advisor, in plain words
|
|
42
59
|
```
|
|
43
60
|
|
|
44
61
|
The last result for each app is kept in `~/.greenlit/sites/` (grade, finding ids and titles only, never keys) so the next run can show what changed.
|
package/bin/greenlit.mjs
CHANGED
|
@@ -8,6 +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 { httpProbe } from "../src/node-probe.mjs";
|
|
11
12
|
import { siteScan, compare, renderSite, allPrompts, explainError } from "../src/grade.mjs";
|
|
12
13
|
import { SEVERITY } from "../src/severity.mjs";
|
|
13
14
|
import { loadLast, saveRun } from "../src/history.mjs";
|
|
@@ -25,6 +26,11 @@ const HELP = `greenlit ${VERSION}: is your AI-built app safe to launch?
|
|
|
25
26
|
npx greenlitlab <url> --fail-on high exit 1 if anything this serious is found (for CI)
|
|
26
27
|
npx greenlitlab mcp run as an MCP server
|
|
27
28
|
|
|
29
|
+
Before you launch, three more that look where no outside check can:
|
|
30
|
+
npx greenlitlab questions seven things only you know (backups, spending limits, email)
|
|
31
|
+
npx greenlitlab scan [folder] read your project's files for rules that let everyone in
|
|
32
|
+
npx greenlitlab advisor results.json Supabase's own Security Advisor, in plain words with fix prompts
|
|
33
|
+
|
|
28
34
|
Run it again after a fix: it shows what got fixed. In the browser: https://greenlit.priberry.com`;
|
|
29
35
|
|
|
30
36
|
let opt, positionals;
|
|
@@ -52,6 +58,59 @@ if (opt.version) {
|
|
|
52
58
|
} else if (positionals[0] === "mcp") {
|
|
53
59
|
const { serve } = await import("../src/mcp.mjs");
|
|
54
60
|
await serve({ version: VERSION });
|
|
61
|
+
} else if (["scan", "advisor", "questions"].includes(positionals[0])) {
|
|
62
|
+
const color = Boolean(process.stdout.isTTY && !process.env.NO_COLOR);
|
|
63
|
+
const { renderList } = await import("../src/plain.mjs");
|
|
64
|
+
const failOn = opt["fail-on"];
|
|
65
|
+
if (failOn && !(failOn in SEVERITY)) {
|
|
66
|
+
console.error(`greenlit: --fail-on takes ${Object.keys(SEVERITY).join(", ")}`);
|
|
67
|
+
process.exit(2);
|
|
68
|
+
}
|
|
69
|
+
const finish = (r, heading, extra) => {
|
|
70
|
+
if (opt.json) console.log(JSON.stringify(r, null, 2));
|
|
71
|
+
else console.log(renderList(heading, r.findings, { color, ...extra }));
|
|
72
|
+
if (failOn && r.findings.some((f) => SEVERITY[f.severity] >= SEVERITY[failOn])) process.exitCode = 1;
|
|
73
|
+
};
|
|
74
|
+
try {
|
|
75
|
+
if (positionals[0] === "scan") {
|
|
76
|
+
const { codeScan } = await import("../src/scan.mjs");
|
|
77
|
+
const r = codeScan(positionals[1] || ".");
|
|
78
|
+
finish(r, `Greenlit scan · ${r.dir} · ${r.files} files read`, { empty: "Nothing found in the patterns Greenlit knows. This is not a full code review.", footer: "Read on your computer; nothing was sent anywhere. Names in .env files were read, never values.\nThis finds known mistakes by pattern. It can't see the live database: for that, run npx greenlitlab <your app> --mine" });
|
|
79
|
+
} else if (positionals[0] === "advisor") {
|
|
80
|
+
const { fromAdvisor, ADVISOR_HOW } = await import("../src/advisor.mjs");
|
|
81
|
+
const file = positionals[1];
|
|
82
|
+
if (!file && process.stdin.isTTY) {
|
|
83
|
+
console.log(`greenlit advisor: Supabase's Security Advisor, in plain words.\n\n${ADVISOR_HOW}`);
|
|
84
|
+
process.exit(2);
|
|
85
|
+
}
|
|
86
|
+
const r = fromAdvisor(fs.readFileSync(!file || file === "-" ? 0 : file, "utf8"));
|
|
87
|
+
finish(r, `Supabase advisor · ${r.lints - r.skipped} result${r.lints - r.skipped === 1 ? "" : "s"}, in plain words${r.skipped ? ` (${r.skipped} unreadable item${r.skipped === 1 ? "" : "s"} skipped)` : ""}`, { empty: "The advisor reported nothing.", footer: "These come from Supabase's own advisor. Greenlit translated them and wrote the prompts; it did not check them itself." });
|
|
88
|
+
} else {
|
|
89
|
+
const { QUESTIONS, advise } = await import("../src/questions.mjs");
|
|
90
|
+
if (opt.json) console.log(JSON.stringify(QUESTIONS, null, 2));
|
|
91
|
+
else if (!process.stdin.isTTY) console.log(QUESTIONS.map((q, i) => `${i + 1}. ${q.ask}\n${q.options.map((o, j) => ` ${String.fromCharCode(97 + j)}) ${o.label}`).join("\n")}`).join("\n\n"));
|
|
92
|
+
else {
|
|
93
|
+
const readline = await import("node:readline/promises");
|
|
94
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
95
|
+
console.log("\nSeven things only you know. No check can see these, so Greenlit asks. Nothing you answer is sent anywhere.\n");
|
|
96
|
+
const answers = {};
|
|
97
|
+
for (const [i, q] of QUESTIONS.entries()) {
|
|
98
|
+
console.log(`${i + 1}. ${q.ask}`);
|
|
99
|
+
q.options.forEach((o, j) => console.log(` ${j + 1}) ${o.label}`));
|
|
100
|
+
const pick = Number((await rl.question(" Your answer (number, or Enter to skip): ")).trim());
|
|
101
|
+
if (q.options[pick - 1]) answers[q.id] = q.options[pick - 1].key;
|
|
102
|
+
console.log("");
|
|
103
|
+
}
|
|
104
|
+
rl.close();
|
|
105
|
+
const todo = advise(answers).filter((a) => a.ok === false);
|
|
106
|
+
const skipped = advise(answers).filter((a) => a.ok === null).length;
|
|
107
|
+
console.log(renderList(`You told us · ${7 - todo.length - skipped} of 7 in place${skipped ? `, ${skipped} skipped` : ""}`, todo.map((a) => ({ severity: "medium", title: a.ask, where: `you said: ${a.answer}`, why: a.note, prompt: a.prompt })), { color, empty: "Everything you answered is in place.", footer: "These are your answers, not something Greenlit checked, so they don't change your app's grade." }));
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
} catch (e) {
|
|
111
|
+
console.error(`greenlit: ${e.message}`);
|
|
112
|
+
process.exit(1);
|
|
113
|
+
}
|
|
55
114
|
} else {
|
|
56
115
|
if (opt["fail-on"] && !(opt["fail-on"] in SEVERITY)) {
|
|
57
116
|
console.error(`greenlit: --fail-on takes ${Object.keys(SEVERITY).join(", ")}`);
|
|
@@ -64,7 +123,7 @@ if (opt.version) {
|
|
|
64
123
|
const timer = quiet ? null : setInterval(() => process.stderr.write(`\r${frames[i++ % frames.length]} looking at ${target} the way a stranger would`), 80);
|
|
65
124
|
let result;
|
|
66
125
|
try {
|
|
67
|
-
result = await siteScan(target, { mine: opt.mine });
|
|
126
|
+
result = await siteScan(target, { mine: opt.mine, httpProbe });
|
|
68
127
|
} catch (e) {
|
|
69
128
|
if (timer) (clearInterval(timer), process.stderr.write("\r\x1b[K"));
|
|
70
129
|
console.error(`greenlit: ${explainError(e.message)}`);
|
|
@@ -94,4 +153,9 @@ if (opt.version) {
|
|
|
94
153
|
else console.log(renderSite(result, change, { color: Boolean(process.stdout.isTTY && !process.env.NO_COLOR) }));
|
|
95
154
|
}
|
|
96
155
|
if (opt["fail-on"] && result.findings.some((f) => SEVERITY[f.severity] >= SEVERITY[opt["fail-on"]])) process.exitCode = 1;
|
|
156
|
+
// "Nothing found" in code that couldn't be read is not a pass.
|
|
157
|
+
else if (opt["fail-on"] && result.grade === "?") {
|
|
158
|
+
console.error("greenlit: this app's code couldn't be read, so there is nothing to pass. Exiting with 3.");
|
|
159
|
+
process.exitCode = 3;
|
|
160
|
+
}
|
|
97
161
|
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "greenlitlab",
|
|
3
|
-
"version": "0.
|
|
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.",
|
|
3
|
+
"version": "0.4.1",
|
|
4
|
+
"description": "Is your AI-built app safe to launch? A grade from A to F for apps built with Lovable, Bolt, v0, Replit or Emergent, with a fix prompt for every problem. Checks leaks, open data and launch basics.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
7
7
|
"greenlit": "bin/greenlit.mjs",
|
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.
|
|
8
|
+
"version": "0.4.1",
|
|
9
9
|
"packages": [
|
|
10
10
|
{
|
|
11
11
|
"registryType": "npm",
|
|
12
12
|
"identifier": "greenlitlab",
|
|
13
|
-
"version": "0.
|
|
13
|
+
"version": "0.4.1",
|
|
14
14
|
"transport": { "type": "stdio" },
|
|
15
15
|
"packageArguments": [{ "type": "positional", "value": "mcp" }]
|
|
16
16
|
}
|
package/src/advisor.mjs
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// Supabase's own Security Advisor knows things nobody can see from outside: which rules are too loose, which
|
|
2
|
+
// functions strangers may run. Its results are written for database people. This turns them into Greenlit
|
|
3
|
+
// findings: plain words, worst first, a fix prompt for each. Input is the advisor's JSON (from the Supabase
|
|
4
|
+
// dashboard, the Supabase MCP server's get_advisors tool, or the Management API). Nothing is sent anywhere.
|
|
5
|
+
// Advisor text is written as SQL strings, with escaped backticks and underscores.
|
|
6
|
+
const clean = (t) => String(t).replace(/\\/g, "").replace(/`/g, "");
|
|
7
|
+
const thing = (l) => l.metadata?.name || l.metadata?.entity || (l.detail || "").match(/[`"\\]+([\w.]+)[`"\\]+/)?.[1] || "your database";
|
|
8
|
+
|
|
9
|
+
// name: [severity, title, why]
|
|
10
|
+
const KNOWN = {
|
|
11
|
+
rls_disabled_in_public: ["critical", (t) => `Anyone may be able to read and change "${t}"`, "Row Level Security is switched off for this table, so the app's public key reaches every row."],
|
|
12
|
+
policy_exists_rls_disabled: ["critical", (t) => `The rules on "${t}" are written but switched off`, "The table has security policies, but Row Level Security isn't enabled, so none of them apply."],
|
|
13
|
+
sensitive_columns_exposed: ["critical", (t) => `"${t}" exposes personal or secret columns to anyone`, "The table holds columns such as emails, passwords or tokens and has no Row Level Security."],
|
|
14
|
+
auth_users_exposed: ["critical", (t) => `Your list of users is exposed through "${t}"`, "A view or table gives the public key a way to read your sign-in records."],
|
|
15
|
+
rls_policy_always_true: ["high", (t) => `A rule on "${t}" lets everyone through`, "A policy uses a condition that is always true, so Row Level Security is on but protects nothing for that action."],
|
|
16
|
+
rls_references_user_metadata: ["high", (t) => `A rule on "${t}" trusts data users can edit themselves`, "The policy reads user_metadata, which any signed-in user can change, so anyone can give themselves access."],
|
|
17
|
+
security_definer_view: ["high", (t) => `The view "${t}" skips your security rules`, "It runs with its creator's rights, so anyone who can read the view sees rows the rules would hide."],
|
|
18
|
+
anon_security_definer_function_executable: ["high", (t) => `Strangers can run the admin-rights function "${t}"`, "This function runs with elevated rights and can be called without signing in."],
|
|
19
|
+
authenticated_security_definer_function_executable: ["medium", (t) => `Any signed-in user can run the admin-rights function "${t}"`, "This function runs with elevated rights. Check that it tests who is calling before it acts."],
|
|
20
|
+
public_bucket_allows_listing: ["high", (t) => `Anyone can list the files in the bucket "${t}"`, "A public bucket has a policy that lets anyone see every file name in it."],
|
|
21
|
+
rls_enabled_no_policy: ["low", (t) => `"${t}" is locked to everyone, including your app`, "Row Level Security is on with no policy, so nothing can read it through the app. Safe, but a feature may be broken."],
|
|
22
|
+
function_search_path_mutable: ["low", (t) => `The function "${t}" should pin its search path`, "Without a fixed search_path, a function can be tricked into running someone else's code."],
|
|
23
|
+
auth_leaked_password_protection: ["low", () => "Passwords known to be leaked are accepted", "Supabase can refuse passwords found in past breaches, and that check is off."],
|
|
24
|
+
auth_otp_long_expiry: ["low", () => "Sign-in codes stay valid too long", "Email codes and links that last more than an hour give a thief more time to use them."],
|
|
25
|
+
auth_insufficient_mfa_options: ["low", () => "Two-step sign-in is barely available", "Too few second-factor options are enabled for your users."],
|
|
26
|
+
vulnerable_postgres_version: ["medium", () => "Your database version has security fixes waiting", "Supabase has a patched Postgres version for this project."],
|
|
27
|
+
};
|
|
28
|
+
const BY_LEVEL = { ERROR: "high", WARN: "medium", INFO: "low" };
|
|
29
|
+
const ORDER = ["critical", "high", "medium", "low", "info"];
|
|
30
|
+
|
|
31
|
+
export function fromAdvisor(input) {
|
|
32
|
+
let raw = input;
|
|
33
|
+
if (typeof input === "string") {
|
|
34
|
+
try {
|
|
35
|
+
raw = JSON.parse(input);
|
|
36
|
+
} catch {
|
|
37
|
+
throw new Error("that isn't JSON. Pass the advisor's results as exported: a list of lints.");
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
const lints = [raw, raw?.lints, raw?.result?.lints, raw?.result, raw?.data?.lints, raw?.data].find(Array.isArray);
|
|
41
|
+
// An error message or an empty object is not "the advisor found nothing".
|
|
42
|
+
if (!lints) throw new Error(`that doesn't look like Supabase advisor output (expected a list of lints)${raw?.message || raw?.error ? `. It says: ${String(raw.message || raw.error).slice(0, 120)}` : ""}`);
|
|
43
|
+
const findings = [];
|
|
44
|
+
const seen = new Set();
|
|
45
|
+
let skipped = 0;
|
|
46
|
+
for (const l of lints) {
|
|
47
|
+
if (!l || typeof l !== "object" || !(l.name || l.title)) {
|
|
48
|
+
skipped++;
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
const lint = l.name || String(l.title).toLowerCase().replace(/[^a-z0-9]+/g, "_");
|
|
52
|
+
const speed = (l.categories || []).includes("PERFORMANCE") && !(l.categories || []).includes("SECURITY");
|
|
53
|
+
const t = thing(l);
|
|
54
|
+
const k = KNOWN[lint];
|
|
55
|
+
// Two policies on one table, or one table name in two schemas, are separate results.
|
|
56
|
+
const id = `advisor:${lint}:${l.cache_key || `${l.metadata?.schema || ""}.${t}:${l.detail || ""}`}`.slice(0, 200);
|
|
57
|
+
if (seen.has(id)) continue;
|
|
58
|
+
seen.add(id);
|
|
59
|
+
const severity = k ? k[0] : speed ? "low" : BY_LEVEL[l.level] || "low";
|
|
60
|
+
const title = k ? k[1](t) : `${l.title || l.name}${t !== "your database" ? `: ${t}` : ""}`;
|
|
61
|
+
const why = `${k ? k[2] : l.description || "Reported by Supabase's advisor."}${l.detail ? ` Supabase says: ${clean(l.detail)}` : ""}`;
|
|
62
|
+
const prompt = `Supabase's ${speed ? "Performance" : "Security"} Advisor reports "${l.title || l.name}" for ${t}. ${l.detail ? `${clean(l.detail)} ` : ""}Fix it${l.remediation ? ` following ${l.remediation}` : ""}. Don't loosen or remove any existing policy, keep each user limited to their own rows, and show me the SQL you ran. If fixing it could break a feature of the app, tell me which before you change anything.`;
|
|
63
|
+
findings.push({ id, severity, where: speed ? "Supabase Performance Advisor" : "Supabase Security Advisor", title, why, fix: l.remediation || "See Supabase → Advisors.", first: null, prompt });
|
|
64
|
+
}
|
|
65
|
+
if (lints.length && skipped === lints.length) throw new Error("none of those items look like advisor results (each should have a name or a title)");
|
|
66
|
+
findings.sort((a, b) => ORDER.indexOf(a.severity) - ORDER.indexOf(b.severity));
|
|
67
|
+
return { source: "Supabase advisor", lints: lints.length, skipped, findings };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// The words an agent or a person needs to get the advisor output in the first place.
|
|
71
|
+
export const ADVISOR_HOW = `Where to get the advisor results:
|
|
72
|
+
- With a coding agent that has the Supabase MCP server: ask it to run get_advisors (type "security") for your project and pass the result to greenlit_advisor.
|
|
73
|
+
- By hand: Supabase dashboard → Advisors → Security Advisor → copy or export the results as JSON, save them to a file, and run: npx greenlitlab advisor results.json`;
|
package/src/grade.mjs
CHANGED
|
@@ -43,9 +43,45 @@ const SECRETS = [
|
|
|
43
43
|
[/-----BEGIN (?:RSA |EC |OPENSSH |ENCRYPTED )?PRIVATE KEY-----(?:\\n|\\r|\s)+[A-Za-z0-9+\/=]{60,}/, "private-key", "A private key", "Whatever this key signs in to or signs for, anyone can now do too.", "the service the key belongs to: replace the key pair there and delete the old one", "PRIVATE_KEY"],
|
|
44
44
|
[/"type"\s*:\s*"service_account"[\s\S]{0,400}"private_key"/, "gcp-service-account", "A Google Cloud or Firebase service-account key", "It's an admin key: anyone can reach your Firebase and Google Cloud data with full rights.", "Google Cloud console → IAM → Service Accounts → Keys → delete this key", "GOOGLE_APPLICATION_CREDENTIALS"],
|
|
45
45
|
[/AIza[0-9A-Za-z_-]{35}(?=[\s\S]{0,400}(generativelanguage|gemini))/, "gemini", "A Google AI (Gemini) API key", "Anyone can run up your Gemini bill. (Firebase keys are public by design; this one sits next to Gemini calls.)", "aistudio.google.com → API keys → delete", "GEMINI_API_KEY"],
|
|
46
|
+
[/\bwhsec_[0-9A-Za-z]{24,}/, "stripe-webhook", "A Stripe webhook signing secret", "Anyone can fake a \"payment succeeded\" message to your app and get paid features for free.", "Stripe → Developers → Webhooks → your endpoint → roll the signing secret", "STRIPE_WEBHOOK_SECRET"],
|
|
47
|
+
[/\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis):\/\/[^\s:"'`\/@]{1,64}:[^\s"'`\/@]{6,}@[A-Za-z0-9.-]+\.[a-z]{2,}/, "database-url", "A database address with its password", "Anyone can connect straight to your database and read, change or delete everything in it.", "your database provider's dashboard: reset the database password, then update the apps that use it", "DATABASE_URL"],
|
|
46
48
|
];
|
|
49
|
+
// Example values in library text, documentation and input-field hints aren't leaks. What marks an example:
|
|
50
|
+
// a template slot, a mask or a placeholder word where the password goes; a documentation host; instruction words
|
|
51
|
+
// inside a key ("your-", "replace", "-here"); a key that counts upward (1234567890abcdef) or repeats one character.
|
|
52
|
+
// Random keys essentially never do any of these. A real password may contain any symbol, and a weak one
|
|
53
|
+
// ("postgres", "password123") is still a leak.
|
|
54
|
+
const SLOT = /^\[.*\]$|^<.*>$|^\{.*\}$|\$\{|^\$[A-Za-z_]\w*$|^%.*%$|^%s$|^[*•●·]+$|^x{3,}$|^\.{3}$|^:\w+$/i;
|
|
55
|
+
const HINT_WORD = /your|placeholder|change[-_]?me|replace|insert|[-_]here$|^here$|(^|[-_])example([-_]|$)/i;
|
|
56
|
+
const ENV_NAME = /^[A-Z][A-Z0-9_]*(PASSWORD|PASS|SECRET|PWD)[A-Z0-9_]*$/;
|
|
57
|
+
// How much of a key is made of runs that count upward (abc, 123, 789…): most of a typed-in fake, none of a random key.
|
|
58
|
+
function countsUpward(text) {
|
|
59
|
+
const t = text.toLowerCase().replace(/[^a-z0-9]/g, "");
|
|
60
|
+
let inRuns = 0, longest = 1, run = 1;
|
|
61
|
+
for (let i = 1; i <= t.length; i++) {
|
|
62
|
+
if (i < t.length && t.charCodeAt(i) === t.charCodeAt(i - 1) + 1) run++;
|
|
63
|
+
else {
|
|
64
|
+
if (run >= 3) inRuns += run;
|
|
65
|
+
longest = Math.max(longest, run);
|
|
66
|
+
run = 1;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return longest >= 8 || (t.length >= 12 && inRuns / t.length >= 0.6);
|
|
70
|
+
}
|
|
71
|
+
export function looksReal(found, kind = "") {
|
|
72
|
+
const url = found.match(/^[a-z+]+:\/\/([^:\/@]*):([^@]+)@([^\/\s:"'`]+)/i);
|
|
73
|
+
if (url) {
|
|
74
|
+
const [, user, password, host] = url;
|
|
75
|
+
if (SLOT.test(user) || SLOT.test(password) || HINT_WORD.test(password) || ENV_NAME.test(password)) return false;
|
|
76
|
+
if (/^(password|passwd|pass|pwd|secret|mypassword)$/i.test(password)) return false;
|
|
77
|
+
return !/(^|\.)example\.(com|org|net)$|^(host|hostname|localhost)$/i.test(host);
|
|
78
|
+
}
|
|
79
|
+
// A Twilio match is two values with other code between them; words in that code say nothing about the values.
|
|
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
|
+
return new Set(found.replace(/[^A-Za-z0-9]/g, "").slice(-16)).size >= 4;
|
|
82
|
+
}
|
|
47
83
|
const JWT = /eyJ[0-9A-Za-z_-]{10,}\.eyJ[0-9A-Za-z_-]{10,}\.[0-9A-Za-z_-]{10,}/g;
|
|
48
|
-
const SUPABASE_URL = /https:\/\/([a-z0-9]{20})\.supabase\.co
|
|
84
|
+
const SUPABASE_URL = /https:\/\/([a-z0-9]{20})\.supabase\.co/g;
|
|
49
85
|
const FB_PROJECT = /projectId["']?\s*:\s*["']([a-z0-9-]{4,40})["']/;
|
|
50
86
|
const FB_DB = /["'](https:\/\/[a-z0-9-]+(?:\.[a-z0-9-]+)*\.(?:firebaseio\.com|firebasedatabase\.app))\/?["']/;
|
|
51
87
|
const FB_KEY = /apiKey["']?\s*:\s*["'](AIza[0-9A-Za-z_-]{35})["']/;
|
|
@@ -56,7 +92,26 @@ const FIRESTORE_GUESSES = ["users", "profiles", "customers", "accounts", "orders
|
|
|
56
92
|
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
93
|
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
94
|
const BUCKET_REF = /storage\s*\.from\(\s*["'`]([A-Za-z0-9_.-]{1,63})["'`]/g;
|
|
59
|
-
const
|
|
95
|
+
const EDGE_REF = /functions\s*\.invoke\(\s*["'`]([A-Za-z0-9_-]{1,63})["'`]|\/functions\/v1\/([A-Za-z0-9_-]{1,63})/g;
|
|
96
|
+
// Column names that mean a readable table holds personal or secret data. Greenlit asks only whether the column exists.
|
|
97
|
+
const SECRET_COLUMNS = ["password", "password_hash", "token", "access_token", "api_key", "secret", "card_number"];
|
|
98
|
+
const CONTACT_COLUMNS = ["email", "phone", "address", "date_of_birth"];
|
|
99
|
+
// Addresses the builder or host owns. The owner can't change DNS, email records or most headers there, and
|
|
100
|
+
// other apps on the same suffix belong to other people.
|
|
101
|
+
const BUILDER_HOST = /\.(lovable\.app|lovableproject\.com|bolt\.host|bolt\.new|replit\.app|repl\.co|replit\.dev|vercel\.app|v0\.app|netlify\.app|pages\.dev|workers\.dev|emergent\.host|emergentagent\.com|base44\.app|web\.app|firebaseapp\.com|appspot\.com|run\.app|github\.io|gitlab\.io|onrender\.com|fly\.dev|railway\.app|herokuapp\.com|azurewebsites\.net|azurestaticapps\.net|amplifyapp\.com|ondigitalocean\.app|deno\.dev|glitch\.me|streamlit\.app|hf\.space|webflow\.io|framer\.app|framer\.website|wixsite\.com|bubbleapps\.io|softr\.app|glide\.page|surge\.sh|netlify\.com|cloudfront\.net|ngrok\.io|ngrok-free\.app)$/i;
|
|
102
|
+
// Cookies set by the host or CDN, not by the app.
|
|
103
|
+
const PLATFORM_COOKIE = /^(__cf|cf_|_cf|__vercel|_vercel|nf_|__Host-next|__Secure-next|AWSALB|ARRAffinity)/i;
|
|
104
|
+
const DEFAULT_TITLE = /^\s*(Lovable App|Lovable Generated Project|Vite \+ React(?: \+ TS)?|Create Next App|v0 App|React App|New Project|My App|Bolt)\s*$/i;
|
|
105
|
+
const AI_DIRECT = /https:\/\/(api\.openai\.com\/v1|api\.anthropic\.com\/v1|generativelanguage\.googleapis\.com\/v1|api\.groq\.com\/openai|openrouter\.ai\/api\/v1|api\.x\.ai\/v1|api\.mistral\.ai\/v1)/;
|
|
106
|
+
// A table or collection about people or money, judged by whole words in its name: "orders" and "user_profiles" are,
|
|
107
|
+
// "leaderboard", "border_styles" and "subscription_plans" are not.
|
|
108
|
+
const PERSONAL_WORD = /^(users?|profiles?|customers?|clients?|accounts?|orders?|payments?|messages?|chats?|contacts?|leads?|emails?|subscribers?|subscriptions?|invoices?|members?|patients?|employees?|applicants?|waitlist|signups?)$/;
|
|
109
|
+
// A list of kinds, shared by everyone ("subscription_plans", "order_types"). Per-user tables such as "user_settings" stay personal.
|
|
110
|
+
const LOOKUP_WORD = /^(plans?|types?|tiers?|styles?|categories|category|templates?|options?|levels?|kinds?|tags?)$/;
|
|
111
|
+
const isPersonal = (name) => {
|
|
112
|
+
const words = String(name).replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
|
|
113
|
+
return words.some((w) => PERSONAL_WORD.test(w)) && !LOOKUP_WORD.test(words.at(-1));
|
|
114
|
+
};
|
|
60
115
|
|
|
61
116
|
// Which app builder made this, so the fix prompt can say where to paste it.
|
|
62
117
|
export function detectBuilder(host, html = "") {
|
|
@@ -141,12 +196,30 @@ export function explainError(message) {
|
|
|
141
196
|
|
|
142
197
|
// 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
198
|
// Scripts on anyone else's site (Stripe, analytics) are that company's code, not the app's.
|
|
199
|
+
// Country domains with a second level (shop.co.uk, shop.ne.jp, shop.com.au): the owner's domain is three labels there.
|
|
200
|
+
// Listed per country, because "web" is a suffix in South Africa and an ordinary name in Germany (web.de).
|
|
201
|
+
const SECOND_LEVEL = {
|
|
202
|
+
at: "co or ac gv", uk: "co org me ltd plc net sch ac gov nhs", jp: "co ne or go ac ad ed gr lg", au: "com net org edu gov asn id", nz: "co net org govt ac school geek gen kiwi maori",
|
|
203
|
+
in: "co net org gen firm ind ac edu res gov nic", br: "com net org gov edu art", za: "co org net gov ac web", kr: "co ne or go re pe ac", cn: "com net org gov edu ac",
|
|
204
|
+
tw: "com net org gov edu idv", hk: "com net org gov edu idv", sg: "com net org gov edu per", my: "com net org gov edu", id: "co or web ac go sch my net", th: "co or ac go in net",
|
|
205
|
+
ph: "com net org gov edu", pk: "com net org gov edu", bd: "com net org gov edu ac", lk: "com net org gov edu", np: "com net org gov edu", il: "co org net ac gov muni",
|
|
206
|
+
tr: "com net org gov edu gen web info biz", mx: "com net org gob edu", ar: "com net org gob edu", co: "com net org gov edu nom", pe: "com net org gob edu nom",
|
|
207
|
+
ve: "com net org co gob edu web info", ec: "com net org gob edu fin info", uy: "com net org gub edu", ng: "com net org gov edu", ke: "co or ne go ac info me", gh: "com org gov edu",
|
|
208
|
+
eg: "com net org gov edu", sa: "com net org gov edu med", ae: "co net org gov ac sch", ua: "com net org gov edu in co", pl: "com net org gov edu info biz waw", es: "com org nom gob edu",
|
|
209
|
+
pt: "com org gov edu nome", gr: "com net org gov edu", cy: "com net org gov ac ltd biz", vn: "com net org gov edu info biz", fr: "gouv asso com", it: "gov edu",
|
|
210
|
+
};
|
|
211
|
+
const isSecondLevel = (label, tld) => (SECOND_LEVEL[tld] ? SECOND_LEVEL[tld].split(" ").includes(label) : tld.length === 2 && /^(co|com|org|net|gov|edu|ac)$/.test(label));
|
|
144
212
|
const siteKey = (host) => {
|
|
145
|
-
const
|
|
146
|
-
|
|
213
|
+
const h = host.toLowerCase();
|
|
214
|
+
// On a builder's shared address, each full name is a different owner.
|
|
215
|
+
if (BUILDER_HOST.test(h)) return h;
|
|
216
|
+
const parts = h.split(".");
|
|
217
|
+
const short = parts.length > 2 && isSecondLevel(parts.at(-2), parts.at(-1));
|
|
218
|
+
// www.gov.uk is the site of gov.uk itself, not a domain registered under it.
|
|
219
|
+
if (short && parts.length === 3 && parts[0] === "www") return parts.slice(-2).join(".");
|
|
147
220
|
return parts.slice(short ? -3 : -2).join(".");
|
|
148
221
|
};
|
|
149
|
-
const HOSTING_CDN = /(^|\.)(cloudfront\.net|azureedge\.net|b-cdn\.net|r2\.dev|fastly\.net|akamaized\.net|
|
|
222
|
+
const HOSTING_CDN = /(^|\.)(cloudfront\.net|azureedge\.net|b-cdn\.net|r2\.dev|fastly\.net|akamaized\.net|storage\.googleapis\.com)$|(^|\.)s3[.-][a-z0-9.-]*amazonaws\.com$/i;
|
|
150
223
|
|
|
151
224
|
// Paths to other scripts mentioned inside a script or page: imports of every form, and the lists of lazy-loaded
|
|
152
225
|
// 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.
|
|
@@ -209,6 +282,19 @@ const P = {
|
|
|
209
282
|
db === "Supabase"
|
|
210
283
|
? "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
284
|
: "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.",
|
|
285
|
+
fnCheck: (names) => `My app calls these backend functions: ${names.join(", ")}. Check each one and change nothing yet. For every function tell me: does it check that the caller is signed in, does it check that the caller is allowed to act on the record it touches, and could a stranger call it directly and cost me money or change data? Then fix every function that fails, and show me what you changed.`,
|
|
286
|
+
localhost: (u) => ({ first: null, prompt: `My live app still points at ${u}, which only exists on a developer's computer, so that part can't work for real visitors. Find every place the app uses a localhost or 127.0.0.1 address and replace it with the live address, read from an environment variable. Then tell me each file you changed.` }),
|
|
287
|
+
mixed: () => ({ first: null, prompt: "My live app loads a script, style or frame over plain http:// from a page served over https://. Browsers block that. Change every such address to https://, or host the file with the app, and tell me what you changed." }),
|
|
288
|
+
testPayments: () => ({ first: "In Stripe, switch to live mode and copy your live publishable key (pk_live_…). Add your live secret key and webhook secret to your backend's secrets, never to the frontend.", prompt: "My live app uses a Stripe test key (pk_test_), so real customers can't pay. Switch the frontend to read the live publishable key from an environment variable, make sure the backend uses the live secret key and the live webhook signing secret from its secrets, and check that the webhook is registered for the live address. Tell me what you changed and what I still need to do in the Stripe dashboard." }),
|
|
289
|
+
title: (t) => ({ first: null, prompt: `My app's page title is still the default "${t}". Set a real title and description for the app in index.html (or the page metadata), plus the Open Graph title, description and image, so shared links look right.` }),
|
|
290
|
+
noindex: () => ({ first: null, prompt: "My live app tells search engines not to list it (a robots noindex tag or header). If this app should be found on Google, remove that tag from the live build only. If it's meant to stay private, leave it and tell me." }),
|
|
291
|
+
aiDirect: () => ({ first: null, prompt: "My app's browser code calls an AI provider's API directly. That only works if the secret key is in the browser, where anyone can copy it and spend my money. Move every AI call into a backend function that reads the key from a secret, checks the user is signed in, and limits how many calls each user can make per day. Remove the provider's key from the frontend. List what you changed." }),
|
|
292
|
+
testSender: () => ({ first: "In your email provider (for example Resend), add and verify your own domain, then choose a sender such as hello@yourdomain.", prompt: "My app sends email from a test address (onboarding@resend.dev), which only delivers to my own inbox. Change the sender to an address on my verified domain, read from an environment variable, and tell me which DNS records I must add for that domain." }),
|
|
293
|
+
cookie: (name) => ({ first: null, prompt: `My app sets the cookie "${name}" without the Secure and HttpOnly flags, so it can leak over plain http or be read by any script on the page. Set Secure, HttpOnly and SameSite=Lax on every sign-in or session cookie, and tell me where you changed it.` }),
|
|
294
|
+
httpsRedirect: () => ({ first: null, prompt: "My app answers on plain http:// without sending visitors to https://. Turn on \"always use HTTPS\" (a permanent redirect from http to https) in my host's settings, and add the header Strict-Transport-Security: max-age=31536000. Tell me exactly where that setting is for my host." }),
|
|
295
|
+
cors: () => ({ first: null, prompt: "My app tells browsers that any website may read its responses with the visitor's login attached (it repeats back whatever Origin it is sent and allows credentials). Change the CORS settings to allow only my own site's address, never a repeated-back origin together with credentials, and show me the new settings." }),
|
|
296
|
+
dmarc: (domain) => ({ first: `Add a TXT record at _dmarc.${domain} with the value: v=DMARC1; p=none; rua=mailto:you@${domain} (use an inbox you read). Your domain provider's DNS page is where this goes.`, prompt: `My domain ${domain} has no DMARC record, so anyone can send email pretending to be me, and Gmail and Outlook trust my real emails less. Tell me, step by step for my DNS provider, how to add a DMARC record starting with p=none, and how to check that my sign-up and password-reset emails pass SPF and DKIM before I tighten it to p=quarantine.` }),
|
|
297
|
+
spf: (domain) => ({ first: null, prompt: `The SPF record for my domain ${domain} is broken (there must be exactly one, and it must not end in +all). Tell me which services send email for my app, write one correct SPF record that covers them and ends in ~all, and tell me exactly what to change at my DNS provider.` }),
|
|
212
298
|
sourceMaps: () => ({
|
|
213
299
|
first: null,
|
|
214
300
|
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.",
|
|
@@ -220,7 +306,7 @@ const P = {
|
|
|
220
306
|
};
|
|
221
307
|
|
|
222
308
|
// --- the check -----------------------------------------------------------------------------------
|
|
223
|
-
export async function siteScan(target, { mine = false, fetcher = fetch, maxScripts = 400, maxBytes = 8 * 1024 * 1024, maxTotalBytes = 200 * 1024 * 1024, deadlineMs = 120000, scriptTimeoutMs = 15000 } = {}) {
|
|
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 } = {}) {
|
|
224
310
|
const deadline = Date.now() + deadlineMs;
|
|
225
311
|
const fetchOpts = (o = {}) => ({ max: maxBytes, ...o, fetcher });
|
|
226
312
|
const url = safeUrl(/^https?:\/\//i.test(String(target).trim()) ? String(target).trim() : `https://${String(target).trim()}`);
|
|
@@ -228,7 +314,7 @@ export async function siteScan(target, { mine = false, fetcher = fetch, maxScrip
|
|
|
228
314
|
const findings = [];
|
|
229
315
|
const add = (f) => findings.push(f);
|
|
230
316
|
|
|
231
|
-
const page = await get(url.href, fetchOpts());
|
|
317
|
+
const page = await get(url.href, fetchOpts({ timeout: pageTimeoutMs }));
|
|
232
318
|
if (!page.status || page.status >= 400) throw new Error(`could not load ${url.href} (${page.error || page.status})`);
|
|
233
319
|
const pageType = page.headers?.get("content-type") || "";
|
|
234
320
|
if (pageType && !/html/i.test(pageType)) throw new Error(`${url.href} isn't a web page`);
|
|
@@ -238,8 +324,10 @@ export async function siteScan(target, { mine = false, fetcher = fetch, maxScrip
|
|
|
238
324
|
const site = siteKey(new URL(origin).hostname);
|
|
239
325
|
const builder = detectBuilder(new URL(origin).host, page.text);
|
|
240
326
|
const isOwn = (href) => {
|
|
241
|
-
const
|
|
242
|
-
|
|
327
|
+
const u = new URL(href);
|
|
328
|
+
// Only the usual web ports: a page must not be able to point the check at another service on its domain.
|
|
329
|
+
if (u.port && u.port !== new URL(origin).port) return false;
|
|
330
|
+
return siteKey(u.hostname) === site || HOSTING_CDN.test(u.hostname);
|
|
243
331
|
};
|
|
244
332
|
|
|
245
333
|
// Every script that belongs to the app: the ones the page loads, then whatever those mention, until none are left.
|
|
@@ -300,6 +388,8 @@ export async function siteScan(target, { mine = false, fetcher = fetch, maxScrip
|
|
|
300
388
|
const noCodeRead = bundles.length === 1 && elsewhere > 0;
|
|
301
389
|
|
|
302
390
|
let mapTries = 0;
|
|
391
|
+
const supabaseUrls = new Map();
|
|
392
|
+
const supabaseRefs = new Set();
|
|
303
393
|
let supabase = null;
|
|
304
394
|
let firebase = null;
|
|
305
395
|
const keysSeen = new Set();
|
|
@@ -311,7 +401,8 @@ export async function siteScan(target, { mine = false, fetcher = fetch, maxScrip
|
|
|
311
401
|
if (o !== origin && /supabase\.co|firebase|googleapis|stripe\.com|clerk|posthog|sentry|vercel/.test(o)) thirdParty.add(o.replace(/^https:\/\/[a-z0-9]{20}\.supabase\.co$/, "https://*.supabase.co"));
|
|
312
402
|
}
|
|
313
403
|
for (const [re, id, title, why, revoke, env] of SECRETS) {
|
|
314
|
-
|
|
404
|
+
// The first match that isn't an example value.
|
|
405
|
+
const m = [...b.text.matchAll(new RegExp(re.source, re.flags.includes("g") ? re.flags : `${re.flags}g`))].find((x) => looksReal(x[0], id));
|
|
315
406
|
if (m && !keysSeen.has(m[0])) {
|
|
316
407
|
keysSeen.add(m[0]);
|
|
317
408
|
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) });
|
|
@@ -324,12 +415,15 @@ export async function siteScan(target, { mine = false, fetcher = fetch, maxScrip
|
|
|
324
415
|
keysSeen.add(t);
|
|
325
416
|
add({ id: "supabase:service_role", severity: "critical", where: b.where, title: "Your Supabase service_role key is in the browser code", why: "This key skips every security rule: anyone can read, change and delete all of your data and users.", fix: "Rotate it in Supabase (Settings → API) and use it only on a server. The browser should only ever have the anon key.", ...P.serviceRole() });
|
|
326
417
|
}
|
|
327
|
-
if (p.role === "anon" && p.iss === "supabase")
|
|
418
|
+
if (p.role === "anon" && p.iss === "supabase") {
|
|
419
|
+
if (p.ref) supabaseRefs.add(p.ref);
|
|
420
|
+
// The first key found is the app's own: the page and its main script come first. Later ones are leftovers.
|
|
421
|
+
if (!supabase?.anon) supabase = { ...(supabase || {}), anon: t, ref: p.ref };
|
|
422
|
+
}
|
|
328
423
|
}
|
|
329
424
|
const pk = b.text.match(/sb_publishable_[0-9A-Za-z_-]{20,}/);
|
|
330
425
|
if (pk) supabase = { ...(supabase || {}), anon: supabase?.anon || pk[0] };
|
|
331
|
-
const
|
|
332
|
-
if (su) supabase = { ...(supabase || {}), url: su[0], ref: supabase?.ref || su[1] };
|
|
426
|
+
for (const m of b.text.matchAll(SUPABASE_URL)) supabaseUrls.set(m[1], m[0]);
|
|
333
427
|
const fp = b.text.match(FB_PROJECT);
|
|
334
428
|
if (fp && /firebase/i.test(b.text)) {
|
|
335
429
|
firebase = { ...(firebase || {}), project: fp[1] };
|
|
@@ -344,12 +438,22 @@ export async function siteScan(target, { mine = false, fetcher = fetch, maxScrip
|
|
|
344
438
|
if (mapUrl && isOwn(mapUrl) && mapTries < 3 && !findings.some((f) => f.id === "sourcemaps")) {
|
|
345
439
|
mapTries++;
|
|
346
440
|
// Check what comes back: hosts that answer every missing file with the home page would look "public" otherwise.
|
|
347
|
-
const r = await get(mapUrl, fetchOpts({ max: 4096 }));
|
|
441
|
+
const r = await get(mapUrl, fetchOpts({ max: 4096, timeout: 3000 }));
|
|
348
442
|
if (r.status === 200 && /^\s*\{[\s\S]*"(version|mappings|sources)"/.test(r.text))
|
|
349
443
|
add({ id: "sourcemaps", severity: "medium", where: new URL(mapUrl).pathname, title: "Source maps are public", why: "Anyone can read your app's original source code, including comments and any logic you assumed was hidden.", fix: "Turn off source maps in production builds (for Vite: build.sourcemap = false).", ...P.sourceMaps() });
|
|
350
444
|
}
|
|
351
445
|
}
|
|
352
446
|
|
|
447
|
+
// Code can mention more than one Supabase project (an old one, a demo). The public key names the real one.
|
|
448
|
+
if (supabaseUrls.size) {
|
|
449
|
+
supabase = supabase || {};
|
|
450
|
+
const ref = supabase.ref && (supabaseUrls.has(supabase.ref) || supabase.anon?.startsWith("eyJ")) ? supabase.ref : [...supabaseUrls.keys()][0];
|
|
451
|
+
supabase.url = supabaseUrls.get(ref) || `https://${ref}.supabase.co`;
|
|
452
|
+
supabase.ref = ref;
|
|
453
|
+
}
|
|
454
|
+
for (const ref of supabaseUrls.keys()) supabaseRefs.add(ref);
|
|
455
|
+
if (supabase?.url && supabaseRefs.size > 1)
|
|
456
|
+
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 });
|
|
353
457
|
const database = supabase?.url && supabase.anon ? "Supabase" : firebase?.project ? "Firebase" : null;
|
|
354
458
|
if (database && !mine)
|
|
355
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) });
|
|
@@ -363,6 +467,9 @@ export async function siteScan(target, { mine = false, fetcher = fetch, maxScrip
|
|
|
363
467
|
let tablesTested = 0;
|
|
364
468
|
let dbBlind = false;
|
|
365
469
|
let tablesListed = false;
|
|
470
|
+
let tablesUntested = 0;
|
|
471
|
+
let keyRejected = false;
|
|
472
|
+
let authSettings = null;
|
|
366
473
|
// Database functions the app calls. Listed for the owner, never called: calling one runs it.
|
|
367
474
|
const functions = new Set();
|
|
368
475
|
const bucketsInCode = new Set();
|
|
@@ -371,6 +478,11 @@ export async function siteScan(target, { mine = false, fetcher = fetch, maxScrip
|
|
|
371
478
|
for (const m of b.text.matchAll(RPC_REF)) functions.add(m[1] || m[2]);
|
|
372
479
|
for (const m of b.text.matchAll(BUCKET_REF)) bucketsInCode.add(m[1]);
|
|
373
480
|
}
|
|
481
|
+
const edge = new Set();
|
|
482
|
+
if (supabase) for (const b of bundles) for (const m of b.text.matchAll(EDGE_REF)) edge.add(m[1] || m[2]);
|
|
483
|
+
const called = [...new Set([...edge, ...functions])];
|
|
484
|
+
if (called.length)
|
|
485
|
+
add({ id: "supabase:functions", severity: "info", where: "Supabase functions", title: `Your app calls ${called.length} backend function${called.length > 1 ? "s" : ""} that Greenlit can't test`, why: `${called.slice(0, 12).join(", ")}${called.length > 12 ? " and more" : ""}. A function that doesn't check who is calling it is open to everyone, and that is how some of the largest leaks from AI-built apps happened. Greenlit lists them and never calls them, because calling one runs it.`, fix: "Have your builder check each function (the prompt below), or open Supabase → Advisors → Security Advisor.", first: null, prompt: null, checkPrompt: P.fnCheck(called.slice(0, 30)) });
|
|
374
486
|
// Signs of Supabase, but not both its address and its public key: nothing can be tested.
|
|
375
487
|
const supabasePartial = Boolean(supabase && !(supabase.url && supabase.anon) && !firebase?.project);
|
|
376
488
|
if (supabasePartial)
|
|
@@ -387,25 +499,59 @@ export async function siteScan(target, { mine = false, fetcher = fetch, maxScrip
|
|
|
387
499
|
tablesListed = names.size > 0;
|
|
388
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]);
|
|
389
501
|
tables = [];
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
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
|
+
}
|
|
395
519
|
tablesTested++;
|
|
396
|
-
const
|
|
397
|
-
|
|
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 });
|
|
398
526
|
}
|
|
527
|
+
if (names.size > 120) untested.push(`${names.size - 120} more names`);
|
|
528
|
+
tablesUntested = untested.length;
|
|
399
529
|
// A check that tested no tables must say so, not report "nothing open".
|
|
400
530
|
dbBlind = tablesTested === 0;
|
|
401
|
-
if (
|
|
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)
|
|
402
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") });
|
|
403
|
-
|
|
404
|
-
|
|
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";
|
|
405
551
|
const why = personal
|
|
406
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."
|
|
407
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.";
|
|
408
|
-
add({ id: `supabase:table:${table}`, severity:
|
|
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) });
|
|
409
555
|
}
|
|
410
556
|
}
|
|
411
557
|
|
|
@@ -425,9 +571,9 @@ export async function siteScan(target, { mine = false, fetcher = fetch, maxScrip
|
|
|
425
571
|
}
|
|
426
572
|
|
|
427
573
|
// Your own app only: Supabase settings that quietly make "signed-in users only" mean "anyone".
|
|
428
|
-
if (mine && supabase?.url && supabase.anon) {
|
|
574
|
+
if (mine && supabase?.url && supabase.anon && !keyRejected) {
|
|
429
575
|
const h = { apikey: supabase.anon, ...(supabase.anon.startsWith("eyJ") && { authorization: `Bearer ${supabase.anon}` }) };
|
|
430
|
-
const st =
|
|
576
|
+
const st = authSettings;
|
|
431
577
|
try {
|
|
432
578
|
const cfg = JSON.parse(st.text);
|
|
433
579
|
if (st.status === 200 && cfg.disable_signup === false && cfg.mailer_autoconfirm === true)
|
|
@@ -472,22 +618,122 @@ export async function siteScan(target, { mine = false, fetcher = fetch, maxScrip
|
|
|
472
618
|
} catch {}
|
|
473
619
|
if (r.status === 200 && n > 0) {
|
|
474
620
|
firebaseOpen.push({ where: `Firestore "${coll}"` });
|
|
475
|
-
add({ id: `firebase:firestore:${coll}`, severity:
|
|
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) });
|
|
476
622
|
}
|
|
477
623
|
}
|
|
478
624
|
}
|
|
479
625
|
|
|
480
|
-
|
|
481
|
-
|
|
626
|
+
// --- launch basics: things that stop a live app working, read from what was already downloaded ---
|
|
627
|
+
const hostName = new URL(origin).hostname;
|
|
628
|
+
const isLocal = /^(localhost|127\.0\.0\.1|\[::1\])$/.test(hostName);
|
|
629
|
+
const secure = origin.startsWith("https:");
|
|
630
|
+
const scripts = bundles.slice(1);
|
|
631
|
+
const inScripts = (re) => scripts.map((b) => b.text.match(re)).find(Boolean);
|
|
632
|
+
// 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[^>]*?\bsrc=["']([^"']+)["']|<form\b[^>]*?\baction=["']([^"']+)["']|<link\b(?=[^>]*\brel=["']?(?:stylesheet|preload|modulepreload|icon|manifest)\b)[^>]*?\bhref=["']([^"']+)["']/gi)].map((m) => m[1] || m[2] || m[3]);
|
|
634
|
+
if (!isLocal) {
|
|
635
|
+
const inPage = loaded.find((u) => /^https?:\/\/(?:localhost|127\.0\.0\.1)(?=[:\/]|$)/i.test(u));
|
|
636
|
+
// A bare http://localhost:3000 in a list is usually an allow-list (Lovable's own preview code has one), so only an address
|
|
637
|
+
// with a path, or one used as a fallback or an API base, counts.
|
|
638
|
+
const inCode = scripts
|
|
639
|
+
.flatMap((b) => [...b.text.matchAll(/["'`](https?:\/\/(?:localhost|127\.0\.0\.1):(\d{2,5})(\/[A-Za-z0-9_][^"'`\s]{0,80})?)["'`]/g)].map((m) => ({ m, before: b.text.slice(Math.max(0, m.index - 40), m.index) })))
|
|
640
|
+
.find(({ m, before }) => !["9999", "4317", "4318", "8969"].includes(m[2]) && (m[3] || /(?:fetch\(|axios\.\w+\(|baseURL\s*:|(?:api|base|server|backend)\w*\s*[:=]|\|\||\?\?)\s*$/i.test(before)))?.m;
|
|
641
|
+
if (inPage) add({ id: "launch:localhost", severity: "high", where: "the page itself", title: "Your live app loads from an address that only works on a developer's computer", why: `The page points at ${inPage.slice(0, 80)}. Visitors' browsers can't reach that, so this part of the app is broken for everyone but its builder.`, fix: "Replace localhost addresses with the live address.", ...P.localhost(inPage.slice(0, 80)) });
|
|
642
|
+
else if (inCode) add({ id: "launch:localhost", severity: "low", where: "your app's scripts", title: "Your app's code mentions a developer-only address", why: `The code contains ${inCode[1].slice(0, 80)}. If the live app ever uses it, that part won't work for visitors. It may only be a fallback, so check it.`, fix: "Make sure the live app never falls back to a localhost address.", ...P.localhost(inCode[1].slice(0, 80)) });
|
|
643
|
+
}
|
|
644
|
+
if (secure && loaded.some((u) => /^http:\/\/(?!localhost|127\.)/i.test(u)))
|
|
645
|
+
add({ id: "launch:mixed", severity: "medium", where: "the page itself", title: "The page loads something over plain http", why: "Browsers block scripts, styles and frames loaded over http:// on an https:// page, so part of your app may silently not load.", fix: "Change the address to https://.", ...P.mixed() });
|
|
646
|
+
const allCode = [page.text, ...scripts.map((b) => b.text)];
|
|
647
|
+
if (allCode.some((t) => /\bpk_test_[0-9A-Za-z]{20,}/.test(t)) && !allCode.some((t) => /\bpk_live_[0-9A-Za-z]{20,}/.test(t)))
|
|
648
|
+
add({ id: "launch:test-payments", severity: "medium", where: "your app's scripts", title: "Payments are still in test mode", why: "The app ships a Stripe test key (pk_test_) and no live key. Real customers can't pay you until it uses live keys.", fix: "Switch to your live Stripe keys.", ...P.testPayments() });
|
|
649
|
+
const title = (page.text.match(/<title[^>]*>([^<]{0,120})<\/title>/i) || [])[1];
|
|
650
|
+
if (title && DEFAULT_TITLE.test(title))
|
|
651
|
+
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[^>]+name=["']robots["'][^>]+content=["'][^"']*noindex/i.test(page.text) || /noindex/i.test(page.headers?.get("x-robots-tag") || ""))
|
|
653
|
+
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
|
+
if (inScripts(AI_DIRECT))
|
|
655
|
+
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
|
+
if (allCode.some((t) => /onboarding@resend\.dev/i.test(t)))
|
|
657
|
+
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
|
+
for (const c of page.headers?.getSetCookie?.() || []) {
|
|
659
|
+
const name = c.split("=")[0].trim();
|
|
660
|
+
// Sign-in cookies only. Anti-forgery cookies (csrf, xsrf) must stay readable by the page's own script.
|
|
661
|
+
if (!secure || PLATFORM_COOKIE.test(name) || /csrf|xsrf/i.test(name) || !/(^|[_.-])(session|sess|sid|auth|token|jwt|login)([_.-]|$)/i.test(name)) continue;
|
|
662
|
+
if (/;\s*secure/i.test(c) && /;\s*httponly/i.test(c)) continue;
|
|
663
|
+
add({ id: `launch:cookie:${name}`, severity: "medium", where: "response headers", title: `The sign-in cookie "${name}" isn't locked down`, why: "Without the Secure and HttpOnly flags, the cookie can travel over plain http or be read by any script on the page, which is how sessions get stolen.", fix: "Set Secure, HttpOnly and SameSite on session cookies.", ...P.cookie(name) });
|
|
664
|
+
break;
|
|
665
|
+
}
|
|
666
|
+
if (bundles.length > 1 && !unread && !cut && !allCode.some((t) => /privacy/i.test(t)))
|
|
667
|
+
add({ id: "launch:no-privacy", severity: "info", where: "the page and its scripts", title: "Greenlit couldn't see a privacy policy", why: "Nothing in the page or its code mentions one. If your app collects emails, names or payments, most countries expect a privacy policy that visitors can open.", fix: "Add a privacy policy page and link it from the footer and the sign-up form.", first: null, prompt: null, checkPrompt: "Add a privacy policy page and a terms page to my app, linked from the footer and from the sign-up form. Draft them from what the app actually collects and which services it sends data to, list those for me, and mark anything a lawyer should check." });
|
|
668
|
+
|
|
669
|
+
// Two single requests: does plain http send visitors to https, and will the app hand a signed-in visitor's data to any site?
|
|
670
|
+
const unchecked = [];
|
|
671
|
+
const tailEnd = Date.now() + tailMs;
|
|
672
|
+
const left = () => Math.min(6000, tailEnd - Date.now());
|
|
673
|
+
if (!secure && !isLocal) {
|
|
674
|
+
// The address was given as http and stayed there. If https also answers, the gap is the missing redirect.
|
|
675
|
+
const https = left() < 500 ? { status: 0 } : await get(`https://${new URL(origin).host}/`, fetchOpts({ max: 2048, timeout: left() }));
|
|
676
|
+
// Any answer over https that stays on https means https exists (a 403 is still an answer).
|
|
677
|
+
if (https.status >= 200 && https.status < 500 && /^https:/i.test(https.url || ""))
|
|
678
|
+
add({ id: "launch:no-https-redirect", severity: "medium", where: "your host", title: "The plain http address doesn't send visitors to https", why: "Someone who types your address without https gets an unprotected page, where passwords can be read on shared Wi-Fi.", fix: "Turn on \"always use HTTPS\" in your host's settings.", ...P.httpsRedirect() });
|
|
679
|
+
else if (!https.status) unchecked.push("whether this app also answers on https");
|
|
680
|
+
else add({ id: "launch:no-https", severity: "high", where: "your host", title: "This app is served over plain http, with no encryption", why: "Anything typed into it, passwords included, can be read by others on the same network, and browsers mark the page \"Not secure\".", fix: "Turn on https for the app, and send every http visit to https.", ...P.httpsRedirect() });
|
|
681
|
+
}
|
|
682
|
+
if (secure && !isLocal) {
|
|
683
|
+
// The CLI passes its own probe (see node-probe.mjs); on the web, fetch follows the redirect and reports where it ended.
|
|
684
|
+
const plainUrl = `http://${new URL(origin).host}/`;
|
|
685
|
+
const plain = left() < 500 ? { status: 0 } : httpProbe ? await httpProbe(plainUrl) : await get(plainUrl, fetchOpts({ max: 2048, timeout: left() }));
|
|
686
|
+
// -1: nothing listens on plain http at all, which is fine.
|
|
687
|
+
if (plain.status === -1) {
|
|
688
|
+
} else if (!plain.status) unchecked.push("whether the plain http address sends visitors to https");
|
|
689
|
+
else if (httpProbe ? plain.status === 200 : plain.status === 200 && /^http:/i.test(plain.url || ""))
|
|
690
|
+
add({ id: "launch:no-https-redirect", severity: "medium", where: "your host", title: "The plain http address doesn't send visitors to https", why: "Someone who types your address without https gets an unprotected page, where passwords can be read on shared Wi-Fi.", fix: "Turn on \"always use HTTPS\" in your host's settings.", ...P.httpsRedirect() });
|
|
691
|
+
const probe = "https://greenlit-origin-check.example";
|
|
692
|
+
const cors = left() < 500 ? { status: 0 } : await get(pageUrl, fetchOpts({ max: 2048, timeout: left(), headers: { origin: probe } }));
|
|
693
|
+
if (!cors.status) unchecked.push("whether other websites can read this app's responses");
|
|
694
|
+
else if (cors.headers?.get("access-control-allow-origin") === probe && /true/i.test(cors.headers?.get("access-control-allow-credentials") || ""))
|
|
695
|
+
add({ id: "launch:cors", severity: "high", where: "response headers", title: "Any website can read your app's responses as a signed-in visitor", why: "The app repeats back whatever site asks and allows logins to be attached. A malicious page your user visits could read their data from your app.", fix: "Allow only your own site's address in the CORS settings.", ...P.cors() });
|
|
696
|
+
}
|
|
482
697
|
|
|
483
|
-
const csp = page.headers?.get("content-security-policy") || "";
|
|
484
698
|
// Lovable's own hosting sets the response headers, and this protection can't be added from inside an app
|
|
485
699
|
// (a meta tag can't do it). What the owner can't change is shown, and costs no points.
|
|
486
700
|
const hostSetsHeaders = /\.lovable\.app$/i.test(new URL(origin).hostname);
|
|
701
|
+
// --- your own domain: can your email be trusted? Looked up in public DNS; skipped on a builder's address. ---
|
|
702
|
+
const onBuilderHost = BUILDER_HOST.test(hostName);
|
|
703
|
+
if (onBuilderHost)
|
|
704
|
+
add({ id: "domain:builder", severity: "info", where: "your address", title: "You're still on the builder's address", why: `${hostName} belongs to your builder or host. Until the app is on a domain you own, you can't send email in your own name, and the host decides its security settings${hostSetsHeaders && !page.headers?.get("x-frame-options") && !/frame-ancestors/i.test(page.headers?.get("content-security-policy") || "") ? " (for example, other sites can show this app in a frame, and only the host can change that, so it costs you no points)" : ""}.`, fix: "Connect your own domain before you launch widely. Then check again here: Greenlit will also check the domain's email records.", first: null, prompt: null });
|
|
705
|
+
else if (!isLocal && hostName.includes(".")) {
|
|
706
|
+
const apex = siteKey(hostName);
|
|
707
|
+
const txt = async (name) => {
|
|
708
|
+
if (left() < 500) return null;
|
|
709
|
+
const r = await get(`https://cloudflare-dns.com/dns-query?name=${encodeURIComponent(name)}&type=TXT`, fetchOpts({ max: 65536, timeout: left(), headers: { accept: "application/dns-json" } }));
|
|
710
|
+
try {
|
|
711
|
+
const j = JSON.parse(r.text);
|
|
712
|
+
if (j.Status !== 0 && j.Status !== 3) return null;
|
|
713
|
+
return (j.Answer || []).filter((a) => a.type === 16).map((a) => String(a.data).replace(/^"|"$/g, "").replace(/"\s+"/g, ""));
|
|
714
|
+
} catch {
|
|
715
|
+
return null; // the lookup didn't work, which is not the same as "no record"
|
|
716
|
+
}
|
|
717
|
+
};
|
|
718
|
+
const dmarc = await txt(`_dmarc.${apex}`);
|
|
719
|
+
if (dmarc && !dmarc.some((t) => /^v=DMARC1/i.test(t)))
|
|
720
|
+
add({ id: "email:no-dmarc", severity: "medium", where: `DNS for ${apex}`, title: `Anyone can send email pretending to be ${apex}`, why: "The domain has no DMARC record, the setting that tells Gmail and Outlook what to do with fakes. Without it, your real sign-up and reset emails are also more likely to land in spam.", fix: `Add a DMARC record at _dmarc.${apex}.`, ...P.dmarc(apex) });
|
|
721
|
+
const spfAll = await txt(apex);
|
|
722
|
+
if (!dmarc || !spfAll) unchecked.push(`the email records for ${apex}`);
|
|
723
|
+
const spf = spfAll?.filter((t) => /^v=spf1/i.test(t));
|
|
724
|
+
if (spf && (spf.length > 1 || spf.some((t) => /\+all\b/i.test(t))))
|
|
725
|
+
add({ id: "email:spf-broken", severity: "medium", where: `DNS for ${apex}`, title: `The email sender record for ${apex} is broken`, why: spf.length > 1 ? "The domain has more than one SPF record. Mail servers treat that as an error, so your emails can fail their checks." : "The SPF record ends in +all, which tells the world that anyone may send email as you.", fix: "Keep exactly one SPF record, ending in ~all or -all.", ...P.spf(apex) });
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
if (unchecked.length)
|
|
729
|
+
add({ id: "launch:unchecked", severity: "info", where: "this check", title: "A few things couldn't be checked this time", why: `Greenlit didn't get an answer about ${unchecked.join("; ")}. That is not the same as passing.`, fix: "Run the check again in a few minutes.", first: null, prompt: null });
|
|
730
|
+
|
|
731
|
+
if (!page.headers?.get("content-security-policy") && !/http-equiv=["']Content-Security-Policy/i.test(page.text))
|
|
732
|
+
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)) });
|
|
733
|
+
|
|
734
|
+
const csp = page.headers?.get("content-security-policy") || "";
|
|
487
735
|
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
|
|
736
|
+
if (!hostSetsHeaders)
|
|
491
737
|
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
738
|
}
|
|
493
739
|
|
|
@@ -505,7 +751,9 @@ export async function siteScan(target, { mine = false, fetcher = fetch, maxScrip
|
|
|
505
751
|
const incomplete = unread > 0 || cut > 0;
|
|
506
752
|
const verdict = ungraded
|
|
507
753
|
? "Not graded: Greenlit couldn't read this app's code."
|
|
508
|
-
: good &&
|
|
754
|
+
: good && tablesUntested && !dbBlind
|
|
755
|
+
? `Nothing serious in the ${incomplete ? "code Greenlit read" : "code"}. Some database tables couldn't be checked.`
|
|
756
|
+
: good && (dbBlind || supabasePartial)
|
|
509
757
|
? `Nothing serious in the ${incomplete ? "code Greenlit read" : "code"}. Your database tables weren't checked.`
|
|
510
758
|
: good && database && !mine
|
|
511
759
|
? `Nothing serious in the ${incomplete ? "code Greenlit read" : "code"}. Your database still needs checking.`
|
|
@@ -523,10 +771,12 @@ export async function siteScan(target, { mine = false, fetcher = fetch, maxScrip
|
|
|
523
771
|
mine,
|
|
524
772
|
scripts: bundles.length - 1,
|
|
525
773
|
scriptsUnread: unread,
|
|
526
|
-
supabase: supabase ? { project: supabase.ref, checked: Boolean(mine && tables && !dbBlind), tablesTested, tablesListed, readable: tables, functions: [...functions].slice(0, 50) } : null,
|
|
774
|
+
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,
|
|
527
775
|
firebase: firebase ? { project: firebase.project, checked: mine, readable: firebaseOpen } : null,
|
|
528
776
|
findings,
|
|
529
777
|
pasteInto: builder || "your AI app builder or coding agent",
|
|
778
|
+
// Only for the report endpoint, which looks for the owner's tag in the page.
|
|
779
|
+
...(wantPage && { page: page.text.slice(0, 200000) }),
|
|
530
780
|
};
|
|
531
781
|
}
|
|
532
782
|
|
|
@@ -535,7 +785,7 @@ export async function siteScan(target, { mine = false, fetcher = fetch, maxScrip
|
|
|
535
785
|
export function allPrompts(r) {
|
|
536
786
|
const list = r.findings.filter((f) => f.prompt);
|
|
537
787
|
if (!list.length) return "";
|
|
538
|
-
const head = `My app has ${list.length}
|
|
788
|
+
const head = `My app has ${list.length} problem${list.length > 1 ? "s" : ""} to fix. Work through them in this order, one at a time. After each one, tell me what you changed before moving on. Don't change anything unrelated.`;
|
|
539
789
|
return [head, ...list.map((f, i) => `${i + 1}. ${f.title}.\n${f.prompt}`)].join("\n\n");
|
|
540
790
|
}
|
|
541
791
|
|
package/src/mcp.mjs
CHANGED
|
@@ -1,23 +1,51 @@
|
|
|
1
1
|
// Greenlit as an MCP server (stdio, newline-delimited JSON-RPC), so an agent in Claude, Cursor or VS Code
|
|
2
2
|
// can grade the app it just deployed and apply the fix prompts itself.
|
|
3
3
|
import readline from "node:readline";
|
|
4
|
+
import { httpProbe } from "./node-probe.mjs";
|
|
4
5
|
import { siteScan, compare, allPrompts } from "./grade.mjs";
|
|
5
6
|
|
|
6
7
|
const TOOLS = [
|
|
7
8
|
{
|
|
8
9
|
name: "greenlit_check",
|
|
9
10
|
description:
|
|
10
|
-
"Grade a deployed web app (built with Lovable, Bolt, v0, Replit, Emergent or by hand) A to F for what a stranger can use against it: secret keys shipped in its JavaScript (Stripe, OpenAI, OpenRouter, Supabase secret keys and
|
|
11
|
+
"Grade a deployed web app (built with Lovable, Bolt, v0, Replit, Emergent or by hand) A to F for what a stranger can use against it: secret keys shipped in its JavaScript (Stripe, OpenAI, OpenRouter, Supabase secret keys and 28 more kinds), a Supabase service_role key in the browser, source maps, clickjacking and missing security headers, plus launch basics (developer-only addresses, Stripe test mode, a test email sender, no https redirect, open CORS, missing DMARC on a custom domain). Every finding has a plain-English reason and a fix prompt; `allFixes` has every fix in one prompt, worst first. Reads only what the site serves to every visitor. Call it again after a fix: `change` shows what got fixed. For the user's own app, have them run `npx greenlitlab <url> --mine`: it also checks which database tables and storage buckets anyone can read, open sign-up, and public .env or .git files.",
|
|
11
12
|
inputSchema: { type: "object", properties: { url: { type: "string", description: "The app's address, for example myapp.lovable.app" } }, required: ["url"], additionalProperties: false },
|
|
12
13
|
annotations: { readOnlyHint: true, openWorldHint: true },
|
|
13
14
|
},
|
|
15
|
+
{
|
|
16
|
+
name: "greenlit_scan",
|
|
17
|
+
description:
|
|
18
|
+
"Read a project folder on this computer for launch mistakes that can't be seen from outside, before deploying: Row Level Security policies whose condition is just `true`, tables created without RLS, Supabase edge functions with verify_jwt = false, Stripe webhook handlers that never verify the signature, secrets behind a public prefix (VITE_, NEXT_PUBLIC_), a tracked .env file, and an agent config with a writable database connection. Pattern-based, not a full code review. Reads names in .env files, never values. Each finding has a fix prompt.",
|
|
19
|
+
inputSchema: { type: "object", properties: { dir: { type: "string", description: "The project folder. Defaults to the current folder." } }, additionalProperties: false },
|
|
20
|
+
annotations: { readOnlyHint: true },
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
name: "greenlit_advisor",
|
|
24
|
+
description:
|
|
25
|
+
"Turn Supabase's Security or Performance Advisor results into plain-English findings with a fix prompt for each, worst first. Get the results from the Supabase MCP server's get_advisors tool (type \"security\") for the user's project, then pass them here as `lints`. This is the reliable way to learn which rules are too loose and whether strangers can change or delete data, which no outside check can see.",
|
|
26
|
+
inputSchema: { type: "object", properties: { lints: { description: "The advisor output: a list of lints, or the object that contains one." } }, required: ["lints"], additionalProperties: false },
|
|
27
|
+
annotations: { readOnlyHint: true },
|
|
28
|
+
},
|
|
29
|
+
{
|
|
30
|
+
name: "greenlit_questions",
|
|
31
|
+
description:
|
|
32
|
+
"Seven launch questions only the app's owner can answer (backups and restore, separate test database, hard spending limits, payment webhook checks, outage alerts, email sender, database plan). Call with no arguments to get the questions and options to ask the user. Call with `answers` ({questionId: optionKey}) to get, for each gap, the fact that makes it matter and a fix prompt. Answers are the owner's word, never graded.",
|
|
33
|
+
inputSchema: { type: "object", properties: { answers: { type: "object", description: "For example {\"backup\": \"no\", \"spend\": \"alerts\"}" } }, additionalProperties: false },
|
|
34
|
+
annotations: { readOnlyHint: true },
|
|
35
|
+
},
|
|
14
36
|
];
|
|
15
37
|
|
|
16
38
|
const last = new Map();
|
|
17
39
|
|
|
18
40
|
async function call(name, args = {}) {
|
|
41
|
+
if (name === "greenlit_scan") return (await import("./scan.mjs")).codeScan(args.dir || ".");
|
|
42
|
+
if (name === "greenlit_advisor") return (await import("./advisor.mjs")).fromAdvisor(args.lints);
|
|
43
|
+
if (name === "greenlit_questions") {
|
|
44
|
+
const { QUESTIONS, advise } = await import("./questions.mjs");
|
|
45
|
+
return args.answers ? { told: advise(args.answers), note: "The owner's own answers. Greenlit did not check them, and they don't change the app's grade." } : { questions: QUESTIONS };
|
|
46
|
+
}
|
|
19
47
|
if (name !== "greenlit_check") throw new Error(`unknown tool ${name}`);
|
|
20
|
-
const result = await siteScan(args.url, { mine: false });
|
|
48
|
+
const result = await siteScan(args.url, { mine: false, httpProbe });
|
|
21
49
|
// Remembered for this session only, so a second call shows what the fixes changed.
|
|
22
50
|
const change = compare(last.get(result.url), result);
|
|
23
51
|
last.set(result.url, { at: new Date().toISOString(), score: result.score, grade: result.grade, findings: result.findings.map(({ id, severity, title }) => ({ id, severity, title })) });
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// Node only. Asks for the plain-http address the way a browser's address bar does, and reports where it leads.
|
|
2
|
+
// Node's fetch adds headers of its own that some sites answer differently, so the CLI uses this instead.
|
|
3
|
+
import http from "node:http";
|
|
4
|
+
|
|
5
|
+
export const httpProbe = (url, timeout = 6000) =>
|
|
6
|
+
new Promise((resolve) => {
|
|
7
|
+
const req = http.get(url, { timeout, headers: { "user-agent": "greenlit (+https://greenlit.priberry.com)", accept: "text/html,*/*" } }, (res) => {
|
|
8
|
+
res.resume();
|
|
9
|
+
resolve({ status: res.statusCode, location: res.headers.location || "" });
|
|
10
|
+
});
|
|
11
|
+
req.on("timeout", () => req.destroy());
|
|
12
|
+
// A refused connection means nothing listens on plain http: reported as -1. Anything else is "no answer".
|
|
13
|
+
req.on("error", (e) => resolve({ status: e.code === "ECONNREFUSED" ? -1 : 0, location: "" }));
|
|
14
|
+
});
|
package/src/plain.mjs
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// A list of findings as text a person reads in a terminal. Used by the advisor, scan and questions commands.
|
|
2
|
+
const wrap = (s, w, pad) => {
|
|
3
|
+
const out = [];
|
|
4
|
+
for (const para of String(s).split("\n")) {
|
|
5
|
+
let line = "";
|
|
6
|
+
for (const word of para.split(" ")) {
|
|
7
|
+
if ((line + " " + word).trim().length > w) (out.push(pad + line.trim()), (line = word));
|
|
8
|
+
else line += " " + word;
|
|
9
|
+
}
|
|
10
|
+
out.push(pad + line.trim());
|
|
11
|
+
}
|
|
12
|
+
return out.join("\n");
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
export function renderList(heading, findings, { color = true, pasteInto = "your AI app builder or coding agent", empty = "Nothing found.", footer = "" } = {}) {
|
|
16
|
+
const k = (code) => (s) => (color ? `\x1b[${code}m${s}\x1b[0m` : s);
|
|
17
|
+
const red = k("31"), green = k("32"), yellow = k("33"), dim = k("2"), bold = k("1"), cyan = k("36");
|
|
18
|
+
const col = { critical: red, high: red, medium: yellow, low: dim, info: dim };
|
|
19
|
+
const L = ["", bold(heading), ""];
|
|
20
|
+
if (!findings.length) L.push(green(` ${empty}`), "");
|
|
21
|
+
let n = 0;
|
|
22
|
+
for (const f of findings) {
|
|
23
|
+
L.push(`${String(++n).padStart(2)}. ${col[f.severity](f.severity.toUpperCase().padEnd(8))} ${bold(f.title)}${f.where ? ` ${dim(`(${f.where})`)}` : ""}`);
|
|
24
|
+
L.push(wrap(f.why, 88, " "));
|
|
25
|
+
if (f.first) L.push(wrap(`${yellow("Do this yourself first:")} ${f.first}`, 88, " "));
|
|
26
|
+
if (f.prompt) {
|
|
27
|
+
L.push(` ${cyan(`Then paste this into ${pasteInto}:`)}`);
|
|
28
|
+
L.push(wrap(f.prompt, 84, ` ${dim("│")} `));
|
|
29
|
+
}
|
|
30
|
+
L.push("");
|
|
31
|
+
}
|
|
32
|
+
if (footer) L.push(dim(footer));
|
|
33
|
+
return L.join("\n");
|
|
34
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// What no check can see: seven things only the owner knows. Answers are never graded, because Greenlit can't
|
|
2
|
+
// verify them. Each "not yet" answer comes with the platform fact that makes it matter and a prompt or step to fix it.
|
|
3
|
+
export const QUESTIONS = [
|
|
4
|
+
{
|
|
5
|
+
id: "backup",
|
|
6
|
+
ask: "If your database were wiped tonight, could you get yesterday's data back?",
|
|
7
|
+
options: [
|
|
8
|
+
{ key: "yes", label: "Yes, and I've tried a restore", ok: true },
|
|
9
|
+
{ key: "auto", label: "The platform backs it up, I've never restored", ok: false, note: "A backup you have never restored is a hope, not a backup. Supabase's free plan keeps no automatic backups at all, and files in storage are never in database backups on any plan.", prompt: "Walk me through restoring my database from a backup into a separate test project, step by step for my provider, so I know it works. Don't touch the live database." },
|
|
10
|
+
{ key: "no", label: "No / I don't know", ok: false, note: "Supabase's free plan has no automatic backups, and free projects can be paused after a week of low activity. One bad AI edit or one deleted table is permanent.", prompt: "Set up a backup for my database that I control. If I'm on a free plan, give me a scheduled export (for Supabase: a pg_dump run from a GitHub Action to private storage, with the connection string kept in a secret). Tell me how to restore from it, and remind me which files in storage are not included." },
|
|
11
|
+
],
|
|
12
|
+
},
|
|
13
|
+
{
|
|
14
|
+
id: "separate",
|
|
15
|
+
ask: "Can your AI builder or coding agent change the live database directly?",
|
|
16
|
+
options: [
|
|
17
|
+
{ key: "no", label: "No, it works on a separate test database", ok: true },
|
|
18
|
+
{ key: "yes", label: "Yes, there is only one database", ok: false, note: "In July 2025 an AI agent deleted a company's production database during a code freeze, because test and live shared one database. The platform's fix was to separate them.", prompt: "Set up a separate development database for this app, so that changes are tried there first and the live database is only changed by a reviewed migration. Make sure you (the AI) hold no credentials that can delete or reset the live database, and tell me how to confirm that." },
|
|
19
|
+
{ key: "unsure", label: "I don't know", ok: false, note: "If you can't tell, assume there is only one. Ask your builder: \"Do preview and live use the same database?\"", prompt: "Tell me whether my preview/development environment and my live app use the same database, and whether you can run destructive commands (drop, truncate, reset) on the live one. Change nothing." },
|
|
20
|
+
],
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
id: "spend",
|
|
24
|
+
ask: "Is there a hard monthly spending limit on every paid service (AI, email, SMS, hosting)?",
|
|
25
|
+
options: [
|
|
26
|
+
{ key: "yes", label: "Yes, hard limits everywhere", ok: true },
|
|
27
|
+
{ key: "alerts", label: "Only alerts, no hard limit", ok: false, note: "An alert tells you after the money is gone. A three-person team reported an $82,314 AI bill in about 48 hours after a key was stolen. Firebase's own checklist warns that budget alerts don't cap spending.", prompt: "List every paid service my app uses (AI providers, email, SMS, hosting, database). For each, tell me exactly where to set a hard monthly limit or usage cap in its dashboard, and what happens to my app when the cap is reached." },
|
|
28
|
+
{ key: "no", label: "No / I don't know", ok: false, note: "One leaked key or one loop can spend without limit. Set a hard cap in each provider's billing page (OpenAI: Limits; Anthropic: spend limits; Google Cloud: quotas, not just budgets).", prompt: "List every paid service my app uses (AI providers, email, SMS, hosting, database). For each, tell me exactly where to set a hard monthly limit or usage cap in its dashboard, and what happens to my app when the cap is reached. Then add a per-user daily limit in my backend for every AI and email call." },
|
|
29
|
+
],
|
|
30
|
+
},
|
|
31
|
+
{
|
|
32
|
+
id: "payments",
|
|
33
|
+
ask: "If you take payments: does your server check that payment messages really come from the payment company?",
|
|
34
|
+
options: [
|
|
35
|
+
{ key: "na", label: "I don't take payments", ok: true },
|
|
36
|
+
{ key: "yes", label: "Yes, signatures are verified and live mode is set up", ok: true },
|
|
37
|
+
{ key: "no", label: "No / I don't know", ok: false, note: "Without signature checks anyone can send your app a fake \"payment succeeded\" message and unlock paid features. Stripe's go-live checklist also requires a webhook registered for the live address with its own signing secret.", prompt: "Check my payment integration and change nothing yet. Tell me: does the webhook handler verify the Stripe-Signature header using the raw request body and the signing secret from a server secret; is \"paid\" decided on the server from that verified message and never from the browser; and is a webhook registered in live mode for my live address? Then fix whatever fails and list what you changed." },
|
|
38
|
+
],
|
|
39
|
+
},
|
|
40
|
+
{
|
|
41
|
+
id: "down",
|
|
42
|
+
ask: "If the app went down right now, would you know within an hour?",
|
|
43
|
+
options: [
|
|
44
|
+
{ key: "yes", label: "Yes, something alerts me", ok: true },
|
|
45
|
+
{ key: "no", label: "No, I'd hear it from users", ok: false, note: "Free uptime monitors check every few minutes and email you. Without one, most small apps learn about outages from an angry message.", prompt: "Add a simple health check address to my app that returns OK only when the app can reach its database. Then tell me how to point a free uptime monitor at it so I get an email when it fails, and add error tracking so I see errors my users hit." },
|
|
46
|
+
],
|
|
47
|
+
},
|
|
48
|
+
{
|
|
49
|
+
id: "email",
|
|
50
|
+
ask: "Which address do your sign-up and password-reset emails come from?",
|
|
51
|
+
options: [
|
|
52
|
+
{ key: "own", label: "An address on my own domain, through an email service", ok: true },
|
|
53
|
+
{ key: "none", label: "The app sends no email", ok: true },
|
|
54
|
+
{ key: "builtin", label: "The platform's built-in sender / I never set it up", ok: false, note: "Supabase's built-in email is for testing: about 2 messages an hour, and only to members of your own project team. Real users won't get their confirmation or reset emails.", prompt: "Set up real email sending for my app's sign-up and password-reset messages: connect an email service (such as Resend) as custom SMTP in my auth settings, send from an address on my own domain, and tell me exactly which DNS records (SPF, DKIM, DMARC) to add at my domain provider. Then tell me how to test that a reset email arrives." },
|
|
55
|
+
],
|
|
56
|
+
},
|
|
57
|
+
{
|
|
58
|
+
id: "plan",
|
|
59
|
+
ask: "Is your database on a free plan?",
|
|
60
|
+
options: [
|
|
61
|
+
{ key: "paid", label: "No, a paid plan", ok: true },
|
|
62
|
+
{ key: "free", label: "Yes, free", ok: false, note: "Fine for building. For a launch, know the limits: Supabase may pause a free project after a week of low activity, keeps no automatic backups, and caps connections. A busy launch day can hit those.", prompt: "Tell me which limits of my database's free plan my app is most likely to hit after launch (pausing, backups, connections, storage, bandwidth, email), how I would notice each, and what the cheapest plan that removes them costs." },
|
|
63
|
+
{ key: "unsure", label: "I don't know", ok: false, note: "Check the billing page of your database provider. On a free plan there are usually no automatic backups.", prompt: "Tell me which plan my database is on and what its limits are. Change nothing." },
|
|
64
|
+
],
|
|
65
|
+
},
|
|
66
|
+
];
|
|
67
|
+
|
|
68
|
+
export function advise(answers = {}) {
|
|
69
|
+
return QUESTIONS.map((q) => {
|
|
70
|
+
const o = q.options.find((o) => o.key === answers[q.id]);
|
|
71
|
+
return { id: q.id, ask: q.ask, answer: o?.label || null, ok: o ? o.ok : null, note: o?.note || null, prompt: o?.prompt || null };
|
|
72
|
+
});
|
|
73
|
+
}
|
package/src/scan.mjs
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
// greenlit scan [folder]: reads a project's own files, on your computer, for the launch mistakes that can't be
|
|
2
|
+
// seen from outside: rules that let everyone in, functions that skip the sign-in check, payment messages nobody
|
|
3
|
+
// verifies, secrets named so they ship to the browser. Node only. Reads names in .env files, never values.
|
|
4
|
+
import fs from "node:fs";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { execFileSync } from "node:child_process";
|
|
7
|
+
|
|
8
|
+
// Build output, dependencies, agents' working copies, and tests (whose made-up secrets and tables aren't the app's).
|
|
9
|
+
const SKIP = new Set(["node_modules", ".claude", "worktrees", "__tests__", "__mocks__", "__fixtures__", "fixtures", "test", "tests", "e2e", "cypress", ".git", "dist", "build", ".next", ".vercel", ".netlify", ".wrangler", "coverage", ".turbo", ".cache", "vendor", "__pycache__", ".venv"]);
|
|
10
|
+
const TEXT = /\.(sql|toml|json|js|jsx|ts|tsx|mjs|cjs|py|vue|svelte)$|(^|\/)\.env[^/]*$/;
|
|
11
|
+
const PUBLIC_PREFIX = "(?:VITE_|NEXT_PUBLIC_|REACT_APP_|EXPO_PUBLIC_|PUBLIC_|NUXT_PUBLIC_)";
|
|
12
|
+
// The name must END in the secret word (or _KEY/_TOKEN after it): VITE_STRIPE_SECRET_KEY is a secret,
|
|
13
|
+
// VITE_PASSWORD_MIN_LENGTH and VITE_WEBHOOK_URL are settings.
|
|
14
|
+
const SECRET_NAME = new RegExp(`\\b(${PUBLIC_PREFIX}[A-Z0-9_]*?(?:SECRET(?:_KEY|_TOKEN)?|SERVICE_ROLE(?:_KEY)?|PRIVATE_KEY|PASSWORD|DATABASE_URL))(?![A-Z0-9_])`, "g");
|
|
15
|
+
// A key for a paid service behind a public prefix (VITE_OPENAI_API_KEY) is the same mistake under another name.
|
|
16
|
+
const PAID_KEY_NAME = new RegExp(`\\b(${PUBLIC_PREFIX}[A-Z0-9_]*?(?:OPENAI|ANTHROPIC|CLAUDE|GEMINI|GROQ|OPENROUTER|MISTRAL|PERPLEXITY|REPLICATE|HUGGINGFACE|RESEND|SENDGRID|MAILGUN|TWILIO|GITHUB)[A-Z0-9_]*?(?:KEY|TOKEN))(?![A-Z0-9_])`, "g");
|
|
17
|
+
// A table or policy target the way SQL writes it: orders, public.orders, "public"."orders".
|
|
18
|
+
const IDENT = String.raw`(?:"?(\w+)"?\s*\.\s*)?"?(\w+)"?`;
|
|
19
|
+
// Comments blanked out, keeping every character's position so line numbers stay right.
|
|
20
|
+
// Text inside single quotes is blanked too: it is data or SQL run later, not a statement in this file.
|
|
21
|
+
// Double-quoted names are matched first and kept as they are, so an apostrophe in a policy's name ("Users can't …") starts nothing.
|
|
22
|
+
const noComments = (sql) => sql.replace(/"(?:[^"]|"")*"|'(?:[^']|'')*'|\/\*[\s\S]*?\*\/|--[^\n]*/g, (m) => (m[0] === '"' ? m : m[0] === "'" ? `'${m.slice(1, -1).replace(/[^\n]/g, " ")}'` : m.replace(/[^\n]/g, " ")));
|
|
23
|
+
|
|
24
|
+
function walk(root, max = 5000) {
|
|
25
|
+
const out = [];
|
|
26
|
+
const stack = [root];
|
|
27
|
+
while (stack.length && out.length < max) {
|
|
28
|
+
const dir = stack.pop();
|
|
29
|
+
let entries = [];
|
|
30
|
+
try {
|
|
31
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
32
|
+
} catch {}
|
|
33
|
+
for (const e of entries) {
|
|
34
|
+
const full = path.join(dir, e.name);
|
|
35
|
+
if (e.isDirectory()) !SKIP.has(e.name) && stack.push(full);
|
|
36
|
+
else if (e.isFile() && TEXT.test(full.split(path.sep).join("/"))) out.push(full);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return out;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const lineOf = (text, index) => text.slice(0, index).split("\n").length;
|
|
43
|
+
|
|
44
|
+
export function codeScan(dir = ".") {
|
|
45
|
+
const root = path.resolve(dir);
|
|
46
|
+
if (!fs.existsSync(root) || !fs.statSync(root).isDirectory()) throw new Error(`"${dir}" isn't a folder`);
|
|
47
|
+
// In name order, which for migrations is the order they ran in: a later file can undo an earlier one.
|
|
48
|
+
const files = walk(root).sort();
|
|
49
|
+
const rel = (f) => path.relative(root, f).split(path.sep).join("/");
|
|
50
|
+
const findings = [];
|
|
51
|
+
const add = (f) => findings.some((x) => x.id === f.id) || findings.push(f);
|
|
52
|
+
const created = new Map(); // table -> where it was created
|
|
53
|
+
const protectedTables = new Set();
|
|
54
|
+
const publicRead = { everyone: [], "every signed-in user": [] };
|
|
55
|
+
let dynamicRls = false;
|
|
56
|
+
// Open policies still standing after every migration: a later "drop policy" or "drop table" removes one.
|
|
57
|
+
const openPolicies = new Map();
|
|
58
|
+
|
|
59
|
+
for (const file of files) {
|
|
60
|
+
const name = rel(file);
|
|
61
|
+
let text = "";
|
|
62
|
+
try {
|
|
63
|
+
if (fs.statSync(file).size > 1024 * 1024) continue;
|
|
64
|
+
text = fs.readFileSync(file, "utf8");
|
|
65
|
+
} catch {
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
if (/\.(test|spec)\.[a-z]+$/i.test(name)) continue;
|
|
69
|
+
const isEnv = /(^|\/)\.env[^/]*$/.test(name);
|
|
70
|
+
|
|
71
|
+
// Names only: a secret behind a public prefix is copied into the code every visitor downloads.
|
|
72
|
+
for (const m of [...text.matchAll(SECRET_NAME), ...text.matchAll(PAID_KEY_NAME)]) {
|
|
73
|
+
if (isEnv && !new RegExp(`^\\s*(?:export\\s+)?${m[1]}\\s*=`, "m").test(text)) continue;
|
|
74
|
+
add({ id: `scan:public-secret:${m[1]}`, severity: "critical", where: `${name}:${lineOf(text, m.index)}`, title: `The secret ${m[1]} is named so it ships to the browser`, why: "Anything whose name starts with a public prefix (VITE_, NEXT_PUBLIC_ and the like) is copied into the JavaScript every visitor downloads. A secret there is public.", fix: "Rename it without the public prefix and use it only in backend code.", first: "Treat this key as leaked if the app has ever been deployed with it: revoke it and make a new one.", prompt: `My project has a secret named ${m[1]}. The public prefix means it is built into the frontend, where anyone can read it. Rename it without the prefix, move every use of it into backend code (an edge function or server route) that checks the user is signed in, and confirm it no longer appears anywhere in the frontend build. List the files you changed.` });
|
|
75
|
+
}
|
|
76
|
+
if (isEnv) continue;
|
|
77
|
+
|
|
78
|
+
if (name.endsWith(".sql")) {
|
|
79
|
+
const sql = noComments(text);
|
|
80
|
+
// What this file does, in the order it does it.
|
|
81
|
+
const events = [];
|
|
82
|
+
// Protection switched on in a loop: foreach t in array['a','b'] loop execute format('alter table … enable row level security', t).
|
|
83
|
+
// The names are inside quotes, so they are read from the file as written.
|
|
84
|
+
for (const m of text.matchAll(/foreach\s+\w+\s+in\s+array\s+(?:array\s*)?\[([^\]]*)\]\s*loop([\s\S]*?)end\s+loop/gi))
|
|
85
|
+
if (/enable\s+row\s+level\s+security/i.test(m[2])) for (const n of m[1].matchAll(/'([\w.]+)'/g)) protectedTables.add(n[1].replace(/^public\./i, "").toLowerCase());
|
|
86
|
+
// Any other statement built at run time that turns it on: the tables it covers can't be known from the file.
|
|
87
|
+
if (/execute\b[\s\S]{0,300}?enable\s+row\s+level\s+security/i.test(text)) dynamicRls = true;
|
|
88
|
+
for (const m of sql.matchAll(new RegExp(String.raw`create\s+(?:unlogged\s+)?table\s+(?:if\s+not\s+exists\s+)?${IDENT}`, "gi"))) {
|
|
89
|
+
// Only the public schema is reachable with the app's public key.
|
|
90
|
+
if ((m[1] || "public").toLowerCase() !== "public") continue;
|
|
91
|
+
const table = m[2].toLowerCase();
|
|
92
|
+
const at = `${name}:${lineOf(sql, m.index)}`;
|
|
93
|
+
events.push({ i: m.index, run: () => created.has(table) || created.set(table, at) });
|
|
94
|
+
}
|
|
95
|
+
for (const m of sql.matchAll(new RegExp(String.raw`alter\s+table\s+(?:if\s+exists\s+)?(?:only\s+)?${IDENT}\s+enable\s+row\s+level\s+security`, "gi"))) if ((m[1] || "public").toLowerCase() === "public") protectedTables.add(m[2].toLowerCase());
|
|
96
|
+
// The policy's own name is skipped first: it is free text and often contains the word "on".
|
|
97
|
+
const policyKey = (schema, table, policy) => `${(schema || "public").toLowerCase()}.${table.toLowerCase()}|${policy.replace(/"/g, "").toLowerCase()}`;
|
|
98
|
+
for (const m of sql.matchAll(new RegExp(String.raw`(?:drop|alter)\s+policy\s+(?:if\s+exists\s+)?("[^"]*"|\w+)\s+on\s+${IDENT}`, "gi"))) {
|
|
99
|
+
const key = policyKey(m[2], m[3], m[1]);
|
|
100
|
+
events.push({ i: m.index, run: () => openPolicies.delete(key) });
|
|
101
|
+
}
|
|
102
|
+
for (const m of sql.matchAll(new RegExp(String.raw`drop\s+table\s+(?:if\s+exists\s+)?${IDENT}`, "gi"))) {
|
|
103
|
+
const gone = `${(m[1] || "public").toLowerCase()}.${m[2].toLowerCase()}|`;
|
|
104
|
+
events.push({ i: m.index, run: () => {
|
|
105
|
+
if ((m[1] || "public").toLowerCase() === "public") created.delete(m[2].toLowerCase());
|
|
106
|
+
for (const k of [...openPolicies.keys()]) if (k.startsWith(gone)) openPolicies.delete(k);
|
|
107
|
+
} });
|
|
108
|
+
}
|
|
109
|
+
for (const full of sql.matchAll(new RegExp(String.raw`create\s+policy\s+("[^"]*"|\w+)\s+on\s+${IDENT}([^;]*);`, "gi"))) {
|
|
110
|
+
const m = [full[0], full[2], full[3], full[4]];
|
|
111
|
+
m.index = full.index;
|
|
112
|
+
const key = policyKey(full[2], full[3], full[1]);
|
|
113
|
+
const rest = m[3];
|
|
114
|
+
if (!/(?:using|with\s+check)\s*\(+\s*true\s*\)+/i.test(rest)) continue;
|
|
115
|
+
// Policies in a private schema open nothing to the app's public key; storage is named in full.
|
|
116
|
+
const schema = (m[1] || "public").toLowerCase();
|
|
117
|
+
if (schema !== "public" && schema !== "storage") continue;
|
|
118
|
+
const roles = (rest.match(/\bto\s+([\w\s,"]+?)(?=\s+(?:using|with)\b|$)/i) || [, ""])[1].toLowerCase();
|
|
119
|
+
// The service role skips every rule anyway; a policy for it alone opens nothing.
|
|
120
|
+
if (/service_role/.test(roles) && !/anon|authenticated|public/.test(roles)) continue;
|
|
121
|
+
const table = schema === "public" ? m[2].toLowerCase() : `${schema}.${m[2].toLowerCase()}`;
|
|
122
|
+
const action = (rest.match(/\bfor\s+(select|insert|update|delete|all)\b/i) || [, "all"])[1].toLowerCase();
|
|
123
|
+
const toAuthed = /authenticated/.test(roles) && !/anon|public/.test(roles);
|
|
124
|
+
const who = toAuthed ? "every signed-in user" : "everyone";
|
|
125
|
+
const where = `${name}:${lineOf(sql, m.index)}`;
|
|
126
|
+
// Reading a whole table is often meant (products, courses), so those are gathered into one question below.
|
|
127
|
+
if (action === "select") {
|
|
128
|
+
events.push({ i: m.index, run: () => openPolicies.set(key, () => publicRead[who].some((t) => t.table === table) || publicRead[who].push({ table, where })) });
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
// Adding rows is right for a contact form, a waitlist or a log. Changing and deleting rarely is.
|
|
132
|
+
const addOnly = action === "insert";
|
|
133
|
+
const finding = { id: `scan:policy-true:${table}:${action}`, severity: addOnly ? "medium" : "high", where, title: `A rule lets ${who} ${action === "all" ? "read, change and delete" : addOnly ? "add" : action} rows in "${table}"`, why: `The policy's condition is simply "true", so Row Level Security is on but checks nothing for this action.${addOnly ? " That is right for a contact form, a waitlist or a log, and a problem if anything in the app trusts what is in this table." : ""}`, fix: "Compare auth.uid() with the row's owner column instead of using true.", first: null, prompt: `In my database, a Row Level Security policy on "${table}" for ${action} uses the condition true, so ${toAuthed ? "any signed-in user" : "anyone"} passes it. ${addOnly ? `Tell me first whether "${table}" is meant to take rows from ${toAuthed ? "any signed-in user" : "strangers"} (a form, a waitlist, a log). If it is, keep it but make sure the new row can't claim to belong to someone else (set the owner column from auth.uid(), never from the request) and can't be flooded. If it isn't, rewrite` : "Rewrite"} it so a user can only ${action === "all" ? "reach" : action} their own rows (auth.uid() = the owner column; add that column if it's missing). Write this as a new migration, don't edit old ones, and show me the SQL.` };
|
|
134
|
+
events.push({ i: m.index, run: () => openPolicies.set(key, () => add(finding)) });
|
|
135
|
+
}
|
|
136
|
+
for (const e of events.sort((a, b) => a.i - b.i)) e.run();
|
|
137
|
+
if (/(^|\/)migrations\//.test(name)) {
|
|
138
|
+
const d = sql.match(/^\s*(drop\s+table|truncate)\b[^;]*;/im);
|
|
139
|
+
if (d) add({ id: `scan:destructive:${name}`, severity: "low", where: `${name}:${lineOf(sql, d.index)}`, title: "A migration deletes data", why: `It contains "${d[0].trim().slice(0, 60)}". Run against the live database, that data is gone unless you have a backup.`, fix: "Make sure a backup exists before this runs on the live database.", first: null, prompt: `My migration ${name} contains a statement that deletes data (${d[1].toLowerCase()}). Tell me exactly what would be lost if it runs on the live database, whether that is intended, and how to back up that data first. Change nothing.` });
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
if (/(^|\/)supabase\/config\.toml$/.test(name)) {
|
|
144
|
+
for (const m of text.matchAll(/\[functions\.([\w-]+)\][^\[]*?verify_jwt\s*=\s*false/g))
|
|
145
|
+
add({ id: `scan:verify-jwt:${m[1]}`, severity: "high", where: `${name}:${lineOf(text, m.index)}`, title: `The function "${m[1]}" skips the sign-in check`, why: "verify_jwt = false means anyone on the internet can call this function. That is right only for webhooks that check a signature themselves.", fix: "Remove verify_jwt = false, or verify a signature inside the function.", first: null, prompt: `My Supabase edge function "${m[1]}" has verify_jwt = false, so anyone can call it. If it is a webhook, make it verify the sender's signature before doing anything. Otherwise remove that setting and make the function check the signed-in user and what they are allowed to do. Show me what you changed.` });
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
if (/webhook/i.test(name) && /\.(js|ts|mjs|tsx|py)$/.test(name) && /stripe/i.test(text) && !/constructEvent|construct_event|stripe-signature/i.test(text))
|
|
149
|
+
add({ id: `scan:webhook:${name}`, severity: "medium", where: name, title: "Greenlit couldn't see a signature check in this payment webhook", why: "This file handles Stripe messages but never mentions the Stripe-Signature header or constructEvent. If the check isn't done in another file it calls, anyone can send a fake \"payment succeeded\" message.", fix: "Verify the signature with stripe.webhooks.constructEvent and the signing secret.", first: null, prompt: `My Stripe webhook handler in ${name} doesn't verify the Stripe-Signature header. Change it to read the raw request body and call stripe.webhooks.constructEvent (constructEventAsync on edge runtimes) with the signing secret from a server secret, reject anything that fails with a 400, and only then act on the event. Show me the change.` });
|
|
150
|
+
|
|
151
|
+
if (/(^|\/)(\.mcp\.json|\.cursor\/mcp\.json|\.vscode\/mcp\.json)$/.test(name) && (/postgres(?:ql)?:\/\//i.test(text) || (/supabase/i.test(text) && !/read[-_]only/i.test(text))))
|
|
152
|
+
add({ id: `scan:agent-db:${name}`, severity: "medium", where: name, title: "Your coding agent can change your database", why: "This agent configuration gives the AI a database connection that isn't read-only. An agent has deleted a production database this way.", fix: "Use the read-only mode, and point the agent at a development database.", first: null, prompt: `My agent configuration in ${name} gives you a database connection that can write. Tell me how to change it to read-only and scoped to a development project (for the Supabase MCP server: the read-only and project-ref options), and whether the live database is reachable with it today. Change nothing until I confirm.` });
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
if (files.some((f) => /(^|\/)supabase\//.test(rel(f))))
|
|
156
|
+
for (const [table, where] of created)
|
|
157
|
+
if (!protectedTables.has(table) && dynamicRls)
|
|
158
|
+
add({ id: `scan:no-rls:${table}`, severity: "medium", where, title: `Greenlit couldn't see Row Level Security being turned on for "${table}"`, why: "Your migrations switch it on for some tables with a statement built while it runs, and Greenlit can't tell which tables that covers. This one may be protected.", fix: "Check it in Supabase → Advisors → Security Advisor, or run npx greenlitlab <your app> --mine.", first: null, prompt: `Tell me whether Row Level Security is enabled on the table "${table}" in my database, and which statement enables it. Change nothing.` });
|
|
159
|
+
else if (!protectedTables.has(table))
|
|
160
|
+
add({ id: `scan:no-rls:${table}`, severity: "high", where, title: `The table "${table}" is created without Row Level Security`, why: "No migration turns Row Level Security on for it. If the app's public key can reach the table, every row is readable. (If you turned it on in the dashboard instead, the live database may be fine: check with npx greenlitlab <your app> --mine.)", fix: `Add: alter table public.${table} enable row level security; plus a policy for the owner.`, first: null, prompt: `My migrations create the table "${table}" but never enable Row Level Security on it. Write a new migration that enables it and adds policies so a signed-in user reaches only their own rows (auth.uid() = the owner column; add one if needed). If the table is meant to be public to read, say so and add a read-only policy. Show me the SQL.` });
|
|
161
|
+
|
|
162
|
+
try {
|
|
163
|
+
const tracked = execFileSync("git", ["-C", root, "ls-files"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).split("\n");
|
|
164
|
+
const env = tracked.find((f) => /(^|\/)\.env(\.local|\.production)?$/.test(f));
|
|
165
|
+
if (env) add({ id: "scan:env-tracked", severity: "high", where: env, title: `Your ${env} file is saved in version control`, why: "Everyone with access to the repository, now or later, has every key in it. If the repository is public, so does the world.", fix: "Remove it from git, add it to .gitignore, and replace the keys it held.", first: "Replace every key in that file: once committed, a key stays in the history.", prompt: `My ${env} file is tracked by git. Remove it from version control without deleting my local copy (git rm --cached), add it to .gitignore, and give me an .env.example with the names only. Then list every key that was in it so I can replace each one.` });
|
|
166
|
+
} catch {}
|
|
167
|
+
|
|
168
|
+
for (const emit of openPolicies.values()) emit();
|
|
169
|
+
for (const [who, list] of Object.entries(publicRead)) {
|
|
170
|
+
if (!list.length) continue;
|
|
171
|
+
const names = list.map((t) => t.table);
|
|
172
|
+
add({ id: `scan:public-read:${who === "everyone" ? "everyone" : "signed-in"}`, severity: "medium", where: list[0].where, title: `${list.length} table${list.length > 1 ? "s" : ""} can be read in full by ${who}`, why: `${names.slice(0, 15).join(", ")}${names.length > 15 ? ` and ${names.length - 15} more` : ""}. Each has a policy whose condition is simply "true". That is fine for a public list such as products or courses, and a leak for anything about people.`, fix: "Go through the list: keep the ones that are meant to be public, and limit the rest to the row's owner.", first: null, prompt: `These tables in my database have a read policy with the condition true, so ${who === "everyone" ? "anyone on the internet" : "any signed-in user"} can read every row: ${names.join(", ")}. Go through them one by one and tell me, for each, whether it holds anything about a specific person (names, emails, messages, payments, activity). Change nothing yet. Then list the ones you would restrict to the row's owner, and wait for my OK.` });
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// A lockfile only matters when there is something to lock.
|
|
176
|
+
let hasDeps = false;
|
|
177
|
+
try {
|
|
178
|
+
const pkg = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8"));
|
|
179
|
+
hasDeps = Object.keys({ ...pkg.dependencies, ...pkg.devDependencies }).length > 0;
|
|
180
|
+
} catch {}
|
|
181
|
+
if (hasDeps && !["package-lock.json", "pnpm-lock.yaml", "yarn.lock", "bun.lockb", "bun.lock"].some((f) => fs.existsSync(path.join(root, f))))
|
|
182
|
+
add({ id: "scan:no-lockfile", severity: "low", where: "package.json", title: "No lockfile", why: "Without a lockfile every build may install different versions of your dependencies, so the app you tested isn't the app you ship.", fix: "Commit the lockfile your package manager creates.", first: null, prompt: "My project has no lockfile. Run the install for the package manager this project uses, commit the lockfile it creates, and make the build use it." });
|
|
183
|
+
|
|
184
|
+
const order = ["critical", "high", "medium", "low", "info"];
|
|
185
|
+
findings.sort((a, b) => order.indexOf(a.severity) - order.indexOf(b.severity));
|
|
186
|
+
return { source: "your project's files", dir: root, files: files.length, findings };
|
|
187
|
+
}
|