launch-doctor 0.2.1 → 0.4.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.
Files changed (66) hide show
  1. package/CHANGELOG.md +105 -4
  2. package/LICENSE +1 -0
  3. package/README.md +239 -39
  4. package/dist/src/access.d.ts +52 -0
  5. package/dist/src/access.js +482 -0
  6. package/dist/src/baseline.d.ts +6 -3
  7. package/dist/src/baseline.js +15 -8
  8. package/dist/src/changed.d.ts +12 -0
  9. package/dist/src/changed.js +34 -0
  10. package/dist/src/checks/access.d.ts +7 -0
  11. package/dist/src/checks/access.js +868 -0
  12. package/dist/src/checks/costs.d.ts +8 -0
  13. package/dist/src/checks/costs.js +54 -11
  14. package/dist/src/checks/database.js +201 -6
  15. package/dist/src/checks/first-impressions.js +247 -117
  16. package/dist/src/checks/legal.js +29 -13
  17. package/dist/src/checks/monitoring.js +47 -15
  18. package/dist/src/checks/payments.js +141 -6
  19. package/dist/src/checks/secrets.d.ts +8 -0
  20. package/dist/src/checks/secrets.js +185 -16
  21. package/dist/src/checks/supabase-storage.d.ts +31 -0
  22. package/dist/src/checks/supabase-storage.js +216 -0
  23. package/dist/src/cli.js +201 -12
  24. package/dist/src/demo.d.ts +13 -0
  25. package/dist/src/demo.js +59 -2
  26. package/dist/src/detect.d.ts +1 -1
  27. package/dist/src/detect.js +5 -2
  28. package/dist/src/fixes.js +10 -7
  29. package/dist/src/git.d.ts +25 -0
  30. package/dist/src/git.js +121 -0
  31. package/dist/src/github.d.ts +90 -0
  32. package/dist/src/github.js +330 -0
  33. package/dist/src/history.js +17 -3
  34. package/dist/src/hook.d.ts +13 -0
  35. package/dist/src/hook.js +96 -0
  36. package/dist/src/hooks-setup.d.ts +24 -0
  37. package/dist/src/hooks-setup.js +187 -0
  38. package/dist/src/ignore.d.ts +36 -0
  39. package/dist/src/ignore.js +164 -0
  40. package/dist/src/index.d.ts +1 -0
  41. package/dist/src/index.js +30 -3
  42. package/dist/src/init.d.ts +1 -1
  43. package/dist/src/init.js +2 -2
  44. package/dist/src/live.d.ts +9 -0
  45. package/dist/src/live.js +73 -22
  46. package/dist/src/mcp.d.ts +140 -0
  47. package/dist/src/mcp.js +386 -0
  48. package/dist/src/net-guard.d.ts +34 -0
  49. package/dist/src/net-guard.js +144 -0
  50. package/dist/src/project.d.ts +42 -5
  51. package/dist/src/project.js +237 -107
  52. package/dist/src/report.d.ts +4 -0
  53. package/dist/src/report.js +23 -1
  54. package/dist/src/routes.d.ts +10 -0
  55. package/dist/src/routes.js +21 -4
  56. package/dist/src/safe-fs.d.ts +19 -0
  57. package/dist/src/safe-fs.js +77 -0
  58. package/dist/src/sanitize.d.ts +17 -0
  59. package/dist/src/sanitize.js +90 -0
  60. package/dist/src/sarif.js +1 -1
  61. package/dist/src/summary.d.ts +7 -0
  62. package/dist/src/summary.js +26 -17
  63. package/dist/src/types.d.ts +26 -0
  64. package/dist/src/util.d.ts +2 -0
  65. package/dist/src/util.js +2 -0
  66. package/package.json +9 -5
@@ -1,9 +1,6 @@
1
1
  import { uniqueBy } from '../util.js';
2
2
  import { appCode, at, emptyOutput, isRouteLike, notApplicable, serverCode, where } from './common.js';
3
3
  const OTHER_PROVIDERS = {
4
- '@lemonsqueezy/lemonsqueezy.js': 'Lemon Squeezy',
5
- '@paddle/paddle-node-sdk': 'Paddle',
6
- '@paddle/paddle-js': 'Paddle',
7
4
  '@polar-sh/sdk': 'Polar',
8
5
  dodopayments: 'Dodo Payments',
9
6
  '@paypal/paypal-js': 'PayPal',
@@ -13,7 +10,12 @@ const OTHER_PROVIDERS = {
13
10
  '@cashfreepayments/cashfree-js': 'Cashfree',
14
11
  };
15
12
  const STRIPE_EVENTS_RE = /checkout\.session\.completed|invoice\.paid|invoice\.payment_succeeded|customer\.subscription\.(?:created|updated|deleted)|payment_intent\.succeeded|stripe-signature/i;
16
- const VERIFY_RE = /webhooks\.constructEvent(?:Async)?\s*\(/;
13
+ /**
14
+ * Stripe's signature check, in every language Stripe has a library for:
15
+ * stripe.webhooks.constructEvent (JS), stripe.Webhook.construct_event (Python), Stripe::Webhook.construct_event (Ruby),
16
+ * Webhook::constructEvent (PHP), webhook.ConstructEvent (Go), Webhook.constructEvent (Java).
17
+ */
18
+ const VERIFY_RE = /\bwebhooks?(?:\.|::)construct_?event(?:async)?\s*\(/i;
17
19
  const READS_BODY = /\b(?:req|request|c\.req)\.(?:text|json|arrayBuffer|body|rawBody|raw|on)\b|\brawBody\b|\bbuffer\s*\(\s*req\b/;
18
20
  const SIGNATURE_PASSED = 'Stripe webhooks check the signature, so fake "payment succeeded" messages are rejected';
19
21
  function parsesJsonFirst(path, content) {
@@ -37,6 +39,121 @@ function unverifiedFinding(loc) {
37
39
  };
38
40
  }
39
41
  const GLOBAL_JSON_PARSER = /\.use\s*\(\s*(?:["'`][^"'`]*["'`]\s*,\s*)?(?:express|bodyParser)\.json\s*\(/;
42
+ /**
43
+ * Is a webhook verified? Yes when its code runs the check itself, or calls a helper that does
44
+ * (an exported function in a non-route file, like lib/webhooks.ts).
45
+ */
46
+ function verifier(ctx, server, verifyRe) {
47
+ const verified = ctx.findCode(verifyRe, server);
48
+ const names = new Set();
49
+ const helperFiles = uniqueBy(verified, (m) => m.file.path)
50
+ .map((m) => m.file)
51
+ .filter((f) => !isRouteLike(f));
52
+ for (const f of helperFiles) {
53
+ for (const h of ctx.codeOf(f).matchAll(/export\s+(?:async\s+)?function\s+(\w+)|export\s+const\s+(\w+)\s*=/g)) {
54
+ names.add((h[1] ?? h[2]));
55
+ }
56
+ }
57
+ const helperRe = names.size ? new RegExp(`\\b(?:${[...names].join('|')})\\s*\\(`) : null;
58
+ return {
59
+ matches: verified,
60
+ test: (content) => verifyRe.test(content) || (helperRe?.test(content) ?? false),
61
+ };
62
+ }
63
+ /** The signature covers the exact raw text, so verifying JSON.stringify(parsedBody) fails for real webhooks. */
64
+ const SIGNS_PARSED_JSON = /(?:\.update|unmarshal|isSignatureValid)\s*\(\s*JSON\.stringify\s*\(/;
65
+ const LEMON_EVENTS_RE = /\b(?:order_(?:created|refunded)|subscription_(?:created|updated|cancelled|resumed|expired|paused|unpaused|payment_(?:success|failed|recovered|refunded))|license_key_(?:created|updated))\b|meta\.event_name/;
66
+ const LEMON_SQUEEZY = {
67
+ name: 'Lemon Squeezy',
68
+ prefix: 'lemonsqueezy',
69
+ isWebhookCode: (c) => LEMON_EVENTS_RE.test(c) || (/x-signature/i.test(c) && /lemon[\s_-]?squeezy/i.test(c)),
70
+ locate: new RegExp(`${LEMON_EVENTS_RE.source}|x-signature`, 'i'),
71
+ verify: /createHmac\s*\(\s*["'`]sha256["'`]|crypto\.subtle\.(?:verify|sign)\s*\(/,
72
+ unverifiedFix: (loc) => `My Lemon Squeezy webhook handler (${where(loc)}) does not check the X-Signature header. Please update it to:\n` +
73
+ `1. Read the raw request body as text (not parsed JSON).\n` +
74
+ `2. Compute an HMAC-SHA256 hex digest of that raw body with process.env.LEMONSQUEEZY_WEBHOOK_SECRET.\n` +
75
+ `3. Compare it with the X-Signature header using crypto.timingSafeEqual, and return 401 if they differ.\n` +
76
+ `4. Only then handle the event (meta.event_name), and make it safe if the same event arrives twice.\n` +
77
+ `Tell me where to set the signing secret (Lemon Squeezy → Settings → Webhooks) and how to send a test event.`,
78
+ parsedFix: (loc) => `In ${where(loc)} my Lemon Squeezy webhook computes its signature over JSON.stringify of the parsed body. The signature is made over the exact raw text, so real webhooks fail the check. ` +
79
+ `Please read the raw body with "await request.text()" (or express.raw on this route), compute the HMAC-SHA256 of that text with LEMONSQUEEZY_WEBHOOK_SECRET, compare it with X-Signature using timingSafeEqual, and only parse the JSON afterwards.`,
80
+ noWebhookFix: `My app sells through Lemon Squeezy but has no webhook. Please add a webhook endpoint that: reads the raw body and checks the X-Signature header (an HMAC-SHA256 of the raw body with LEMONSQUEEZY_WEBHOOK_SECRET, compared with timingSafeEqual); ` +
81
+ `handles order_created (give the customer access), subscription_updated, subscription_cancelled and subscription_expired (change or remove access) and subscription_payment_failed; ` +
82
+ `and is safe if the same event arrives twice. Move any "unlock the feature" logic from the thank-you page into this webhook. Explain how to register it in Lemon Squeezy → Settings → Webhooks.`,
83
+ };
84
+ const PADDLE_EVENTS_RE = /paddle-signature|webhooks\.unmarshal|isSignatureValid|EventName\.\w+|\b(?:transaction|subscription|customer|adjustment)\.(?:completed|paid|created|updated|canceled|activated|past_due|payment_failed|trialing|resumed|paused)\b/i;
85
+ const PADDLE = {
86
+ name: 'Paddle',
87
+ prefix: 'paddle',
88
+ isWebhookCode: (c, path) => PADDLE_EVENTS_RE.test(c) && (/paddle/i.test(c) || /paddle/i.test(path)),
89
+ locate: PADDLE_EVENTS_RE,
90
+ verify: /webhooks\.unmarshal\s*\(|\.isSignatureValid\s*\(|createHmac\s*\(\s*["'`]sha256["'`]|crypto\.subtle\.(?:verify|sign)\s*\(/,
91
+ unverifiedFix: (loc) => `My Paddle webhook handler (${where(loc)}) does not check the Paddle-Signature header. Please update it to:\n` +
92
+ `1. Read the raw request body as text (not parsed JSON).\n` +
93
+ `2. Verify it with paddle.webhooks.unmarshal(rawBody, process.env.PADDLE_WEBHOOK_SECRET, signature) from @paddle/paddle-node-sdk, where signature is the "paddle-signature" header.\n` +
94
+ `3. Return 400 if verification fails, and only handle the event after it passes.\n` +
95
+ `4. Make the handler safe if Paddle sends the same event twice (check the event id or whether the order was already processed).\n` +
96
+ `Tell me where to find the webhook secret key (Paddle → Developer tools → Notifications) and how to send a test event.`,
97
+ parsedFix: (loc) => `In ${where(loc)} my Paddle webhook verifies the signature over JSON.stringify of the parsed body. Paddle signs the exact raw text, so real webhooks fail the check. ` +
98
+ `Please read the raw body with "await request.text()" (or express.raw on this route), pass that text to paddle.webhooks.unmarshal with the paddle-signature header and PADDLE_WEBHOOK_SECRET, and use the event it returns.`,
99
+ noWebhookFix: `My app takes payments with Paddle but has no webhook. Please add a webhook endpoint that: verifies the paddle-signature header with paddle.webhooks.unmarshal(rawBody, PADDLE_WEBHOOK_SECRET, signature); ` +
100
+ `handles transaction.completed (give the customer access), subscription.updated and subscription.canceled (change or remove access) and transaction.payment_failed; ` +
101
+ `and is safe if the same event arrives twice. Move any "unlock the feature" logic from the success page into this webhook. Explain how to add a notification destination in Paddle → Developer tools → Notifications.`,
102
+ };
103
+ /** Signature checks for Lemon Squeezy and Paddle webhooks, the same way as for Stripe. */
104
+ function checkWebhooks(ctx, out, server, p) {
105
+ const hints = ctx.files.filter((f) => server(f) && p.isWebhookCode(ctx.codeOf(f), f.path));
106
+ const routes = hints.filter((f) => isRouteLike(f) && READS_BODY.test(f.content));
107
+ const v = verifier(ctx, server, p.verify);
108
+ /** The first line in a file that matches, or just the file. */
109
+ const pointAt = (file, re) => {
110
+ const m = ctx.findCode(re, (x) => x.path === file.path, 1)[0];
111
+ return m ? at(m) : { file: file.path };
112
+ };
113
+ const unverified = (loc) => ({
114
+ id: `${p.prefix}-webhook-unverified`,
115
+ severity: 'critical',
116
+ title: `Your ${p.name} webhook doesn't check that messages really come from ${p.name}`,
117
+ why: `Anyone can send a fake "payment succeeded" message to your webhook URL and get your product for free. ${p.name} signs every webhook; your code has to check that signature.`,
118
+ location: loc,
119
+ fixPrompt: p.unverifiedFix(loc),
120
+ });
121
+ const parsed = (loc) => ({
122
+ id: `${p.prefix}-webhook-parsed-body`,
123
+ severity: 'warning',
124
+ title: `${p.name} webhook checks the signature of re-encoded JSON instead of the raw body`,
125
+ why: `${p.name} signs the exact text it sends. JSON.stringify of the parsed body is never quite the same text, so every real webhook fails the check: customers pay, but your app never finds out.`,
126
+ location: loc,
127
+ fixPrompt: p.parsedFix(loc),
128
+ });
129
+ if (routes.length) {
130
+ const bad = routes.filter((f) => !v.test(ctx.codeOf(f)));
131
+ for (const f of bad)
132
+ out.findings.push(unverified(pointAt(f, p.locate)));
133
+ for (const f of routes) {
134
+ if (!bad.includes(f) && SIGNS_PARSED_JSON.test(ctx.codeOf(f))) {
135
+ out.findings.push(parsed(pointAt(f, SIGNS_PARSED_JSON)));
136
+ }
137
+ }
138
+ if (!bad.length)
139
+ out.passed.push(`${p.name} webhooks check the signature, so fake payment messages are rejected`);
140
+ }
141
+ else if (v.matches.length && hints.length) {
142
+ out.passed.push(`${p.name} webhooks check the signature, so fake payment messages are rejected`);
143
+ }
144
+ else if (hints.length) {
145
+ out.findings.push(unverified(pointAt(hints[0], p.locate)));
146
+ }
147
+ else {
148
+ out.findings.push({
149
+ id: `${p.prefix}-no-webhook`,
150
+ severity: 'warning',
151
+ title: `No ${p.name} webhook found`,
152
+ why: `If you unlock features from the "thank you" page, customers who close the tab after paying get nothing, and people who cancel or whose card fails keep access. Webhooks tell your server what really happened.`,
153
+ fixPrompt: p.noWebhookFix,
154
+ });
155
+ }
156
+ }
40
157
  function parsedBodyFinding(loc, globalParser = false) {
41
158
  return {
42
159
  id: 'stripe-webhook-parsed-body',
@@ -64,6 +181,12 @@ export const paymentsCheck = {
64
181
  'stripe-webhook-parsed-body',
65
182
  'stripe-no-webhook',
66
183
  'razorpay-unverified',
184
+ 'lemonsqueezy-webhook-unverified',
185
+ 'lemonsqueezy-webhook-parsed-body',
186
+ 'lemonsqueezy-no-webhook',
187
+ 'paddle-webhook-unverified',
188
+ 'paddle-webhook-parsed-body',
189
+ 'paddle-no-webhook',
67
190
  'other-provider-webhooks',
68
191
  'live-test-purchase',
69
192
  'failed-and-cancelled',
@@ -74,12 +197,16 @@ export const paymentsCheck = {
74
197
  const stripeClient = ctx.usesAny(['@stripe/stripe-js', '@stripe/react-stripe-js']);
75
198
  const stripeLinks = ctx.find(/https:\/\/buy\.stripe\.com\//, appCode, 1).length > 0;
76
199
  const razorpay = ctx.uses('razorpay') || ctx.find(/checkout\.razorpay\.com/, appCode, 1).length > 0;
200
+ const lemon = ctx.uses('@lemonsqueezy/lemonsqueezy.js') ||
201
+ ctx.find(/\.lemonsqueezy\.com\/(?:checkout|buy)\/|api\.lemonsqueezy\.com/, appCode, 1).length > 0;
202
+ const paddle = ctx.usesAny(['@paddle/paddle-node-sdk', '@paddle/paddle-js']) ||
203
+ ctx.find(/cdn\.paddle\.com\/paddle\//, appCode, 1).length > 0;
77
204
  const others = [
78
205
  ...new Set(Object.entries(OTHER_PROVIDERS)
79
206
  .filter(([pkg]) => ctx.uses(pkg))
80
207
  .map(([, name]) => name)),
81
208
  ];
82
- if (!stripeServer && !stripeClient && !stripeLinks && !razorpay && !others.length) {
209
+ if (!stripeServer && !stripeClient && !stripeLinks && !razorpay && !lemon && !paddle && !others.length) {
83
210
  return notApplicable('No payment provider found');
84
211
  }
85
212
  const out = emptyOutput();
@@ -127,7 +254,10 @@ export const paymentsCheck = {
127
254
  }
128
255
  // A global JSON body parser (Express) eats the raw body before any webhook route sees it.
129
256
  if (verified.length || eventHints.length) {
130
- const globalJson = ctx.find(GLOBAL_JSON_PARSER, server)[0];
257
+ // express.json({ verify: (req, res, buf) => { req.rawBody = buf } }) keeps the raw body on purpose: Stripe's own samples do this.
258
+ const globalJson = ctx
259
+ .find(GLOBAL_JSON_PARSER, server)
260
+ .filter((m) => !/\bverify\s*:/.test(m.file.content.slice(m.index, m.index + 600)))[0];
131
261
  const rawUsed = ctx.find(/\b(?:express|bodyParser)\.raw\s*\(/, server, 1).length > 0;
132
262
  if (globalJson && !rawUsed)
133
263
  out.findings.push(parsedBodyFinding(at(globalJson), true));
@@ -167,6 +297,11 @@ export const paymentsCheck = {
167
297
  });
168
298
  }
169
299
  }
300
+ // ---- Lemon Squeezy and Paddle ----
301
+ if (lemon)
302
+ checkWebhooks(ctx, out, server, LEMON_SQUEEZY);
303
+ if (paddle)
304
+ checkWebhooks(ctx, out, server, PADDLE);
170
305
  if (others.length) {
171
306
  out.manual.push({
172
307
  id: 'other-provider-webhooks',
@@ -20,4 +20,12 @@ export interface KeyMatch {
20
20
  export declare function matchKeys(text: string): KeyMatch[];
21
21
  export type { KeyPattern };
22
22
  export declare function isSensitivePublicName(rest: string): boolean;
23
+ /**
24
+ * Does this value (of a variable whose name sounds secret) look like a real secret? Empty values,
25
+ * placeholders ("changethis", "your_key_here", "test_secret", "discord-client-secret"), switches and numbers,
26
+ * publishable keys, the public Supabase demo keys and database URLs for a local machine do not.
27
+ */
28
+ export declare function envValueLooksReal(raw: string): boolean;
29
+ /** Does an env file hold anything that looks like a real secret (a provider key, or a secret-sounding variable with a real-looking value)? */
30
+ export declare function holdsRealSecret(content: string): boolean;
23
31
  export declare const secretsCheck: Check;
@@ -1,5 +1,5 @@
1
1
  import { isCodeFile, isEnvPath, isRealEnvPath } from '../project.js';
2
- import { decodeJwtPayload, looksLikePlaceholder, mask } from '../util.js';
2
+ import { decodeJwtPayload, lineTextAt, looksLikePlaceholder, mask } from '../util.js';
3
3
  import { at, emptyOutput, where } from './common.js';
4
4
  function looksRandom(value, kind) {
5
5
  const hasDigit = /\d/.test(value);
@@ -132,7 +132,86 @@ const KEY_PATTERNS = [
132
132
  envName: 'PRIVATE_KEY',
133
133
  rotate: 'wherever this key was created (Google Cloud, Firebase, Apple, etc.)',
134
134
  },
135
+ {
136
+ id: 'paddle-live-key',
137
+ name: 'Paddle live API key',
138
+ re: /\bpdl_live_apikey_[A-Za-z0-9_]{30,}/g,
139
+ severity: 'critical',
140
+ envName: 'PADDLE_API_KEY',
141
+ rotate: 'Paddle → Developer tools → Authentication → API keys',
142
+ },
143
+ {
144
+ id: 'paddle-sandbox-key',
145
+ name: 'Paddle sandbox API key',
146
+ re: /\bpdl_sdbx_apikey_[A-Za-z0-9_]{30,}/g,
147
+ severity: 'warning',
148
+ envName: 'PADDLE_API_KEY',
149
+ rotate: 'Paddle sandbox → Developer tools → Authentication → API keys',
150
+ },
151
+ {
152
+ id: 'convex-deploy-key',
153
+ name: 'Convex deploy key',
154
+ re: /\b(?:prod|preview|dev):[a-z0-9]+(?:-[a-z0-9]+)*(?::[a-z0-9-]+)?\|[A-Za-z0-9+/=_-]{30,}/g,
155
+ severity: 'critical',
156
+ envName: 'CONVEX_DEPLOY_KEY',
157
+ rotate: 'Convex dashboard → your deployment → Settings → Deploy keys',
158
+ mustLookRandom: 'mixed',
159
+ },
160
+ {
161
+ // Appwrite keys are long hex strings (newer ones start with "standard_"); passed to setKey() they are unmistakable.
162
+ id: 'appwrite-api-key',
163
+ name: 'Appwrite API key',
164
+ re: /(?<=\.setKey\(\s*["'`])(?:standard_)?[a-f0-9]{64,}(?=["'`])|\bstandard_[a-f0-9]{64,}/g,
165
+ severity: 'critical',
166
+ envName: 'APPWRITE_API_KEY',
167
+ rotate: 'Appwrite Console → your project → Overview → Integrations → API keys',
168
+ mustLookRandom: 'digits-letters',
169
+ },
135
170
  ];
171
+ /**
172
+ * Clerk secret keys use the same sk_live_ / sk_test_ prefixes as Stripe. A key is Clerk's when
173
+ * its line says so (CLERK_SECRET_KEY, clerkClient...) or when the app uses Clerk and not Stripe.
174
+ */
175
+ const CLERK_KEYS = {
176
+ 'stripe-live-key': {
177
+ id: 'clerk-secret-key',
178
+ name: 'Clerk secret key',
179
+ re: /\bsk_live_[0-9a-zA-Z]{20,}/g,
180
+ severity: 'critical',
181
+ envName: 'CLERK_SECRET_KEY',
182
+ rotate: 'Clerk Dashboard → API keys → Secret keys',
183
+ },
184
+ 'stripe-test-key': {
185
+ id: 'clerk-test-secret-key',
186
+ name: 'Clerk development secret key',
187
+ re: /\bsk_test_[0-9a-zA-Z]{20,}/g,
188
+ severity: 'warning',
189
+ envName: 'CLERK_SECRET_KEY',
190
+ rotate: 'Clerk Dashboard → API keys → Secret keys (development instance)',
191
+ },
192
+ };
193
+ const STRIPE_PACKAGES = ['stripe', '@stripe/stripe-js', '@stripe/react-stripe-js'];
194
+ /** The pattern to report a match as: Stripe's, unless the key turns out to be Clerk's. */
195
+ function keyKind(ctx, p, m) {
196
+ const clerk = CLERK_KEYS[p.id];
197
+ if (!clerk || !m.match[0].startsWith('sk_'))
198
+ return p;
199
+ const line = lineTextAt(m.file.content, m.index);
200
+ if (/clerk/i.test(line))
201
+ return clerk;
202
+ if (/stripe/i.test(line))
203
+ return p;
204
+ return ctx.uses('@clerk/') && !ctx.usesAny(STRIPE_PACKAGES) ? clerk : p;
205
+ }
206
+ /** Not in KEY_PATTERNS: a Lemon Squeezy key is a JWT, so only its context tells it apart. */
207
+ const LEMON_SQUEEZY_KEY = {
208
+ id: 'lemonsqueezy-api-key',
209
+ name: 'Lemon Squeezy API key',
210
+ re: /\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g,
211
+ severity: 'critical',
212
+ envName: 'LEMONSQUEEZY_API_KEY',
213
+ rotate: 'Lemon Squeezy → Settings → API',
214
+ };
136
215
  /** Every real-looking API key in a piece of text (placeholders like "sk_live_xxxx" are skipped). */
137
216
  export function matchKeys(text) {
138
217
  const out = [];
@@ -155,28 +234,86 @@ const LOCAL_HOST_RE = /^(localhost|127\.0\.0\.1|0\.0\.0\.0|host\.docker\.interna
155
234
  const WEAK_PLACEHOLDER_PW = /^(password|pass|postgres|root|secret|admin|pwd|user|mysql|test)$/i;
156
235
  const JWT_RE = /\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g;
157
236
  const PUBLIC_VAR_RE = /\b(NEXT_PUBLIC_|VITE_|REACT_APP_|EXPO_PUBLIC_|NUXT_PUBLIC_|GATSBY_|PUBLIC_)([A-Z0-9_]+)/g;
158
- const SENSITIVE_PART = /(SECRET|SERVICE_ROLE|PRIVATE|PASSWORD|PASSWD|OPENAI|ANTHROPIC|CLAUDE|GEMINI|GROQ|MISTRAL|DEEPSEEK|OPENROUTER|PERPLEXITY|REPLICATE|HUGGING|HF_TOKEN|COHERE|TOGETHER|ELEVENLABS|RESEND|SENDGRID|MAILGUN|POSTMARK|TWILIO_AUTH|AUTH_TOKEN|ACCESS_TOKEN|ADMIN_KEY)/;
237
+ const SENSITIVE_PART = /(SECRET|SERVICE_ROLE|PRIVATE|PASSWORD|PASSWD|OPENAI|ANTHROPIC|CLAUDE|GEMINI|GROQ|MISTRAL|DEEPSEEK|OPENROUTER|PERPLEXITY|REPLICATE|HUGGING|HF_TOKEN|COHERE|TOGETHER|ELEVENLABS|RESEND|SENDGRID|MAILGUN|POSTMARK|TWILIO_AUTH|AUTH_TOKEN|ACCESS_TOKEN|ADMIN_KEY|LEMONSQUEEZY|LEMON_SQUEEZY|PADDLE_API|CONVEX_DEPLOY|APPWRITE_API|APPWRITE_KEY)/;
159
238
  const DB_PART = /(DATABASE_URL|DB_URL|POSTGRES_URL|MONGODB_URI|MONGO_URI)/;
160
239
  // Settings that only mention a sensitive word, like VITE_PASSWORD_MIN_LENGTH.
161
240
  const SAFE_SUFFIX = /(_URL|_URI|_ENDPOINT|_MODEL|_BASE|_HOST|_REGION|_VERSION|_ENABLED|_ID|_NAME|_LENGTH|_MIN|_MAX|_LIMIT|_COUNT|_TIMEOUT|_MODE|_LABEL|_TITLE|_TEXT|_PATH|_LINK)$/;
241
+ // A name that says it is a switch or a rule (NEXT_PUBLIC_DISABLE_EMAIL_PASSWORD_SIGNUP, ..._PASSWORD_REGEX_PATTERN)
242
+ // is a setting, not a secret, unless it still ends in a word that looks like one.
243
+ const SETTING_WORD = /(?:^|_)(?:DISABLE|DISABLED|ENABLE|ENABLED|REQUIRE|REQUIRED|ALLOW|ALLOWED|SHOW|HIDE|PATTERN|REGEX|REGEXP|POLICY|STRENGTH|COMPLEXITY)(?:_|$)/;
244
+ const SECRET_ENDING = /(?:KEY|SECRET|TOKEN|PASSWORD|PASSWD|CREDENTIALS?)$/;
245
+ /** What follows the name in an env file (=true, =1) or in code (=== 'true'): a switch, not a secret. */
246
+ const FLAG_USE = /^\s*(?:=\s*['"]?(?:true|false|yes|no|on|off|\d+)['"]?\s*(?:#.*)?(?:\r?\n|$)|(?:===|!==|==|!=)\s*['"]?(?:true|false|1|0)['"]?)/i;
162
247
  export function isSensitivePublicName(rest) {
163
248
  if (DB_PART.test(rest))
164
249
  return true;
165
250
  if (SAFE_SUFFIX.test(rest))
166
251
  return false;
252
+ if (SETTING_WORD.test(rest) && !SECRET_ENDING.test(rest))
253
+ return false;
167
254
  return SENSITIVE_PART.test(rest);
168
255
  }
256
+ const SECRETISH_NAME = /SECRET|TOKEN|PASSWORD|PASSWD|PWD|PRIVATE|CREDENTIAL|API_?KEY|ACCESS_?KEY|AUTH_?KEY|SIGNING|SALT|DSN|DATABASE_URL|DB_URL|CONNECTION_STRING|(?:^|_)KEY$/i;
257
+ const PLACEHOLDER_VALUE = /^(?:changeme|changethis|change_me|change-me|secret|password|passw0rd|test|testing|dev|development|local|none|null|undefined|todo|tbd|xxx+|\*+|\.{2,})$/i;
258
+ /**
259
+ * Does this value (of a variable whose name sounds secret) look like a real secret? Empty values,
260
+ * placeholders ("changethis", "your_key_here", "test_secret", "discord-client-secret"), switches and numbers,
261
+ * publishable keys, the public Supabase demo keys and database URLs for a local machine do not.
262
+ */
263
+ export function envValueLooksReal(raw) {
264
+ const v = raw.trim().replace(/^['"]|['"]$/g, '');
265
+ if (v.length < 8)
266
+ return false;
267
+ // A database URL is judged by its password and host (its other parts, like a host called "example.net", prove nothing).
268
+ const db = new RegExp(DB_URL_RE.source).exec(v);
269
+ if (db) {
270
+ const password = db[2];
271
+ return !(LOCAL_HOST_RE.test(db[3]) || WEAK_PLACEHOLDER_PW.test(password) || looksLikePlaceholder(password));
272
+ }
273
+ if (looksLikePlaceholder(v) || PLACEHOLDER_VALUE.test(v))
274
+ return false;
275
+ if (/^(?:true|false|yes|no|on|off|null|\d+)$/i.test(v))
276
+ return false;
277
+ if (/^(?:test|demo|fake|dummy|mock|sample)[-_]/i.test(v))
278
+ return false;
279
+ // Only lower-case words joined by - or _ describes the value ("alpha-vantage-api-key"); a secret has digits or mixed case.
280
+ if (/^[a-z]+(?:[-_ /][a-z]+)+$/.test(v))
281
+ return false;
282
+ if (/^pk_(?:test|live)_/.test(v))
283
+ return false;
284
+ const jwt = decodeJwtPayload(v);
285
+ if (jwt && (jwt.iss === 'supabase-demo' || jwt.role === 'anon'))
286
+ return false;
287
+ return true;
288
+ }
289
+ /** Does an env file hold anything that looks like a real secret (a provider key, or a secret-sounding variable with a real-looking value)? */
290
+ export function holdsRealSecret(content) {
291
+ if (matchKeys(content).length > 0)
292
+ return true;
293
+ for (const line of content.split(/\r?\n/)) {
294
+ const kv = /^\s*(?:export\s+)?([A-Za-z_]\w*)\s*=\s*(.*)$/.exec(line);
295
+ if (!kv || !SECRETISH_NAME.test(kv[1]))
296
+ continue;
297
+ const value = kv[2].replace(/\s+#.*$/, '');
298
+ if (envValueLooksReal(value))
299
+ return true;
300
+ }
301
+ return false;
302
+ }
169
303
  /** Files to search for hard-coded secrets: everything except real .env files (secrets belong there). */
170
304
  const notRealEnv = (f) => !isRealEnvPath(f.path);
171
305
  function hardcodedFinding(ctx, p, m) {
172
306
  const client = ctx.isClient(m.file);
173
307
  const shown = p.id === 'private-key' ? '-----BEGIN … PRIVATE KEY-----' : mask(m.match[0]);
308
+ const shipped = ctx.isMobileFile(m.file.path)
309
+ ? `This file is built into your app, and anyone who installs it can unpack the app and copy the key (${shown}).`
310
+ : `This file is sent to every visitor's browser, so anyone can copy the key (${shown}) and use your account.`;
174
311
  return {
175
312
  id: p.id,
176
313
  severity: client ? 'critical' : p.severity,
177
314
  title: `${capitalize(p.name)} is written directly in your code`,
178
315
  why: client
179
- ? `This file is sent to every visitor's browser, so anyone can copy the key (${shown}) and use your account.`
316
+ ? shipped
180
317
  : `Anyone who can see your code (GitHub, collaborators, AI tools) can copy this key (${shown}) and use your account. Keys belong in environment variables.`,
181
318
  location: at(m),
182
319
  fixPrompt: `In ${where(at(m))} there is a hard-coded ${p.name} (it starts with "${shown}"). Please:\n` +
@@ -195,6 +332,8 @@ export const secretsCheck = {
195
332
  weight: 3,
196
333
  ids: [
197
334
  ...KEY_PATTERNS.map((p) => p.id),
335
+ ...Object.values(CLERK_KEYS).map((p) => p.id),
336
+ 'lemonsqueezy-api-key',
198
337
  'database-password',
199
338
  'supabase-service-role-key',
200
339
  'public-secret-variable',
@@ -214,13 +353,14 @@ export const secretsCheck = {
214
353
  continue;
215
354
  if (p.mustLookRandom && !looksRandom(m.match[0], p.mustLookRandom))
216
355
  continue;
217
- const key = `${p.id}|${m.file.path}`;
356
+ const kind = keyKind(ctx, p, m);
357
+ const key = `${kind.id}|${m.file.path}`;
218
358
  if (seen.has(key))
219
359
  continue;
220
360
  seen.add(key);
221
361
  if (++hardcoded > 10)
222
362
  break;
223
- out.findings.push(hardcodedFinding(ctx, p, m));
363
+ out.findings.push(hardcodedFinding(ctx, kind, m));
224
364
  }
225
365
  }
226
366
  // 2. Database connection strings with real passwords
@@ -251,8 +391,20 @@ export const secretsCheck = {
251
391
  // 3. Supabase service_role keys (they bypass all database security)
252
392
  for (const m of ctx.find(JWT_RE, notRealEnv)) {
253
393
  const payload = decodeJwtPayload(m.match[0]);
254
- if (payload?.role !== 'service_role')
394
+ // The keys `supabase start` prints for a local database are the same for everyone and are public.
395
+ if (payload?.iss === 'supabase-demo')
396
+ continue;
397
+ if (payload?.role !== 'service_role') {
398
+ if (!/lemon[\s_-]?squeezy/i.test(lineTextAt(m.file.content, m.index)))
399
+ continue;
400
+ const key = `lemonsqueezy|${m.file.path}`;
401
+ if (seen.has(key))
402
+ continue;
403
+ seen.add(key);
404
+ hardcoded++;
405
+ out.findings.push(hardcodedFinding(ctx, LEMON_SQUEEZY_KEY, m));
255
406
  continue;
407
+ }
256
408
  const key = `service-role|${m.file.path}`;
257
409
  if (seen.has(key))
258
410
  continue;
@@ -279,13 +431,17 @@ export const secretsCheck = {
279
431
  const full = m.match[0];
280
432
  if (!isSensitivePublicName(m.match[2]) || publicHits.has(full))
281
433
  continue;
434
+ // A variable that is set to, or compared with, true / false / a number is a switch, not a secret.
435
+ if (FLAG_USE.test(m.file.content.slice(m.index + full.length, m.index + full.length + 60)))
436
+ continue;
282
437
  publicHits.set(full, at(m));
283
438
  }
284
439
  // A public variable that actually holds a service_role key
285
440
  for (const file of ctx.files.filter((f) => isEnvPath(f.path))) {
286
441
  file.content.split(/\r?\n/).forEach((line, i) => {
287
442
  const kv = /^\s*(?:export\s+)?((?:NEXT_PUBLIC_|VITE_|REACT_APP_|EXPO_PUBLIC_|NUXT_PUBLIC_|PUBLIC_)[A-Z0-9_]+)\s*=\s*['"]?([^'"\s#]+)/.exec(line);
288
- if (kv && decodeJwtPayload(kv[2])?.role === 'service_role' && !publicHits.has(kv[1])) {
443
+ const payload = kv ? decodeJwtPayload(kv[2]) : null;
444
+ if (kv && payload?.role === 'service_role' && payload.iss !== 'supabase-demo' && !publicHits.has(kv[1])) {
289
445
  publicHits.set(kv[1], { file: file.path, line: i + 1 });
290
446
  }
291
447
  });
@@ -299,7 +455,9 @@ export const secretsCheck = {
299
455
  id: 'public-secret-variable',
300
456
  severity: 'critical',
301
457
  title: `Secret exposed through the public variable ${name}`,
302
- why: `Anything starting with ${prefix} gets copied into your website's JavaScript, so every visitor can read it. That prefix is only for values that are safe to be public.`,
458
+ why: prefix === 'EXPO_PUBLIC_'
459
+ ? 'Anything starting with EXPO_PUBLIC_ is built into your app, so anyone who installs it can read it. That prefix is only for values that are safe to be public.'
460
+ : `Anything starting with ${prefix} gets copied into your website's JavaScript, so every visitor can read it. That prefix is only for values that are safe to be public.`,
303
461
  location: loc,
304
462
  fixPrompt: `My app has an environment variable called ${name} (see ${where(loc)}). Because it starts with ${prefix}, it is bundled into the browser code and anyone can read it. Please:\n` +
305
463
  `1. Rename it to a server-only name without the ${prefix} prefix.\n` +
@@ -319,24 +477,35 @@ export const secretsCheck = {
319
477
  const ignored = ctx.ignoredAmong(notCommitted.map((f) => f.path));
320
478
  const exposed = notCommitted.filter((f) => !ignored.has(f.path));
321
479
  for (const f of committed.slice(0, 3)) {
480
+ // Critical only when the file holds something that looks like a real secret. Many starters commit a
481
+ // .env with placeholders and public settings on purpose; that is a habit to fix, but nothing has leaked.
482
+ const real = holdsRealSecret(f.content);
322
483
  out.findings.push({
323
484
  id: 'env-committed',
324
- severity: 'critical',
485
+ severity: real ? 'critical' : 'warning',
325
486
  title: `${f.path} is saved in git`,
326
- why: 'Your .env file holds your secret keys and it has been committed to git. If this repo is ever pushed to GitHub (even privately), those keys are exposed — and they stay in the git history even after you delete the file.',
487
+ why: real
488
+ ? 'Your .env file holds your secret keys and it has been committed to git. If this repo is ever pushed to GitHub (even privately), those keys are exposed — and they stay in the git history even after you delete the file.'
489
+ : "This .env file is saved in git. It only holds placeholders and public settings right now, so nothing has leaked, but the first real key you add to it will be uploaded with your code (and stays in git history). Keep real keys in an untracked file or in your host's settings.",
327
490
  location: { file: f.path },
328
- fixPrompt: `My ${f.path} file (with secret keys) is tracked by git. Please: add it to .gitignore, run "git rm --cached ${f.path}" so git stops tracking it (the file stays on my computer), ` +
329
- `and create a .env.example with the same variable names but no values. Then list every key inside it and tell me how to rotate each one, because they are in my git history.`,
491
+ fixPrompt: real
492
+ ? `My ${f.path} file (with secret keys) is tracked by git. Please: add it to .gitignore, run "git rm --cached ${f.path}" so git stops tracking it (the file stays on my computer), ` +
493
+ `and create a .env.example with the same variable names but no values. Then list every key inside it and tell me how to rotate each one, because they are in my git history.`
494
+ : `My ${f.path} file is tracked by git. It only has placeholders and public settings today, but real keys will end up in it. Please rename it to ${f.path.replace(/\.env(?=[^/]*$)/, '.env.example')} (keep it in git as the template) ` +
495
+ `and add ${f.path} to .gitignore, so each developer's real values stay on their own machine.`,
330
496
  });
331
497
  }
332
498
  for (const f of exposed.slice(0, 3)) {
499
+ const real = holdsRealSecret(f.content);
333
500
  out.findings.push({
334
501
  id: 'env-not-ignored',
335
- severity: ctx.gitRoot ? 'critical' : 'warning',
502
+ severity: ctx.gitRoot && real ? 'critical' : 'warning',
336
503
  title: `${f.path} is not in .gitignore`,
337
- why: ctx.gitRoot
338
- ? 'The next "git add ." will upload your secret keys along with your code.'
339
- : 'As soon as you put this project on GitHub, your secret keys will be uploaded with it.',
504
+ why: !real
505
+ ? 'This .env file only holds placeholders and public settings right now, but it is not in .gitignore, so the first real key you add will be uploaded with your code.'
506
+ : ctx.gitRoot
507
+ ? 'The next "git add ." will upload your secret keys along with your code.'
508
+ : 'As soon as you put this project on GitHub, your secret keys will be uploaded with it.',
340
509
  location: { file: f.path },
341
510
  fixPrompt: `Add ${f.path} (and other .env files except .env.example) to my .gitignore so my secret keys are never committed. ` +
342
511
  `Use a pattern like ".env*" followed by "!.env.example". Then create .env.example with the same variable names but empty values.`,
@@ -0,0 +1,31 @@
1
+ import type { ProjectContext } from '../project.js';
2
+ import type { Location } from '../types.js';
3
+ /** A Supabase Storage bucket that is set to public somewhere in the repo. */
4
+ export interface PublicBucket {
5
+ name: string;
6
+ loc: Location;
7
+ }
8
+ /**
9
+ * A policy on storage.objects that lets signed-out visitors change files, or lets any
10
+ * signed-in user replace or delete every file, with no owner check.
11
+ */
12
+ export interface OpenStoragePolicy {
13
+ name: string;
14
+ /** Buckets the policy names (empty when it covers every bucket). */
15
+ buckets: string[];
16
+ /** True when the policy only allows uploads (insert), not replacing or deleting files. */
17
+ insertOnly: boolean;
18
+ /** True when the policy is limited to signed-in users (they can still change everyone's files). */
19
+ signedIn: boolean;
20
+ loc: Location;
21
+ }
22
+ /**
23
+ * Bucket names that suggest files people expect to stay private. A public bucket serves every
24
+ * file to anyone who has (or guesses) its URL, so these get a warning instead of a checklist item.
25
+ */
26
+ export declare const PRIVATE_BUCKET_NAME: RegExp;
27
+ export declare function analyzeStorage(ctx: ProjectContext): {
28
+ buckets: PublicBucket[];
29
+ policies: OpenStoragePolicy[];
30
+ usesStorage: boolean;
31
+ };