launch-doctor 0.3.0 → 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 (61) hide show
  1. package/CHANGELOG.md +77 -6
  2. package/LICENSE +1 -0
  3. package/README.md +95 -20
  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 +7 -0
  13. package/dist/src/checks/costs.js +14 -6
  14. package/dist/src/checks/database.js +79 -3
  15. package/dist/src/checks/first-impressions.js +22 -2
  16. package/dist/src/checks/legal.js +3 -1
  17. package/dist/src/checks/monitoring.js +8 -5
  18. package/dist/src/checks/payments.js +10 -2
  19. package/dist/src/checks/secrets.d.ts +8 -0
  20. package/dist/src/checks/secrets.js +82 -9
  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 +111 -9
  24. package/dist/src/demo.js +1 -0
  25. package/dist/src/detect.d.ts +1 -1
  26. package/dist/src/detect.js +1 -1
  27. package/dist/src/fixes.js +8 -5
  28. package/dist/src/git.d.ts +25 -0
  29. package/dist/src/git.js +121 -0
  30. package/dist/src/github.d.ts +11 -1
  31. package/dist/src/github.js +56 -14
  32. package/dist/src/history.js +17 -3
  33. package/dist/src/hook.d.ts +13 -0
  34. package/dist/src/hook.js +96 -0
  35. package/dist/src/hooks-setup.d.ts +24 -0
  36. package/dist/src/hooks-setup.js +187 -0
  37. package/dist/src/ignore.d.ts +36 -0
  38. package/dist/src/ignore.js +164 -0
  39. package/dist/src/index.js +28 -3
  40. package/dist/src/live.d.ts +9 -0
  41. package/dist/src/live.js +73 -22
  42. package/dist/src/mcp.js +7 -2
  43. package/dist/src/net-guard.d.ts +34 -0
  44. package/dist/src/net-guard.js +144 -0
  45. package/dist/src/project.d.ts +34 -5
  46. package/dist/src/project.js +145 -111
  47. package/dist/src/report.d.ts +2 -0
  48. package/dist/src/report.js +11 -0
  49. package/dist/src/routes.d.ts +10 -0
  50. package/dist/src/routes.js +21 -4
  51. package/dist/src/safe-fs.d.ts +19 -0
  52. package/dist/src/safe-fs.js +77 -0
  53. package/dist/src/sanitize.d.ts +17 -0
  54. package/dist/src/sanitize.js +90 -0
  55. package/dist/src/sarif.js +1 -1
  56. package/dist/src/summary.d.ts +4 -0
  57. package/dist/src/summary.js +9 -4
  58. package/dist/src/types.d.ts +24 -0
  59. package/dist/src/util.d.ts +1 -1
  60. package/dist/src/util.js +1 -1
  61. package/package.json +9 -5
@@ -1,6 +1,13 @@
1
1
  import type { SourceFile } from '../project.js';
2
2
  import type { Check } from '../types.js';
3
3
  export declare function hasCustomLimiter(code: string): boolean;
4
+ /** Code in a middleware file that actually turns away signed-out requests. */
5
+ export declare const MIDDLEWARE_BLOCKS: RegExp;
6
+ /**
7
+ * The strings in `matcher: "..."` or `matcher: ["...", "..."]`, or null if there is no matcher.
8
+ * Read string by string, because matcher patterns often contain "]" themselves.
9
+ */
10
+ export declare function matcherEntries(content: string): string[] | null;
4
11
  /**
5
12
  * True when a Next.js-style middleware (or proxy) file blocks signed-out users AND runs on /api routes.
6
13
  * Middleware that only refreshes the session (e.g. Supabase's updateSession) doesn't count.
@@ -1,5 +1,5 @@
1
1
  import { AUTH_CHECK_RE } from '../detect.js';
2
- import { authIsUsed, evidenceOf, handlersOf, matcherCovers } from '../routes.js';
2
+ import { authIsUsed, evidenceOf, handlersOf, matcherCovers, withoutImports } from '../routes.js';
3
3
  import { lineTextAt, uniqueBy } from '../util.js';
4
4
  import { appCode, at, clientCode, emptyOutput, isRouteLike, notApplicable, serverCode, where } from './common.js';
5
5
  const AI_PACKAGES = [
@@ -23,7 +23,12 @@ const AI_PACKAGES = [
23
23
  '@openrouter/ai-sdk-provider',
24
24
  ];
25
25
  /** SDKs that need a secret key, so they must never run in the browser. */
26
- const BROWSER_FORBIDDEN_IMPORT = /(?:\bfrom\s*|\brequire\s*\(\s*|\bimport\s*\(\s*)["'](?:npm:)?(openai|@anthropic-ai\/sdk|@google\/generative-ai|@google\/genai|groq-sdk|@mistralai\/mistralai|replicate|cohere-ai|together-ai|twilio)(?:[@/][^"']*)?["']/;
26
+ const BROWSER_FORBIDDEN_IMPORT = /(?:\bfrom\s*|\brequire\s*\(\s*|\bimport\s*\(\s*)["'](?:npm:)?(openai|@anthropic-ai\/sdk|@google\/generative-ai|@google\/genai|groq-sdk|@mistralai\/mistralai|replicate|cohere-ai|together-ai|twilio)((?:[@/][^"']*)?)["']/;
27
+ /**
28
+ * "together-ai/lib/ChatCompletionStream.mjs" is a helper for reading a stream your own server sends, not the
29
+ * client that holds the key. A deep import counts only when it is the package's index file.
30
+ */
31
+ const isHelperSubpath = (sub) => !!sub && sub.startsWith('/') && !/^\/index(?:\.[cm]?js)?$/.test(sub);
27
32
  const AI_DIRECT_URL = /api\.openai\.com|api\.anthropic\.com|generativelanguage\.googleapis\.com|api\.groq\.com|openrouter\.ai\/api|api\.mistral\.ai|api\.deepseek\.com|api\.replicate\.com|api\.elevenlabs\.io|api\.together\.xyz/;
28
33
  const AI_CALL = /\.chat\.completions\.create\s*\(|\.responses\.create\s*\(|\.messages\.(?:create|stream)\s*\(|\b(?:generateText|streamText|generateObject|streamObject)\s*\(|\.generateContent(?:Stream)?\s*\(|\.images\.generate\s*\(|\.audio\.speech\.create\s*\(/;
29
34
  const RATE_LIMIT_PACKAGES = [
@@ -68,12 +73,12 @@ function rateLimitLibrary(ctx) {
68
73
  return 'a rate-limiting library that fits my stack';
69
74
  }
70
75
  /** Code in a middleware file that actually turns away signed-out requests. */
71
- const MIDDLEWARE_BLOCKS = /\.protect\s*\(|status\s*:\s*401|NextResponse\.redirect\s*\(|\bredirect\s*\([^)]*["'`][^"'`]*\/(?:login|sign-?in)\b/i;
76
+ export const MIDDLEWARE_BLOCKS = /\.protect\s*\(|status\s*:\s*401|NextResponse\.redirect\s*\(|\bredirect\s*\([^)]*["'`][^"'`]*\/(?:login|sign-?in)\b/i;
72
77
  /**
73
78
  * The strings in `matcher: "..."` or `matcher: ["...", "..."]`, or null if there is no matcher.
74
79
  * Read string by string, because matcher patterns often contain "]" themselves.
75
80
  */
76
- function matcherEntries(content) {
81
+ export function matcherEntries(content) {
77
82
  const start = /matcher\s*:\s*/.exec(content);
78
83
  if (!start)
79
84
  return null;
@@ -143,7 +148,8 @@ export const costsCheck = {
143
148
  // "import type" is removed at build time, so it never reaches the browser.
144
149
  const realImports = ctx
145
150
  .find(BROWSER_FORBIDDEN_IMPORT, client)
146
- .filter((m) => !/^\s*(?:import|export)\s+type\b/.test(lineTextAt(m.file.content, m.index)));
151
+ .filter((m) => !/^\s*(?:import|export)\s+type\b/.test(lineTextAt(m.file.content, m.index)))
152
+ .filter((m) => !isHelperSubpath(m.match[2]));
147
153
  const browserHits = uniqueBy([...realImports, ...ctx.find(AI_DIRECT_URL, client), ...ctx.find(/dangerouslyAllowBrowser\s*:\s*true/, appCode)], (m) => m.file.path);
148
154
  for (const m of browserHits.slice(0, 3)) {
149
155
  out.findings.push({
@@ -170,7 +176,9 @@ export const costsCheck = {
170
176
  const aiHandlers = handlers.filter((h) => AI_CALL.test(evidenceOf(ctx, h).calls));
171
177
  const unprotectedHandlers = aiHandlers.filter((h) => !authIsUsed(AUTH_CHECK_RE, evidenceOf(ctx, h)) && !middlewareCovers(ctx, h, MIDDLEWARE_BLOCKS));
172
178
  const aiRoutes = uniqueBy(ctx.find(AI_CALL, (f) => server(f) && isRouteLike(f) && !analysed.has(f.path)), (m) => m.file.path);
173
- const unprotected = middlewareProtects ? [] : aiRoutes.filter((m) => !AUTH_CHECK_RE.test(ctx.codeOf(m.file)));
179
+ const unprotected = middlewareProtects
180
+ ? []
181
+ : aiRoutes.filter((m) => !AUTH_CHECK_RE.test(withoutImports(ctx.codeOf(m.file))));
174
182
  for (const m of unprotected.slice(0, 3)) {
175
183
  out.findings.push({
176
184
  id: 'ai-endpoint-no-auth',
@@ -2,6 +2,7 @@ import { detectAuth, detectDatabase } from '../detect.js';
2
2
  import { isTestPath } from '../project.js';
3
3
  import { lineAt, plural } from '../util.js';
4
4
  import { appCode, at, emptyOutput, notApplicable, where } from './common.js';
5
+ import { analyzeStorage, PRIVATE_BUCKET_NAME } from './supabase-storage.js';
5
6
  // ---------- Convex ----------
6
7
  /** Public Convex functions that can change data. internalMutation / internalAction can't be called from outside. */
7
8
  const CONVEX_PUBLIC_WRITE = /export\s+const\s+(\w+)\s*=\s*(mutation|action)\s*\(/g;
@@ -64,9 +65,13 @@ function analyzeSupabaseSql(files) {
64
65
  else
65
66
  rls.delete(name);
66
67
  }
67
- const policyRe = /create\s+policy\s+("([^"]+)"|(\w+))\s+on\s+(?:"?\w+"?\s*\.\s*)?"?(\w+)"?([\s\S]*?);/gi;
68
+ const policyRe = /create\s+policy\s+("([^"]+)"|(\w+))\s+on\s+(?:"?(\w+)"?\s*\.\s*)?"?(\w+)"?([\s\S]*?);/gi;
68
69
  while ((m = policyRe.exec(sql))) {
69
- const body = m[5] ?? '';
70
+ const schema = (m[4] ?? 'public').toLowerCase();
71
+ // Storage policies (storage.objects) are judged by the storage check, which knows about buckets.
72
+ if (schema === 'storage')
73
+ continue;
74
+ const body = m[6] ?? '';
70
75
  const open = /(?:using|with\s+check)\s*\(\s*true\s*\)/i.test(body);
71
76
  if (!open)
72
77
  continue;
@@ -86,11 +91,13 @@ function analyzeSupabaseSql(files) {
86
91
  kind = 'signed-in-write';
87
92
  else if (!writes && toEveryone)
88
93
  kind = 'public-read';
94
+ else if (!writes && toSignedIn)
95
+ kind = 'signed-in-read';
89
96
  if (kind) {
90
97
  policies.push({
91
98
  kind,
92
99
  name: m[2] ?? m[3] ?? 'policy',
93
- table: m[4].toLowerCase(),
100
+ table: m[5].toLowerCase(),
94
101
  loc: { file: file.path, line: lineAt(sql, m.index) },
95
102
  });
96
103
  }
@@ -107,8 +114,12 @@ export const databaseCheck = {
107
114
  'supabase-rls-missing',
108
115
  'supabase-open-policy',
109
116
  'supabase-signed-in-write-policy',
117
+ 'supabase-signed-in-read-policy',
110
118
  'supabase-public-read',
111
119
  'supabase-rls-dashboard',
120
+ 'supabase-public-bucket',
121
+ 'supabase-storage-open-write',
122
+ 'supabase-storage-dashboard',
112
123
  'firebase-open-rules',
113
124
  'firebase-rules-console',
114
125
  'convex-public-mutation',
@@ -175,6 +186,71 @@ export const databaseCheck = {
175
186
  `Please change it so users can only change rows they own (e.g. using (auth.uid() = user_id) with check (auth.uid() = user_id)), adding a user_id column if the table needs one.`,
176
187
  });
177
188
  }
189
+ for (const p of policies.filter((x) => x.kind === 'signed-in-read').slice(0, 3)) {
190
+ out.findings.push({
191
+ id: 'supabase-signed-in-read-policy',
192
+ severity: 'warning',
193
+ title: `Supabase policy "${p.name}": any signed-in user can read every row in ${p.table}`,
194
+ why: 'The policy is limited to signed-in users, but its rule is "true". Anyone who creates a free account can read every row, ' +
195
+ "including other people's data. This is how many AI-built apps have leaked their users' emails, messages and orders.",
196
+ location: p.loc,
197
+ fixPrompt: `In ${where(p.loc)} the Supabase policy "${p.name}" on "${p.table}" is "for select to authenticated using (true)", so any signed-in user can read every row. ` +
198
+ `Please write a new SQL migration that drops it and creates a policy that only lets users read their own rows: ` +
199
+ `create policy "Users read their own ${p.table}" on public.${p.table} for select to authenticated using ((select auth.uid()) = user_id); ` +
200
+ `adding a user_id uuid column (references auth.users, default auth.uid()) if the table doesn't have one. ` +
201
+ `If every signed-in user really is meant to see every row (for example a shared list of categories), keep the policy, tell me so, and explain why that data is safe to share.`,
202
+ });
203
+ }
204
+ // ---- Supabase Storage ----
205
+ const storage = analyzeStorage(ctx);
206
+ const privateLooking = storage.buckets.filter((b) => PRIVATE_BUCKET_NAME.test(b.name));
207
+ for (const b of privateLooking.slice(0, 3)) {
208
+ out.findings.push({
209
+ id: 'supabase-public-bucket',
210
+ severity: 'warning',
211
+ title: `Supabase Storage bucket "${b.name}" is public, but its name suggests private files`,
212
+ why: 'Every file in a public bucket can be downloaded by anyone who has its URL, with no sign-in and no policy check. ' +
213
+ 'URLs end up in emails, logs and browser history, and names are often easy to guess. Invoices, IDs and documents should not be there.',
214
+ location: b.loc,
215
+ fixPrompt: `In ${where(b.loc)} the Supabase Storage bucket "${b.name}" is made public. ` +
216
+ `Please make it private (public = false in the SQL migration or supabase/config.toml, or in Supabase → Storage → bucket settings), ` +
217
+ `add storage.objects policies so users can only read their own files (for example: for select to authenticated using (bucket_id = '${b.name}' and (select auth.uid())::text = (storage.foldername(name))[1])), ` +
218
+ `store each user's files under a folder named after their user id, and serve files with supabase.storage.from('${b.name}').createSignedUrl(path, 60) instead of getPublicUrl(). ` +
219
+ `If these files really are meant to be public, keep it and tell me why that is safe.`,
220
+ });
221
+ }
222
+ for (const p of storage.policies.slice(0, 3)) {
223
+ const scope = p.buckets.length
224
+ ? `the ${p.buckets.map((b) => `"${b}"`).join(', ')} bucket${p.buckets.length > 1 ? 's' : ''}`
225
+ : 'every bucket';
226
+ const who = p.signedIn ? 'any signed-in user' : 'anyone, even signed-out visitors,';
227
+ const what = p.insertOnly ? 'upload files to' : 'replace or delete every file in';
228
+ out.findings.push({
229
+ id: 'supabase-storage-open-write',
230
+ severity: p.signedIn || p.insertOnly ? 'warning' : 'critical',
231
+ title: `Supabase Storage policy "${p.name}" lets ${who.replace(/,$/, '')} ${what} ${scope}`,
232
+ why: p.insertOnly
233
+ ? '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.'
234
+ : `The policy only checks which bucket a file is in, not who owns it, so ${who.replace(/,$/, '')} can overwrite or delete other people's files.`,
235
+ location: p.loc,
236
+ fixPrompt: `In ${where(p.loc)} the Supabase Storage policy "${p.name}" on storage.objects lets ${who} ${what} ${scope}. ` +
237
+ `Please write a new SQL migration that drops it and creates policies for authenticated users only, limited to their own folder: ` +
238
+ `using (bucket_id = '${p.buckets[0] ?? '<bucket>'}' and (select auth.uid())::text = (storage.foldername(name))[1]) ` +
239
+ `(and the same condition in "with check" for uploads), and upload each user's files under a folder named after their user id.`,
240
+ });
241
+ }
242
+ if (storage.usesStorage) {
243
+ const others = storage.buckets.filter((b) => !PRIVATE_BUCKET_NAME.test(b.name)).map((b) => b.name);
244
+ out.manual.push({
245
+ id: 'supabase-storage-dashboard',
246
+ title: others.length
247
+ ? `Public Supabase Storage buckets: ${others.slice(0, 5).join(', ')}${others.length > 5 ? ` and ${others.length - 5} more` : ''}. Make sure nothing private goes in them`
248
+ : 'Check your Supabase Storage buckets on the dashboard',
249
+ how: 'Open Supabase → Storage. A bucket marked "Public" serves every file to anyone with its URL, with no sign-in. ' +
250
+ 'Keep only things like avatars and product images there; anything personal (documents, invoices, IDs, private messages) belongs in a private bucket with policies, served with signed URLs. ' +
251
+ 'Buckets created in the dashboard are not in your code, so Launch Doctor cannot see them. Then open Storage → Policies and check that no policy lets signed-out visitors upload, replace or delete files.',
252
+ });
253
+ }
178
254
  const publicReadTables = [...new Set(policies.filter((x) => x.kind === 'public-read').map((x) => x.table))];
179
255
  for (const table of publicReadTables.slice(0, 5)) {
180
256
  out.manual.push({
@@ -4,6 +4,20 @@ import { appCode, at, emptyOutput, notApplicable, where } from './common.js';
4
4
  const DEFAULT_TITLE = /<title>\s*(?:Vite \+ (?:React|Vue|Svelte|Preact|Lit|Solid|TS)(?: \+ TS)?|Vite App|React App|Create Next App|Lovable App|Nuxt App|SvelteKit App)\s*<\/title>|title\s*:\s*["'`]Create Next App["'`]|Generated by create next app/i;
5
5
  const LOVABLE_DEFAULTS = /Lovable Generated Project|lovable\.dev\/opengraph-image|@lovable_dev|gpt-engineer/i;
6
6
  const CONFIG_OR_SCRIPT = /(^|\/)(vite|next|nuxt|svelte|astro|playwright|vitest|jest|webpack|tailwind|postcss|eslint|tsup|rollup)\.config\.|(^|\/)(scripts|tools|seed|e2e)\/|(^|\/)seed\.|\.md$/i;
7
+ /** Places where localhost is expected: docs and examples, setup and seed scripts, test and tool config, framework settings files. */
8
+ const LOCALHOST_DEV_PATH = /(^|\/)(?:docs?|docs_src|examples?|tutorials?|samples?|setup|scripts?|tools|seed|e2e|cypress|docker|\.github)\/|(^|\/)(?:setup|seed|settings|conftest|dev|local|development)[\w.-]*\.(?:py|rb|php|[cm]?[jt]s)$|(^|\/)settings\/|(^|\/)config\.(?:py|rb)$|\.config\.[cm]?[jt]s$|\/tutorial\//i;
9
+ /** Words that show a localhost URL is a fallback or only used in development. */
10
+ const LOCALHOST_GUARD = /process\.env|import\.meta\.env|Deno\.env|\bos\.environ|\?\?|\|\||NODE_ENV|console\.|logger\.|isDev|\bdev\b|\bDEBUG\b|__DEV__|development|emulator|\bDEFAULT_|\bdefault\b|location\.(?:origin|hostname|host)\b/i;
11
+ /** The text of the line at `index` plus `before` lines above it and `after` lines below it. */
12
+ function linesAround(text, index, before, after) {
13
+ let start = text.lastIndexOf('\n', index - 1) + 1;
14
+ for (let i = 0; i < before && start > 0; i++)
15
+ start = text.lastIndexOf('\n', start - 2) + 1;
16
+ let end = text.indexOf('\n', index);
17
+ for (let i = 0; i < after && end !== -1; i++)
18
+ end = text.indexOf('\n', end + 1);
19
+ return text.slice(start, end === -1 ? text.length : end);
20
+ }
7
21
  const htmlOrLayout = (f) => appCode(f) &&
8
22
  (/\.html?$/i.test(f.path) ||
9
23
  /(^|\/)(app\/layout|_document|_app|app\.html|\+layout|nuxt\.config|layouts?\/)/i.test(f.path) ||
@@ -127,10 +141,16 @@ function websiteImpressions(ctx, out) {
127
141
  }
128
142
  // Hard-coded localhost URLs
129
143
  const localhost = ctx
130
- .find(/https?:\/\/(?:localhost|127\.0\.0\.1)(?::\d+)?/, (f) => appCode(f) && !CONFIG_OR_SCRIPT.test(f.path) && !ctx.isMobileFile(f.path))
144
+ .find(/https?:\/\/(?:localhost|127\.0\.0\.1)(?::\d+)?/, (f) => appCode(f) && !CONFIG_OR_SCRIPT.test(f.path) && !LOCALHOST_DEV_PATH.test(f.path) && !ctx.isMobileFile(f.path))
131
145
  .filter((m) => {
132
146
  const line = lineTextAt(m.file.content, m.index);
133
- return !/process\.env|import\.meta\.env|Deno\.env|\?\?|\|\||NODE_ENV|console\.|isDev|development/i.test(line);
147
+ // A comment or documentation line is not code that ships.
148
+ if (/^\s*(?:\/\/|\*|\/\*|#|<!--)/.test(line))
149
+ return false;
150
+ // A fallback, or a development-only branch, is often written a few lines away from the URL:
151
+ // const url = process.env.SITE_URL ?? ...\n ?? 'http://localhost:3000' | dev ? 'http://localhost:5173' : ...
152
+ const around = linesAround(m.file.content, m.index, 4, 2);
153
+ return !LOCALHOST_GUARD.test(around);
134
154
  });
135
155
  if (localhost.length) {
136
156
  const m = localhost[0];
@@ -14,7 +14,9 @@ function hasPage(ctx, words, fullUrls = false) {
14
14
  if (!fullUrls)
15
15
  return false;
16
16
  // Mobile apps (and many sites) link to a policy hosted elsewhere: https://myapp.com/privacy
17
- const urlRe = new RegExp(`https?://[^\\s"'\`]+/(?:[\\w-]+/)*(?:${alt})[\\w-]*\\b`, 'i');
17
+ // Host, then path segments split at "/" (each can only be read one way), then the policy word. The old form,
18
+ // "[^\s]+/(?:[\w-]+/)*", could split a long path in many ways and was quadratic on long URLs.
19
+ const urlRe = new RegExp(`https?://[^\\s"'\`/]+(?:/[^\\s"'\`/]+)*?/(?:${alt})[\\w-]*\\b`, 'i');
18
20
  return ctx.find(urlRe, appCode, 1).length > 0;
19
21
  }
20
22
  export const legalCheck = {
@@ -68,17 +68,20 @@ export const monitoringCheck = {
68
68
  // Friendly crash screen instead of a blank white page
69
69
  if (ctx.uses('react') || ctx.uses('next')) {
70
70
  const nextAppRouter = ctx.hasPath(/(^|\/)app\/(?:.*\/)?page\.(?:t|j)sx?$/);
71
+ // A boundary written by hand counts in any framework: a class with componentDidCatch, react-error-boundary,
72
+ // Remix / React Router's exported ErrorBoundary, or a router's errorElement / errorComponent.
73
+ const handWritten = ctx.uses('react-error-boundary') ||
74
+ ctx.findCode(/ErrorBoundary|componentDidCatch|errorElement\s*[:=]|errorComponent\s*[:=]/, appCode, 1).length >
75
+ 0;
71
76
  let hasBoundary;
72
77
  if (nextAppRouter) {
73
- hasBoundary = ctx.hasPath(/(^|\/)app\/(?:.*\/)?(?:error|global-error)\.(?:t|j)sx?$/);
78
+ hasBoundary = ctx.hasPath(/(^|\/)app\/(?:.*\/)?(?:error|global-error)\.(?:t|j)sx?$/) || handWritten;
74
79
  }
75
80
  else if (ctx.uses('next')) {
76
- hasBoundary = ctx.hasPath(/(^|\/)pages\/(?:_error|500)\.(?:t|j)sx?$/);
81
+ hasBoundary = ctx.hasPath(/(^|\/)pages\/(?:_error|500)\.(?:t|j)sx?$/) || handWritten;
77
82
  }
78
83
  else {
79
- hasBoundary =
80
- ctx.uses('react-error-boundary') ||
81
- ctx.findCode(/ErrorBoundary|componentDidCatch|errorElement\s*[:=]/, appCode, 1).length > 0;
84
+ hasBoundary = handWritten;
82
85
  }
83
86
  if (hasBoundary) {
84
87
  out.passed.push('Crashes show an error screen instead of a blank page');
@@ -10,7 +10,12 @@ const OTHER_PROVIDERS = {
10
10
  '@cashfreepayments/cashfree-js': 'Cashfree',
11
11
  };
12
12
  const STRIPE_EVENTS_RE = /checkout\.session\.completed|invoice\.paid|invoice\.payment_succeeded|customer\.subscription\.(?:created|updated|deleted)|payment_intent\.succeeded|stripe-signature/i;
13
- 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;
14
19
  const READS_BODY = /\b(?:req|request|c\.req)\.(?:text|json|arrayBuffer|body|rawBody|raw|on)\b|\brawBody\b|\bbuffer\s*\(\s*req\b/;
15
20
  const SIGNATURE_PASSED = 'Stripe webhooks check the signature, so fake "payment succeeded" messages are rejected';
16
21
  function parsesJsonFirst(path, content) {
@@ -249,7 +254,10 @@ export const paymentsCheck = {
249
254
  }
250
255
  // A global JSON body parser (Express) eats the raw body before any webhook route sees it.
251
256
  if (verified.length || eventHints.length) {
252
- 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];
253
261
  const rawUsed = ctx.find(/\b(?:express|bodyParser)\.raw\s*\(/, server, 1).length > 0;
254
262
  if (globalJson && !rawUsed)
255
263
  out.findings.push(parsedBodyFinding(at(globalJson), true));
@@ -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;
@@ -238,13 +238,68 @@ const SENSITIVE_PART = /(SECRET|SERVICE_ROLE|PRIVATE|PASSWORD|PASSWD|OPENAI|ANTH
238
238
  const DB_PART = /(DATABASE_URL|DB_URL|POSTGRES_URL|MONGODB_URI|MONGO_URI)/;
239
239
  // Settings that only mention a sensitive word, like VITE_PASSWORD_MIN_LENGTH.
240
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;
241
247
  export function isSensitivePublicName(rest) {
242
248
  if (DB_PART.test(rest))
243
249
  return true;
244
250
  if (SAFE_SUFFIX.test(rest))
245
251
  return false;
252
+ if (SETTING_WORD.test(rest) && !SECRET_ENDING.test(rest))
253
+ return false;
246
254
  return SENSITIVE_PART.test(rest);
247
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
+ }
248
303
  /** Files to search for hard-coded secrets: everything except real .env files (secrets belong there). */
249
304
  const notRealEnv = (f) => !isRealEnvPath(f.path);
250
305
  function hardcodedFinding(ctx, p, m) {
@@ -336,6 +391,9 @@ export const secretsCheck = {
336
391
  // 3. Supabase service_role keys (they bypass all database security)
337
392
  for (const m of ctx.find(JWT_RE, notRealEnv)) {
338
393
  const payload = decodeJwtPayload(m.match[0]);
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;
339
397
  if (payload?.role !== 'service_role') {
340
398
  if (!/lemon[\s_-]?squeezy/i.test(lineTextAt(m.file.content, m.index)))
341
399
  continue;
@@ -373,13 +431,17 @@ export const secretsCheck = {
373
431
  const full = m.match[0];
374
432
  if (!isSensitivePublicName(m.match[2]) || publicHits.has(full))
375
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;
376
437
  publicHits.set(full, at(m));
377
438
  }
378
439
  // A public variable that actually holds a service_role key
379
440
  for (const file of ctx.files.filter((f) => isEnvPath(f.path))) {
380
441
  file.content.split(/\r?\n/).forEach((line, i) => {
381
442
  const kv = /^\s*(?:export\s+)?((?:NEXT_PUBLIC_|VITE_|REACT_APP_|EXPO_PUBLIC_|NUXT_PUBLIC_|PUBLIC_)[A-Z0-9_]+)\s*=\s*['"]?([^'"\s#]+)/.exec(line);
382
- 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])) {
383
445
  publicHits.set(kv[1], { file: file.path, line: i + 1 });
384
446
  }
385
447
  });
@@ -415,24 +477,35 @@ export const secretsCheck = {
415
477
  const ignored = ctx.ignoredAmong(notCommitted.map((f) => f.path));
416
478
  const exposed = notCommitted.filter((f) => !ignored.has(f.path));
417
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);
418
483
  out.findings.push({
419
484
  id: 'env-committed',
420
- severity: 'critical',
485
+ severity: real ? 'critical' : 'warning',
421
486
  title: `${f.path} is saved in git`,
422
- 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.",
423
490
  location: { file: f.path },
424
- 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), ` +
425
- `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.`,
426
496
  });
427
497
  }
428
498
  for (const f of exposed.slice(0, 3)) {
499
+ const real = holdsRealSecret(f.content);
429
500
  out.findings.push({
430
501
  id: 'env-not-ignored',
431
- severity: ctx.gitRoot ? 'critical' : 'warning',
502
+ severity: ctx.gitRoot && real ? 'critical' : 'warning',
432
503
  title: `${f.path} is not in .gitignore`,
433
- why: ctx.gitRoot
434
- ? 'The next "git add ." will upload your secret keys along with your code.'
435
- : '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.',
436
509
  location: { file: f.path },
437
510
  fixPrompt: `Add ${f.path} (and other .env files except .env.example) to my .gitignore so my secret keys are never committed. ` +
438
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
+ };