launch-doctor 0.3.0 → 0.4.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 (67) hide show
  1. package/CHANGELOG.md +92 -6
  2. package/LICENSE +1 -0
  3. package/README.md +138 -22
  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 +175 -12
  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/grades.d.ts +42 -0
  33. package/dist/src/grades.js +163 -0
  34. package/dist/src/history.js +17 -3
  35. package/dist/src/hook.d.ts +13 -0
  36. package/dist/src/hook.js +96 -0
  37. package/dist/src/hooks-setup.d.ts +24 -0
  38. package/dist/src/hooks-setup.js +187 -0
  39. package/dist/src/ignore.d.ts +36 -0
  40. package/dist/src/ignore.js +164 -0
  41. package/dist/src/index.js +28 -3
  42. package/dist/src/init.d.ts +32 -2
  43. package/dist/src/init.js +120 -6
  44. package/dist/src/live.d.ts +13 -1
  45. package/dist/src/live.js +111 -23
  46. package/dist/src/mcp.js +7 -2
  47. package/dist/src/net-guard.d.ts +42 -0
  48. package/dist/src/net-guard.js +147 -0
  49. package/dist/src/pinned-http.d.ts +31 -0
  50. package/dist/src/pinned-http.js +104 -0
  51. package/dist/src/project.d.ts +34 -5
  52. package/dist/src/project.js +145 -111
  53. package/dist/src/report.d.ts +4 -0
  54. package/dist/src/report.js +13 -0
  55. package/dist/src/routes.d.ts +10 -0
  56. package/dist/src/routes.js +21 -4
  57. package/dist/src/safe-fs.d.ts +19 -0
  58. package/dist/src/safe-fs.js +77 -0
  59. package/dist/src/sanitize.d.ts +17 -0
  60. package/dist/src/sanitize.js +90 -0
  61. package/dist/src/sarif.js +1 -1
  62. package/dist/src/summary.d.ts +4 -0
  63. package/dist/src/summary.js +9 -4
  64. package/dist/src/types.d.ts +24 -0
  65. package/dist/src/util.d.ts +1 -1
  66. package/dist/src/util.js +1 -1
  67. package/package.json +9 -5
@@ -0,0 +1,216 @@
1
+ import { lineAt } from '../util.js';
2
+ import { appCode, at } from './common.js';
3
+ /**
4
+ * Bucket names that suggest files people expect to stay private. A public bucket serves every
5
+ * file to anyone who has (or guesses) its URL, so these get a warning instead of a checklist item.
6
+ */
7
+ export const PRIVATE_BUCKET_NAME = /private|invoice|receipt|document|contract|statement|passport|licen[cs]e|id[-_]?cards?|kyc|identit|verification|medical|health|resume|payslip|payroll|tax|bank|backup|export|attachment/i;
8
+ /** Remove SQL comments but keep line numbers the same. */
9
+ function stripSqlComments(sql) {
10
+ return sql.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ' ')).replace(/--[^\n]*/g, '');
11
+ }
12
+ /** Split on commas that are not inside quotes, parentheses or brackets. */
13
+ function splitTopLevel(text) {
14
+ const parts = [];
15
+ let depth = 0;
16
+ let quote = false;
17
+ let start = 0;
18
+ for (let i = 0; i < text.length; i++) {
19
+ const c = text[i];
20
+ if (quote) {
21
+ if (c === "'") {
22
+ // '' is an escaped quote inside a string
23
+ if (text[i + 1] === "'")
24
+ i++;
25
+ else
26
+ quote = false;
27
+ }
28
+ }
29
+ else if (c === "'")
30
+ quote = true;
31
+ else if (c === '(' || c === '[')
32
+ depth++;
33
+ else if (c === ')' || c === ']')
34
+ depth--;
35
+ else if (c === ',' && depth === 0) {
36
+ parts.push(text.slice(start, i).trim());
37
+ start = i + 1;
38
+ }
39
+ }
40
+ parts.push(text.slice(start).trim());
41
+ return parts;
42
+ }
43
+ /** The top-level "( ... )" groups in a VALUES list. */
44
+ function tuples(text) {
45
+ const out = [];
46
+ let depth = 0;
47
+ let quote = false;
48
+ let start = -1;
49
+ for (let i = 0; i < text.length; i++) {
50
+ const c = text[i];
51
+ if (quote) {
52
+ if (c === "'") {
53
+ // '' is an escaped quote inside a string
54
+ if (text[i + 1] === "'")
55
+ i++;
56
+ else
57
+ quote = false;
58
+ }
59
+ }
60
+ else if (c === "'")
61
+ quote = true;
62
+ else if (c === '(') {
63
+ if (depth === 0)
64
+ start = i + 1;
65
+ depth++;
66
+ }
67
+ else if (c === ')') {
68
+ depth--;
69
+ if (depth === 0 && start >= 0)
70
+ out.push(text.slice(start, i));
71
+ }
72
+ }
73
+ return out;
74
+ }
75
+ const unquote = (v) => v
76
+ .replace(/::\w+$/, '')
77
+ .replace(/^'(.*)'$/s, '$1')
78
+ .trim();
79
+ /** The text inside "using ( ... )" or "with check ( ... )", with balanced parentheses. */
80
+ function clause(body, keyword) {
81
+ const m = keyword.exec(body);
82
+ if (!m)
83
+ return null;
84
+ let i = m.index + m[0].length;
85
+ while (/\s/.test(body[i] ?? ''))
86
+ i++;
87
+ if (body[i] !== '(')
88
+ return null;
89
+ let depth = 0;
90
+ for (let j = i; j < body.length; j++) {
91
+ if (body[j] === '(')
92
+ depth++;
93
+ else if (body[j] === ')' && --depth === 0)
94
+ return body.slice(i + 1, j).trim();
95
+ }
96
+ return null;
97
+ }
98
+ /**
99
+ * Is this policy condition open to anyone? "true", or only a bucket check like
100
+ * "bucket_id = 'avatars'", says nothing about who the caller is.
101
+ */
102
+ function openCondition(cond) {
103
+ let c = cond.trim();
104
+ while (/^\(([\s\S]*)\)$/.test(c))
105
+ c = c.slice(1, -1).trim();
106
+ if (/^true$/i.test(c))
107
+ return { open: true, buckets: [] };
108
+ const buckets = [];
109
+ const parts = c.split(/\s+and\s+/i);
110
+ for (const raw of parts) {
111
+ let p = raw.trim();
112
+ while (/^\(([\s\S]*)\)$/.test(p))
113
+ p = p.slice(1, -1).trim();
114
+ const m = /^bucket_id\s*=\s*'([^']+)'(?:::text)?$/i.exec(p);
115
+ if (!m)
116
+ return { open: false, buckets: [] };
117
+ buckets.push(m[1]);
118
+ }
119
+ return { open: true, buckets };
120
+ }
121
+ function analyzeSql(file, buckets, policies) {
122
+ const sql = stripSqlComments(file.content);
123
+ let m;
124
+ // insert into storage.buckets (id, name, public) values ('avatars', 'avatars', true), (...);
125
+ const insertRe = /insert\s+into\s+"?storage"?\s*\.\s*"?buckets"?\s*\(([^)]*)\)\s*values\s*([\s\S]*?);/gi;
126
+ while ((m = insertRe.exec(sql))) {
127
+ const cols = m[1].split(',').map((c) => c.replace(/"/g, '').trim().toLowerCase());
128
+ const pub = cols.indexOf('public');
129
+ if (pub < 0)
130
+ continue;
131
+ const nameCol = cols.indexOf('name') >= 0 ? cols.indexOf('name') : cols.indexOf('id');
132
+ const values = m[2].replace(/\bon\s+conflict[\s\S]*$/i, '');
133
+ for (const tuple of tuples(values)) {
134
+ const vals = splitTopLevel(tuple);
135
+ if (!/^true$/i.test(unquote(vals[pub] ?? '')))
136
+ continue;
137
+ buckets.push({
138
+ name: nameCol >= 0 ? unquote(vals[nameCol] ?? '') : 'bucket',
139
+ loc: { file: file.path, line: lineAt(sql, m.index) },
140
+ });
141
+ }
142
+ }
143
+ // update storage.buckets set public = true where id = 'avatars';
144
+ const updateRe = /update\s+"?storage"?\s*\.\s*"?buckets"?\s+set\s+[^;]*?\bpublic\s*=\s*true\b[^;]*?where\s+(?:id|name)\s*=\s*'([^']+)'/gi;
145
+ while ((m = updateRe.exec(sql))) {
146
+ buckets.push({ name: m[1], loc: { file: file.path, line: lineAt(sql, m.index) } });
147
+ }
148
+ // create policy "..." on storage.objects for insert to anon with check (bucket_id = 'avatars');
149
+ const policyRe = /create\s+policy\s+("([^"]+)"|(\w+))\s+on\s+"?storage"?\s*\.\s*"?objects"?([\s\S]*?);/gi;
150
+ while ((m = policyRe.exec(sql))) {
151
+ const body = m[4] ?? '';
152
+ const rolesMatch = /\bto\s+((?:"?\w+"?\s*,\s*)*"?\w+"?)/i.exec(body);
153
+ const roles = rolesMatch ? rolesMatch[1].split(',').map((r) => r.replace(/"/g, '').trim().toLowerCase()) : [];
154
+ // No "to ..." clause means the policy applies to everyone, signed out too.
155
+ const toEveryone = !roles.length || roles.some((r) => r === 'anon' || r === 'public');
156
+ const signedIn = !toEveryone && roles.includes('authenticated');
157
+ if (!toEveryone && !signedIn)
158
+ continue;
159
+ const command = /\bfor\s+(all|select|insert|update|delete)\b/i.exec(body)?.[1]?.toLowerCase() ?? 'all';
160
+ if (command === 'select')
161
+ continue; // reading files is what a public bucket is for; covered by the bucket item
162
+ // Signed-in users uploading files is normal; replacing or deleting everyone's files is not.
163
+ if (signedIn && command === 'insert')
164
+ continue;
165
+ const conds = [clause(body, /\busing\b/i), clause(body, /\bwith\s+check\b/i)].filter((c) => c !== null);
166
+ if (!conds.length)
167
+ continue;
168
+ const checks = conds.map(openCondition);
169
+ if (!checks.every((c) => c.open))
170
+ continue;
171
+ policies.push({
172
+ name: m[2] ?? m[3] ?? 'policy',
173
+ buckets: [...new Set(checks.flatMap((c) => c.buckets))],
174
+ insertOnly: command === 'insert',
175
+ signedIn,
176
+ loc: { file: file.path, line: lineAt(sql, m.index) },
177
+ });
178
+ }
179
+ }
180
+ /** [storage.buckets.avatars] ... public = true in supabase/config.toml */
181
+ function analyzeConfig(file, buckets) {
182
+ // [ \t]* rather than \s*: with the m flag, \s* runs across every following newline from each line start.
183
+ const re = /^[ \t]*\[storage\.buckets\.([\w-]+)\][ \t]*$([\s\S]*?)(?=^[ \t]*\[|(?![\s\S]))/gm;
184
+ let m;
185
+ while ((m = re.exec(file.content))) {
186
+ const pub = /^[ \t]*public[ \t]*=[ \t]*true\b/m.exec(m[2]);
187
+ if (!pub)
188
+ continue;
189
+ buckets.push({ name: m[1], loc: { file: file.path, line: lineAt(file.content, m.index + m[0].indexOf('[')) } });
190
+ }
191
+ }
192
+ /** supabase.storage.createBucket('avatars', { public: true }) and updateBucket(...) in app code. */
193
+ const CODE_BUCKET = /\.(?:createBucket|updateBucket)\s*\(\s*(["'`])([^"'`]+)\1\s*,\s*\{[^}]*\bpublic\s*:\s*true\b/g;
194
+ /** Does the app use Supabase Storage at all? */
195
+ const USES_STORAGE = /\.storage\s*\.\s*(?:from|createBucket|updateBucket|listBuckets|getBucket)\s*\(/;
196
+ export function analyzeStorage(ctx) {
197
+ const buckets = [];
198
+ const policies = [];
199
+ for (const f of ctx.files) {
200
+ const lower = f.path.toLowerCase();
201
+ if (lower.endsWith('.sql'))
202
+ analyzeSql(f, buckets, policies);
203
+ else if (/(^|\/)supabase\/config\.toml$/.test(lower))
204
+ analyzeConfig(f, buckets);
205
+ }
206
+ for (const m of ctx.findCode(CODE_BUCKET, appCode, 20))
207
+ buckets.push({ name: m.match[2], loc: at(m) });
208
+ // One entry per bucket name (the first place it is made public).
209
+ const seen = new Set();
210
+ const unique = buckets.filter((b) => !seen.has(b.name) && seen.add(b.name));
211
+ const usesStorage = unique.length > 0 ||
212
+ policies.length > 0 ||
213
+ ctx.findCode(USES_STORAGE, appCode, 1).length > 0 ||
214
+ ctx.files.some((f) => f.path.toLowerCase().endsWith('.sql') && /storage\s*\.\s*(?:buckets|objects)/i.test(f.content));
215
+ return { buckets: unique, policies, usesStorage };
216
+ }
package/dist/src/cli.js CHANGED
@@ -1,17 +1,24 @@
1
1
  #!/usr/bin/env node
2
- import { appendFileSync, existsSync, rmSync, statSync, writeFileSync } from 'node:fs';
2
+ import { appendFileSync, existsSync, rmSync, statSync } from 'node:fs';
3
3
  import { isAbsolute, join, relative, resolve } from 'node:path';
4
4
  import { applyBaseline, BASELINE_FILE, loadBaseline, writeBaseline } from './baseline.js';
5
+ import { changedFiles } from './changed.js';
5
6
  import { createDemoProject, removeOnSignal } from './demo.js';
6
7
  import { renderFixes } from './fixes.js';
7
8
  import { explainGitHubError, postPrFeedback, prContextFromEnv } from './github.js';
9
+ import { git } from './git.js';
8
10
  import { failingFindings } from './grade.js';
11
+ import { BADGE_FILE, describeEntry, entryFor, GRADES_FILE, headCommit, loadGrades, recordGrade, renderGradeTable, } from './grades.js';
9
12
  import { DEFAULT_HISTORY_DEPTH } from './history.js';
13
+ import { runHook } from './hook.js';
14
+ import { setupHooks } from './hooks-setup.js';
10
15
  import { CATEGORY_IDS, runDoctor } from './index.js';
11
- import { runInit } from './init.js';
16
+ import { badgeUrl, GRADES_BRANCH, githubRepo, runInit } from './init.js';
12
17
  import { runLiveScan } from './live.js';
13
18
  import { runMcpServer } from './mcp.js';
19
+ import { assertConfigRef } from './project.js';
14
20
  import { bold, dim, renderReport } from './report.js';
21
+ import { writeRegularFile } from './safe-fs.js';
15
22
  import { renderSarif } from './sarif.js';
16
23
  import { renderStepSummary } from './summary.js';
17
24
  import { version } from './version.js';
@@ -21,6 +28,9 @@ const HELP = `
21
28
  ${bold('Usage')}
22
29
  npx launch-doctor [folder] [options]
23
30
  npx launch-doctor init [folder] Create .launchdoctorignore and a GitHub Actions workflow
31
+ npx launch-doctor init --hooks Set up hooks that check every AI edit and every commit
32
+ npx launch-doctor init --monitor Add a GitHub Actions workflow that re-checks the project every week
33
+ npx launch-doctor grades [folder] Show the grades saved with --record
24
34
  npx launch-doctor scan <url> Check your deployed site (exposed files, source maps, open Supabase tables, headers)
25
35
  npx launch-doctor mcp Start an MCP server so Claude Code, Cursor and other AI tools can run checks
26
36
 
@@ -40,6 +50,13 @@ const HELP = `
40
50
  --history-depth <n> How many commits --history reads (default 500)
41
51
  --update-baseline Save today's findings to .launchdoctor-baseline.json as accepted
42
52
  --no-baseline Ignore .launchdoctor-baseline.json and show every finding
53
+ --record Save the grade to .launchdoctor/grades.json and redraw .launchdoctor/badge.svg
54
+ --config-from <ref> Read .launchdoctorignore and the baseline from this git ref (a branch,
55
+ tag or commit) instead of the folder, and ignore inline ignore comments on
56
+ lines changed since then. The GitHub Action uses it so a pull request
57
+ can't silence its own findings
58
+ --changed Only report on files changed since the last commit (fast, for hooks)
59
+ --staged Only report on files staged for the next commit (for a pre-commit hook)
43
60
  --demo Scan a built-in sample app full of mistakes
44
61
  -h, --help Show this help
45
62
  -v, --version Show the version
@@ -64,6 +81,11 @@ const HELP = `
64
81
  npx launch-doctor ./my-app --domain myapp.com
65
82
  npx launch-doctor --ci --fail-on warning
66
83
  `;
84
+ function setChangeMode(current, next) {
85
+ if (current && current !== next)
86
+ fail('Use either --changed or --staged, not both');
87
+ return next;
88
+ }
67
89
  function parseArgs(argv) {
68
90
  const args = {
69
91
  writeFile: true,
@@ -76,6 +98,7 @@ function parseArgs(argv) {
76
98
  baseline: true,
77
99
  history: false,
78
100
  historyDepth: DEFAULT_HISTORY_DEPTH,
101
+ record: false,
79
102
  demo: false,
80
103
  help: false,
81
104
  version: false,
@@ -108,6 +131,16 @@ function parseArgs(argv) {
108
131
  args.updateBaseline = true;
109
132
  else if (a === '--no-baseline')
110
133
  args.baseline = false;
134
+ else if (a === '--record')
135
+ args.record = true;
136
+ else if (a === '--changed')
137
+ args.changeMode = setChangeMode(args.changeMode, 'changed');
138
+ else if (a === '--staged')
139
+ args.changeMode = setChangeMode(args.changeMode, 'staged');
140
+ else if (a === '--config-from')
141
+ args.configFrom = value();
142
+ else if (a.startsWith('--config-from='))
143
+ args.configFrom = a.slice(14);
111
144
  else if (a === '--history')
112
145
  args.history = true;
113
146
  else if (a === '--history-depth')
@@ -189,19 +222,83 @@ function fail(message) {
189
222
  process.exit(2);
190
223
  }
191
224
  function init(argv) {
192
- const extra = argv.filter((a) => a.startsWith('-'));
225
+ const hooks = argv.includes('--hooks');
226
+ const monitor = argv.includes('--monitor');
227
+ const rest = argv.filter((a) => a !== '--hooks' && a !== '--monitor');
228
+ const extra = rest.filter((a) => a.startsWith('-'));
193
229
  if (extra.length)
194
- fail(`init doesn't take options (got ${extra.join(' ')})`);
195
- if (argv.length > 1)
230
+ fail(`init only takes --hooks or --monitor (got ${extra.join(' ')})`);
231
+ if (hooks && monitor)
232
+ fail('Run "init --hooks" and "init --monitor" one at a time');
233
+ if (rest.length > 1)
196
234
  fail('init takes at most one folder');
197
- const root = resolve(argv[0] ?? '.');
235
+ const root = resolve(rest[0] ?? '.');
198
236
  if (!existsSync(root) || !statSync(root).isDirectory())
199
237
  fail(`Folder not found: ${root}`);
200
- const { created, skipped } = runInit(root);
238
+ if (hooks) {
239
+ const result = setupHooks(root);
240
+ for (const f of result.created)
241
+ process.stdout.write(` created ${f}
242
+ `);
243
+ for (const f of result.updated)
244
+ process.stdout.write(` updated ${f} ${dim('(a launch-doctor hook was added; your other settings are untouched)')}
245
+ `);
246
+ for (const [f, why] of result.skipped)
247
+ process.stdout.write(` skipped ${f} ${dim(`(${why})`)}
248
+ `);
249
+ return;
250
+ }
251
+ const { created, skipped } = runInit(root, { monitor });
201
252
  for (const f of created)
202
253
  process.stdout.write(` created ${f}\n`);
203
254
  for (const f of skipped)
204
255
  process.stdout.write(` skipped ${f} ${dim('(already exists)')}\n`);
256
+ if (monitor && created.length) {
257
+ const repo = githubRepo(git(root, ['remote', 'get-url', 'origin'])) ?? undefined;
258
+ process.stdout.write(`\n It runs every Monday and keeps grades.json and badge.svg on the ${GRADES_BRANCH} branch\n` +
259
+ ` (never on your default branch). Show the grade in your README:\n` +
260
+ ` ![Launch Doctor grade](${badgeUrl(repo)})\n` +
261
+ ` ${dim('To check your deployed site too, add a repository variable named LAUNCH_DOCTOR_URL.')}\n`);
262
+ }
263
+ }
264
+ /** `launch-doctor grades [folder] [--json]`: the grades saved with --record, newest first. */
265
+ function grades(argv) {
266
+ const json = argv.includes('--json');
267
+ const rest = argv.filter((a) => a !== '--json');
268
+ const extra = rest.filter((a) => a.startsWith('-'));
269
+ if (extra.length)
270
+ fail(`grades only takes --json (got ${extra.join(' ')})`);
271
+ if (rest.length > 1)
272
+ fail('grades takes at most one folder');
273
+ const root = resolve(rest[0] ?? '.');
274
+ if (!existsSync(root) || !statSync(root).isDirectory())
275
+ fail(`Folder not found: ${root}`);
276
+ const entries = loadGrades(root);
277
+ if (json)
278
+ process.stdout.write(`${JSON.stringify(entries, null, 2)}\n`);
279
+ else
280
+ process.stdout.write(renderGradeTable(entries));
281
+ }
282
+ /** The JSON an AI tool sends to a hook on stdin. A terminal has nothing to send. */
283
+ async function readStdin() {
284
+ if (process.stdin.isTTY)
285
+ return '';
286
+ const chunks = [];
287
+ for await (const chunk of process.stdin)
288
+ chunks.push(chunk);
289
+ return Buffer.concat(chunks).toString('utf8');
290
+ }
291
+ async function hook(argv) {
292
+ const kind = argv[0];
293
+ if (kind !== 'claude' && kind !== 'cursor') {
294
+ fail('hook needs the tool it runs for: "launch-doctor hook claude" or "launch-doctor hook cursor". Set both up with "launch-doctor init --hooks".');
295
+ }
296
+ const result = await runHook(kind, await readStdin());
297
+ if (result.stdout)
298
+ process.stdout.write(result.stdout);
299
+ if (result.stderr)
300
+ process.stderr.write(result.stderr);
301
+ process.exitCode = result.exitCode;
205
302
  }
206
303
  const MCP_HELP = `
207
304
  ${bold('launch-doctor mcp')} - an MCP server for Claude Code, Cursor and other AI coding tools
@@ -305,7 +402,7 @@ async function scan(argv) {
305
402
  if (writeFile && hasSomething) {
306
403
  const target = out ? resolve(process.cwd(), out) : resolve(process.cwd(), 'LAUNCH_FIXES_LIVE.md');
307
404
  try {
308
- writeFileSync(target, renderFixes(report));
405
+ writeRegularFile(target, renderFixes(report));
309
406
  const rel = relative(process.cwd(), target);
310
407
  fixFile = rel && !rel.startsWith('..') ? rel : target;
311
408
  }
@@ -380,6 +477,10 @@ async function main() {
380
477
  return scan(process.argv.slice(3));
381
478
  if (process.argv[2] === 'mcp')
382
479
  return mcp(process.argv.slice(3));
480
+ if (process.argv[2] === 'hook')
481
+ return hook(process.argv.slice(3));
482
+ if (process.argv[2] === 'grades')
483
+ return grades(process.argv.slice(3));
383
484
  const args = parseArgs(process.argv.slice(2));
384
485
  if (args.help) {
385
486
  process.stdout.write(HELP);
@@ -407,15 +508,56 @@ async function main() {
407
508
  const root = resolve(args.path ?? '.');
408
509
  if (!existsSync(root) || !statSync(root).isDirectory())
409
510
  fail(`Folder not found: ${root}`);
511
+ if (args.record) {
512
+ // A recorded grade is compared with the next one, so it has to be for the whole project.
513
+ if (args.demo)
514
+ fail('--record needs a real project folder, not --demo');
515
+ if (args.only || args.skip)
516
+ fail('--record saves the grade for the whole project, so leave out --only and --skip');
517
+ }
518
+ if (args.configFrom) {
519
+ if (args.updateBaseline)
520
+ fail('--config-from reads the baseline from git, so it cannot be used with --update-baseline');
521
+ try {
522
+ assertConfigRef(root, args.configFrom);
523
+ }
524
+ catch (err) {
525
+ fail(err.message);
526
+ }
527
+ }
528
+ let onlyFiles;
529
+ if (args.changeMode) {
530
+ const flag = `--${args.changeMode}`;
531
+ if (args.demo)
532
+ fail(`${flag} needs a real project folder, not --demo`);
533
+ for (const [on, name] of [
534
+ [args.updateBaseline, '--update-baseline'],
535
+ [args.prComment, '--pr-comment'],
536
+ [args.history, '--history'],
537
+ [args.record, '--record'],
538
+ ]) {
539
+ if (on)
540
+ fail(`${flag} reports on some files only, so it can't be used with ${name}`);
541
+ }
542
+ const files = changedFiles(root, args.changeMode);
543
+ if (!files)
544
+ fail(`${flag} needs a folder inside a git repository`);
545
+ onlyFiles = files;
546
+ // A partial report must not overwrite LAUNCH_FIXES.md, which describes the whole project.
547
+ if (!args.out)
548
+ args.writeFile = false;
549
+ }
410
550
  let report;
411
551
  try {
412
552
  report = await runDoctor(root, {
553
+ onlyFiles,
413
554
  offline: args.offline,
414
555
  domain: args.domain,
415
556
  only: args.only,
416
557
  skip: args.skip,
417
558
  // When updating, start from scratch so every current finding is saved.
418
559
  baseline: args.baseline && !args.updateBaseline,
560
+ configFrom: args.configFrom,
419
561
  history: args.history ? { depth: args.historyDepth } : undefined,
420
562
  });
421
563
  }
@@ -432,7 +574,13 @@ async function main() {
432
574
  if (args.updateBaseline) {
433
575
  if (args.demo)
434
576
  fail('--update-baseline needs a real project folder, not --demo');
435
- const saved = writeBaseline(root, report);
577
+ let saved = 0;
578
+ try {
579
+ saved = writeBaseline(root, report);
580
+ }
581
+ catch (err) {
582
+ fail(`Couldn't write ${BASELINE_FILE}: ${err.message}`);
583
+ }
436
584
  applyBaseline(report, loadBaseline(root) ?? new Set());
437
585
  const msg = `Saved ${saved} finding${saved === 1 ? '' : 's'} to ${BASELINE_FILE}. Future runs (and --ci) only report new problems.`;
438
586
  (args.json ? process.stderr : process.stdout).write(`\n ${dim(msg)}\n`);
@@ -447,7 +595,7 @@ async function main() {
447
595
  // Rewrite an existing file even when everything passes, so old problems don't linger in it.
448
596
  if (args.writeFile && (hasSomething || existsSync(target))) {
449
597
  try {
450
- writeFileSync(target, renderFixes(report));
598
+ writeRegularFile(target, renderFixes(report));
451
599
  const rel = relative(process.cwd(), target);
452
600
  fixFile = rel && !rel.startsWith('..') ? rel : target;
453
601
  }
@@ -459,7 +607,7 @@ async function main() {
459
607
  const sarifPath = isAbsolute(args.sarif) ? args.sarif : resolve(process.cwd(), args.sarif);
460
608
  const fallbackUri = ['package.json', 'pyproject.toml', 'requirements.txt', 'README.md'].find((f) => existsSync(join(root, f)));
461
609
  try {
462
- writeFileSync(sarifPath, renderSarif(report, { fallbackUri }));
610
+ writeRegularFile(sarifPath, renderSarif(report, { fallbackUri }));
463
611
  }
464
612
  catch (err) {
465
613
  fail(`Couldn't write ${sarifPath}: ${err.message}`);
@@ -478,10 +626,25 @@ async function main() {
478
626
  writeStepOutputs(report);
479
627
  if (args.prComment)
480
628
  await commentOnPr(report, root);
629
+ // The last recorded grade, read before this run adds one. Not for a partial report or the demo.
630
+ const last = args.demo || onlyFiles || args.only || args.skip ? undefined : loadGrades(root).at(-1);
631
+ let recorded;
632
+ if (args.record) {
633
+ try {
634
+ recordGrade(root, entryFor(report, headCommit(root)));
635
+ recorded = `Recorded grade ${report.grade} in ${GRADES_FILE} and ${BADGE_FILE}.`;
636
+ }
637
+ catch (err) {
638
+ process.stderr.write(`\n ${dim(`Couldn't record the grade: ${err.message}`)}\n`);
639
+ process.exitCode = 2;
640
+ }
641
+ }
481
642
  if (args.json)
482
643
  process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
483
644
  else
484
- process.stdout.write(renderReport(report, { fixFile }));
645
+ process.stdout.write(renderReport(report, { fixFile, lastRecorded: last && describeEntry(last) }));
646
+ if (recorded)
647
+ (args.json ? process.stderr : process.stdout).write(` ${dim(recorded)}\n\n`);
485
648
  if (args.ci && failingFindings(report, args.failOn).length > 0)
486
649
  process.exitCode = 1;
487
650
  }
package/dist/src/demo.js CHANGED
@@ -96,6 +96,7 @@ export function createDemoProject() {
96
96
  'src/lib/supabase.ts': "import { createClient } from '@supabase/supabase-js';\nexport const supabase = createClient(import.meta.env.VITE_SUPABASE_URL, import.meta.env.VITE_SUPABASE_ANON_KEY);\n",
97
97
  'src/lib/ai.ts': "import OpenAI from 'openai';\n\nconst openai = new OpenAI({ apiKey: import.meta.env.VITE_OPENAI_API_KEY, dangerouslyAllowBrowser: true });\n\nexport async function summarize(text: string) {\n return openai.chat.completions.create({ model: 'gpt-5-mini', messages: [{ role: 'user', content: text }] });\n}\n",
98
98
  'src/pages/Signup.tsx': "import { supabase } from '../lib/supabase';\n\nexport function Signup() {\n return <button onClick={() => supabase.auth.signUp({ email: '', password: '' })}>Create account</button>;\n}\n",
99
+ 'src/pages/Admin.tsx': "export function Admin({ user }: { user: { email: string } }) {\n if (user.email !== 'founder@example.com') return <p>Not allowed</p>;\n return <AllUsersTable />;\n}\n",
99
100
  'src/api.ts': "export const getNotes = () => fetch('http://localhost:3001/notes').then((r) => r.json());\n",
100
101
  'supabase/functions/stripe-webhook/index.ts': "Deno.serve(async (req) => {\n const event = await req.json();\n if (event.type === 'checkout.session.completed') {\n // mark the user as paid\n }\n return new Response('ok');\n});\n",
101
102
  'supabase/functions/welcome-email/index.ts': "import { Resend } from 'npm:resend';\nconst resend = new Resend(Deno.env.get('RESEND_API_KEY'));\nDeno.serve(async () => {\n await resend.emails.send({ from: 'onboarding@resend.dev', to: 'user@example.com', subject: 'Welcome!', html: '<p>Hi</p>' });\n return new Response('sent');\n});\n",
@@ -6,5 +6,5 @@ export declare function detectPayments(ctx: ProjectContext): boolean;
6
6
  /** Analytics that set cookies (cookieless tools like Plausible are left out on purpose). */
7
7
  export declare function detectCookieAnalytics(ctx: ProjectContext): boolean;
8
8
  export declare function detectEmailProviders(ctx: ProjectContext): string[];
9
- /** Common ways code checks who the user is. */
9
+ /** Common ways code checks who the user is. Test it on withoutImports(code) (routes.ts): an import checks nothing. */
10
10
  export declare const AUTH_CHECK_RE: RegExp;
@@ -128,5 +128,5 @@ export function detectEmailProviders(ctx) {
128
128
  }
129
129
  return out;
130
130
  }
131
- /** Common ways code checks who the user is. */
131
+ /** Common ways code checks who the user is. Test it on withoutImports(code) (routes.ts): an import checks nothing. */
132
132
  export const AUTH_CHECK_RE = /getServerSession|\bauth\s*\(\s*\)|currentUser\s*\(|getAuth\s*\(|\.getUser\s*\(|getSession\s*\(|verifyIdToken|verifyToken|jwtVerify|jwt\.verify|clerkClient|withAuth|requireAuth|requireUser|isAuthenticated|ensureAuth|session\?\.user|session\.user|req\.user|request\.user|ctx\.user|locals\.user|validateRequest|getKindeServerSession|getToken\s*\(/;
package/dist/src/fixes.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { shortWhere } from './checks/common.js';
2
+ import { md, mdCode } from './sanitize.js';
2
3
  import { ISSUES_URL, plural } from './util.js';
3
4
  function fence(text) {
4
5
  // Use a fence longer than any backtick run inside the prompt.
@@ -6,13 +7,15 @@ function fence(text) {
6
7
  const ticks = '`'.repeat(longest + 1);
7
8
  return `${ticks}text\n${text}\n${ticks}`;
8
9
  }
10
+ // Titles, explanations and paths can hold text from scanned files, so they go through md() / mdCode() (no links,
11
+ // HTML or @mentions); the prompts are in code fences, where nothing renders.
9
12
  function section(f, n) {
10
- const parts = [`### ${n}. ${f.title}`, ''];
13
+ const parts = [`### ${n}. ${md(f.title)}`, ''];
11
14
  if (f.location)
12
- parts.push(`**Where:** \`${shortWhere(f.location)}\``, '');
15
+ parts.push(`**Where:** ${mdCode(shortWhere(f.location))}`, '');
13
16
  if (f.baseline)
14
17
  parts.push('_Existing issue, recorded in .launchdoctor-baseline.json._', '');
15
- parts.push(`**Why it matters:** ${f.why}`, '', '**Prompt to paste:**', '', fence(f.fixPrompt), '');
18
+ parts.push(`**Why it matters:** ${md(f.why, { oneLine: false })}`, '', '**Prompt to paste:**', '', fence(f.fixPrompt), '');
16
19
  parts.push(`<sub>Not relevant to your app? Add \`${f.id}\` to a \`.launchdoctorignore\` file.</sub>`, '');
17
20
  return parts.join('\n');
18
21
  }
@@ -25,7 +28,7 @@ export function renderFixes(report) {
25
28
  const manual = report.categories.flatMap((c) => c.manual);
26
29
  const date = report.generatedAt.slice(0, 10);
27
30
  const out = [
28
- `# Launch Doctor fixes for ${report.projectName}`,
31
+ `# Launch Doctor fixes for ${md(report.projectName)}`,
29
32
  '',
30
33
  `**Grade: ${report.grade}** · ${report.verdict} · ${plural(critical.length, 'critical issue')} · ${plural(warnings.length, 'warning')} · checked ${date}`,
31
34
  '',
@@ -59,7 +62,7 @@ export function renderFixes(report) {
59
62
  out.push('## Check yourself', '');
60
63
  out.push("Things Launch Doctor can't see from your code:", '');
61
64
  for (const m of manual)
62
- out.push(`- [ ] **${m.title}** - ${m.how}`);
65
+ out.push(`- [ ] **${md(m.title)}** - ${md(m.how)}`);
63
66
  out.push('');
64
67
  }
65
68
  out.push('---', '', `_Generated by [Launch Doctor](https://www.npmjs.com/package/launch-doctor) v${report.version}. Safe to delete or add to .gitignore._`, '', `_A finding that is wrong, or a problem it missed? Please [report it](${ISSUES_URL}). Launch Doctor reads code with pattern rules, so it can make mistakes both ways._`, '');
@@ -0,0 +1,25 @@
1
+ /** Flags for every command that prints a diff or compares files (log -p, diff). */
2
+ export declare const SAFE_DIFF: string[];
3
+ /** No git command we run should take this long; a hang (a FIFO for a config file, for example) is cut off. */
4
+ export declare const GIT_TIMEOUT_MS = 60000;
5
+ /**
6
+ * The full argument list for a git command run in `cwd`, or null when it isn't safe to run git there.
7
+ * Every git call goes through here (a test checks this).
8
+ */
9
+ export declare function gitArgs(cwd: string, args: string[], { ownHooks }?: {
10
+ ownHooks?: boolean | undefined;
11
+ }): string[] | null;
12
+ /** Run git in `cwd`. Returns stdout, or null when git fails, isn't installed, times out or isn't safe to run. */
13
+ export declare function git(cwd: string, args: string[]): string | null;
14
+ /**
15
+ * The repository's own hooks folder (core.hooksPath, or .git/hooks), for `init --hooks`, which you run on your own
16
+ * project to install a hook there. The only git command that sees the repository's hooks setting; it runs nothing.
17
+ */
18
+ export declare function gitHooksDir(cwd: string): string | null;
19
+ /** Like git(), but also reports the exit code, for commands where exit code 1 is an answer, not a failure. */
20
+ export declare function gitStatus(cwd: string, args: string[], opts?: {
21
+ ownHooks?: boolean;
22
+ }): {
23
+ stdout: string | null;
24
+ status: number | null;
25
+ };