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
package/dist/src/live.js CHANGED
@@ -1,6 +1,8 @@
1
1
  import { emptyOutput, notApplicable } from './checks/common.js';
2
2
  import { matchKeys } from './checks/secrets.js';
3
3
  import { overall, scoreCategory, toGrade } from './grade.js';
4
+ import { checkHost, defaultLookup } from './net-guard.js';
5
+ import { sanitizeReport } from './sanitize.js';
4
6
  import { decodeJwtPayload, mask, plural } from './util.js';
5
7
  import { version } from './version.js';
6
8
  /** Ids of every finding a live scan can produce (for docs and tests). */
@@ -19,9 +21,11 @@ export const LIVE_IDS = [
19
21
  'live-missing-csp',
20
22
  'live-missing-basic-headers',
21
23
  ];
24
+ /** Redirects followed for one request. */
25
+ const MAX_REDIRECTS = 5;
22
26
  const MAX_SCRIPTS = 20;
23
27
  const MAX_TABLES = 25;
24
- const USER_AGENT = `launch-doctor/${version()} (+https://github.com/SHARAJ379/launch-doctor)`;
28
+ const USER_AGENT = `launch-doctor/${version()} (+https://github.com/SHARAJ379/Launch-Doctor)`;
25
29
  /** "myapp.com" or "https://myapp.com/x" -> a URL object. Throws a friendly error for anything else. */
26
30
  export function parseTarget(input) {
27
31
  const text = input.trim();
@@ -45,29 +49,60 @@ function isLocal(url) {
45
49
  class Fetcher {
46
50
  opts;
47
51
  requests = 0;
52
+ /** Requests not sent because they would have reached a private or local address. */
53
+ blocked = [];
48
54
  constructor(opts) {
49
55
  this.opts = opts;
50
56
  }
51
- /** One GET. Returns null when the site can't be reached. Never throws. */
57
+ /**
58
+ * One GET. Returns null when the site can't be reached. Never throws. Redirects are followed here, one hop at a
59
+ * time, so every address is checked before anything is sent to it.
60
+ */
52
61
  async get(url, init = {}) {
53
- this.requests++;
54
- try {
55
- const res = await this.opts.fetch(url, {
56
- method: 'GET',
57
- redirect: init.follow === false ? 'manual' : 'follow',
58
- signal: AbortSignal.timeout(this.opts.timeoutMs),
59
- headers: { 'user-agent': USER_AGENT, accept: '*/*', ...init.headers },
60
- });
61
- return {
62
- url: res.url || url,
63
- status: res.status,
64
- headers: res.headers,
65
- body: await readCapped(res, this.opts.maxBytes),
66
- };
67
- }
68
- catch {
69
- return null;
62
+ let current = url;
63
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
64
+ let parsed;
65
+ try {
66
+ parsed = new URL(current);
67
+ }
68
+ catch {
69
+ return null;
70
+ }
71
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')
72
+ return null;
73
+ if (!this.opts.allowPrivate) {
74
+ const host = await checkHost(parsed, this.opts.lookup);
75
+ if (host.kind === 'private')
76
+ this.blocked.push(host.reason);
77
+ if (host.kind !== 'public')
78
+ return null;
79
+ }
80
+ this.requests++;
81
+ try {
82
+ const res = await this.opts.fetch(current, {
83
+ method: 'GET',
84
+ redirect: 'manual',
85
+ signal: AbortSignal.timeout(this.opts.timeoutMs),
86
+ headers: { 'user-agent': USER_AGENT, accept: '*/*', ...init.headers },
87
+ });
88
+ const location = res.headers.get('location');
89
+ if (init.follow !== false && res.status >= 300 && res.status < 400 && location) {
90
+ await res.body?.cancel().catch(() => { });
91
+ current = new URL(location, current).href;
92
+ continue;
93
+ }
94
+ return {
95
+ url: current,
96
+ status: res.status,
97
+ headers: res.headers,
98
+ body: await readCapped(res, this.opts.maxBytes),
99
+ };
100
+ }
101
+ catch {
102
+ return null;
103
+ }
70
104
  }
105
+ return null; // too many redirects
71
106
  }
72
107
  }
73
108
  async function readCapped(res, maxBytes) {
@@ -201,7 +236,7 @@ const PROBES = [
201
236
  path: '/.git/config',
202
237
  id: 'live-exposed-git',
203
238
  what: 'your git settings (.git/config)',
204
- valid: (b) => /^\s*\[core\]/m.test(b),
239
+ valid: (b) => /^[ \t]*\[core\]/m.test(b),
205
240
  },
206
241
  {
207
242
  path: '/.git/HEAD',
@@ -455,13 +490,24 @@ function capitalize(s) {
455
490
  // ---------------------------------------------------------------------------
456
491
  export async function runLiveScan(input, options = {}) {
457
492
  const target = parseTarget(input);
493
+ const lookup = options.lookup ?? defaultLookup;
494
+ const targetHost = await checkHost(target, lookup);
495
+ if (targetHost.kind === 'private' && options.allowPrivateTarget === false) {
496
+ throw new Error(`Only public sites can be scanned here: ${targetHost.reason}.`);
497
+ }
458
498
  const fetcher = new Fetcher({
459
499
  timeoutMs: options.timeoutMs ?? 10_000,
460
500
  maxBytes: options.maxBytes ?? 3_000_000,
461
501
  fetch: options.fetch ?? fetch,
502
+ lookup,
503
+ // A scan you start at a private address (your own dev server) stays usable; one that starts on a public site
504
+ // never reaches a private address.
505
+ allowPrivate: targetHost.kind === 'private',
462
506
  });
463
507
  const home = await fetcher.get(target.href);
464
508
  if (!home) {
509
+ if (fetcher.blocked.length)
510
+ throw new Error(`${target.origin} redirected to ${fetcher.blocked[0]}, so it wasn't scanned.`);
465
511
  throw new Error(`Couldn't reach ${target.origin}. Check the address and that the site is online.`);
466
512
  }
467
513
  if (home.status >= 500)
@@ -491,7 +537,12 @@ export async function runLiveScan(input, options = {}) {
491
537
  grade: score === null ? null : toGrade(score),
492
538
  });
493
539
  }
494
- return {
540
+ if (fetcher.blocked.length) {
541
+ const hosts = [...new Set(fetcher.blocked.map((b) => b.split(' ')[0]))].slice(0, 3).join(', ');
542
+ categories[0].passed.push(`Skipped ${plural(fetcher.blocked.length, 'request')} to private or local network addresses (${hosts}) that this public site pointed to`);
543
+ }
544
+ // Text from the site (table names, paths) can hold terminal escape sequences; none reach any output.
545
+ return sanitizeReport({
495
546
  tool: 'launch-doctor',
496
547
  version: version(),
497
548
  mode: 'live',
@@ -505,5 +556,5 @@ export async function runLiveScan(input, options = {}) {
505
556
  ...overall(categories),
506
557
  categories,
507
558
  generatedAt: new Date().toISOString(),
508
- };
559
+ });
509
560
  }
@@ -0,0 +1,140 @@
1
+ import type { Readable, Writable } from 'node:stream';
2
+ import type { Report } from './types.js';
3
+ /**
4
+ * A Model Context Protocol server over stdio, so AI coding tools (Claude Code, Cursor, ...)
5
+ * can run Launch Doctor themselves. One JSON-RPC 2.0 message per line on stdin and stdout.
6
+ * Nothing else may be written to stdout: it is the protocol channel.
7
+ */
8
+ /** Protocol versions this server speaks, newest first. */
9
+ export declare const PROTOCOL_VERSIONS: string[];
10
+ interface ToolResult {
11
+ content: {
12
+ type: 'text';
13
+ text: string;
14
+ }[];
15
+ structuredContent?: Record<string, unknown>;
16
+ isError?: boolean;
17
+ }
18
+ /** The tools this server offers, with JSON Schemas for their arguments. */
19
+ export declare function mcpTools(): ({
20
+ name: string;
21
+ title: string;
22
+ description: string;
23
+ inputSchema: {
24
+ type: string;
25
+ properties: {
26
+ path: {
27
+ type: string;
28
+ description: string;
29
+ };
30
+ only: {
31
+ type: string;
32
+ items: {
33
+ type: string;
34
+ enum: string[];
35
+ };
36
+ description: string;
37
+ };
38
+ skip: {
39
+ type: string;
40
+ items: {
41
+ type: string;
42
+ enum: string[];
43
+ };
44
+ description: string;
45
+ };
46
+ offline: {
47
+ type: string;
48
+ description: string;
49
+ };
50
+ domain: {
51
+ type: string;
52
+ description: string;
53
+ };
54
+ history: {
55
+ type: string;
56
+ description: string;
57
+ };
58
+ includeBaseline: {
59
+ type: string;
60
+ description: string;
61
+ };
62
+ url?: undefined;
63
+ skipDatabase?: undefined;
64
+ };
65
+ additionalProperties: boolean;
66
+ required?: undefined;
67
+ };
68
+ annotations: {
69
+ readOnlyHint: boolean;
70
+ idempotentHint: boolean;
71
+ openWorldHint: boolean;
72
+ };
73
+ } | {
74
+ name: string;
75
+ title: string;
76
+ description: string;
77
+ inputSchema: {
78
+ type: string;
79
+ properties: {
80
+ path?: undefined;
81
+ only?: undefined;
82
+ skip?: undefined;
83
+ offline?: undefined;
84
+ domain?: undefined;
85
+ history?: undefined;
86
+ includeBaseline?: undefined;
87
+ url: {
88
+ type: string;
89
+ description: string;
90
+ };
91
+ skipDatabase: {
92
+ type: string;
93
+ description: string;
94
+ };
95
+ };
96
+ required: string[];
97
+ additionalProperties: boolean;
98
+ };
99
+ annotations: {
100
+ readOnlyHint: boolean;
101
+ idempotentHint: boolean;
102
+ openWorldHint: boolean;
103
+ };
104
+ } | {
105
+ name: string;
106
+ title: string;
107
+ description: string;
108
+ inputSchema: {
109
+ required?: undefined;
110
+ type: string;
111
+ properties: {
112
+ path?: undefined;
113
+ only?: undefined;
114
+ skip?: undefined;
115
+ offline?: undefined;
116
+ domain?: undefined;
117
+ history?: undefined;
118
+ includeBaseline?: undefined;
119
+ url?: undefined;
120
+ skipDatabase?: undefined;
121
+ };
122
+ additionalProperties: boolean;
123
+ };
124
+ annotations: {
125
+ readOnlyHint: boolean;
126
+ idempotentHint: boolean;
127
+ openWorldHint: boolean;
128
+ };
129
+ })[];
130
+ /** Plain-text summary of a report, written for an AI assistant that will act on it. */
131
+ export declare function reportText(report: Report, includeBaseline?: boolean): string;
132
+ /** The same report as data, for clients that read structured tool output. */
133
+ export declare function reportData(report: Report, includeBaseline?: boolean): Record<string, unknown>;
134
+ /** Run one tool. Unknown tool names are a protocol error; bad arguments are a tool error the model can fix. */
135
+ export declare function callTool(name: unknown, args: unknown, cwd?: string): Promise<ToolResult>;
136
+ /** Handle one parsed message (or a batch). Returns what to send back, or null for nothing. */
137
+ export declare function handleMessage(msg: unknown, cwd?: string): Promise<object | null>;
138
+ /** Serve MCP on stdin/stdout until stdin closes. */
139
+ export declare function runMcpServer(input?: Readable, output?: Writable, cwd?: string): Promise<void>;
140
+ export {};
@@ -0,0 +1,386 @@
1
+ import { existsSync, statSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
+ import { createInterface } from 'node:readline';
4
+ import { shortWhere } from './checks/common.js';
5
+ import { DEFAULT_HISTORY_DEPTH } from './history.js';
6
+ import { CHECKS, runDoctor } from './index.js';
7
+ import { runLiveScan } from './live.js';
8
+ import { BYTE_LIMIT_NOTE, nestedReposNote } from './report.js';
9
+ import { plural } from './util.js';
10
+ import { version } from './version.js';
11
+ /**
12
+ * A Model Context Protocol server over stdio, so AI coding tools (Claude Code, Cursor, ...)
13
+ * can run Launch Doctor themselves. One JSON-RPC 2.0 message per line on stdin and stdout.
14
+ * Nothing else may be written to stdout: it is the protocol channel.
15
+ */
16
+ /** Protocol versions this server speaks, newest first. */
17
+ export const PROTOCOL_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
18
+ /** Offered when a client asks for a version this server doesn't know. */
19
+ const DEFAULT_PROTOCOL = '2025-06-18';
20
+ /** Findings and checklist items listed per section in a tool result. */
21
+ const MAX_LISTED = 50;
22
+ class RpcError extends Error {
23
+ code;
24
+ constructor(code, message) {
25
+ super(message);
26
+ this.code = code;
27
+ }
28
+ }
29
+ const UNKNOWN_METHOD = Symbol('unknown method');
30
+ /** The tools this server offers, with JSON Schemas for their arguments. */
31
+ export function mcpTools() {
32
+ const categories = CHECKS.map((c) => c.id);
33
+ return [
34
+ {
35
+ name: 'scan_project',
36
+ title: 'Check a project before launch',
37
+ description: 'Runs Launch Doctor on a project folder and grades it A to F on secrets and API keys, database safety, payments, AI and API costs, email delivery, error tracking, legal pages and first impressions. ' +
38
+ 'Returns every problem with its file and line, why it matters, and a fix prompt that describes the change to make, plus a checklist of things to verify outside the code. It only reads files.',
39
+ inputSchema: {
40
+ type: 'object',
41
+ properties: {
42
+ path: {
43
+ type: 'string',
44
+ description: 'Project folder to check: absolute, or relative to the folder the server started in (the default).',
45
+ },
46
+ only: {
47
+ type: 'array',
48
+ items: { type: 'string', enum: categories },
49
+ description: 'Check only these categories.',
50
+ },
51
+ skip: {
52
+ type: 'array',
53
+ items: { type: 'string', enum: categories },
54
+ description: 'Leave out these categories.',
55
+ },
56
+ offline: {
57
+ type: 'boolean',
58
+ description: 'Skip the email DNS lookups (SPF, DKIM, DMARC). Default false.',
59
+ },
60
+ domain: { type: 'string', description: "Domain the app sends email from, if the code doesn't show it." },
61
+ history: {
62
+ type: 'boolean',
63
+ description: 'Also look for API keys that are still in git history. Slower. Default false.',
64
+ },
65
+ includeBaseline: {
66
+ type: 'boolean',
67
+ description: 'Also list findings accepted in .launchdoctor-baseline.json. Default false.',
68
+ },
69
+ },
70
+ additionalProperties: false,
71
+ },
72
+ annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: true },
73
+ },
74
+ {
75
+ name: 'scan_url',
76
+ title: 'Check a deployed site',
77
+ description: 'Checks a live website from the outside, the way an attacker would: downloadable .env, .git and backup files, public source maps, API keys in the JavaScript, Supabase tables readable with the public key, and HTTPS and security headers. ' +
78
+ 'Sends ordinary GET requests only.',
79
+ inputSchema: {
80
+ type: 'object',
81
+ properties: {
82
+ url: { type: 'string', description: 'The site to check, for example https://myapp.com.' },
83
+ skipDatabase: {
84
+ type: 'boolean',
85
+ description: "Don't test Supabase tables with the public key found in the page. Default false.",
86
+ },
87
+ },
88
+ required: ['url'],
89
+ additionalProperties: false,
90
+ },
91
+ annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: true },
92
+ },
93
+ {
94
+ name: 'list_checks',
95
+ title: 'List the checks',
96
+ description: 'Lists the categories and every finding and checklist id, for the only and skip options and for .launchdoctorignore.',
97
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
98
+ annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
99
+ },
100
+ ];
101
+ }
102
+ // ---------- tool results ----------
103
+ function indent(text, by = ' ') {
104
+ return text
105
+ .split('\n')
106
+ .map((l) => (l ? by + l : l))
107
+ .join('\n');
108
+ }
109
+ function findingEntry(n, f) {
110
+ const where = f.location ? ` (${shortWhere(f.location)})` : '';
111
+ const known = f.baseline ? ' [in baseline]' : '';
112
+ return [
113
+ `${n}. ${f.title}${where} · id: ${f.id}${known}`,
114
+ indent(`Why it matters: ${f.why}`),
115
+ indent(`Fix prompt:\n${indent(f.fixPrompt, ' ')}`),
116
+ ].join('\n');
117
+ }
118
+ function listSection(title, items, entry) {
119
+ if (!items.length)
120
+ return [];
121
+ const out = ['', `${title} (${items.length})`, ''];
122
+ for (const [i, item] of items.slice(0, MAX_LISTED).entries())
123
+ out.push(entry(item, i + 1));
124
+ if (items.length > MAX_LISTED)
125
+ out.push(`...and ${items.length - MAX_LISTED} more.`);
126
+ return out;
127
+ }
128
+ /** Plain-text summary of a report, written for an AI assistant that will act on it. */
129
+ export function reportText(report, includeBaseline = false) {
130
+ const all = report.categories.flatMap((c) => c.findings);
131
+ const shown = includeBaseline ? all : all.filter((f) => !f.baseline);
132
+ const hiddenBaseline = all.length - shown.length;
133
+ const manual = report.categories.flatMap((c) => c.manual);
134
+ const unit = report.mode === 'live' ? 'request' : 'file';
135
+ const lines = [
136
+ `Launch Doctor ${report.version}: grade ${report.grade} (${report.score}/100) for ${report.projectName}. ${plural(report.filesScanned, unit)} checked.`,
137
+ report.verdict,
138
+ ];
139
+ if (report.nestedRepos?.length)
140
+ lines.push(nestedReposNote(report.nestedRepos));
141
+ if (report.truncated)
142
+ lines.push('Very large project: only the first 20,000 files were checked.');
143
+ if (report.byteLimitReached)
144
+ lines.push(BYTE_LIMIT_NOTE);
145
+ lines.push(...listSection('Critical', shown.filter((f) => f.severity === 'critical'), (f, n) => findingEntry(n, f)), ...listSection('Warnings', shown.filter((f) => f.severity === 'warning'), (f, n) => findingEntry(n, f)), ...listSection('Check by hand, outside the code', manual, (m, n) => `${n}. ${m.title} · id: ${m.id}\n${indent(m.how)}`));
146
+ if (!shown.length) {
147
+ lines.push('', hiddenBaseline
148
+ ? `No new problems found. The grade still counts the ${plural(hiddenBaseline, 'known finding')} accepted in .launchdoctor-baseline.json.`
149
+ : 'No problems found.');
150
+ }
151
+ lines.push('', `Scorecard: ${report.categories.map((c) => `${c.name} ${c.skipped ? 'skipped' : c.applicable ? (c.grade ?? '-') : 'not used'}`).join(' · ')}`);
152
+ if (hiddenBaseline) {
153
+ lines.push(`${plural(hiddenBaseline, 'known finding')} in .launchdoctor-baseline.json not listed (set includeBaseline to see them).`);
154
+ }
155
+ if (report.ignored) {
156
+ lines.push(`${plural(report.ignored, 'item')} silenced by .launchdoctorignore or launch-doctor-ignore comments.`);
157
+ }
158
+ return lines.join('\n');
159
+ }
160
+ /** The same report as data, for clients that read structured tool output. */
161
+ export function reportData(report, includeBaseline = false) {
162
+ return {
163
+ grade: report.grade,
164
+ score: report.score,
165
+ verdict: report.verdict,
166
+ projectName: report.projectName,
167
+ counts: report.counts,
168
+ ...(report.nestedRepos?.length ? { nestedRepos: report.nestedRepos } : {}),
169
+ categories: report.categories.map((c) => ({
170
+ id: c.id,
171
+ name: c.name,
172
+ grade: c.grade,
173
+ applicable: c.applicable,
174
+ skipped: Boolean(c.skipped),
175
+ })),
176
+ findings: report.categories.flatMap((c) => c.findings
177
+ .filter((f) => includeBaseline || !f.baseline)
178
+ .map((f) => ({
179
+ id: f.id,
180
+ category: c.id,
181
+ severity: f.severity,
182
+ title: f.title,
183
+ file: f.location?.file,
184
+ line: f.location?.line,
185
+ why: f.why,
186
+ fixPrompt: f.fixPrompt,
187
+ baseline: Boolean(f.baseline),
188
+ }))),
189
+ manual: report.categories.flatMap((c) => c.manual.map((m) => ({ id: m.id, category: c.id, title: m.title, how: m.how }))),
190
+ };
191
+ }
192
+ function toolError(message) {
193
+ return { content: [{ type: 'text', text: message }], isError: true };
194
+ }
195
+ function reportResult(report, includeBaseline) {
196
+ return {
197
+ content: [{ type: 'text', text: reportText(report, includeBaseline) }],
198
+ structuredContent: reportData(report, includeBaseline),
199
+ };
200
+ }
201
+ const isStringArray = (v) => Array.isArray(v) && v.every((x) => typeof x === 'string');
202
+ /** Checks the arguments by hand (no schema library), so a bad call gets a message the model can act on. */
203
+ function badArgs(args, shape) {
204
+ for (const key of Object.keys(args))
205
+ if (!(key in shape))
206
+ return `Unknown argument "${key}".`;
207
+ for (const [key, type] of Object.entries(shape)) {
208
+ const v = args[key];
209
+ if (v === undefined)
210
+ continue;
211
+ const ok = type === 'string[]' ? isStringArray(v) : typeof v === type;
212
+ if (!ok)
213
+ return `"${key}" must be ${type === 'string[]' ? 'a list of strings' : `a ${type}`}.`;
214
+ }
215
+ return null;
216
+ }
217
+ async function scanProject(args, cwd) {
218
+ const problem = badArgs(args, {
219
+ path: 'string',
220
+ only: 'string[]',
221
+ skip: 'string[]',
222
+ offline: 'boolean',
223
+ domain: 'string',
224
+ history: 'boolean',
225
+ includeBaseline: 'boolean',
226
+ });
227
+ if (problem)
228
+ return toolError(problem);
229
+ const root = resolve(cwd, args.path ?? '.');
230
+ if (!existsSync(root) || !statSync(root).isDirectory())
231
+ return toolError(`Folder not found: ${root}`);
232
+ const domain = args.domain
233
+ ?.trim()
234
+ .toLowerCase()
235
+ .replace(/^https?:\/\//, '')
236
+ .replace(/[/?#].*$/, '');
237
+ let report;
238
+ try {
239
+ report = await runDoctor(root, {
240
+ offline: args.offline === true,
241
+ domain: domain || undefined,
242
+ only: args.only,
243
+ skip: args.skip,
244
+ history: args.history === true ? { depth: DEFAULT_HISTORY_DEPTH } : undefined,
245
+ });
246
+ }
247
+ catch (err) {
248
+ return toolError(err.message);
249
+ }
250
+ if (report.filesScanned === 0)
251
+ return toolError(`No project files found in ${root}.`);
252
+ return reportResult(report, args.includeBaseline === true);
253
+ }
254
+ async function scanUrl(args) {
255
+ const problem = badArgs(args, { url: 'string', skipDatabase: 'boolean' });
256
+ if (problem)
257
+ return toolError(problem);
258
+ if (typeof args.url !== 'string' || !args.url.trim())
259
+ return toolError('"url" is required, for example https://myapp.com.');
260
+ try {
261
+ // An AI tool decides what to scan here, and a prompt injection could aim it at your network, so only public
262
+ // sites are allowed. The CLI (where you type the address yourself) also accepts your own dev server.
263
+ const report = await runLiveScan(args.url, { skipDatabase: args.skipDatabase === true, allowPrivateTarget: false });
264
+ return reportResult(report, false);
265
+ }
266
+ catch (err) {
267
+ return toolError(err.message);
268
+ }
269
+ }
270
+ function listChecks() {
271
+ const categories = CHECKS.map((c) => ({ id: c.id, name: c.name, ids: [...c.ids] }));
272
+ const text = categories.map((c) => `${c.id} (${c.name}): ${c.ids.join(', ')}`).join('\n');
273
+ return { content: [{ type: 'text', text }], structuredContent: { categories } };
274
+ }
275
+ /** Run one tool. Unknown tool names are a protocol error; bad arguments are a tool error the model can fix. */
276
+ export async function callTool(name, args, cwd = process.cwd()) {
277
+ const a = args === undefined || args === null ? {} : args;
278
+ if (typeof a !== 'object' || Array.isArray(a))
279
+ return toolError('Arguments must be an object.');
280
+ const params = a;
281
+ if (name === 'scan_project')
282
+ return scanProject(params, cwd);
283
+ if (name === 'scan_url')
284
+ return scanUrl(params);
285
+ if (name === 'list_checks')
286
+ return listChecks();
287
+ throw new RpcError(-32602, `Unknown tool: ${String(name)}`);
288
+ }
289
+ // ---------- JSON-RPC ----------
290
+ function negotiate(params) {
291
+ const asked = params.protocolVersion;
292
+ const protocolVersion = typeof asked === 'string' && PROTOCOL_VERSIONS.includes(asked) ? asked : DEFAULT_PROTOCOL;
293
+ return {
294
+ protocolVersion,
295
+ capabilities: { tools: { listChanged: false } },
296
+ serverInfo: { name: 'launch-doctor', title: 'Launch Doctor', version: version() },
297
+ instructions: 'Use scan_project before a launch or a big release to find leaked keys, open databases, unverified payment webhooks, unprotected AI endpoints and missing legal pages. ' +
298
+ 'Each finding has a fix prompt: apply fixes one at a time, critical first, then run scan_project again. Use scan_url on the deployed site after deploying.',
299
+ };
300
+ }
301
+ async function dispatch(method, params, cwd) {
302
+ switch (method) {
303
+ case 'initialize':
304
+ return negotiate(params);
305
+ case 'ping':
306
+ return {};
307
+ case 'tools/list':
308
+ return { tools: mcpTools() };
309
+ case 'tools/call':
310
+ return callTool(params.name, params.arguments, cwd);
311
+ default:
312
+ return UNKNOWN_METHOD;
313
+ }
314
+ }
315
+ const rpcError = (id, code, message) => ({
316
+ jsonrpc: '2.0',
317
+ id,
318
+ error: { code, message },
319
+ });
320
+ async function handleOne(msg, cwd) {
321
+ if (!msg || typeof msg !== 'object' || Array.isArray(msg))
322
+ return rpcError(null, -32600, 'Invalid Request');
323
+ const { id, method, params } = msg;
324
+ // A message without an id is a notification (like notifications/initialized): never answered.
325
+ const notification = id === undefined;
326
+ const replyId = id ?? null;
327
+ if (typeof method !== 'string')
328
+ return notification ? null : rpcError(replyId, -32600, 'Invalid Request');
329
+ if (params !== undefined && (typeof params !== 'object' || params === null)) {
330
+ return notification ? null : rpcError(replyId, -32602, 'params must be an object');
331
+ }
332
+ try {
333
+ const result = await dispatch(method, (params ?? {}), cwd);
334
+ if (notification)
335
+ return null;
336
+ if (result === UNKNOWN_METHOD)
337
+ return rpcError(replyId, -32601, `Method not found: ${method}`);
338
+ return { jsonrpc: '2.0', id: replyId, result };
339
+ }
340
+ catch (err) {
341
+ if (notification)
342
+ return null;
343
+ if (err instanceof RpcError)
344
+ return rpcError(replyId, err.code, err.message);
345
+ return rpcError(replyId, -32603, `Internal error: ${err.message}`);
346
+ }
347
+ }
348
+ /** Handle one parsed message (or a batch). Returns what to send back, or null for nothing. */
349
+ export async function handleMessage(msg, cwd = process.cwd()) {
350
+ if (Array.isArray(msg)) {
351
+ if (!msg.length)
352
+ return rpcError(null, -32600, 'Invalid Request');
353
+ const replies = (await Promise.all(msg.map((m) => handleOne(m, cwd)))).filter((r) => r !== null);
354
+ return replies.length ? replies : null;
355
+ }
356
+ return handleOne(msg, cwd);
357
+ }
358
+ /** Serve MCP on stdin/stdout until stdin closes. */
359
+ export function runMcpServer(input = process.stdin, output = process.stdout, cwd = process.cwd()) {
360
+ const send = (msg) => output.write(`${JSON.stringify(msg)}\n`);
361
+ const lines = createInterface({ input, crlfDelay: Number.POSITIVE_INFINITY });
362
+ const pending = new Set();
363
+ lines.on('line', (line) => {
364
+ if (!line.trim())
365
+ return;
366
+ let msg;
367
+ try {
368
+ msg = JSON.parse(line);
369
+ }
370
+ catch {
371
+ send(rpcError(null, -32700, 'Parse error'));
372
+ return;
373
+ }
374
+ const job = handleMessage(msg, cwd).then((reply) => {
375
+ if (reply)
376
+ send(reply);
377
+ });
378
+ pending.add(job);
379
+ void job.finally(() => pending.delete(job));
380
+ });
381
+ return new Promise((done) => {
382
+ lines.on('close', () => {
383
+ void Promise.allSettled([...pending]).then(() => done());
384
+ });
385
+ });
386
+ }