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
@@ -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,15 +1,22 @@
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 { createDemoProject } from './demo.js';
5
+ import { changedFiles } from './changed.js';
6
+ import { createDemoProject, removeOnSignal } from './demo.js';
6
7
  import { renderFixes } from './fixes.js';
8
+ import { explainGitHubError, postPrFeedback, prContextFromEnv } from './github.js';
7
9
  import { failingFindings } from './grade.js';
8
10
  import { DEFAULT_HISTORY_DEPTH } from './history.js';
11
+ import { runHook } from './hook.js';
12
+ import { setupHooks } from './hooks-setup.js';
9
13
  import { CATEGORY_IDS, runDoctor } from './index.js';
10
14
  import { runInit } from './init.js';
11
15
  import { runLiveScan } from './live.js';
16
+ import { runMcpServer } from './mcp.js';
17
+ import { assertConfigRef } from './project.js';
12
18
  import { bold, dim, renderReport } from './report.js';
19
+ import { writeRegularFile } from './safe-fs.js';
13
20
  import { renderSarif } from './sarif.js';
14
21
  import { renderStepSummary } from './summary.js';
15
22
  import { version } from './version.js';
@@ -19,7 +26,9 @@ const HELP = `
19
26
  ${bold('Usage')}
20
27
  npx launch-doctor [folder] [options]
21
28
  npx launch-doctor init [folder] Create .launchdoctorignore and a GitHub Actions workflow
29
+ npx launch-doctor init --hooks Set up hooks that check every AI edit and every commit
22
30
  npx launch-doctor scan <url> Check your deployed site (exposed files, source maps, open Supabase tables, headers)
31
+ npx launch-doctor mcp Start an MCP server so Claude Code, Cursor and other AI tools can run checks
23
32
 
24
33
  ${bold('Options')}
25
34
  --domain <domain> Domain you send email from (checks SPF / DKIM / DMARC)
@@ -27,6 +36,7 @@ const HELP = `
27
36
  --no-file Don't write the fix prompts file
28
37
  --json Print the full report as JSON (no fix file unless --out is given)
29
38
  --sarif <file> Also write a SARIF 2.1.0 file (for GitHub code scanning)
39
+ --pr-comment On a GitHub pull request, post a summary comment and inline fix prompts
30
40
  --offline Skip network checks (email DNS)
31
41
  --ci Exit with code 1 on findings at or above --fail-on (no fix file unless --out)
32
42
  --fail-on <level> With --ci, the lowest severity that fails: critical (default) or warning
@@ -36,6 +46,12 @@ const HELP = `
36
46
  --history-depth <n> How many commits --history reads (default 500)
37
47
  --update-baseline Save today's findings to .launchdoctor-baseline.json as accepted
38
48
  --no-baseline Ignore .launchdoctor-baseline.json and show every finding
49
+ --config-from <ref> Read .launchdoctorignore and the baseline from this git ref (a branch,
50
+ tag or commit) instead of the folder, and ignore inline ignore comments on
51
+ lines changed since then. The GitHub Action uses it so a pull request
52
+ can't silence its own findings
53
+ --changed Only report on files changed since the last commit (fast, for hooks)
54
+ --staged Only report on files staged for the next commit (for a pre-commit hook)
39
55
  --demo Scan a built-in sample app full of mistakes
40
56
  -h, --help Show this help
41
57
  -v, --version Show the version
@@ -52,12 +68,19 @@ const HELP = `
52
68
 
53
69
  ${bold('GitHub Actions')}
54
70
  When GITHUB_STEP_SUMMARY is set, a Markdown summary is added to the job summary page.
71
+ When GITHUB_OUTPUT is set, the grade, score and counts are saved as step outputs.
72
+ --pr-comment needs GITHUB_TOKEN and "permissions: pull-requests: write".
55
73
 
56
74
  ${bold('Examples')}
57
75
  npx launch-doctor
58
76
  npx launch-doctor ./my-app --domain myapp.com
59
77
  npx launch-doctor --ci --fail-on warning
60
78
  `;
79
+ function setChangeMode(current, next) {
80
+ if (current && current !== next)
81
+ fail('Use either --changed or --staged, not both');
82
+ return next;
83
+ }
61
84
  function parseArgs(argv) {
62
85
  const args = {
63
86
  writeFile: true,
@@ -65,6 +88,7 @@ function parseArgs(argv) {
65
88
  offline: false,
66
89
  ci: false,
67
90
  failOn: 'critical',
91
+ prComment: false,
68
92
  updateBaseline: false,
69
93
  baseline: true,
70
94
  history: false,
@@ -93,12 +117,22 @@ function parseArgs(argv) {
93
117
  args.ci = true;
94
118
  else if (a === '--demo')
95
119
  args.demo = true;
120
+ else if (a === '--pr-comment')
121
+ args.prComment = true;
96
122
  else if (a === '--no-file')
97
123
  args.writeFile = false;
98
124
  else if (a === '--update-baseline')
99
125
  args.updateBaseline = true;
100
126
  else if (a === '--no-baseline')
101
127
  args.baseline = false;
128
+ else if (a === '--changed')
129
+ args.changeMode = setChangeMode(args.changeMode, 'changed');
130
+ else if (a === '--staged')
131
+ args.changeMode = setChangeMode(args.changeMode, 'staged');
132
+ else if (a === '--config-from')
133
+ args.configFrom = value();
134
+ else if (a.startsWith('--config-from='))
135
+ args.configFrom = a.slice(14);
102
136
  else if (a === '--history')
103
137
  args.history = true;
104
138
  else if (a === '--history-depth')
@@ -180,20 +214,81 @@ function fail(message) {
180
214
  process.exit(2);
181
215
  }
182
216
  function init(argv) {
183
- const extra = argv.filter((a) => a.startsWith('-'));
217
+ const hooks = argv.includes('--hooks');
218
+ const rest = argv.filter((a) => a !== '--hooks');
219
+ const extra = rest.filter((a) => a.startsWith('-'));
184
220
  if (extra.length)
185
- fail(`init doesn't take options (got ${extra.join(' ')})`);
186
- if (argv.length > 1)
221
+ fail(`init only takes --hooks (got ${extra.join(' ')})`);
222
+ if (rest.length > 1)
187
223
  fail('init takes at most one folder');
188
- const root = resolve(argv[0] ?? '.');
224
+ const root = resolve(rest[0] ?? '.');
189
225
  if (!existsSync(root) || !statSync(root).isDirectory())
190
226
  fail(`Folder not found: ${root}`);
227
+ if (hooks) {
228
+ const result = setupHooks(root);
229
+ for (const f of result.created)
230
+ process.stdout.write(` created ${f}
231
+ `);
232
+ for (const f of result.updated)
233
+ process.stdout.write(` updated ${f} ${dim('(a launch-doctor hook was added; your other settings are untouched)')}
234
+ `);
235
+ for (const [f, why] of result.skipped)
236
+ process.stdout.write(` skipped ${f} ${dim(`(${why})`)}
237
+ `);
238
+ return;
239
+ }
191
240
  const { created, skipped } = runInit(root);
192
241
  for (const f of created)
193
242
  process.stdout.write(` created ${f}\n`);
194
243
  for (const f of skipped)
195
244
  process.stdout.write(` skipped ${f} ${dim('(already exists)')}\n`);
196
245
  }
246
+ /** The JSON an AI tool sends to a hook on stdin. A terminal has nothing to send. */
247
+ async function readStdin() {
248
+ if (process.stdin.isTTY)
249
+ return '';
250
+ const chunks = [];
251
+ for await (const chunk of process.stdin)
252
+ chunks.push(chunk);
253
+ return Buffer.concat(chunks).toString('utf8');
254
+ }
255
+ async function hook(argv) {
256
+ const kind = argv[0];
257
+ if (kind !== 'claude' && kind !== 'cursor') {
258
+ 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".');
259
+ }
260
+ const result = await runHook(kind, await readStdin());
261
+ if (result.stdout)
262
+ process.stdout.write(result.stdout);
263
+ if (result.stderr)
264
+ process.stderr.write(result.stderr);
265
+ process.exitCode = result.exitCode;
266
+ }
267
+ const MCP_HELP = `
268
+ ${bold('launch-doctor mcp')} - an MCP server for Claude Code, Cursor and other AI coding tools
269
+
270
+ ${bold('Usage')}
271
+ npx launch-doctor mcp Your AI tool starts this itself and talks to it over stdin and stdout
272
+
273
+ ${bold('Tools it offers')}
274
+ scan_project Check a project folder: grade, findings with fix prompts, and the checklist
275
+ scan_url Check a deployed site from the outside
276
+ list_checks List the categories and finding ids
277
+
278
+ ${bold('Set it up')}
279
+ Claude Code claude mcp add launch-doctor -- npx -y launch-doctor mcp
280
+ Cursor add to .cursor/mcp.json:
281
+ { "mcpServers": { "launch-doctor": { "command": "npx", "args": ["-y", "launch-doctor", "mcp"] } } }
282
+ `;
283
+ async function mcp(argv) {
284
+ if (argv.some((a) => a === '-h' || a === '--help')) {
285
+ process.stdout.write(MCP_HELP);
286
+ return;
287
+ }
288
+ if (argv.length)
289
+ fail(`mcp doesn't take options (got ${argv.join(' ')}). Run "launch-doctor mcp --help" for setup.`);
290
+ await runMcpServer();
291
+ }
197
292
  const SCAN_HELP = `
198
293
  ${bold('launch-doctor scan')} - check your deployed site from the outside
199
294
 
@@ -271,7 +366,7 @@ async function scan(argv) {
271
366
  if (writeFile && hasSomething) {
272
367
  const target = out ? resolve(process.cwd(), out) : resolve(process.cwd(), 'LAUNCH_FIXES_LIVE.md');
273
368
  try {
274
- writeFileSync(target, renderFixes(report));
369
+ writeRegularFile(target, renderFixes(report));
275
370
  const rel = relative(process.cwd(), target);
276
371
  fixFile = rel && !rel.startsWith('..') ? rel : target;
277
372
  }
@@ -290,6 +385,7 @@ async function scan(argv) {
290
385
  // the summary is optional
291
386
  }
292
387
  }
388
+ writeStepOutputs(report);
293
389
  if (json)
294
390
  process.stdout.write(`${JSON.stringify(report, null, 2)}
295
391
  `);
@@ -298,11 +394,55 @@ async function scan(argv) {
298
394
  if (ci && failingFindings(report, failOn).length > 0)
299
395
  process.exitCode = 1;
300
396
  }
397
+ /** On GitHub Actions, save the grade and counts as step outputs (steps.<id>.outputs.grade and so on). */
398
+ function writeStepOutputs(report) {
399
+ const file = process.env.GITHUB_OUTPUT;
400
+ if (!file)
401
+ return;
402
+ const lines = [
403
+ `grade=${report.grade}`,
404
+ `score=${report.score}`,
405
+ `critical=${report.counts.critical}`,
406
+ `warnings=${report.counts.warning}`,
407
+ ];
408
+ try {
409
+ appendFileSync(file, `${lines.join('\n')}\n`);
410
+ }
411
+ catch (err) {
412
+ process.stderr.write(`${dim(`Couldn't write the GitHub step outputs: ${err.message}`)}\n`);
413
+ }
414
+ }
415
+ /** --pr-comment: post the results to the pull request. Never fails the run; problems are explained on stderr. */
416
+ async function commentOnPr(report, root) {
417
+ const ctx = prContextFromEnv(root);
418
+ if (typeof ctx === 'string') {
419
+ process.stderr.write(`\n ${dim(`--pr-comment: skipped, ${ctx}.`)}\n`);
420
+ return;
421
+ }
422
+ try {
423
+ const r = await postPrFeedback(report, ctx);
424
+ const parts = [`summary comment ${r.summary}`, `${r.posted} new inline comment${r.posted === 1 ? '' : 's'}`];
425
+ if (r.alreadyPosted)
426
+ parts.push(`${r.alreadyPosted} already posted earlier`);
427
+ if (r.overLimit)
428
+ parts.push(`${r.overLimit} more listed in the summary only`);
429
+ process.stderr.write(`\n ${dim(`Pull request #${ctx.number}: ${parts.join(', ')}.`)}\n`);
430
+ if (r.inlineError)
431
+ process.stderr.write(` ${dim(r.inlineError)}\n`);
432
+ }
433
+ catch (err) {
434
+ process.stderr.write(`\n ${dim(explainGitHubError(err))}\n`);
435
+ }
436
+ }
301
437
  async function main() {
302
438
  if (process.argv[2] === 'init')
303
439
  return init(process.argv.slice(3));
304
440
  if (process.argv[2] === 'scan')
305
441
  return scan(process.argv.slice(3));
442
+ if (process.argv[2] === 'mcp')
443
+ return mcp(process.argv.slice(3));
444
+ if (process.argv[2] === 'hook')
445
+ return hook(process.argv.slice(3));
306
446
  const args = parseArgs(process.argv.slice(2));
307
447
  if (args.help) {
308
448
  process.stdout.write(HELP);
@@ -312,10 +452,15 @@ async function main() {
312
452
  process.stdout.write(`${version()}\n`);
313
453
  return;
314
454
  }
455
+ let stopDemoCleanup;
315
456
  if (args.demo) {
316
457
  if (args.path)
317
458
  fail('--demo scans a built-in sample app, so leave out the folder');
318
- args.path = createDemoProject();
459
+ // Ctrl+C mid-scan would otherwise skip the finally below and leave the folder in the temp directory.
460
+ let demoDir;
461
+ stopDemoCleanup = removeOnSignal(() => demoDir);
462
+ demoDir = createDemoProject();
463
+ args.path = demoDir;
319
464
  args.offline = true;
320
465
  if (!args.out)
321
466
  args.writeFile = false;
@@ -325,22 +470,57 @@ async function main() {
325
470
  const root = resolve(args.path ?? '.');
326
471
  if (!existsSync(root) || !statSync(root).isDirectory())
327
472
  fail(`Folder not found: ${root}`);
473
+ if (args.configFrom) {
474
+ if (args.updateBaseline)
475
+ fail('--config-from reads the baseline from git, so it cannot be used with --update-baseline');
476
+ try {
477
+ assertConfigRef(root, args.configFrom);
478
+ }
479
+ catch (err) {
480
+ fail(err.message);
481
+ }
482
+ }
483
+ let onlyFiles;
484
+ if (args.changeMode) {
485
+ const flag = `--${args.changeMode}`;
486
+ if (args.demo)
487
+ fail(`${flag} needs a real project folder, not --demo`);
488
+ for (const [on, name] of [
489
+ [args.updateBaseline, '--update-baseline'],
490
+ [args.prComment, '--pr-comment'],
491
+ [args.history, '--history'],
492
+ ]) {
493
+ if (on)
494
+ fail(`${flag} reports on some files only, so it can't be used with ${name}`);
495
+ }
496
+ const files = changedFiles(root, args.changeMode);
497
+ if (!files)
498
+ fail(`${flag} needs a folder inside a git repository`);
499
+ onlyFiles = files;
500
+ // A partial report must not overwrite LAUNCH_FIXES.md, which describes the whole project.
501
+ if (!args.out)
502
+ args.writeFile = false;
503
+ }
328
504
  let report;
329
505
  try {
330
506
  report = await runDoctor(root, {
507
+ onlyFiles,
331
508
  offline: args.offline,
332
509
  domain: args.domain,
333
510
  only: args.only,
334
511
  skip: args.skip,
335
512
  // When updating, start from scratch so every current finding is saved.
336
513
  baseline: args.baseline && !args.updateBaseline,
514
+ configFrom: args.configFrom,
337
515
  history: args.history ? { depth: args.historyDepth } : undefined,
338
516
  });
339
517
  }
340
518
  finally {
341
519
  // The demo project lives in a temp folder; always clean it up, even if the scan throws.
342
- if (args.demo)
520
+ if (args.demo) {
343
521
  rmSync(root, { recursive: true, force: true });
522
+ stopDemoCleanup?.();
523
+ }
344
524
  }
345
525
  if (report.filesScanned === 0) {
346
526
  fail(`No project files found in ${root}. Run this inside your app's folder.`);
@@ -348,7 +528,13 @@ async function main() {
348
528
  if (args.updateBaseline) {
349
529
  if (args.demo)
350
530
  fail('--update-baseline needs a real project folder, not --demo');
351
- const saved = writeBaseline(root, report);
531
+ let saved = 0;
532
+ try {
533
+ saved = writeBaseline(root, report);
534
+ }
535
+ catch (err) {
536
+ fail(`Couldn't write ${BASELINE_FILE}: ${err.message}`);
537
+ }
352
538
  applyBaseline(report, loadBaseline(root) ?? new Set());
353
539
  const msg = `Saved ${saved} finding${saved === 1 ? '' : 's'} to ${BASELINE_FILE}. Future runs (and --ci) only report new problems.`;
354
540
  (args.json ? process.stderr : process.stdout).write(`\n ${dim(msg)}\n`);
@@ -363,7 +549,7 @@ async function main() {
363
549
  // Rewrite an existing file even when everything passes, so old problems don't linger in it.
364
550
  if (args.writeFile && (hasSomething || existsSync(target))) {
365
551
  try {
366
- writeFileSync(target, renderFixes(report));
552
+ writeRegularFile(target, renderFixes(report));
367
553
  const rel = relative(process.cwd(), target);
368
554
  fixFile = rel && !rel.startsWith('..') ? rel : target;
369
555
  }
@@ -375,7 +561,7 @@ async function main() {
375
561
  const sarifPath = isAbsolute(args.sarif) ? args.sarif : resolve(process.cwd(), args.sarif);
376
562
  const fallbackUri = ['package.json', 'pyproject.toml', 'requirements.txt', 'README.md'].find((f) => existsSync(join(root, f)));
377
563
  try {
378
- writeFileSync(sarifPath, renderSarif(report, { fallbackUri }));
564
+ writeRegularFile(sarifPath, renderSarif(report, { fallbackUri }));
379
565
  }
380
566
  catch (err) {
381
567
  fail(`Couldn't write ${sarifPath}: ${err.message}`);
@@ -391,6 +577,9 @@ async function main() {
391
577
  process.stderr.write(`${dim(`Couldn't write the GitHub step summary: ${err.message}`)}\n`);
392
578
  }
393
579
  }
580
+ writeStepOutputs(report);
581
+ if (args.prComment)
582
+ await commentOnPr(report, root);
394
583
  if (args.json)
395
584
  process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
396
585
  else
@@ -1,2 +1,15 @@
1
+ /**
2
+ * Remove demo folders that killed runs left in the temp folder. Only folders named
3
+ * launch-doctor-demo-* that are over an hour old are touched, so a demo running in
4
+ * another terminal right now is left alone. Returns how many were removed.
5
+ */
6
+ export declare function sweepStaleDemos(now?: number, dir?: string): number;
7
+ /**
8
+ * Delete the demo folder if the run is stopped with Ctrl+C (SIGINT), SIGTERM or SIGHUP.
9
+ * Register it before creating the folder: signal handlers run between JavaScript tasks,
10
+ * so the folder name is always known by the time one runs.
11
+ * Returns a function that removes the handlers again once the run has cleaned up normally.
12
+ */
13
+ export declare function removeOnSignal(getDir: () => string | undefined): () => void;
1
14
  /** Writes a small "weekend project" with the classic launch mistakes and returns its folder. */
2
15
  export declare function createDemoProject(): string;