launch-doctor 0.0.0-stage → 0.2.1

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 (60) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/LICENSE +21 -0
  3. package/README.md +376 -2
  4. package/dist/src/baseline.d.ts +14 -0
  5. package/dist/src/baseline.js +71 -0
  6. package/dist/src/checks/common.d.ts +16 -0
  7. package/dist/src/checks/common.js +33 -0
  8. package/dist/src/checks/costs.d.ts +8 -0
  9. package/dist/src/checks/costs.js +210 -0
  10. package/dist/src/checks/database.d.ts +2 -0
  11. package/dist/src/checks/database.js +239 -0
  12. package/dist/src/checks/email.d.ts +19 -0
  13. package/dist/src/checks/email.js +270 -0
  14. package/dist/src/checks/first-impressions.d.ts +2 -0
  15. package/dist/src/checks/first-impressions.js +160 -0
  16. package/dist/src/checks/legal.d.ts +2 -0
  17. package/dist/src/checks/legal.js +122 -0
  18. package/dist/src/checks/monitoring.d.ts +2 -0
  19. package/dist/src/checks/monitoring.js +93 -0
  20. package/dist/src/checks/payments.d.ts +2 -0
  21. package/dist/src/checks/payments.js +188 -0
  22. package/dist/src/checks/secrets.d.ts +23 -0
  23. package/dist/src/checks/secrets.js +355 -0
  24. package/dist/src/cli.d.ts +2 -0
  25. package/dist/src/cli.js +404 -0
  26. package/dist/src/comments.d.ts +8 -0
  27. package/dist/src/comments.js +143 -0
  28. package/dist/src/demo.d.ts +2 -0
  29. package/dist/src/demo.js +54 -0
  30. package/dist/src/detect.d.ts +10 -0
  31. package/dist/src/detect.js +129 -0
  32. package/dist/src/fixes.d.ts +3 -0
  33. package/dist/src/fixes.js +67 -0
  34. package/dist/src/grade.d.ts +16 -0
  35. package/dist/src/grade.js +52 -0
  36. package/dist/src/history.d.ts +16 -0
  37. package/dist/src/history.js +88 -0
  38. package/dist/src/index.d.ts +12 -0
  39. package/dist/src/index.js +147 -0
  40. package/dist/src/init.d.ts +9 -0
  41. package/dist/src/init.js +49 -0
  42. package/dist/src/live.d.ts +16 -0
  43. package/dist/src/live.js +509 -0
  44. package/dist/src/project.d.ts +97 -0
  45. package/dist/src/project.js +724 -0
  46. package/dist/src/report.d.ts +6 -0
  47. package/dist/src/report.js +136 -0
  48. package/dist/src/routes.d.ts +40 -0
  49. package/dist/src/routes.js +227 -0
  50. package/dist/src/sarif.d.ts +14 -0
  51. package/dist/src/sarif.js +54 -0
  52. package/dist/src/summary.d.ts +6 -0
  53. package/dist/src/summary.js +44 -0
  54. package/dist/src/types.d.ts +102 -0
  55. package/dist/src/types.js +1 -0
  56. package/dist/src/util.d.ts +13 -0
  57. package/dist/src/util.js +75 -0
  58. package/dist/src/version.d.ts +2 -0
  59. package/dist/src/version.js +21 -0
  60. package/package.json +61 -4
@@ -0,0 +1,210 @@
1
+ import { AUTH_CHECK_RE } from '../detect.js';
2
+ import { authIsUsed, evidenceOf, handlersOf, matcherCovers } from '../routes.js';
3
+ import { lineTextAt, uniqueBy } from '../util.js';
4
+ import { appCode, at, clientCode, emptyOutput, isRouteLike, notApplicable, serverCode, where } from './common.js';
5
+ const AI_PACKAGES = [
6
+ 'openai',
7
+ '@anthropic-ai/sdk',
8
+ '@google/generative-ai',
9
+ '@google/genai',
10
+ 'ai',
11
+ '@ai-sdk/',
12
+ 'groq-sdk',
13
+ '@mistralai/mistralai',
14
+ 'replicate',
15
+ 'cohere-ai',
16
+ 'together-ai',
17
+ '@huggingface/inference',
18
+ 'elevenlabs',
19
+ '@elevenlabs/elevenlabs-js',
20
+ '@fal-ai/client',
21
+ '@langchain/',
22
+ 'langchain',
23
+ '@openrouter/ai-sdk-provider',
24
+ ];
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)(?:[@/][^"']*)?["']/;
27
+ 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
+ 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
+ const RATE_LIMIT_PACKAGES = [
30
+ '@upstash/ratelimit',
31
+ 'express-rate-limit',
32
+ 'rate-limiter-flexible',
33
+ '@arcjet/',
34
+ '@unkey/ratelimit',
35
+ 'hono-rate-limiter',
36
+ '@nestjs/throttler',
37
+ 'next-rate-limit',
38
+ 'limiter',
39
+ '@fastify/rate-limit',
40
+ 'koa-ratelimit',
41
+ ];
42
+ 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*\(/;
43
+ /** 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;
45
+ /**
46
+ * The strings in `matcher: "..."` or `matcher: ["...", "..."]`, or null if there is no matcher.
47
+ * Read string by string, because matcher patterns often contain "]" themselves.
48
+ */
49
+ function matcherEntries(content) {
50
+ const start = /matcher\s*:\s*/.exec(content);
51
+ if (!start)
52
+ return null;
53
+ let i = start.index + start[0].length;
54
+ const inArray = content[i] === '[';
55
+ if (inArray)
56
+ i++;
57
+ const entries = [];
58
+ const str = /\s*,?\s*(["'`])((?:\\.|(?!\1)[^\\])*)\1/y;
59
+ for (;;) {
60
+ str.lastIndex = i;
61
+ const m = str.exec(content);
62
+ if (!m)
63
+ break;
64
+ entries.push(m[2]);
65
+ i = str.lastIndex;
66
+ if (!inArray)
67
+ break;
68
+ }
69
+ return entries;
70
+ }
71
+ /**
72
+ * True when a Next.js-style middleware (or proxy) file blocks signed-out users AND runs on /api routes.
73
+ * Middleware that only refreshes the session (e.g. Supabase's updateSession) doesn't count.
74
+ */
75
+ export function middlewareBlocksApi(f, code = f.content) {
76
+ if (!/(^|\/)(?:src\/)?(middleware|proxy)\.(t|j)s$/.test(f.path))
77
+ return false;
78
+ if (!MIDDLEWARE_BLOCKS.test(code))
79
+ return false;
80
+ const entries = matcherEntries(code);
81
+ if (!entries)
82
+ return true; // no matcher: runs on every route
83
+ return entries.some((e) => {
84
+ if (/(^|\/)\(?api\b|\(api\||\|api\)/.test(e) && !/\(\?!/.test(e))
85
+ return true; // e.g. "/api/:path*" or "/(api|trpc)(.*)"
86
+ const catchAll = /^\/(\(.*\)|:path\*|\.\*)/.test(e) || e === '/(.*)';
87
+ const excludesApi = /\(\?![^)]*\bapi\b/.test(e);
88
+ return catchAll && !excludesApi;
89
+ });
90
+ }
91
+ /** Does a middleware file with this kind of code run on the handler's URL path? */
92
+ function middlewareCovers(ctx, h, pattern) {
93
+ return ctx.files.some((f) => {
94
+ if (!/(^|\/)(?:src\/)?(middleware|proxy)\.(t|j)s$/.test(f.path))
95
+ return false;
96
+ const code = ctx.codeOf(f);
97
+ if (!pattern.test(code))
98
+ return false;
99
+ return matcherCovers(matcherEntries(code), h.urlPath) !== false;
100
+ });
101
+ }
102
+ export const costsCheck = {
103
+ id: 'costs',
104
+ name: 'AI & API costs',
105
+ weight: 2,
106
+ ids: ['ai-in-browser', 'ai-endpoint-no-auth', 'no-rate-limit', 'spending-limits', 'twilio-geo'],
107
+ run(ctx) {
108
+ const usesAI = ctx.usesAny(AI_PACKAGES) || ctx.find(AI_DIRECT_URL, appCode, 1).length > 0;
109
+ const usesTwilio = ctx.uses('twilio');
110
+ if (!usesAI && !usesTwilio)
111
+ return notApplicable('No paid AI or SMS APIs found');
112
+ const out = emptyOutput();
113
+ const client = clientCode(ctx);
114
+ const server = serverCode(ctx);
115
+ // 1. Paid APIs called straight from the browser
116
+ // "import type" is removed at build time, so it never reaches the browser.
117
+ const realImports = ctx
118
+ .find(BROWSER_FORBIDDEN_IMPORT, client)
119
+ .filter((m) => !/^\s*(?:import|export)\s+type\b/.test(lineTextAt(m.file.content, m.index)));
120
+ const browserHits = uniqueBy([...realImports, ...ctx.find(AI_DIRECT_URL, client), ...ctx.find(/dangerouslyAllowBrowser\s*:\s*true/, appCode)], (m) => m.file.path);
121
+ for (const m of browserHits.slice(0, 3)) {
122
+ out.findings.push({
123
+ id: 'ai-in-browser',
124
+ severity: 'critical',
125
+ title: `A paid ${/twilio/i.test(m.match[0]) ? 'SMS' : 'AI'} API is called straight from the browser`,
126
+ 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.',
127
+ location: at(m),
128
+ 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` +
129
+ `1. Create a server-side endpoint (an API route, server action, or Supabase Edge Function) that makes the AI call using a server-only environment variable.\n` +
130
+ `2. Make that endpoint check the user is signed in and limit how many requests each user can make.\n` +
131
+ `3. Change the frontend to call my endpoint instead, and remove the key and any "dangerouslyAllowBrowser" option.\n` +
132
+ `Then remind me to rotate the old key, because it has been public.`,
133
+ });
134
+ }
135
+ if (!browserHits.length)
136
+ out.passed.push('Paid AI APIs are only called from your server');
137
+ // 2. AI endpoints that anyone can call
138
+ const middlewareProtects = ctx.files.some((f) => middlewareBlocksApi(f, ctx.codeOf(f)));
139
+ // Route files with exported handlers are judged one handler at a time (what the handler itself,
140
+ // or the local modules it imports, does). Everything else keeps the older whole-file check.
141
+ const handlers = ctx.files.filter((f) => server(f) && isRouteLike(f)).flatMap((f) => handlersOf(ctx, f));
142
+ const analysed = new Set(handlers.map((h) => h.file.path));
143
+ const aiHandlers = handlers.filter((h) => AI_CALL.test(evidenceOf(ctx, h).calls));
144
+ const unprotectedHandlers = aiHandlers.filter((h) => !authIsUsed(AUTH_CHECK_RE, evidenceOf(ctx, h)) && !middlewareCovers(ctx, h, MIDDLEWARE_BLOCKS));
145
+ 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)));
147
+ for (const m of unprotected.slice(0, 3)) {
148
+ out.findings.push({
149
+ id: 'ai-endpoint-no-auth',
150
+ severity: 'warning',
151
+ title: `Paid API endpoint doesn't check who is calling it (${m.file.path})`,
152
+ why: 'Anyone on the internet can call this endpoint over and over, and every call is billed to you. Only signed-in users (or a paid plan) should be able to use it.',
153
+ location: at(m),
154
+ fixPrompt: `The endpoint in ${where(at(m))} calls a paid AI API but doesn't check who is calling. Please add a check at the top that rejects requests from users who aren't signed in (return 401), ` +
155
+ `using the auth system my app already has. Also cap the size of the input and set a max tokens / max output limit on the AI call.`,
156
+ });
157
+ }
158
+ for (const h of unprotectedHandlers.slice(0, 3)) {
159
+ const loc = { file: h.file.path, line: h.line };
160
+ out.findings.push({
161
+ id: 'ai-endpoint-no-auth',
162
+ severity: 'warning',
163
+ title: `Paid API endpoint doesn't check who is calling it (${h.method} ${h.urlPath ?? h.file.path})`,
164
+ why: 'Anyone on the internet can call this endpoint over and over, and every call is billed to you. Only signed-in users (or a paid plan) should be able to use it.',
165
+ location: loc,
166
+ fixPrompt: `The ${h.method} handler in ${where(loc)} reaches a paid AI API but doesn't reject callers who aren't signed in. Please add a check at the top that returns 401 when there is no signed-in user, ` +
167
+ `using the auth system my app already has (checking the result, not just calling it). Also cap the size of the input and set a max tokens / max output limit on the AI call.`,
168
+ });
169
+ }
170
+ if ((aiRoutes.length || aiHandlers.length) && !unprotected.length && !unprotectedHandlers.length)
171
+ out.passed.push('AI endpoints check who is calling');
172
+ // 3. Rate limiting: an imported rate-limit package, or code that really sets up a limiter.
173
+ // (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;
175
+ // 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);
177
+ const unlimitedHandlers = aiHandlers.filter((h) => !limitedHere(h));
178
+ const legacyAiRoutes = aiRoutes.length > 0;
179
+ const rateLimited = aiHandlers.length
180
+ ? unlimitedHandlers.length === 0 && (!legacyAiRoutes || projectRateLimited)
181
+ : projectRateLimited;
182
+ if (rateLimited) {
183
+ out.passed.push('Rate limiting is in place');
184
+ }
185
+ else {
186
+ out.findings.push({
187
+ id: 'no-rate-limit',
188
+ severity: 'warning',
189
+ 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.`,
193
+ });
194
+ }
195
+ // 4. Things only the dashboards can show
196
+ out.manual.push({
197
+ id: 'spending-limits',
198
+ title: 'Set a monthly spending limit with your AI and hosting providers',
199
+ how: 'Set hard limits and email alerts in OpenAI / Anthropic / Google AI billing, and in your host (e.g. Vercel Spend Management, Supabase spend cap). A leaked key or a bug then costs a little, not a lot.',
200
+ });
201
+ if (usesTwilio) {
202
+ out.manual.push({
203
+ id: 'twilio-geo',
204
+ title: 'Turn on Twilio geo-permissions and SMS fraud protection',
205
+ how: 'Bots trigger thousands of SMS codes to expensive countries ("SMS pumping"). Only allow the countries your users are in, and enable Twilio Verify Fraud Guard.',
206
+ });
207
+ }
208
+ return out;
209
+ },
210
+ };
@@ -0,0 +1,2 @@
1
+ import type { Check } from '../types.js';
2
+ export declare const databaseCheck: Check;
@@ -0,0 +1,239 @@
1
+ import { detectDatabase } from '../detect.js';
2
+ import { lineAt, plural } from '../util.js';
3
+ import { emptyOutput, notApplicable, where } from './common.js';
4
+ /** Remove SQL comments but keep line numbers the same. */
5
+ function stripSqlComments(sql) {
6
+ return sql.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ' ')).replace(/--[^\n]*/g, '');
7
+ }
8
+ function analyzeSupabaseSql(files) {
9
+ const created = new Map();
10
+ const rls = new Set();
11
+ const policies = [];
12
+ for (const file of files) {
13
+ const sql = stripSqlComments(file.content);
14
+ const createRe = /create\s+table\s+(?:if\s+not\s+exists\s+)?(?:"?(\w+)"?\s*\.\s*)?"?(\w+)"?/gi;
15
+ let m;
16
+ while ((m = createRe.exec(sql))) {
17
+ const schema = (m[1] ?? 'public').toLowerCase();
18
+ if (schema !== 'public')
19
+ continue;
20
+ const name = m[2].toLowerCase();
21
+ if (!created.has(name))
22
+ created.set(name, { name, loc: { file: file.path, line: lineAt(sql, m.index) } });
23
+ }
24
+ const dropRe = /drop\s+table\s+(?:if\s+exists\s+)?(?:"?(\w+)"?\s*\.\s*)?"?(\w+)"?/gi;
25
+ while ((m = dropRe.exec(sql)))
26
+ created.delete(m[2].toLowerCase());
27
+ // Track enable/disable in order, so a later "disable" wins.
28
+ const rlsRe = /alter\s+table\s+(?:if\s+exists\s+)?(?:only\s+)?(?:"?(\w+)"?\s*\.\s*)?"?(\w+)"?\s+(enable|disable)\s+row\s+level\s+security/gi;
29
+ while ((m = rlsRe.exec(sql))) {
30
+ const name = m[2].toLowerCase();
31
+ if (m[3].toLowerCase() === 'enable')
32
+ rls.add(name);
33
+ else
34
+ rls.delete(name);
35
+ }
36
+ const policyRe = /create\s+policy\s+("([^"]+)"|(\w+))\s+on\s+(?:"?\w+"?\s*\.\s*)?"?(\w+)"?([\s\S]*?);/gi;
37
+ while ((m = policyRe.exec(sql))) {
38
+ const body = m[5] ?? '';
39
+ const open = /(?:using|with\s+check)\s*\(\s*true\s*\)/i.test(body);
40
+ if (!open)
41
+ continue;
42
+ // No "to ..." clause means the policy applies to everyone (public).
43
+ const rolesMatch = /\bto\s+((?:"?\w+"?\s*,\s*)*"?\w+"?)/i.exec(body);
44
+ const roles = rolesMatch ? rolesMatch[1].split(',').map((r) => r.replace(/"/g, '').trim().toLowerCase()) : [];
45
+ if (roles.length && roles.every((r) => r === 'service_role'))
46
+ continue;
47
+ const toEveryone = !roles.length || roles.some((r) => r === 'anon' || r === 'public');
48
+ const toSignedIn = roles.includes('authenticated');
49
+ // No "for ..." clause means FOR ALL, which includes writes.
50
+ const writes = /\bfor\s+(all|insert|update|delete)\b/i.test(body) || !/\bfor\s+select\b/i.test(body);
51
+ let kind = null;
52
+ if (writes && toEveryone)
53
+ kind = 'open-write';
54
+ else if (writes && toSignedIn)
55
+ kind = 'signed-in-write';
56
+ else if (!writes && toEveryone)
57
+ kind = 'public-read';
58
+ if (kind) {
59
+ policies.push({
60
+ kind,
61
+ name: m[2] ?? m[3] ?? 'policy',
62
+ table: m[4].toLowerCase(),
63
+ loc: { file: file.path, line: lineAt(sql, m.index) },
64
+ });
65
+ }
66
+ }
67
+ }
68
+ const missing = [...created.values()].filter((t) => !rls.has(t.name));
69
+ return { created, missing, policies };
70
+ }
71
+ export const databaseCheck = {
72
+ id: 'database',
73
+ name: 'Database & backups',
74
+ weight: 3,
75
+ ids: [
76
+ 'supabase-rls-missing',
77
+ 'supabase-open-policy',
78
+ 'supabase-signed-in-write-policy',
79
+ 'supabase-public-read',
80
+ 'supabase-rls-dashboard',
81
+ 'firebase-open-rules',
82
+ 'firebase-rules-console',
83
+ 'sqlite-on-serverless',
84
+ 'prisma-db-push',
85
+ 'backups',
86
+ ],
87
+ run(ctx) {
88
+ const dbs = detectDatabase(ctx);
89
+ if (!dbs.length)
90
+ return notApplicable('No database found');
91
+ const out = emptyOutput();
92
+ const supabaseClient = ctx.usesAny(['@supabase/supabase-js', '@supabase/ssr', '@supabase/auth-helpers-nextjs']);
93
+ const sqlFiles = ctx.files.filter((f) => f.path.toLowerCase().endsWith('.sql'));
94
+ // ---- Supabase Row Level Security ----
95
+ if (supabaseClient || dbs.includes('Supabase')) {
96
+ const { created, missing, policies } = analyzeSupabaseSql(sqlFiles);
97
+ if (!created.size) {
98
+ out.manual.push({
99
+ id: 'supabase-rls-dashboard',
100
+ title: 'Turn on Row Level Security for every Supabase table',
101
+ how: 'Open Supabase → Table Editor. Every table should show "RLS enabled", with policies so people can only see their own data. Without RLS, anyone with your public key can read and change every row.',
102
+ });
103
+ }
104
+ else if (missing.length) {
105
+ const names = missing.slice(0, 6).map((t) => t.name);
106
+ const more = missing.length > 6 ? ` and ${missing.length - 6} more` : '';
107
+ out.findings.push({
108
+ id: 'supabase-rls-missing',
109
+ severity: 'critical',
110
+ title: `${plural(missing.length, 'Supabase table')} without Row Level Security: ${names.join(', ')}${more}`,
111
+ 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.',
112
+ location: missing[0].loc,
113
+ fixPrompt: `These Supabase tables don't have Row Level Security enabled: ${missing.map((t) => t.name).join(', ')}. ` +
114
+ `Please write a new SQL migration that runs "alter table <name> enable row level security;" for each one, and add policies so signed-in users can only read and change their own rows (using auth.uid()). ` +
115
+ `If a table is meant to be publicly readable (like a product list), add a read-only policy for it and no public write policy. Explain each policy in one plain-English sentence.`,
116
+ });
117
+ }
118
+ else {
119
+ out.passed.push(`Row Level Security is on for all ${plural(created.size, 'table')}`);
120
+ }
121
+ for (const p of policies.filter((x) => x.kind === 'open-write').slice(0, 3)) {
122
+ out.findings.push({
123
+ id: 'supabase-open-policy',
124
+ severity: 'critical',
125
+ title: `Supabase policy "${p.name}" lets anyone change the ${p.table} table`,
126
+ 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.',
127
+ location: p.loc,
128
+ fixPrompt: `In ${where(p.loc)} the Supabase policy "${p.name}" on table "${p.table}" uses (true), so anyone can write to it. ` +
129
+ `Please replace it with policies that only let signed-in users change their own rows (e.g. using (auth.uid() = user_id)), and keep public read access only if the data is meant to be public.`,
130
+ });
131
+ }
132
+ for (const p of policies.filter((x) => x.kind === 'signed-in-write').slice(0, 3)) {
133
+ out.findings.push({
134
+ id: 'supabase-signed-in-write-policy',
135
+ severity: 'warning',
136
+ title: `Supabase policy "${p.name}": any signed-in user can change every row in ${p.table}`,
137
+ why: 'The policy is limited to signed-in users, but its rule is "true". Anyone who creates a free account can edit or delete other people\'s rows.',
138
+ location: p.loc,
139
+ fixPrompt: `In ${where(p.loc)} the Supabase policy "${p.name}" on "${p.table}" lets any authenticated user write any row (using/with check (true)). ` +
140
+ `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
+ });
142
+ }
143
+ const publicReadTables = [...new Set(policies.filter((x) => x.kind === 'public-read').map((x) => x.table))];
144
+ for (const table of publicReadTables.slice(0, 5)) {
145
+ out.manual.push({
146
+ id: 'supabase-public-read',
147
+ title: `Anyone can read every row of ${table}; make sure that is intended`,
148
+ how: `A "for select using (true)" policy makes ${table} readable by everyone, even signed-out visitors. That's fine for things like a product list, but not for anything personal (emails, orders, messages).`,
149
+ });
150
+ }
151
+ }
152
+ // ---- Firebase security rules ----
153
+ if (dbs.includes('Firebase')) {
154
+ const ruleFiles = ctx.files.filter((f) => /(^|\/)(firestore|storage)\.rules$|(^|\/)database\.rules\.json$|\.rules$/.test(f.path));
155
+ let openFound = false;
156
+ for (const f of ruleFiles) {
157
+ const testMode = /request\.time\s*<\s*timestamp\.date\s*\(/.exec(f.content);
158
+ // Any rule that allows writing (write/create/update/delete) to everyone.
159
+ const openAll = /allow\s+[\w\s,]*\b(?:write|create|update|delete)\b[\w\s,]*:\s*if\s+true\s*;|allow\s+[\w\s,]*\b(?:write|create|update|delete)\b[\w\s,]*;/.exec(f.content);
160
+ const rtdbOpen = f.path.endsWith('.json') ? /"\.write"\s*:\s*true/.exec(f.content) : null;
161
+ const hit = testMode ?? openAll ?? rtdbOpen;
162
+ if (!hit)
163
+ continue;
164
+ openFound = true;
165
+ const loc = { file: f.path, line: lineAt(f.content, hit.index) };
166
+ out.findings.push({
167
+ id: 'firebase-open-rules',
168
+ severity: 'critical',
169
+ title: testMode ? 'Firebase is still in "test mode"' : 'Firebase rules let anyone write to your database',
170
+ why: testMode
171
+ ? '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.'
172
+ : 'These rules allow anyone, even people who are not signed in, to change or delete your data.',
173
+ location: loc,
174
+ fixPrompt: `My Firebase security rules in ${where(loc)} are wide open${testMode ? ' (test mode with a date)' : ''}. ` +
175
+ `Please rewrite them so only signed-in users can read and write their own documents (match on request.auth.uid), public data is read-only, and everything else is denied by default. ` +
176
+ `Explain each rule in plain English and tell me how to test them with the Firebase Emulator before deploying.`,
177
+ });
178
+ }
179
+ if (!ruleFiles.length) {
180
+ out.manual.push({
181
+ id: 'firebase-rules-console',
182
+ title: 'Check your Firebase security rules',
183
+ how: 'Open Firebase Console → Firestore/Storage → Rules. If they say "allow read, write: if true" or have a request.time date, your data is open to everyone.',
184
+ });
185
+ }
186
+ else if (!openFound) {
187
+ out.passed.push('Firebase security rules are not wide open');
188
+ }
189
+ }
190
+ // ---- SQLite on serverless hosting ----
191
+ const prismaSqlite = ctx.find(/provider\s*=\s*"sqlite"/, (f) => f.path.endsWith('.prisma'), 1)[0];
192
+ const sqliteLib = ctx.usesAny(['better-sqlite3', 'sqlite3']);
193
+ const serverless = ctx.uses('next') || ctx.hasPath(/(^|\/)(vercel\.json|netlify\.toml)$/);
194
+ if ((prismaSqlite || sqliteLib) && serverless) {
195
+ const loc = prismaSqlite ? { file: prismaSqlite.file.path, line: prismaSqlite.line } : undefined;
196
+ out.findings.push({
197
+ id: 'sqlite-on-serverless',
198
+ severity: 'warning',
199
+ title: 'Your database is a file on disk (SQLite)',
200
+ why: "That works on your laptop, but hosts like Vercel and Netlify don't keep files between requests, so saved data disappears or writes fail once you deploy. Use a hosted database, or a server with a permanent disk.",
201
+ location: loc,
202
+ fixPrompt: `My app uses SQLite (a database stored in a file)${loc ? ` — see ${where(loc)}` : ''}, and I want to deploy it to serverless hosting like Vercel. ` +
203
+ `Help me switch to a hosted database (for example Neon or Supabase Postgres, or Turso if I want to stay with SQLite). ` +
204
+ `Update the database config and environment variables, create proper migrations, and explain how to copy my existing data across.`,
205
+ });
206
+ }
207
+ // ---- Risky schema changes ----
208
+ if (dbs.includes('Prisma')) {
209
+ const usesDbPush = ctx.scripts.some((s) => /prisma\s+db\s+push/.test(s));
210
+ const dataLoss = ctx.scripts.some((s) => /--accept-data-loss/.test(s));
211
+ const hasMigrations = ctx.hasPath(/(^|\/)prisma\/migrations\//);
212
+ if (dataLoss || (usesDbPush && !hasMigrations)) {
213
+ out.findings.push({
214
+ id: 'prisma-db-push',
215
+ severity: 'warning',
216
+ title: dataLoss
217
+ ? 'Your scripts run database changes with --accept-data-loss'
218
+ : 'Database changes use "prisma db push" instead of migrations',
219
+ why: '"db push" changes your live database to match your code, and can silently delete columns and the data in them. Migrations keep a history and let you review changes before they hit real data.',
220
+ location: { file: 'package.json' },
221
+ fixPrompt: `My project changes the database with "prisma db push"${dataLoss ? ' and --accept-data-loss' : ''}. Before launch I want safe migrations instead. ` +
222
+ `Please create a baseline migration from my current schema with "prisma migrate dev", update my package.json scripts to use "prisma migrate deploy" in production, ` +
223
+ `remove --accept-data-loss, and explain the new workflow for changing the schema later.`,
224
+ });
225
+ }
226
+ else if (hasMigrations) {
227
+ out.passed.push('Database changes are tracked with migrations');
228
+ }
229
+ }
230
+ // ---- Backups (can't be seen from code) ----
231
+ const how = dbs.includes('Supabase')
232
+ ? '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
+ : dbs.includes('Firebase')
234
+ ? '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.';
236
+ out.manual.push({ id: 'backups', title: 'Turn on automatic backups and test a restore', how });
237
+ return out;
238
+ },
239
+ };
@@ -0,0 +1,19 @@
1
+ import type { Check, CheckOutput } from '../types.js';
2
+ export interface EmailDnsResult {
3
+ offline: boolean;
4
+ /** The domain itself doesn't exist (no NS records, ENOTFOUND). */
5
+ notFound: boolean;
6
+ /** null: the lookup failed (timeout, refused), so we can't tell whether the record exists. */
7
+ spf: boolean | null;
8
+ dkim: boolean;
9
+ dmarc: boolean | null;
10
+ }
11
+ /** The two DNS calls we need; a real Resolver, or a fake one in tests. */
12
+ export interface DnsLike {
13
+ resolveNs(name: string): Promise<string[]>;
14
+ resolveTxt(name: string): Promise<string[][]>;
15
+ }
16
+ export declare function checkEmailDns(domain: string, resolver?: DnsLike): Promise<EmailDnsResult>;
17
+ /** Turn DNS results into findings, passes and checklist items. */
18
+ export declare function applyEmailDns(out: CheckOutput, domain: string, dns: EmailDnsResult, providers: string[]): void;
19
+ export declare const emailCheck: Check;