launch-doctor 0.4.0 → 0.4.2

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.
@@ -0,0 +1,35 @@
1
+ /**
2
+ * The ASCII banner shown at the top of an interactive full scan.
3
+ *
4
+ * Pre-rendered in the "ANSI Shadow" figlet font (two lines, because one line would be about 100
5
+ * columns wide and wrap in an 80-column terminal). It is a plain string constant on purpose: no
6
+ * figlet dependency. The test suite checks the shape (width, line count); the letters were checked
7
+ * against the real font when it was added.
8
+ */
9
+ export const BANNER = [
10
+ '██╗ █████╗ ██╗ ██╗███╗ ██╗ ██████╗██╗ ██╗',
11
+ '██║ ██╔══██╗██║ ██║████╗ ██║██╔════╝██║ ██║',
12
+ '██║ ███████║██║ ██║██╔██╗ ██║██║ ███████║',
13
+ '██║ ██╔══██║██║ ██║██║╚██╗██║██║ ██╔══██║',
14
+ '███████╗██║ ██║╚██████╔╝██║ ╚████║╚██████╗██║ ██║',
15
+ '╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝╚═╝ ╚═╝',
16
+ '',
17
+ '██████╗ ██████╗ ██████╗████████╗ ██████╗ ██████╗',
18
+ '██╔══██╗██╔═══██╗██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗',
19
+ '██║ ██║██║ ██║██║ ██║ ██║ ██║██████╔╝',
20
+ '██║ ██║██║ ██║██║ ██║ ██║ ██║██╔══██╗',
21
+ '██████╔╝╚██████╔╝╚██████╗ ██║ ╚██████╔╝██║ ██║',
22
+ '╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝',
23
+ ];
24
+ /** Spaces in front of every banner line (the same indent as the rest of the report). */
25
+ export const BANNER_INDENT = ' ';
26
+ /** Columns the terminal needs to show the banner without wrapping. */
27
+ export const BANNER_WIDTH = BANNER_INDENT.length + Math.max(...BANNER.map((l) => l.length));
28
+ /** Show the banner only on an interactive terminal that is wide enough, and never in CI. */
29
+ export function shouldShowBanner(ctx) {
30
+ if (!ctx.wanted || !ctx.isTTY)
31
+ return false;
32
+ if (ctx.env.CI || ctx.env.GITHUB_ACTIONS)
33
+ return false;
34
+ return (ctx.columns ?? 0) >= BANNER_WIDTH;
35
+ }
@@ -0,0 +1,35 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ // The command's entry point. It checks the Node.js version before the real program (cli.js) is loaded, so an
4
+ // old Node prints one clear message instead of a syntax or import error.
5
+ //
6
+ // Keep this file to old syntax (var, function, string concatenation): it has to parse on old versions of Node.
7
+ // No arrow functions, template strings, let/const, classes, async, optional chaining or import statements.
8
+ // test/bin.test.ts checks this.
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ (function () {
11
+ var MIN_MAJOR = 22;
12
+ var found = process.versions.node;
13
+ var major = Number(found.split('.')[0]);
14
+ if (!(major >= MIN_MAJOR)) {
15
+ process.stderr.write('launch-doctor needs Node.js ' +
16
+ MIN_MAJOR +
17
+ ' or newer, but this is Node.js ' +
18
+ found +
19
+ '.\n' +
20
+ 'Update it from https://nodejs.org/en/download, or with a version manager: nvm install ' +
21
+ MIN_MAJOR +
22
+ ' (or fnm install ' +
23
+ MIN_MAJOR +
24
+ ').\n');
25
+ process.exit(1);
26
+ }
27
+ var path = require('path');
28
+ var url = require('url');
29
+ // import() written inside a Function, so this file still parses where import() is not known.
30
+ var load = new Function('specifier', 'return import(specifier)');
31
+ load(url.pathToFileURL(path.join(__dirname, 'cli.js')).href).catch(function (err) {
32
+ process.stderr.write('launch-doctor could not start: ' + ((err && err.stack) || err) + '\n');
33
+ process.exit(2);
34
+ });
35
+ })();
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -643,6 +643,10 @@ export const accessCheck = {
643
643
  out.findings.push({
644
644
  id: 'user-metadata-role',
645
645
  severity: inBrowser ? 'warning' : 'critical',
646
+ display: {
647
+ title: `Any user can give themselves extra rights: "${mf.key}" is read from ${field}`,
648
+ reason: `every user can edit ${field}`,
649
+ },
646
650
  title: mf.sql
647
651
  ? `A database rule trusts user_metadata, which every user can edit (${mf.file.path})`
648
652
  : `"${mf.key}" is read from ${field}, which every user can edit`,
@@ -792,6 +796,10 @@ export const accessCheck = {
792
796
  id: 'jwt-none-algorithm',
793
797
  severity: 'critical',
794
798
  title: `Tokens with no signature ("none" algorithm) are accepted (${f.path})`,
799
+ display: {
800
+ title: 'Anyone can sign in as any user: tokens with no signature are accepted',
801
+ reason: 'the "none" algorithm is allowed',
802
+ },
795
803
  why: 'With the "none" algorithm a token needs no signature at all, so anyone can write their own token and sign in as any user, including an admin.',
796
804
  location: l,
797
805
  fixPrompt: `In ${where(l)} my JWT code allows the "none" algorithm. Please remove it and only allow the one algorithm my tokens are actually signed with (for example HS256 or RS256), and reject every other token.`,
@@ -156,6 +156,12 @@ export const costsCheck = {
156
156
  id: 'ai-in-browser',
157
157
  severity: 'critical',
158
158
  title: `A paid ${/twilio/i.test(m.match[0]) ? 'SMS' : 'AI'} API is called straight from the browser`,
159
+ display: {
160
+ title: /twilio/i.test(m.match[0])
161
+ ? 'Anyone can send texts on your bill: an SMS API is called from the browser'
162
+ : 'Anyone can run up your AI bill: a paid AI API is called from the browser',
163
+ reason: 'the API key has to be in the browser too',
164
+ },
159
165
  why: 'For that to work, your secret API key has to be in the browser too, so anyone can copy it and run up your bill. Bots scan websites for exactly this.',
160
166
  location: at(m),
161
167
  fixPrompt: `In ${where(at(m))} my frontend calls a paid AI API directly, which means my API key is exposed in the browser. Please:\n` +
@@ -154,6 +154,12 @@ export const databaseCheck = {
154
154
  id: 'supabase-rls-missing',
155
155
  severity: 'critical',
156
156
  title: `${plural(missing.length, 'Supabase table')} without Row Level Security: ${names.join(', ')}${more}`,
157
+ display: {
158
+ title: missing.length === 1
159
+ ? `Anyone can read, change or delete every row in the ${names[0]} table`
160
+ : `Anyone can read, change or delete every row in ${missing.length} tables (${names.slice(0, 3).join(', ')}${missing.length > 3 ? ', ...' : ''})`,
161
+ reason: 'Row Level Security is off',
162
+ },
157
163
  why: 'Your Supabase public (anon) key is inside your website, which is normal. But without Row Level Security, anyone holding that key can read, change or delete every row in these tables.',
158
164
  location: missing[0].loc,
159
165
  fixPrompt: `These Supabase tables don't have Row Level Security enabled: ${missing.map((t) => t.name).join(', ')}. ` +
@@ -169,6 +175,10 @@ export const databaseCheck = {
169
175
  id: 'supabase-open-policy',
170
176
  severity: 'critical',
171
177
  title: `Supabase policy "${p.name}" lets anyone change the ${p.table} table`,
178
+ display: {
179
+ title: `Anyone can add, edit or delete rows in the ${p.table} table`,
180
+ reason: `policy "${p.name}" allows it with (true)`,
181
+ },
172
182
  why: 'This policy uses "true" as its rule, so anyone (even people who are not signed in) can add, edit or delete rows. That is as bad as having no Row Level Security at all.',
173
183
  location: p.loc,
174
184
  fixPrompt: `In ${where(p.loc)} the Supabase policy "${p.name}" on table "${p.table}" uses (true), so anyone can write to it. ` +
@@ -228,6 +238,10 @@ export const databaseCheck = {
228
238
  out.findings.push({
229
239
  id: 'supabase-storage-open-write',
230
240
  severity: p.signedIn || p.insertOnly ? 'warning' : 'critical',
241
+ display: {
242
+ title: `${p.signedIn ? 'Any signed-in user' : 'Anyone'} can ${what} ${scope}`,
243
+ reason: p.insertOnly ? 'uploads need no sign-in' : `policy "${p.name}" doesn't check who owns a file`,
244
+ },
231
245
  title: `Supabase Storage policy "${p.name}" lets ${who.replace(/,$/, '')} ${what} ${scope}`,
232
246
  why: p.insertOnly
233
247
  ? 'Signed-out visitors can upload as many files as they like: your storage bill grows, and your bucket can be used to host spam or malware under your domain.'
@@ -278,6 +292,15 @@ export const databaseCheck = {
278
292
  id: 'firebase-open-rules',
279
293
  severity: 'critical',
280
294
  title: testMode ? 'Firebase is still in "test mode"' : 'Firebase rules let anyone write to your database',
295
+ display: testMode
296
+ ? {
297
+ title: 'Anyone can read and change all your data: Firebase is in test mode',
298
+ reason: 'and the app stops working when the date runs out',
299
+ }
300
+ : {
301
+ title: 'Anyone can change or delete your data: Firebase rules allow it',
302
+ reason: 'writes need no sign-in',
303
+ },
281
304
  why: testMode
282
305
  ? 'Test-mode rules let anyone on the internet read and change all your data until the date runs out — then your app suddenly stops working for everyone.'
283
306
  : 'These rules allow anyone, even people who are not signed in, to change or delete your data.',
@@ -342,6 +365,12 @@ export const databaseCheck = {
342
365
  out.findings.push({
343
366
  id: 'appwrite-open-permission',
344
367
  severity: createOnly ? 'warning' : 'critical',
368
+ display: {
369
+ title: createOnly
370
+ ? `Anyone can fill your Appwrite collection with junk: ${who} can create documents`
371
+ : `Anyone can ${action === 'write' ? 'change and delete' : action} your Appwrite data`,
372
+ reason: `permission is granted to "${m.match[2]}"`,
373
+ },
345
374
  title: createOnly
346
375
  ? `Appwrite lets ${who} create documents (${action} for ${m.match[2]})`
347
376
  : `Appwrite lets ${who} ${action === 'write' ? 'change and delete' : action} your data`,
@@ -28,6 +28,10 @@ function unverifiedFinding(loc) {
28
28
  id: 'stripe-webhook-unverified',
29
29
  severity: 'critical',
30
30
  title: "Your Stripe webhook doesn't check that messages really come from Stripe",
31
+ display: {
32
+ title: "Anyone can fake a Stripe payment: your webhook doesn't check signatures",
33
+ reason: 'fake "payment succeeded" messages are accepted',
34
+ },
31
35
  why: 'Anyone can send a fake "payment succeeded" message to your webhook URL and get your product for free. Stripe signs every webhook; your code has to verify that signature.',
32
36
  location: loc,
33
37
  fixPrompt: `My Stripe webhook handler (${where(loc)}) does not verify the Stripe signature. Please update it to:\n` +
@@ -114,6 +118,10 @@ function checkWebhooks(ctx, out, server, p) {
114
118
  id: `${p.prefix}-webhook-unverified`,
115
119
  severity: 'critical',
116
120
  title: `Your ${p.name} webhook doesn't check that messages really come from ${p.name}`,
121
+ display: {
122
+ title: `Anyone can fake a ${p.name} payment: your webhook doesn't check signatures`,
123
+ reason: 'fake "payment succeeded" messages are accepted',
124
+ },
117
125
  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
126
  location: loc,
119
127
  fixPrompt: p.unverifiedFix(loc),
@@ -289,6 +297,10 @@ export const paymentsCheck = {
289
297
  id: 'razorpay-unverified',
290
298
  severity: 'critical',
291
299
  title: "Razorpay payments aren't verified on your server",
300
+ display: {
301
+ title: "Anyone can fake a Razorpay payment: payments aren't verified on your server",
302
+ reason: "Razorpay's signature is never checked",
303
+ },
292
304
  why: "Without checking Razorpay's signature on your server, someone can fake a successful payment from their browser and get your product without paying.",
293
305
  location: m ? at(m) : undefined,
294
306
  fixPrompt: `My app uses Razorpay but never verifies payments on the server. Please: after checkout, send razorpay_order_id, razorpay_payment_id and razorpay_signature to a server route ` +
@@ -1,4 +1,4 @@
1
- import type { Check, Severity } from '../types.js';
1
+ import type { Check, FindingDisplay, Severity } from '../types.js';
2
2
  interface KeyPattern {
3
3
  id: string;
4
4
  name: string;
@@ -19,6 +19,31 @@ export interface KeyMatch {
19
19
  /** Every real-looking API key in a piece of text (placeholders like "sk_live_xxxx" are skipped). */
20
20
  export declare function matchKeys(text: string): KeyMatch[];
21
21
  export type { KeyPattern };
22
+ /** The provider table, for tests: display entries and usage links by finding id. */
23
+ export declare const KEY_PROVIDERS: {
24
+ display: Record<string, {
25
+ title: string;
26
+ url?: string;
27
+ }>;
28
+ usage: Record<string, string>;
29
+ };
30
+ /** Every key kind the secret checks can report, for tests. */
31
+ export declare function allKeyPatterns(): KeyPattern[];
32
+ /** Where to revoke a leaked key of this kind: the provider's key page, or the menu path to it. */
33
+ export declare function rotateHint(p: KeyPattern): string;
34
+ /** The provider's usage or activity log for this kind of key, when we know it. */
35
+ export declare function usageLink(id: string): string | undefined;
36
+ /**
37
+ * What to do after rotating a leaked key, added to the end of its fix prompt: check the usage log for someone else's
38
+ * activity, look for other keys in old commits (--history) and check the live site (scan <url>). The pointer that
39
+ * the finding itself came from (history, or a live scan) is left out.
40
+ */
41
+ export declare function leakPlaybook(opts: {
42
+ usage?: string;
43
+ from?: 'history' | 'live';
44
+ }): string;
45
+ /** Display for a leaked key of this kind (title, where to rotate it and where to check its use). */
46
+ export declare function keyDisplay(p: KeyPattern, reason?: string): FindingDisplay;
22
47
  export declare function isSensitivePublicName(rest: string): boolean;
23
48
  /**
24
49
  * Does this value (of a variable whose name sounds secret) look like a real secret? Empty values,
@@ -229,6 +229,205 @@ export function matchKeys(text) {
229
229
  }
230
230
  return out;
231
231
  }
232
+ /**
233
+ * How the short terminal report names a leaked key: what someone can do with it, then where it is.
234
+ * url: the provider's page for revoking keys (the menu path in `rotate` is used when there is none).
235
+ */
236
+ const KEY_DISPLAY = {
237
+ 'stripe-live-key': {
238
+ title: 'Anyone can use your Stripe account: the live secret key is in your code',
239
+ url: 'https://dashboard.stripe.com/apikeys',
240
+ },
241
+ 'stripe-test-key': {
242
+ title: 'Anyone can use your Stripe test account: the test secret key is in your code',
243
+ url: 'https://dashboard.stripe.com/test/apikeys',
244
+ },
245
+ 'anthropic-key': {
246
+ title: 'Anyone can run up your Anthropic bill: the API key is in your code',
247
+ url: 'https://console.anthropic.com/settings/keys',
248
+ },
249
+ 'openrouter-key': {
250
+ title: 'Anyone can run up your OpenRouter bill: the API key is in your code',
251
+ url: 'https://openrouter.ai/settings/keys',
252
+ },
253
+ 'openai-key': {
254
+ title: 'Anyone can run up your OpenAI bill: the API key is in your code',
255
+ url: 'https://platform.openai.com/api-keys',
256
+ },
257
+ 'supabase-secret-key': {
258
+ title: 'Anyone can read and delete all your Supabase data: the secret key is in your code',
259
+ url: 'https://supabase.com/dashboard/project/_/settings/api-keys',
260
+ },
261
+ 'stripe-webhook-secret': {
262
+ title: 'Anyone can fake Stripe payment events: the webhook secret is in your code',
263
+ url: 'https://dashboard.stripe.com/webhooks',
264
+ },
265
+ 'groq-key': {
266
+ title: 'Anyone can run up your Groq bill: the API key is in your code',
267
+ url: 'https://console.groq.com/keys',
268
+ },
269
+ 'huggingface-token': {
270
+ title: 'Anyone can use your Hugging Face account: the token is in your code',
271
+ url: 'https://huggingface.co/settings/tokens',
272
+ },
273
+ 'aws-key': {
274
+ title: 'Anyone can use your AWS account: the access key is in your code',
275
+ url: 'https://console.aws.amazon.com/iam/home#/security_credentials',
276
+ },
277
+ 'github-token': {
278
+ title: 'Anyone can use your GitHub account: the token is in your code',
279
+ url: 'https://github.com/settings/tokens',
280
+ },
281
+ 'slack-token': {
282
+ title: 'Anyone can post as your Slack app: the token is in your code',
283
+ url: 'https://api.slack.com/apps',
284
+ },
285
+ 'sendgrid-key': {
286
+ title: 'Anyone can send email as you: the SendGrid API key is in your code',
287
+ url: 'https://app.sendgrid.com/settings/api_keys',
288
+ },
289
+ 'resend-key': {
290
+ title: 'Anyone can send email as you: the Resend API key is in your code',
291
+ url: 'https://resend.com/api-keys',
292
+ },
293
+ 'private-key': { title: 'Anyone can use your private key: it is in your code' },
294
+ 'paddle-live-key': { title: 'Anyone can use your Paddle account: the live API key is in your code' },
295
+ 'paddle-sandbox-key': { title: 'Anyone can use your Paddle sandbox: the API key is in your code' },
296
+ 'convex-deploy-key': {
297
+ title: 'Anyone can deploy to your Convex backend: the deploy key is in your code',
298
+ url: 'https://dashboard.convex.dev',
299
+ },
300
+ 'appwrite-api-key': { title: 'Anyone can read and change your Appwrite data: the API key is in your code' },
301
+ 'clerk-secret-key': {
302
+ title: 'Anyone can manage your users: the Clerk secret key is in your code',
303
+ url: 'https://dashboard.clerk.com/last-active?path=api-keys',
304
+ },
305
+ 'clerk-test-secret-key': {
306
+ title: 'Anyone can manage your Clerk test users: the development secret key is in your code',
307
+ url: 'https://dashboard.clerk.com/last-active?path=api-keys',
308
+ },
309
+ 'lemonsqueezy-api-key': {
310
+ title: 'Anyone can use your Lemon Squeezy store: the API key is in your code',
311
+ url: 'https://app.lemonsqueezy.com/settings/api',
312
+ },
313
+ };
314
+ /**
315
+ * Where to see what a key was used for (request, usage or activity logs), to check whether someone else used it
316
+ * before it was rotated. Only pages we are sure of; other providers get a general pointer instead.
317
+ */
318
+ const KEY_USAGE = {
319
+ 'stripe-live-key': 'https://dashboard.stripe.com/logs',
320
+ 'stripe-test-key': 'https://dashboard.stripe.com/test/logs',
321
+ 'openai-key': 'https://platform.openai.com/usage',
322
+ 'openrouter-key': 'https://openrouter.ai/activity',
323
+ 'supabase-secret-key': 'https://supabase.com/dashboard/project/_/logs/explorer',
324
+ 'supabase-service-role-key': 'https://supabase.com/dashboard/project/_/logs/explorer',
325
+ 'aws-key': 'https://console.aws.amazon.com/cloudtrail/home',
326
+ 'github-token': 'https://github.com/settings/security-log',
327
+ 'sendgrid-key': 'https://app.sendgrid.com/email_activity',
328
+ 'resend-key': 'https://resend.com/emails',
329
+ };
330
+ /** The provider table, for tests: display entries and usage links by finding id. */
331
+ export const KEY_PROVIDERS = { display: KEY_DISPLAY, usage: KEY_USAGE };
332
+ /** Every key kind the secret checks can report, for tests. */
333
+ export function allKeyPatterns() {
334
+ return [...KEY_PATTERNS, ...Object.values(CLERK_KEYS), LEMON_SQUEEZY_KEY];
335
+ }
336
+ /** Where to revoke a leaked key of this kind: the provider's key page, or the menu path to it. */
337
+ export function rotateHint(p) {
338
+ return KEY_DISPLAY[p.id]?.url ?? p.rotate;
339
+ }
340
+ /** The provider's usage or activity log for this kind of key, when we know it. */
341
+ export function usageLink(id) {
342
+ return KEY_USAGE[id];
343
+ }
344
+ /**
345
+ * What to do after rotating a leaked key, added to the end of its fix prompt: check the usage log for someone else's
346
+ * activity, look for other keys in old commits (--history) and check the live site (scan <url>). The pointer that
347
+ * the finding itself came from (history, or a live scan) is left out.
348
+ */
349
+ export function leakPlaybook(opts) {
350
+ const steps = [
351
+ opts.usage
352
+ ? `check ${opts.usage} for activity I don't recognise from before the key was rotated`
353
+ : "check the provider's usage or activity log for activity I don't recognise from before the key was rotated",
354
+ ...(opts.from === 'history' ? [] : ['run `npx launch-doctor --history` to find keys still in old git commits']),
355
+ ...(opts.from === 'live'
356
+ ? []
357
+ : [
358
+ "after deploying, run `npx launch-doctor scan https://my-site.com` to check the live site doesn't still serve the key",
359
+ ]),
360
+ ];
361
+ return `\nAfter that, remind me to:\n${steps.map((s) => `- ${s}`).join('\n')}`;
362
+ }
363
+ /** Display for a leaked key of this kind (title, where to rotate it and where to check its use). */
364
+ export function keyDisplay(p, reason) {
365
+ const usage = usageLink(p.id);
366
+ return {
367
+ title: KEY_DISPLAY[p.id]?.title ?? `Anyone can use your ${p.name}: it is in your code`,
368
+ ...(reason ? { reason } : {}),
369
+ rotate: rotateHint(p),
370
+ ...(usage ? { usage } : {}),
371
+ };
372
+ }
373
+ /**
374
+ * A secret in a public variable (an OpenAI key behind a VITE_ prefix, say): what it unlocks, and where to rotate
375
+ * it, guessed from the variable's name.
376
+ * The first match wins, so the more specific names come first.
377
+ */
378
+ const PUBLIC_VAR_PROVIDERS = [
379
+ [
380
+ /SERVICE_ROLE/,
381
+ 'read and delete every row in your database',
382
+ 'https://supabase.com/dashboard/project/_/settings/api-keys',
383
+ 'https://supabase.com/dashboard/project/_/logs/explorer',
384
+ ],
385
+ [/DATABASE_URL|DB_URL|POSTGRES_URL|MONGODB_URI|MONGO_URI|PASSWORD|PASSWD/, 'log into your database'],
386
+ [/OPENAI/, 'run up your OpenAI bill', 'https://platform.openai.com/api-keys', 'https://platform.openai.com/usage'],
387
+ [/ANTHROPIC|CLAUDE/, 'run up your Anthropic bill', 'https://console.anthropic.com/settings/keys'],
388
+ [/GEMINI/, 'run up your Google AI bill', 'https://aistudio.google.com/app/apikey'],
389
+ [/GROQ/, 'run up your Groq bill', 'https://console.groq.com/keys'],
390
+ [
391
+ /OPENROUTER/,
392
+ 'run up your OpenRouter bill',
393
+ 'https://openrouter.ai/settings/keys',
394
+ 'https://openrouter.ai/activity',
395
+ ],
396
+ [/MISTRAL/, 'run up your Mistral bill'],
397
+ [/DEEPSEEK/, 'run up your DeepSeek bill'],
398
+ [/PERPLEXITY/, 'run up your Perplexity bill'],
399
+ [/REPLICATE/, 'run up your Replicate bill'],
400
+ [/HUGGING|HF_TOKEN/, 'use your Hugging Face account', 'https://huggingface.co/settings/tokens'],
401
+ [/COHERE/, 'run up your Cohere bill'],
402
+ [/TOGETHER/, 'run up your Together AI bill'],
403
+ [/ELEVENLABS/, 'run up your ElevenLabs bill'],
404
+ [/RESEND/, 'send email as you', 'https://resend.com/api-keys', 'https://resend.com/emails'],
405
+ [
406
+ /SENDGRID/,
407
+ 'send email as you',
408
+ 'https://app.sendgrid.com/settings/api_keys',
409
+ 'https://app.sendgrid.com/email_activity',
410
+ ],
411
+ [/MAILGUN|POSTMARK/, 'send email as you'],
412
+ [/TWILIO/, 'send texts on your bill'],
413
+ [/STRIPE/, 'use your Stripe account', 'https://dashboard.stripe.com/apikeys', 'https://dashboard.stripe.com/logs'],
414
+ [/LEMON_?SQUEEZY/, 'use your Lemon Squeezy store', 'https://app.lemonsqueezy.com/settings/api'],
415
+ [/PADDLE/, 'use your Paddle account'],
416
+ [/CONVEX_DEPLOY/, 'deploy to your Convex backend', 'https://dashboard.convex.dev'],
417
+ [/APPWRITE/, 'read and change your Appwrite data'],
418
+ ];
419
+ function publicVariableDisplay(name, mobile) {
420
+ const hit = PUBLIC_VAR_PROVIDERS.find(([re]) => re.test(name));
421
+ const where = mobile ? 'your app' : 'your website';
422
+ return {
423
+ title: hit
424
+ ? `Anyone can ${hit[1]}: the key is public in ${where}`
425
+ : `Anyone can read a secret: it is public in ${where}`,
426
+ reason: mobile ? `${name} is built into your app` : `${name} is copied into your site's JavaScript`,
427
+ rotate: hit?.[2] ?? "in that provider's dashboard",
428
+ ...(hit?.[3] ? { usage: hit[3] } : {}),
429
+ };
430
+ }
232
431
  const DB_URL_RE = /\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|rediss?):\/\/([^:\s'"`/@]+):([^@\s'"`]+)@([^\s'"`/:?,]+)/g;
233
432
  const LOCAL_HOST_RE = /^(localhost|127\.0\.0\.1|0\.0\.0\.0|host\.docker\.internal|db|database|postgres|mysql|mongo|mongodb|redis)$/i;
234
433
  const WEAK_PLACEHOLDER_PW = /^(password|pass|postgres|root|secret|admin|pwd|user|mysql|test)$/i;
@@ -316,11 +515,17 @@ function hardcodedFinding(ctx, p, m) {
316
515
  ? shipped
317
516
  : `Anyone who can see your code (GitHub, collaborators, AI tools) can copy this key (${shown}) and use your account. Keys belong in environment variables.`,
318
517
  location: at(m),
518
+ display: keyDisplay(p, !client
519
+ ? 'visible to anyone who can see your code'
520
+ : ctx.isMobileFile(m.file.path)
521
+ ? 'built into your app'
522
+ : "sent to every visitor's browser"),
319
523
  fixPrompt: `In ${where(at(m))} there is a hard-coded ${p.name} (it starts with "${shown}"). Please:\n` +
320
524
  `1. Move it into an environment variable called ${p.envName} in my .env file and read it with process.env.${p.envName}, only in server-side code (never in browser/frontend code).\n` +
321
525
  `2. Make sure .env is listed in .gitignore.\n` +
322
526
  `3. Search the whole project for any other copies of this key and remove them.\n` +
323
- `Then tell me step by step how to revoke this key and create a new one (${p.rotate}), because it has probably already leaked.`,
527
+ `Then tell me step by step how to revoke this key and create a new one (${p.rotate}), because it has probably already leaked.` +
528
+ leakPlaybook({ usage: usageLink(p.id) }),
324
529
  };
325
530
  }
326
531
  function capitalize(s) {
@@ -382,6 +587,10 @@ export const secretsCheck = {
382
587
  title: 'Your database password is written directly in your code',
383
588
  why: 'Anyone who sees this file can log straight into your database and read, change or delete everything.',
384
589
  location: at(m),
590
+ display: {
591
+ title: 'Anyone can log into your database: the password is in your code',
592
+ reason: 'visible to anyone who can see this file',
593
+ },
385
594
  fixPrompt: `In ${where(at(m))} there is a database connection string with the password written in it. ` +
386
595
  `Move it into an environment variable called DATABASE_URL in .env (make sure .env is in .gitignore), ` +
387
596
  `read it with process.env.DATABASE_URL only on the server, and remove every hard-coded copy. ` +
@@ -416,10 +625,17 @@ export const secretsCheck = {
416
625
  title: 'Supabase service_role key is written directly in your code',
417
626
  why: 'The service_role key skips all of your database security rules (RLS). Anyone who finds it can read and delete every row in every table.',
418
627
  location: at(m),
628
+ display: {
629
+ title: 'Anyone can read and delete every row: the Supabase service_role key is in your code',
630
+ reason: 'this key skips Row Level Security',
631
+ rotate: 'https://supabase.com/dashboard/project/_/settings/api-keys',
632
+ usage: 'https://supabase.com/dashboard/project/_/logs/explorer',
633
+ },
419
634
  fixPrompt: `In ${where(at(m))} my Supabase service_role key is hard-coded. Please remove it from the code. ` +
420
635
  `Frontend code must only use the anon (public) key. If some feature truly needs admin access, move that code into a server-only place ` +
421
636
  `(an API route or a Supabase Edge Function) that reads SUPABASE_SERVICE_ROLE_KEY from environment variables. ` +
422
- `Then tell me how to rotate the service_role key / JWT secret in the Supabase dashboard.`,
637
+ `Then tell me how to rotate the service_role key / JWT secret in the Supabase dashboard.` +
638
+ leakPlaybook({ usage: usageLink('supabase-service-role-key') }),
423
639
  });
424
640
  }
425
641
  if (hardcoded === 0)
@@ -427,7 +643,12 @@ export const secretsCheck = {
427
643
  // 4. Secrets exposed through "public" env variable names
428
644
  const publicHits = new Map();
429
645
  // Big apps reference public variables thousands of times, so don't stop early.
430
- for (const m of ctx.find(PUBLIC_VAR_RE, (f) => isCodeFile(f) || isEnvPath(f.path), 200_000)) {
646
+ // A name that only appears in a comment ("// never use VITE_..._KEY") exposes nothing, so comments are left
647
+ // out: findCode() blanks them in code files, and commented-out lines are skipped in .env files.
648
+ // Real key values are still found in comments, by the hard-coded key search above, which reads raw text.
649
+ for (const m of ctx.findCode(PUBLIC_VAR_RE, (f) => isCodeFile(f) || isEnvPath(f.path), 200_000)) {
650
+ if (isEnvPath(m.file.path) && /^\s*#/.test(lineTextAt(m.file.content, m.index)))
651
+ continue;
431
652
  const full = m.match[0];
432
653
  if (!isSensitivePublicName(m.match[2]) || publicHits.has(full))
433
654
  continue;
@@ -459,11 +680,13 @@ export const secretsCheck = {
459
680
  ? '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
681
  : `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.`,
461
682
  location: loc,
683
+ display: publicVariableDisplay(name, prefix === 'EXPO_PUBLIC_'),
462
684
  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` +
463
685
  `1. Rename it to a server-only name without the ${prefix} prefix.\n` +
464
686
  `2. Move every piece of code that uses it into server-side code (an API route, server action, or Supabase Edge Function) and make the frontend call that instead.\n` +
465
687
  `3. Update .env and .env.example.\n` +
466
- `Then tell me how to rotate this key in the provider's dashboard, because it has already been public.`,
688
+ `Then tell me how to rotate this key in the provider's dashboard, because it has already been public.` +
689
+ leakPlaybook({ usage: publicVariableDisplay(name, prefix === 'EXPO_PUBLIC_').usage }),
467
690
  });
468
691
  }
469
692
  if (publicHits.size === 0) {
@@ -488,9 +711,18 @@ export const secretsCheck = {
488
711
  ? '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
712
  : "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.",
490
713
  location: { file: f.path },
714
+ ...(real
715
+ ? {
716
+ display: {
717
+ title: `Your secret keys are in git: ${f.path} is committed`,
718
+ reason: 'they stay in git history, so rotate every key in it',
719
+ },
720
+ }
721
+ : {}),
491
722
  fixPrompt: real
492
723
  ? `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.`
724
+ `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.` +
725
+ leakPlaybook({})
494
726
  : `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
727
  `and add ${f.path} to .gitignore, so each developer's real values stay on their own machine.`,
496
728
  });
@@ -507,6 +739,14 @@ export const secretsCheck = {
507
739
  ? 'The next "git add ." will upload your secret keys along with your code.'
508
740
  : 'As soon as you put this project on GitHub, your secret keys will be uploaded with it.',
509
741
  location: { file: f.path },
742
+ ...(ctx.gitRoot && real
743
+ ? {
744
+ display: {
745
+ title: `Your secret keys will be uploaded with your code: ${f.path} is not in .gitignore`,
746
+ reason: 'the next "git add ." includes it',
747
+ },
748
+ }
749
+ : {}),
510
750
  fixPrompt: `Add ${f.path} (and other .env files except .env.example) to my .gitignore so my secret keys are never committed. ` +
511
751
  `Use a pattern like ".env*" followed by "!.env.example". Then create .env.example with the same variable names but empty values.`,
512
752
  });