greenlitlab 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,20 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.0 (8 November 2026)
4
+
5
+ - 18 more kinds of leaked keys: Supabase secret keys (sb_secret_) and access tokens, OpenRouter, xAI, Perplexity, Hugging Face, Replicate, Pinecone, GitLab, npm, Shopify, Brevo, Mailchimp, Mailgun, Telegram bots, secret Mapbox tokens, private keys and Google service-account JSON. `sk_live_` keys are named for Stripe, Clerk and similar.
6
+ - Clickjacking: flags a site any other site can put in a frame.
7
+ - With `--mine`: Supabase sign-up open to anyone without email confirmation (which turns "signed-in only" rules into "anyone"), storage buckets that list files to anyone, and public `.env` files or `.git` folders. Hosts that answer every path with the home page don't count.
8
+ - "Copy all fixes": every fix prompt in one, worst first, on the web, with `--prompt all`, and as `allFixes` in the MCP tool.
9
+
10
+ ## 0.1.1 (8 November 2026)
11
+
12
+ - Hosts that answer every missing file with the home page (Lovable, Netlify, Vercel) are no longer reported as publishing source maps.
13
+ - Using a database is a note, not a problem: it costs no points.
14
+ - A broken script address in a page, or a huge file, no longer stops or slows the check. Scripts load six at a time.
15
+ - The web check keeps results and visitor limits in Cloudflare's cache, so a busy day can't use up the free plan's storage writes. Errors are in plain words.
16
+ - Clear error for anything that isn't a web address.
17
+
3
18
  ## 0.1.0 (8 November 2026)
4
19
 
5
20
  First release. Greenlit grew out of `crumple site` and is now its own product.
package/README.md CHANGED
@@ -14,14 +14,17 @@ npx greenlitlab myapp.lovable.app
14
14
 
15
15
  | Check | Where it runs |
16
16
  |---|---|
17
- | Secret keys (Stripe, OpenAI, AWS, GitHub and more) in the JavaScript every visitor downloads | everywhere |
17
+ | Secret keys in the JavaScript every visitor downloads: 30 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
- | Missing security headers (CSP, framing) | everywhere |
20
+ | Clickjacking (no `frame-ancestors` or `X-Frame-Options`) and no Content-Security-Policy | everywhere |
21
21
  | Supabase tables anyone can read with the public key | your own app, `--mine` |
22
+ | Supabase storage buckets that list their files to anyone | your own app, `--mine` |
23
+ | Supabase sign-up open to anyone without email confirmation | your own app, `--mine` |
24
+ | A public `.env` file or `.git` folder | your own app, `--mine` |
22
25
  | Firebase Realtime Database and Firestore open to everyone | your own app, `--mine` |
23
26
 
24
- The database checks ask for a row count (Supabase) or one document name (Firebase), never for data. They run only when you say the app is yours, because testing someone else's database without permission isn't OK.
27
+ 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.
25
28
 
26
29
  ## Commands
27
30
 
@@ -29,6 +32,7 @@ The database checks ask for a row count (Supabase) or one document name (Firebas
29
32
  npx greenlitlab <url> # grade an app
30
33
  npx greenlitlab <url> --mine # your own app: database checks too
31
34
  npx greenlitlab <url> --prompt 1 # print fix prompt 1 only (pipe it to pbcopy)
35
+ npx greenlitlab <url> --prompt all # every fix in one prompt, worst first
32
36
  npx greenlitlab <url> --json # the full result
33
37
  npx greenlitlab <url> --fail-on high # exit 1 if anything this serious is found, for CI
34
38
  ```
@@ -40,7 +44,7 @@ The last result for each app is kept in `~/.greenlit/sites/` (grade, finding ids
40
44
  Add Greenlit as an MCP server:
41
45
 
42
46
  ```json
43
- { "mcpServers": { "greenlit": { "command": "npx", "args": ["-y", "greenlitlab@0.1.0", "mcp"] } } }
47
+ { "mcpServers": { "greenlit": { "command": "npx", "args": ["-y", "greenlitlab@0.2.0", "mcp"] } } }
44
48
  ```
45
49
 
46
50
  Then ask your agent to check the app it just deployed and apply the fixes. The `greenlit_check` tool returns the grade, every finding and its fix prompt.
package/bin/greenlit.mjs CHANGED
@@ -8,7 +8,7 @@ import fs from "node:fs";
8
8
  import path from "node:path";
9
9
  import { parseArgs } from "node:util";
10
10
  import { fileURLToPath } from "node:url";
11
- import { siteScan, compare, renderSite } from "../src/grade.mjs";
11
+ import { siteScan, compare, renderSite, allPrompts } from "../src/grade.mjs";
12
12
  import { SEVERITY } from "../src/severity.mjs";
13
13
  import { loadLast, saveRun } from "../src/history.mjs";
14
14
 
@@ -20,6 +20,7 @@ const HELP = `greenlit ${VERSION}: is your AI-built app safe to launch?
20
20
  npx greenlitlab <url> grade an app from what every visitor can see
21
21
  npx greenlitlab <url> --mine your own app: also check which database tables anyone can read
22
22
  npx greenlitlab <url> --prompt 1 print just fix prompt 1, to copy (add | pbcopy on a Mac)
23
+ npx greenlitlab <url> --prompt all every fix in one prompt, worst first
23
24
  npx greenlitlab <url> --json the full result as JSON
24
25
  npx greenlitlab <url> --fail-on high exit 1 if anything this serious is found (for CI)
25
26
  npx greenlitlab mcp run as an MCP server
@@ -71,7 +72,14 @@ if (opt.version) {
71
72
  }
72
73
  if (timer) (clearInterval(timer), process.stderr.write("\r\x1b[K"));
73
74
 
74
- if (opt.prompt) {
75
+ if (opt.prompt === "all") {
76
+ const all = allPrompts(result);
77
+ if (!all) {
78
+ console.error("greenlit: nothing to fix here.");
79
+ process.exit(2);
80
+ }
81
+ console.log(all);
82
+ } else if (opt.prompt) {
75
83
  const withPrompt = result.findings.filter((f) => f.prompt);
76
84
  const p = withPrompt[Number(opt.prompt) - 1];
77
85
  if (!p) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "greenlitlab",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Is your AI-built app safe to launch? A grade from A to F for apps built with Lovable, Bolt, v0, Replit or Emergent, with a fix prompt for every problem.",
5
5
  "type": "module",
6
6
  "bin": {
package/server.json CHANGED
@@ -5,12 +5,12 @@
5
5
  "description": "Grade apps built with Lovable, Bolt, v0 or Replit A to F, with a fix prompt for every problem.",
6
6
  "websiteUrl": "https://greenlit.priberry.com",
7
7
  "repository": { "url": "https://github.com/priberry-data/greenlitlab", "source": "github" },
8
- "version": "0.1.0",
8
+ "version": "0.2.0",
9
9
  "packages": [
10
10
  {
11
11
  "registryType": "npm",
12
12
  "identifier": "greenlitlab",
13
- "version": "0.1.0",
13
+ "version": "0.2.0",
14
14
  "transport": { "type": "stdio" },
15
15
  "packageArguments": [{ "type": "positional", "value": "mcp" }]
16
16
  }
package/src/grade.mjs CHANGED
@@ -12,17 +12,36 @@ import { SEVERITY } from "./severity.mjs";
12
12
 
13
13
  // [pattern, id, what it is, what a stranger can do with it, where to revoke it]
14
14
  const SECRETS = [
15
- [/sk_live_[0-9A-Za-z]{20,}/, "stripe", "A live Stripe secret key", "Anyone can charge, refund and read your customers' payments.", "Stripe → Developers → API keys → Roll key", "STRIPE_SECRET_KEY"],
15
+ // sk_live_ is used by Stripe and by other services (Clerk, Paystack); the advice is the same for all of them.
16
+ [/\bsk_live_[0-9A-Za-z]{20,}/, "stripe", "A live secret key for payments or sign-in (Stripe, Clerk or similar)", "With Stripe, anyone can charge, refund and read your customers' payments; with Clerk, anyone can manage your users.", "the dashboard of the service it belongs to (Stripe: Developers → API keys → Roll key; Clerk: API keys → roll the secret key)", "STRIPE_SECRET_KEY"],
16
17
  [/rk_live_[0-9A-Za-z]{20,}/, "stripe-restricted", "A live Stripe restricted key", "Anyone can do whatever this key allows on your Stripe account.", "Stripe → Developers → API keys → delete the restricted key", "STRIPE_RESTRICTED_KEY"],
17
18
  [/sk-(proj|svcacct|admin)-[0-9A-Za-z_-]{20,}|sk-[0-9A-Za-z]{48}\b/, "openai", "An OpenAI API key", "Anyone can run up your OpenAI bill.", "platform.openai.com → API keys → revoke", "OPENAI_API_KEY"],
18
19
  [/sk-ant-[0-9A-Za-z_-]{20,}/, "anthropic", "An Anthropic API key", "Anyone can run up your Anthropic bill.", "console.anthropic.com → API keys → disable", "ANTHROPIC_API_KEY"],
19
- [/AKIA[0-9A-Z]{16}/, "aws", "An AWS access key", "Depending on its rights: your servers, storage and bill.", "AWS console → IAM → Users → Security credentials → deactivate the key", "AWS_SECRET_ACCESS_KEY"],
20
+ [/\bAKIA[0-9A-Z]{16}\b/, "aws", "An AWS access key", "Depending on its rights: your servers, storage and bill.", "AWS console → IAM → Users → Security credentials → deactivate the key", "AWS_SECRET_ACCESS_KEY"],
20
21
  [/gh[pousr]_[0-9A-Za-z]{30,}|github_pat_[0-9A-Za-z_]{20,}/, "github", "A GitHub token", "Access to your code, and possibly the right to change it.", "GitHub → Settings → Developer settings → tokens → delete", "GITHUB_TOKEN"],
21
22
  [/xox[bpas]-[0-9A-Za-z-]{10,}/, "slack", "A Slack token", "Anyone can read or post in your Slack.", "api.slack.com/apps → your app → reinstall to get a new token", "SLACK_TOKEN"],
22
23
  [/re_[0-9A-Za-z]{8}_[0-9A-Za-z]{20,}/, "resend", "A Resend API key", "Anyone can send email as you.", "resend.com → API Keys → delete", "RESEND_API_KEY"],
23
24
  [/SG\.[0-9A-Za-z_-]{20,}\.[0-9A-Za-z_-]{20,}/, "sendgrid", "A SendGrid API key", "Anyone can send email as you.", "SendGrid → Settings → API Keys → delete", "SENDGRID_API_KEY"],
24
- [/AC[0-9a-f]{32}[^0-9a-f][\s\S]{0,80}?[0-9a-f]{32}/, "twilio", "Twilio credentials", "Anyone can send texts and make calls on your account.", "Twilio console → Account → API keys & tokens → rotate the auth token", "TWILIO_AUTH_TOKEN"],
25
+ [/\bAC[0-9a-f]{32}\b[\s\S]{0,80}?\b[0-9a-f]{32}\b/, "twilio", "Twilio credentials", "Anyone can send texts and make calls on your account.", "Twilio console → Account → API keys & tokens → rotate the auth token", "TWILIO_AUTH_TOKEN"],
25
26
  [/gsk_[0-9A-Za-z]{40,}/, "groq", "A Groq API key", "Anyone can run up your Groq bill.", "console.groq.com → API Keys → delete", "GROQ_API_KEY"],
27
+ [/\bsb_secret_[0-9A-Za-z_-]{20,}/, "supabase-secret", "A Supabase secret key", "It skips every security rule: anyone can read, change and delete all of your data and users.", "Supabase → Project Settings → API Keys → delete this secret key and create a new one", "SUPABASE_SECRET_KEY"],
28
+ [/\bsbp_[0-9a-f]{40}\b/, "supabase-token", "A Supabase personal access token", "Anyone can manage your Supabase account: every project, database and setting.", "supabase.com → Account → Access Tokens → revoke", "SUPABASE_ACCESS_TOKEN"],
29
+ [/\bsk-or-v1-[0-9a-f]{64}\b/, "openrouter", "An OpenRouter API key", "Anyone can run up your OpenRouter bill on any model.", "openrouter.ai → Keys → delete", "OPENROUTER_API_KEY"],
30
+ [/\bxai-[0-9A-Za-z]{60,}/, "xai", "An xAI (Grok) API key", "Anyone can run up your xAI bill.", "console.x.ai → API Keys → delete", "XAI_API_KEY"],
31
+ [/\bpplx-[0-9A-Za-z]{40,}/, "perplexity", "A Perplexity API key", "Anyone can run up your Perplexity bill.", "perplexity.ai → Settings → API → revoke", "PERPLEXITY_API_KEY"],
32
+ [/\bhf_[0-9A-Za-z]{34,}/, "huggingface", "A Hugging Face token", "Anyone can use your Hugging Face account and, with a write token, change your models.", "huggingface.co → Settings → Access Tokens → delete", "HF_TOKEN"],
33
+ [/\br8_[0-9A-Za-z]{37}\b/, "replicate", "A Replicate API token", "Anyone can run up your Replicate bill.", "replicate.com → Account → API tokens → delete", "REPLICATE_API_TOKEN"],
34
+ [/\bpcsk_[0-9A-Za-z_]{40,}/, "pinecone", "A Pinecone API key", "Anyone can read, change and delete your vector database.", "app.pinecone.io → API Keys → delete", "PINECONE_API_KEY"],
35
+ [/\b(?:glpat|gldt)-[0-9A-Za-z_-]{20,}/, "gitlab", "A GitLab token", "Access to your code, and possibly the right to change it.", "GitLab → Preferences → Access Tokens → revoke", "GITLAB_TOKEN"],
36
+ [/\bnpm_[0-9A-Za-z]{36}\b/, "npm", "An npm token", "Anyone can publish packages as you, which can infect everyone who installs them.", "npmjs.com → Access Tokens → delete", "NPM_TOKEN"],
37
+ [/\bshp(?:at|ca|pa|ss)_[0-9a-fA-F]{32}\b/, "shopify", "A Shopify access token", "Anyone can read and change your store, orders and customers.", "Shopify admin → Apps → your app → API credentials → rotate", "SHOPIFY_ACCESS_TOKEN"],
38
+ [/\bxkeysib-[0-9a-f]{64}-[0-9A-Za-z]{16}\b/, "brevo", "A Brevo (Sendinblue) API key", "Anyone can send email as you and read your contacts.", "Brevo → SMTP & API → API Keys → delete", "BREVO_API_KEY"],
39
+ [/\b[0-9a-f]{32}-us\d{1,2}\b/, "mailchimp", "A Mailchimp API key", "Anyone can read your mailing list and send campaigns as you.", "Mailchimp → Profile → Extras → API keys → delete", "MAILCHIMP_API_KEY"],
40
+ [/\bkey-[0-9a-f]{32}\b/, "mailgun", "A Mailgun API key", "Anyone can send email as you.", "Mailgun → API Security → delete the key", "MAILGUN_API_KEY"],
41
+ [/\b\d{8,10}:AA[0-9A-Za-z_-]{33}\b/, "telegram", "A Telegram bot token", "Anyone can take over your bot and read the messages people send it.", "Telegram → @BotFather → /revoke", "TELEGRAM_BOT_TOKEN"],
42
+ [/\bsk\.eyJ[0-9A-Za-z_-]{20,}\.[0-9A-Za-z_-]{20,}/, "mapbox", "A secret Mapbox token", "Anyone can use your Mapbox account and run up your bill. (Public pk. tokens are fine.)", "account.mapbox.com → Tokens → delete", "MAPBOX_SECRET_TOKEN"],
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
+ [/"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"],
26
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"],
27
46
  ];
28
47
  const JWT = /eyJ[0-9A-Za-z_-]{10,}\.eyJ[0-9A-Za-z_-]{10,}\.[0-9A-Za-z_-]{10,}/g;
@@ -42,7 +61,7 @@ export function detectBuilder(host, html = "") {
42
61
  if (/\.replit\.app$|\.repl\.co$|\.replit\.dev$/.test(h)) return "Replit";
43
62
  if (/\.emergent\.host$|\.emergentagent\.com$|\.preview\.emergentagent\.com$/.test(h)) return "Emergent";
44
63
  if (/\.base44\.app$/.test(h)) return "Base44";
45
- if (/v0\.dev|v0\.app/.test(h) || /generated by v0/i.test(html)) return "v0";
64
+ if (/(^|\.)v0\.(dev|app)$/.test(h) || /generated by v0/i.test(html)) return "v0";
46
65
  return null;
47
66
  }
48
67
 
@@ -55,12 +74,44 @@ const decodeJwt = (t) => {
55
74
  }
56
75
  };
57
76
 
58
- async function get(url, { timeout = 15000, headers = {}, method = "GET", max = 8 * 1024 * 1024, fetcher = fetch } = {}) {
77
+ // Reads at most `max` bytes, so a huge file can't use up the memory of the machine doing the check.
78
+ async function readCapped(r, max) {
79
+ if (!r.body?.getReader) return (await r.text()).slice(0, max);
80
+ const reader = r.body.getReader();
81
+ const parts = [];
82
+ let size = 0;
83
+ while (size < max) {
84
+ const { done, value } = await reader.read();
85
+ if (done) break;
86
+ parts.push(value);
87
+ size += value.byteLength;
88
+ }
89
+ reader.cancel().catch(() => {});
90
+ const all = new Uint8Array(Math.min(size, max));
91
+ let at = 0;
92
+ for (const p of parts) {
93
+ const take = Math.min(p.byteLength, all.length - at);
94
+ all.set(p.subarray(0, take), at);
95
+ at += take;
96
+ if (at >= all.length) break;
97
+ }
98
+ return new TextDecoder().decode(all);
99
+ }
100
+
101
+ const safeUrl = (u, base) => {
102
+ try {
103
+ return new URL(u, base);
104
+ } catch {
105
+ return null;
106
+ }
107
+ };
108
+
109
+ async function get(url, { timeout = 15000, headers = {}, method = "GET", body = null, max = 8 * 1024 * 1024, fetcher = fetch } = {}) {
59
110
  const ctl = new AbortController();
60
111
  const t = setTimeout(() => ctl.abort(), timeout);
61
112
  try {
62
- const r = await fetcher(url, { method, headers: { "user-agent": "greenlit (+https://greenlit.priberry.com)", ...headers }, signal: ctl.signal, redirect: "follow" });
63
- const text = method === "HEAD" ? "" : (await r.text()).slice(0, max);
113
+ const r = await fetcher(url, { method, headers: { "user-agent": "greenlit (+https://greenlit.priberry.com)", ...headers }, ...(body != null && { body }), signal: ctl.signal, redirect: "follow" });
114
+ const text = method === "HEAD" ? "" : await readCapped(r, max);
64
115
  return { status: r.status, headers: r.headers, text, url: r.url };
65
116
  } catch (e) {
66
117
  return { status: 0, error: e.name === "AbortError" ? "timed out" : e.message, text: "" };
@@ -98,6 +149,26 @@ const P = {
98
149
  first: null,
99
150
  prompt: `Anyone on the internet can read the Firestore collection "${coll}". Rewrite my Firestore security rules so "${coll}" (and every other collection) is closed by default, and a signed-in user can only read and write documents they own, for example match /${coll}/{id} { allow read, write: if request.auth != null && request.auth.uid == resource.data.userId; }. Adjust the owner field to whatever this app uses. Show me the final rules.`,
100
151
  }),
152
+ signup: () => ({
153
+ first: "Supabase → Authentication → Sign In / Providers → Email: turn on \"Confirm email\". If only people you invite should get in, turn off \"Allow new users to sign up\" too.",
154
+ prompt: "In my Supabase project, anyone can create an account with any email address without confirming it. Find every Row Level Security policy that only checks that a user is signed in (for example `to authenticated using (true)`, or `auth.role() = 'authenticated'`), because to a stranger those are open. Rewrite each one so a user reaches only their own rows (auth.uid() = user_id), or only rows they were given access to. List each policy you changed, and show me the SQL.",
155
+ }),
156
+ storage: (bucket) => ({
157
+ first: null,
158
+ prompt: `In my Supabase project, anyone on the internet can list the files in the storage bucket "${bucket}". Change the storage policies so files in "${bucket}" can only be listed and read by the user who uploaded them (for example, store files under a folder named after auth.uid() and check (storage.foldername(name))[1] = auth.uid()::text). If some files must be public, keep them in a separate public bucket and tell me which. Show me the SQL.`,
159
+ }),
160
+ envFile: (path) => ({
161
+ first: `Assume every key in ${path} is public: revoke and replace each one in the dashboard of the service it belongs to.`,
162
+ prompt: `My live site serves the file ${path} to anyone who asks for it. Make sure ${path} is never deployed: add it to .gitignore and to the host's ignore settings, move its values into the host's environment variable settings, redeploy, and confirm that opening ${path} on the live site now returns "not found".`,
163
+ }),
164
+ gitDir: () => ({
165
+ first: "Assume anyone can now download your whole code history, including any key ever committed: revoke and replace those keys.",
166
+ prompt: "My live site serves its .git folder, so anyone can download my whole code history. Change the deployment so the .git folder is never uploaded or served (deploy only the build output folder), redeploy, and confirm that opening /.git/config on the live site returns \"not found\".",
167
+ }),
168
+ framing: () => ({
169
+ first: null,
170
+ prompt: "Any other website can show my app inside a hidden frame and trick my users into clicking things (clickjacking). Add the response header `Content-Security-Policy: frame-ancestors 'self'` (or `X-Frame-Options: DENY`) in my host's header settings, redeploy, and confirm the header is there.",
171
+ }),
101
172
  sourceMaps: () => ({
102
173
  first: null,
103
174
  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.",
@@ -109,9 +180,10 @@ const P = {
109
180
  };
110
181
 
111
182
  // --- the check -----------------------------------------------------------------------------------
112
- export async function siteScan(target, { mine = false, fetcher = fetch, maxScripts = 40 } = {}) {
113
- const fetchOpts = (o = {}) => ({ ...o, fetcher });
114
- const url = new URL(/^https?:\/\//.test(target) ? target : `https://${target}`);
183
+ export async function siteScan(target, { mine = false, fetcher = fetch, maxScripts = 40, maxBytes = 8 * 1024 * 1024 } = {}) {
184
+ const fetchOpts = (o = {}) => ({ max: maxBytes, ...o, fetcher });
185
+ const url = safeUrl(/^https?:\/\//i.test(String(target).trim()) ? String(target).trim() : `https://${String(target).trim()}`);
186
+ if (!url || !/^https?:$/.test(url.protocol) || !url.hostname.includes(".")) throw new Error(`"${target}" doesn't look like a web address`);
115
187
  const findings = [];
116
188
  const add = (f) => findings.push(f);
117
189
 
@@ -123,20 +195,24 @@ export async function siteScan(target, { mine = false, fetcher = fetch, maxScrip
123
195
  // Every script the page loads from its own site, plus the scripts those import.
124
196
  const srcs = new Set();
125
197
  const collect = (html, base) => {
126
- for (const m of html.matchAll(/<script[^>]+src=["']([^"']+)["']/gi)) srcs.add(new URL(m[1], base).href);
127
- for (const m of html.matchAll(/<link[^>]+href=["']([^"']+\.m?js)["']/gi)) srcs.add(new URL(m[1], base).href);
198
+ for (const m of html.matchAll(/<script[^>]+src=["']([^"']+)["']/gi)) safeUrl(m[1], base) && srcs.add(safeUrl(m[1], base).href);
199
+ for (const m of html.matchAll(/<link[^>]+href=["']([^"']+\.m?js)["']/gi)) safeUrl(m[1], base) && srcs.add(safeUrl(m[1], base).href);
128
200
  };
129
201
  collect(page.text, origin);
130
202
  const bundles = [{ where: "the page itself", text: page.text }];
131
203
  const seen = new Set();
204
+ // Two rounds: the scripts the page names, then the scripts those import. Six at a time.
132
205
  for (let pass = 0; pass < 2; pass++) {
133
- for (const src of [...srcs]) {
134
- if (seen.has(src) || seen.size >= maxScripts || new URL(src).origin !== origin) continue;
135
- seen.add(src);
136
- const r = await get(src, fetchOpts());
137
- if (r.status !== 200) continue;
138
- bundles.push({ where: new URL(src).pathname, text: r.text, url: src });
139
- for (const m of r.text.matchAll(/(?:import\(|from\s*)["'](\.{0,2}\/[^"']+\.m?js)["']/g)) srcs.add(new URL(m[1], src).href);
206
+ const batch = [...srcs].filter((src) => !seen.has(src) && new URL(src).origin === origin).slice(0, Math.max(0, maxScripts - seen.size));
207
+ for (const src of batch) seen.add(src);
208
+ for (let i = 0; i < batch.length; i += 6) {
209
+ const got = await Promise.all(batch.slice(i, i + 6).map((src) => get(src, fetchOpts()).then((r) => ({ src, r }))));
210
+ for (const { src, r } of got) {
211
+ // Many hosts answer a missing file with the home page; that isn't a script.
212
+ if (r.status !== 200 || /text\/html/i.test(r.headers?.get("content-type") || "")) continue;
213
+ bundles.push({ where: new URL(src).pathname, text: r.text, url: src });
214
+ for (const m of r.text.matchAll(/(?:import\(|from\s*)["'](\.{0,2}\/[^"']+\.m?js)["']/g)) safeUrl(m[1], src) && srcs.add(safeUrl(m[1], src).href);
215
+ }
140
216
  }
141
217
  }
142
218
 
@@ -146,7 +222,8 @@ export async function siteScan(target, { mine = false, fetcher = fetch, maxScrip
146
222
  const thirdParty = new Set();
147
223
  for (const b of bundles) {
148
224
  for (const m of b.text.matchAll(/https:\/\/([a-z0-9-]+\.)+[a-z]{2,}/gi)) {
149
- const o = new URL(m[0]).origin;
225
+ const o = safeUrl(m[0])?.origin;
226
+ if (!o) continue;
150
227
  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"));
151
228
  }
152
229
  for (const [re, id, title, why, revoke, env] of SECRETS) {
@@ -177,17 +254,19 @@ export async function siteScan(target, { mine = false, fetcher = fetch, maxScrip
177
254
  const k = b.text.match(FB_KEY);
178
255
  if (k) firebase.key = k[1];
179
256
  }
180
- if (b.url && /sourceMappingURL=([^\s'"]+\.map)/.test(b.text)) {
181
- const mapUrl = new URL(b.text.match(/sourceMappingURL=([^\s'"]+\.map)/)[1], b.url).href;
182
- const r = await get(mapUrl, fetchOpts({ method: "HEAD" }));
183
- if (r.status === 200 && !findings.some((f) => f.id === "sourcemaps"))
257
+ const sm = b.url && b.text.match(/sourceMappingURL=([^\s'"]+\.map)/);
258
+ const mapUrl = sm && safeUrl(sm[1], b.url)?.href;
259
+ if (mapUrl && safeUrl(mapUrl).origin === origin && !findings.some((f) => f.id === "sourcemaps")) {
260
+ // Check what comes back: hosts that answer every missing file with the home page would look "public" otherwise.
261
+ const r = await get(mapUrl, fetchOpts({ max: 4096 }));
262
+ if (r.status === 200 && /^\s*\{[\s\S]*"(version|mappings|sources)"/.test(r.text))
184
263
  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() });
185
264
  }
186
265
  }
187
266
 
188
267
  const database = supabase?.url && supabase.anon ? "Supabase" : firebase?.project ? "Firebase" : null;
189
268
  if (database && !mine)
190
- add({ id: "db:skipped", severity: "low", where: database, title: "Database checks skipped", why: `This app uses ${database}. Greenlit can check which of its data anyone on the internet can read, but only for an app you own.`, fix: `Run \`npx greenlitlab ${url.host} --mine\` if this is your app.`, first: null, prompt: null });
269
+ add({ id: "db:skipped", severity: "info", where: database, title: `Your ${database} database wasn't checked`, why: `This app uses ${database}. Greenlit can check which of its data anyone on the internet can read, but only on your own computer, for an app you own.`, fix: `Run \`npx greenlitlab ${url.host} --mine\` if this is your app.`, first: null, prompt: null });
191
270
 
192
271
  // Supabase: with the public anon key, which tables can anyone read?
193
272
  let tables = null;
@@ -215,6 +294,42 @@ export async function siteScan(target, { mine = false, fetcher = fetch, maxScrip
215
294
  }
216
295
  }
217
296
 
297
+ // Your own app only: files that should never be on a live site. A real .env has KEY=value lines; a real .git
298
+ // folder has a config file with [core]. Anything else (often the home page served for every path) doesn't count.
299
+ if (mine) {
300
+ for (const path of ["/.env", "/.env.local", "/.env.production"]) {
301
+ const r = await get(new URL(path, origin).href, fetchOpts({ max: 4096 }));
302
+ if (r.status === 200 && !/^\s*</.test(r.text) && /^[A-Z][A-Z0-9_]*=/m.test(r.text)) {
303
+ add({ id: `exposed:${path}`, severity: "critical", where: path, title: `Your ${path} file is public`, why: "This file usually holds every secret key the app uses, and anyone can download it.", fix: `Stop deploying ${path}, then revoke every key it contained.`, ...P.envFile(path) });
304
+ break;
305
+ }
306
+ }
307
+ const g = await get(new URL("/.git/config", origin).href, fetchOpts({ max: 4096 }));
308
+ if (g.status === 200 && /\[core\]/.test(g.text))
309
+ add({ id: "exposed:git", severity: "high", where: "/.git/", title: "Your code history (.git folder) is public", why: "Anyone can download your full source code and every past version of it, including keys that were committed once and later removed.", fix: "Deploy only the build output, never the .git folder.", ...P.gitDir() });
310
+ }
311
+
312
+ // Your own app only: Supabase settings that quietly make "signed-in users only" mean "anyone".
313
+ if (mine && supabase?.url && supabase.anon) {
314
+ const h = { apikey: supabase.anon, ...(supabase.anon.startsWith("eyJ") && { authorization: `Bearer ${supabase.anon}` }) };
315
+ const st = await get(`${supabase.url}/auth/v1/settings`, fetchOpts({ headers: h, max: 65536 }));
316
+ try {
317
+ const cfg = JSON.parse(st.text);
318
+ if (st.status === 200 && cfg.disable_signup === false && cfg.mailer_autoconfirm === true)
319
+ add({ id: "supabase:open-signup", severity: "high", where: "Supabase Auth settings", title: "Anyone can sign up with any email, without confirming it", why: "Rules that only check \"is the user signed in?\" protect nothing: a stranger can make an account in seconds, even with someone else's email address.", fix: "Turn on email confirmation in Supabase Auth, and make every policy check who owns the row, not just that someone is signed in.", ...P.signup() });
320
+ } catch {}
321
+ // Storage: which common buckets list their files to anyone? Asks for one file name, never the file.
322
+ for (const bucket of ["avatars", "uploads", "files", "documents", "images", "attachments", "receipts", "invoices", "private"]) {
323
+ const r = await get(`${supabase.url}/storage/v1/object/list/${bucket}`, fetchOpts({ method: "POST", headers: { ...h, "content-type": "application/json" }, body: JSON.stringify({ prefix: "", limit: 1, offset: 0 }), max: 65536 }));
324
+ let n = 0;
325
+ try {
326
+ n = Array.isArray(JSON.parse(r.text)) ? JSON.parse(r.text).length : 0;
327
+ } catch {}
328
+ if (r.status === 200 && n > 0)
329
+ add({ id: `supabase:storage:${bucket}`, severity: /receipt|invoice|document|private|attachment/.test(bucket) ? "critical" : "high", where: `Supabase storage bucket "${bucket}"`, title: `Anyone can list the files in the storage bucket "${bucket}"`, why: "Strangers can see every file name in it and, if the files are readable too, download them. Greenlit asked for one file name and opened nothing.", fix: `In Supabase → Storage → Policies, limit "${bucket}" so users list and read only their own files.`, ...P.storage(bucket) });
330
+ }
331
+ }
332
+
218
333
  // Firebase: is the Realtime Database or a common Firestore collection open to anyone?
219
334
  let firebaseOpen = null;
220
335
  if (mine && firebase?.project) {
@@ -250,10 +365,14 @@ export async function siteScan(target, { mine = false, fetcher = fetch, maxScrip
250
365
  if (!page.headers?.get("content-security-policy") && !/http-equiv=["']Content-Security-Policy/i.test(page.text))
251
366
  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)) });
252
367
 
368
+ const csp = page.headers?.get("content-security-policy") || "";
369
+ if (!page.headers?.get("x-frame-options") && !/frame-ancestors/i.test(csp))
370
+ add({ id: "framing", severity: "low", where: "response headers", title: "Other sites can put your app in a frame", why: "A malicious page can show your app inside an invisible frame and trick your users into clicking buttons they can't see (clickjacking).", fix: "Add the header Content-Security-Policy: frame-ancestors 'self' (or X-Frame-Options: DENY).", ...P.framing() });
371
+
253
372
  const penalty = findings.reduce((a, f) => a + SEVERITY[f.severity], 0);
254
373
  const score = Math.max(0, 100 - penalty);
255
374
  const grade = score >= 90 ? "A" : score >= 75 ? "B" : score >= 60 ? "C" : score >= 40 ? "D" : "F";
256
- const order = ["critical", "high", "medium", "low"];
375
+ const order = ["critical", "high", "medium", "low", "info"];
257
376
  findings.sort((a, b) => order.indexOf(a.severity) - order.indexOf(b.severity));
258
377
  return {
259
378
  url: origin,
@@ -270,6 +389,15 @@ export async function siteScan(target, { mine = false, fetcher = fetch, maxScrip
270
389
  };
271
390
  }
272
391
 
392
+ // Every fix prompt in one, worst first, for people who'd rather paste once. The builder still gets one
393
+ // problem at a time, and checks in after each.
394
+ export function allPrompts(r) {
395
+ const list = r.findings.filter((f) => f.prompt);
396
+ if (!list.length) return "";
397
+ const head = `My app has ${list.length} security 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.`;
398
+ return [head, ...list.map((f, i) => `${i + 1}. ${f.title}.\n${f.prompt}`)].join("\n\n");
399
+ }
400
+
273
401
  export const VERDICT = {
274
402
  A: "Nothing serious a stranger can use against you.",
275
403
  B: "No open doors, a few loose ends.",
@@ -311,7 +439,7 @@ const wrap = (s, w = 92, pad = " ") => {
311
439
  export function renderSite(r, change, { color = true, mine = r.mine } = {}) {
312
440
  const k = (code) => (s) => (color ? `\x1b[${code}m${s}\x1b[0m` : s);
313
441
  const red = k("31"), green = k("32"), yellow = k("33"), dim = k("2"), bold = k("1"), cyan = k("36");
314
- const col = { critical: red, high: red, medium: yellow, low: dim };
442
+ const col = { critical: red, high: red, medium: yellow, low: dim, info: dim };
315
443
  const gcol = r.score >= 75 ? green : r.score >= 55 ? yellow : red;
316
444
  const L = [];
317
445
  L.push("", `${bold("Greenlit check")} · ${r.url}${r.builder ? ` · built with ${r.builder}` : ""} · ${r.scripts} scripts read${r.supabase ? " · Supabase" : ""}${r.firebase ? " · Firebase" : ""}`, "");
@@ -339,7 +467,7 @@ export function renderSite(r, change, { color = true, mine = r.mine } = {}) {
339
467
  }
340
468
  L.push(dim(`Read only what the site serves to every visitor${mine ? "; database checked with counts and names only, never data" : ""}.`));
341
469
  if (n) {
342
- L.push(dim(`Fix the red items first, one prompt at a time. Copy one prompt: npx greenlitlab ${new URL(r.url).host}${mine ? " --mine" : ""} --prompt 1 | pbcopy`));
470
+ L.push(dim(`Fix the red items first, one prompt at a time. Copy one prompt: npx greenlitlab ${new URL(r.url).host}${mine ? " --mine" : ""} --prompt 1 | pbcopy (or --prompt all for every fix in one)`));
343
471
  L.push(dim("After the fixes are live, run this same command again: it shows what got fixed."));
344
472
  }
345
473
  return L.join("\n");
package/src/mcp.mjs CHANGED
@@ -1,13 +1,13 @@
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 { siteScan, compare } from "./grade.mjs";
4
+ import { siteScan, compare, allPrompts } from "./grade.mjs";
5
5
 
6
6
  const TOOLS = [
7
7
  {
8
8
  name: "greenlit_check",
9
9
  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, a Supabase service_role key in the browser, source maps, missing security headers. Every finding has a plain-English reason and a fix prompt. Reads only what the site serves to every visitor. Call it again after a fix: `change` shows what got fixed. For database checks on the user's own app, have them run `npx greenlitlab <url> --mine`.",
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 25 more kinds), a Supabase service_role key in the browser, source maps, clickjacking and missing security headers. 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
11
  inputSchema: { type: "object", properties: { url: { type: "string", description: "The app's address, for example myapp.lovable.app" } }, required: ["url"], additionalProperties: false },
12
12
  annotations: { readOnlyHint: true, openWorldHint: true },
13
13
  },
@@ -21,7 +21,7 @@ async function call(name, args = {}) {
21
21
  // Remembered for this session only, so a second call shows what the fixes changed.
22
22
  const change = compare(last.get(result.url), result);
23
23
  last.set(result.url, { at: new Date().toISOString(), score: result.score, grade: result.grade, findings: result.findings.map(({ id, severity, title }) => ({ id, severity, title })) });
24
- return { ...result, change };
24
+ return { ...result, change, allFixes: allPrompts(result) };
25
25
  }
26
26
 
27
27
  export function serve({ version, input = process.stdin, output = process.stdout } = {}) {
package/src/severity.mjs CHANGED
@@ -1,2 +1,2 @@
1
- // How much each finding takes off a 100-point score. Shared by scan, site and the web check.
2
- export const SEVERITY = { critical: 40, high: 15, medium: 5, low: 1 };
1
+ // How much each finding takes off a 100-point score. "info" is a note, not a problem: it costs nothing.
2
+ export const SEVERITY = { critical: 40, high: 15, medium: 5, low: 1, info: 0 };