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,5 +1,13 @@
1
1
  import type { SourceFile } from '../project.js';
2
2
  import type { Check } from '../types.js';
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;
3
11
  /**
4
12
  * True when a Next.js-style middleware (or proxy) file blocks signed-out users AND runs on /api routes.
5
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 = [
@@ -40,13 +45,40 @@ const RATE_LIMIT_PACKAGES = [
40
45
  'koa-ratelimit',
41
46
  ];
42
47
  const RATE_LIMIT_USAGE = /new\s+Ratelimit\s*\(|Ratelimit\.slidingWindow\s*\(|\brateLimit\s*\(\s*\{|new\s+RateLimiter\w*\s*\(|\blimiter\.(?:limit|consume|removeTokens)\s*\(|@limiter\.limit\s*\(|\barcjet\s*\(/;
48
+ /**
49
+ * A hand-written limiter: something named like a rate limit (not the provider's RateLimitError) together
50
+ * with a 429 "Too Many Requests" response. Many apps keep the counter in their own database or Redis.
51
+ */
52
+ const CUSTOM_LIMIT_NAME = /rate[_-]?limit(?!\w*(?:Error|Exception))/i;
53
+ const TOO_MANY_REQUESTS = /\b429\b|HTTP_429|too[_ ]many[_ ]requests|TooManyRequests/i;
54
+ export function hasCustomLimiter(code) {
55
+ return CUSTOM_LIMIT_NAME.test(code) && TOO_MANY_REQUESTS.test(code);
56
+ }
57
+ /** The rate-limit library to suggest for this project's server framework. */
58
+ function rateLimitLibrary(ctx) {
59
+ if (ctx.uses('fastapi'))
60
+ return 'slowapi (made for FastAPI)';
61
+ if (ctx.uses('flask'))
62
+ return 'Flask-Limiter';
63
+ if (ctx.uses('django'))
64
+ return 'django-ratelimit';
65
+ if (ctx.uses('express'))
66
+ return 'express-rate-limit (with a Redis store if I run more than one server)';
67
+ if (ctx.uses('fastify'))
68
+ return '@fastify/rate-limit';
69
+ if (ctx.uses('hono'))
70
+ return 'hono-rate-limiter';
71
+ if (ctx.usesAny(['next', '@sveltejs/kit', 'nuxt', 'astro', '@remix-run/node']) || ctx.hasPath(/(^|\/)vercel\.json$/))
72
+ return '@upstash/ratelimit (works on Vercel and other serverless hosts)';
73
+ return 'a rate-limiting library that fits my stack';
74
+ }
43
75
  /** Code in a middleware file that actually turns away signed-out requests. */
44
- 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;
45
77
  /**
46
78
  * The strings in `matcher: "..."` or `matcher: ["...", "..."]`, or null if there is no matcher.
47
79
  * Read string by string, because matcher patterns often contain "]" themselves.
48
80
  */
49
- function matcherEntries(content) {
81
+ export function matcherEntries(content) {
50
82
  const start = /matcher\s*:\s*/.exec(content);
51
83
  if (!start)
52
84
  return null;
@@ -116,7 +148,8 @@ export const costsCheck = {
116
148
  // "import type" is removed at build time, so it never reaches the browser.
117
149
  const realImports = ctx
118
150
  .find(BROWSER_FORBIDDEN_IMPORT, client)
119
- .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]));
120
153
  const browserHits = uniqueBy([...realImports, ...ctx.find(AI_DIRECT_URL, client), ...ctx.find(/dangerouslyAllowBrowser\s*:\s*true/, appCode)], (m) => m.file.path);
121
154
  for (const m of browserHits.slice(0, 3)) {
122
155
  out.findings.push({
@@ -143,7 +176,9 @@ export const costsCheck = {
143
176
  const aiHandlers = handlers.filter((h) => AI_CALL.test(evidenceOf(ctx, h).calls));
144
177
  const unprotectedHandlers = aiHandlers.filter((h) => !authIsUsed(AUTH_CHECK_RE, evidenceOf(ctx, h)) && !middlewareCovers(ctx, h, MIDDLEWARE_BLOCKS));
145
178
  const aiRoutes = uniqueBy(ctx.find(AI_CALL, (f) => server(f) && isRouteLike(f) && !analysed.has(f.path)), (m) => m.file.path);
146
- 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))));
147
182
  for (const m of unprotected.slice(0, 3)) {
148
183
  out.findings.push({
149
184
  id: 'ai-endpoint-no-auth',
@@ -171,9 +206,14 @@ export const costsCheck = {
171
206
  out.passed.push('AI endpoints check who is calling');
172
207
  // 3. Rate limiting: an imported rate-limit package, or code that really sets up a limiter.
173
208
  // (Comments and "RateLimitError" handling don't count.)
174
- const projectRateLimited = RATE_LIMIT_PACKAGES.some((p) => ctx.imported(p)) || ctx.findCode(RATE_LIMIT_USAGE, server, 1).length > 0;
209
+ const projectRateLimited = RATE_LIMIT_PACKAGES.some((p) => ctx.imported(p)) ||
210
+ ctx.findCode(RATE_LIMIT_USAGE, server, 1).length > 0 ||
211
+ ctx.files.some((f) => server(f) && hasCustomLimiter(ctx.codeOf(f)));
175
212
  // With analysed handlers, a limiter only counts for a handler that can reach it (or that middleware covers).
176
- const limitedHere = (h) => RATE_LIMIT_USAGE.test(evidenceOf(ctx, h).scope) || middlewareCovers(ctx, h, RATE_LIMIT_USAGE);
213
+ const limitedHere = (h) => {
214
+ const scope = evidenceOf(ctx, h).scope;
215
+ return RATE_LIMIT_USAGE.test(scope) || hasCustomLimiter(scope) || middlewareCovers(ctx, h, RATE_LIMIT_USAGE);
216
+ };
177
217
  const unlimitedHandlers = aiHandlers.filter((h) => !limitedHere(h));
178
218
  const legacyAiRoutes = aiRoutes.length > 0;
179
219
  const rateLimited = aiHandlers.length
@@ -187,9 +227,12 @@ export const costsCheck = {
187
227
  id: 'no-rate-limit',
188
228
  severity: 'warning',
189
229
  title: usesAI ? 'No rate limiting on your AI features' : 'No rate limiting on paid API calls',
190
- why: 'One user — or one bot — can send thousands of requests a minute, and you pay for every one. A simple limit per user (say 20 a minute) protects your wallet.',
191
- fixPrompt: `Add rate limiting to the endpoints in my app that call paid APIs (${usesAI ? 'AI' : 'SMS'}). Limit each signed-in user (and each IP address for signed-out visitors) to a sensible number of requests per minute and per day, ` +
192
- `return a friendly "slow down" message when they hit it, and use @upstash/ratelimit (works on Vercel/serverless) unless my stack already has a better option.`,
230
+ why: 'One user — or one bot — can send thousands of requests a minute, and you pay for every one. A simple limit per user (say 20 a minute) protects your wallet. ' +
231
+ 'We looked for a rate-limit package being used, or your own limit check that answers with HTTP 429 "Too Many Requests", and found neither.',
232
+ fixPrompt: `Launch Doctor found no rate limiting on the endpoints in my app that call paid APIs (${usesAI ? 'AI' : 'SMS'}). First check whether I already limit requests somewhere it couldn't see ` +
233
+ `(for example in my database, Redis, a gateway or my host's settings); if I do, show me where and confirm it covers these endpoints. ` +
234
+ `If not, limit each signed-in user (and each IP address for signed-out visitors) to a sensible number of requests per minute and per day, ` +
235
+ `return a friendly "slow down" message with HTTP 429 when they hit it, and use ${rateLimitLibrary(ctx)}.`,
193
236
  });
194
237
  }
195
238
  // 4. Things only the dashboards can show
@@ -1,6 +1,38 @@
1
- import { detectDatabase } from '../detect.js';
1
+ import { detectAuth, detectDatabase } from '../detect.js';
2
+ import { isTestPath } from '../project.js';
2
3
  import { lineAt, plural } from '../util.js';
3
- import { emptyOutput, notApplicable, where } from './common.js';
4
+ import { appCode, at, emptyOutput, notApplicable, where } from './common.js';
5
+ import { analyzeStorage, PRIVATE_BUCKET_NAME } from './supabase-storage.js';
6
+ // ---------- Convex ----------
7
+ /** Public Convex functions that can change data. internalMutation / internalAction can't be called from outside. */
8
+ const CONVEX_PUBLIC_WRITE = /export\s+const\s+(\w+)\s*=\s*(mutation|action)\s*\(/g;
9
+ /** Ways a Convex function finds out who is calling. */
10
+ const CONVEX_AUTH = /ctx\.auth\b|getAuthUserId\s*\(|getAuthSessionId\s*\(|\b(?:requireUser|requireAuth|getCurrentUser|getUserOrThrow|ensureUser|assertUser|currentUser|checkAuth|getViewer|mustGetCurrentUser|getMe)\w*\s*\(/;
11
+ const isConvexFunctionFile = (f) => /(^|\/)convex\/(?!_generated\/).+\.[cm]?[jt]s$/.test(f.path) && !isTestPath(f.path);
12
+ /** Public mutations and actions whose body never asks who the caller is. */
13
+ function unprotectedConvexFunctions(ctx) {
14
+ const out = [];
15
+ for (const f of ctx.files.filter(isConvexFunctionFile)) {
16
+ const code = ctx.codeOf(f);
17
+ const starts = [...code.matchAll(/^export\s/gm)].map((m) => m.index);
18
+ for (const m of code.matchAll(CONVEX_PUBLIC_WRITE)) {
19
+ const next = starts.find((i) => i > m.index) ?? code.length;
20
+ if (CONVEX_AUTH.test(code.slice(m.index, next)))
21
+ continue;
22
+ out.push({ name: m[1], loc: { file: f.path, line: lineAt(code, m.index) } });
23
+ }
24
+ }
25
+ return out;
26
+ }
27
+ // ---------- Appwrite ----------
28
+ /** Document or collection permissions that let anyone (even signed-out visitors) write. */
29
+ const APPWRITE_OPEN = /Permission\.(write|create|update|delete)\s*\(\s*Role\.(any|guests)\s*\(\s*\)\s*\)/;
30
+ /** Update or delete rights for every signed-in user (create for everyone signed in is normal). */
31
+ const APPWRITE_USERS = /Permission\.(write|update|delete)\s*\(\s*Role\.users\s*\(\s*\)\s*\)/;
32
+ /** The same in appwrite.json (the Appwrite CLI config): "update(\"any\")". */
33
+ const APPWRITE_JSON_OPEN = /"(write|create|update|delete)\(\\"(any|guests)\\"\)"/;
34
+ const APPWRITE_JSON_USERS = /"(write|update|delete)\(\\"users\\"\)"/;
35
+ const isAppwriteConfig = (f) => /(^|\/)appwrite(?:\.config)?\.json$/.test(f.path);
4
36
  /** Remove SQL comments but keep line numbers the same. */
5
37
  function stripSqlComments(sql) {
6
38
  return sql.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ' ')).replace(/--[^\n]*/g, '');
@@ -33,9 +65,13 @@ function analyzeSupabaseSql(files) {
33
65
  else
34
66
  rls.delete(name);
35
67
  }
36
- 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;
37
69
  while ((m = policyRe.exec(sql))) {
38
- 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] ?? '';
39
75
  const open = /(?:using|with\s+check)\s*\(\s*true\s*\)/i.test(body);
40
76
  if (!open)
41
77
  continue;
@@ -55,11 +91,13 @@ function analyzeSupabaseSql(files) {
55
91
  kind = 'signed-in-write';
56
92
  else if (!writes && toEveryone)
57
93
  kind = 'public-read';
94
+ else if (!writes && toSignedIn)
95
+ kind = 'signed-in-read';
58
96
  if (kind) {
59
97
  policies.push({
60
98
  kind,
61
99
  name: m[2] ?? m[3] ?? 'policy',
62
- table: m[4].toLowerCase(),
100
+ table: m[5].toLowerCase(),
63
101
  loc: { file: file.path, line: lineAt(sql, m.index) },
64
102
  });
65
103
  }
@@ -76,10 +114,18 @@ export const databaseCheck = {
76
114
  'supabase-rls-missing',
77
115
  'supabase-open-policy',
78
116
  'supabase-signed-in-write-policy',
117
+ 'supabase-signed-in-read-policy',
79
118
  'supabase-public-read',
80
119
  'supabase-rls-dashboard',
120
+ 'supabase-public-bucket',
121
+ 'supabase-storage-open-write',
122
+ 'supabase-storage-dashboard',
81
123
  'firebase-open-rules',
82
124
  'firebase-rules-console',
125
+ 'convex-public-mutation',
126
+ 'appwrite-open-permission',
127
+ 'appwrite-signed-in-write',
128
+ 'appwrite-permissions-console',
83
129
  'sqlite-on-serverless',
84
130
  'prisma-db-push',
85
131
  'backups',
@@ -140,6 +186,71 @@ export const databaseCheck = {
140
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.`,
141
187
  });
142
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
+ }
143
254
  const publicReadTables = [...new Set(policies.filter((x) => x.kind === 'public-read').map((x) => x.table))];
144
255
  for (const table of publicReadTables.slice(0, 5)) {
145
256
  out.manual.push({
@@ -187,6 +298,86 @@ export const databaseCheck = {
187
298
  out.passed.push('Firebase security rules are not wide open');
188
299
  }
189
300
  }
301
+ // ---- Convex: public functions that never check who is calling ----
302
+ if (dbs.includes('Convex')) {
303
+ const convexFiles = ctx.files.filter(isConvexFunctionFile);
304
+ // Only an app with accounts has a "who is calling" to check; a public guestbook may write without one.
305
+ const hasAccounts = !!detectAuth(ctx) ||
306
+ ctx.uses('@convex-dev/auth') ||
307
+ convexFiles.some((f) => /ctx\.auth\b|getAuthUserId\s*\(/.test(ctx.codeOf(f)));
308
+ const anyPublicWrite = convexFiles.some((f) => new RegExp(CONVEX_PUBLIC_WRITE.source).test(ctx.codeOf(f)));
309
+ const open = hasAccounts ? unprotectedConvexFunctions(ctx) : [];
310
+ if (open.length) {
311
+ const names = open.slice(0, 5).map((o) => o.name);
312
+ const more = open.length > 5 ? ` and ${open.length - 5} more` : '';
313
+ out.findings.push({
314
+ id: 'convex-public-mutation',
315
+ severity: 'warning',
316
+ title: `${plural(open.length, 'Convex function')} anyone can call without signing in: ${names.join(', ')}${more}`,
317
+ why: 'Every mutation and action exported from your convex/ folder is a public API. Your Convex URL is inside your app, so anyone can call these directly, signed in or not. These never check who is calling, so anyone can change data through them.',
318
+ location: open[0].loc,
319
+ fixPrompt: `These Convex functions never check who is calling: ${open.map((o) => `${o.name} (${where(o.loc)})`).join(', ')}. For each one:\n` +
320
+ `1. At the top of the handler, add: const identity = await ctx.auth.getUserIdentity(); if (!identity) throw new Error("Not signed in");\n` +
321
+ `2. Before changing a document, check that it belongs to the signed-in user.\n` +
322
+ `3. If a function is only called by other Convex functions, crons or the scheduler, make it an internalMutation or internalAction instead, so it can't be called from outside.\n` +
323
+ `Explain each change in one sentence.`,
324
+ });
325
+ }
326
+ else if (hasAccounts && anyPublicWrite) {
327
+ out.passed.push('Convex mutations check who is calling');
328
+ }
329
+ }
330
+ // ---- Appwrite permissions ----
331
+ if (dbs.includes('Appwrite')) {
332
+ const inCode = (re) => [
333
+ ...ctx.findCode(re, appCode, 3),
334
+ ...ctx.find(re === APPWRITE_OPEN ? APPWRITE_JSON_OPEN : APPWRITE_JSON_USERS, isAppwriteConfig, 3),
335
+ ];
336
+ const open = inCode(APPWRITE_OPEN);
337
+ const signedIn = inCode(APPWRITE_USERS);
338
+ for (const m of open.slice(0, 3)) {
339
+ const action = m.match[1];
340
+ const who = m.match[2] === 'guests' ? 'signed-out visitors' : 'anyone';
341
+ const createOnly = action === 'create';
342
+ out.findings.push({
343
+ id: 'appwrite-open-permission',
344
+ severity: createOnly ? 'warning' : 'critical',
345
+ title: createOnly
346
+ ? `Appwrite lets ${who} create documents (${action} for ${m.match[2]})`
347
+ : `Appwrite lets ${who} ${action === 'write' ? 'change and delete' : action} your data`,
348
+ why: createOnly
349
+ ? 'Anyone, even people who are not signed in, can add documents here. Fine for something like a contact form, but bots can fill it with junk unless you add a captcha or rate limit.'
350
+ : 'This permission is granted to "any" (or guests), so anyone on the internet can use your public project ID to change or delete these documents, without signing in.',
351
+ location: at(m),
352
+ fixPrompt: `In ${where(at(m))} an Appwrite permission gives "${action}" to Role.${m.match[2]}(). ` +
353
+ `Please change it so only the document's owner can update or delete it (Permission.update(Role.user(userId)), Permission.delete(Role.user(userId))), ` +
354
+ `keep public read only if the data is meant to be public, and turn on "Document security" for the collection if documents need per-user permissions. Explain each permission in one sentence.`,
355
+ });
356
+ }
357
+ for (const m of signedIn.slice(0, 3)) {
358
+ out.findings.push({
359
+ id: 'appwrite-signed-in-write',
360
+ severity: 'warning',
361
+ title: `Appwrite: any signed-in user can ${m.match[1] === 'write' ? 'change and delete' : m.match[1]} these documents`,
362
+ why: `The permission is granted to Role.users(), which means every account. Anyone who creates a free account can edit or delete other people's documents.`,
363
+ location: at(m),
364
+ fixPrompt: `In ${where(at(m))} an Appwrite permission gives "${m.match[1]}" to Role.users(), so every signed-in user can change every document. ` +
365
+ `Please give update and delete rights only to the owner (Role.user(userId)) when creating each document, with "Document security" turned on for the collection.`,
366
+ });
367
+ }
368
+ const anyPermissions = ctx.findCode(/Permission\.\w+\s*\(\s*Role\./, appCode, 1).length > 0 ||
369
+ ctx.files.some((f) => isAppwriteConfig(f) && /\$permissions|"permissions"/.test(f.content));
370
+ if (!anyPermissions) {
371
+ out.manual.push({
372
+ id: 'appwrite-permissions-console',
373
+ title: 'Check your Appwrite collection and bucket permissions',
374
+ how: 'Open the Appwrite Console → Databases → each collection → Settings → Permissions (and Storage → each bucket). "Any" with create, update or delete lets anyone change your data; give those rights to users or to the document owner instead.',
375
+ });
376
+ }
377
+ else if (!open.length && !signedIn.length) {
378
+ out.passed.push("Appwrite permissions don't let anyone change other people's data");
379
+ }
380
+ }
190
381
  // ---- SQLite on serverless hosting ----
191
382
  const prismaSqlite = ctx.find(/provider\s*=\s*"sqlite"/, (f) => f.path.endsWith('.prisma'), 1)[0];
192
383
  const sqliteLib = ctx.usesAny(['better-sqlite3', 'sqlite3']);
@@ -232,7 +423,11 @@ export const databaseCheck = {
232
423
  ? 'In Supabase → Database → Backups, check that backups exist for your plan (free projects may not include them). Download or restore one once to be sure it works.'
233
424
  : dbs.includes('Firebase')
234
425
  ? 'Turn on scheduled Firestore backups (Google Cloud → Firestore → Disaster recovery), then restore one into a test project once.'
235
- : 'Turn on automatic daily backups with your database host, then restore one into a test database once to prove it works.';
426
+ : dbs.includes('Convex')
427
+ ? 'In the Convex dashboard → your production deployment → Backups, turn on periodic backups, then download or restore one once to be sure it works.'
428
+ : dbs.includes('Appwrite')
429
+ ? 'Turn on database backups in the Appwrite Console (Databases → Backups), or back up your server volumes if you host Appwrite yourself, then restore one into a test project once.'
430
+ : 'Turn on automatic daily backups with your database host, then restore one into a test database once to prove it works.';
236
431
  out.manual.push({ id: 'backups', title: 'Turn on automatic backups and test a restore', how });
237
432
  return out;
238
433
  },