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.
- package/CHANGELOG.md +105 -4
- package/LICENSE +1 -0
- package/README.md +239 -39
- package/dist/src/access.d.ts +52 -0
- package/dist/src/access.js +482 -0
- package/dist/src/baseline.d.ts +6 -3
- package/dist/src/baseline.js +15 -8
- package/dist/src/changed.d.ts +12 -0
- package/dist/src/changed.js +34 -0
- package/dist/src/checks/access.d.ts +7 -0
- package/dist/src/checks/access.js +868 -0
- package/dist/src/checks/costs.d.ts +8 -0
- package/dist/src/checks/costs.js +54 -11
- package/dist/src/checks/database.js +201 -6
- package/dist/src/checks/first-impressions.js +247 -117
- package/dist/src/checks/legal.js +29 -13
- package/dist/src/checks/monitoring.js +47 -15
- package/dist/src/checks/payments.js +141 -6
- package/dist/src/checks/secrets.d.ts +8 -0
- package/dist/src/checks/secrets.js +185 -16
- package/dist/src/checks/supabase-storage.d.ts +31 -0
- package/dist/src/checks/supabase-storage.js +216 -0
- package/dist/src/cli.js +201 -12
- package/dist/src/demo.d.ts +13 -0
- package/dist/src/demo.js +59 -2
- package/dist/src/detect.d.ts +1 -1
- package/dist/src/detect.js +5 -2
- package/dist/src/fixes.js +10 -7
- package/dist/src/git.d.ts +25 -0
- package/dist/src/git.js +121 -0
- package/dist/src/github.d.ts +90 -0
- package/dist/src/github.js +330 -0
- package/dist/src/history.js +17 -3
- package/dist/src/hook.d.ts +13 -0
- package/dist/src/hook.js +96 -0
- package/dist/src/hooks-setup.d.ts +24 -0
- package/dist/src/hooks-setup.js +187 -0
- package/dist/src/ignore.d.ts +36 -0
- package/dist/src/ignore.js +164 -0
- package/dist/src/index.d.ts +1 -0
- package/dist/src/index.js +30 -3
- package/dist/src/init.d.ts +1 -1
- package/dist/src/init.js +2 -2
- package/dist/src/live.d.ts +9 -0
- package/dist/src/live.js +73 -22
- package/dist/src/mcp.d.ts +140 -0
- package/dist/src/mcp.js +386 -0
- package/dist/src/net-guard.d.ts +34 -0
- package/dist/src/net-guard.js +144 -0
- package/dist/src/project.d.ts +42 -5
- package/dist/src/project.js +237 -107
- package/dist/src/report.d.ts +4 -0
- package/dist/src/report.js +23 -1
- package/dist/src/routes.d.ts +10 -0
- package/dist/src/routes.js +21 -4
- package/dist/src/safe-fs.d.ts +19 -0
- package/dist/src/safe-fs.js +77 -0
- package/dist/src/sanitize.d.ts +17 -0
- package/dist/src/sanitize.js +90 -0
- package/dist/src/sarif.js +1 -1
- package/dist/src/summary.d.ts +7 -0
- package/dist/src/summary.js +26 -17
- package/dist/src/types.d.ts +26 -0
- package/dist/src/util.d.ts +2 -0
- package/dist/src/util.js +2 -0
- package/package.json +9 -5
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { isAbsolute, relative } from 'node:path';
|
|
3
|
+
import { htmlCommentSafe, md, mdCode } from './sanitize.js';
|
|
4
|
+
import { categoryTable, escapeCell } from './summary.js';
|
|
5
|
+
/** Marks our one summary comment on a pull request, so later runs edit it instead of adding another. */
|
|
6
|
+
export const SUMMARY_MARKER = '<!-- launch-doctor:summary -->';
|
|
7
|
+
const FINDING_MARKER = /<!-- launch-doctor:finding (\S+) -->/;
|
|
8
|
+
/**
|
|
9
|
+
* A finding's key as written into its inline comment's hidden marker: a file path in it can't end the HTML comment
|
|
10
|
+
* ("-->"), and it has no spaces, so FINDING_MARKER reads it back whole (keys with spaces were reposted every run).
|
|
11
|
+
*/
|
|
12
|
+
function markerKey(key) {
|
|
13
|
+
return htmlCommentSafe(key).replace(/\s/g, '_');
|
|
14
|
+
}
|
|
15
|
+
/** At most this many inline comments per run, so a big pull request isn't buried. */
|
|
16
|
+
export const MAX_INLINE = 20;
|
|
17
|
+
/** At most this many findings per list in the summary comment. */
|
|
18
|
+
const MAX_LISTED = 50;
|
|
19
|
+
/**
|
|
20
|
+
* GitHub rejects a comment longer than 65,536 characters (and then no summary is posted at all). The summary comment
|
|
21
|
+
* is kept under this, with room to spare: lists get shorter until it fits.
|
|
22
|
+
*/
|
|
23
|
+
export const MAX_COMMENT_CHARS = 60_000;
|
|
24
|
+
/** A finding title longer than this is cut in lists (a title can hold a long name from a file). */
|
|
25
|
+
const MAX_TITLE_CHARS = 300;
|
|
26
|
+
/**
|
|
27
|
+
* Work out which pull request we're running for from the GitHub Actions environment.
|
|
28
|
+
* Returns a reason string instead when there's nothing to comment on.
|
|
29
|
+
*/
|
|
30
|
+
export function prContextFromEnv(root, env = process.env) {
|
|
31
|
+
if (env.GITHUB_ACTIONS !== 'true')
|
|
32
|
+
return 'not running on GitHub Actions';
|
|
33
|
+
const event = env.GITHUB_EVENT_NAME ?? '';
|
|
34
|
+
if (event !== 'pull_request' && event !== 'pull_request_target') {
|
|
35
|
+
return `this run was started by "${event || 'unknown'}", not by a pull request`;
|
|
36
|
+
}
|
|
37
|
+
const token = env.GITHUB_TOKEN || env.GH_TOKEN;
|
|
38
|
+
if (!token)
|
|
39
|
+
return 'GITHUB_TOKEN is not set (give the step the workflow token as a GITHUB_TOKEN environment variable)';
|
|
40
|
+
const repo = env.GITHUB_REPOSITORY;
|
|
41
|
+
if (!repo || !env.GITHUB_EVENT_PATH)
|
|
42
|
+
return 'GITHUB_REPOSITORY or GITHUB_EVENT_PATH is missing';
|
|
43
|
+
let payload;
|
|
44
|
+
try {
|
|
45
|
+
payload = JSON.parse(readFileSync(env.GITHUB_EVENT_PATH, 'utf8'));
|
|
46
|
+
}
|
|
47
|
+
catch (err) {
|
|
48
|
+
return `couldn't read the event file: ${err.message}`;
|
|
49
|
+
}
|
|
50
|
+
const number = payload.pull_request?.number;
|
|
51
|
+
const headSha = payload.pull_request?.head?.sha;
|
|
52
|
+
if (typeof number !== 'number' || typeof headSha !== 'string')
|
|
53
|
+
return 'the event has no pull request in it';
|
|
54
|
+
const workspace = env.GITHUB_WORKSPACE || process.cwd();
|
|
55
|
+
const rel = relative(workspace, root).replace(/\\/g, '/');
|
|
56
|
+
const prefix = rel === '' || rel.startsWith('..') || isAbsolute(rel) ? '' : rel;
|
|
57
|
+
return {
|
|
58
|
+
apiUrl: (env.GITHUB_API_URL || 'https://api.github.com').replace(/\/$/, ''),
|
|
59
|
+
serverUrl: (env.GITHUB_SERVER_URL || 'https://github.com').replace(/\/$/, ''),
|
|
60
|
+
repo,
|
|
61
|
+
number,
|
|
62
|
+
headSha,
|
|
63
|
+
token,
|
|
64
|
+
prefix,
|
|
65
|
+
...(env.GITHUB_RUN_ID ? { runId: env.GITHUB_RUN_ID } : {}),
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
/** Line numbers (in the new version of the file) that a unified diff patch adds. */
|
|
69
|
+
export function addedLines(patch) {
|
|
70
|
+
const out = new Set();
|
|
71
|
+
let line = 0;
|
|
72
|
+
for (const row of patch.split('\n')) {
|
|
73
|
+
const hunk = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(row);
|
|
74
|
+
if (hunk) {
|
|
75
|
+
line = Number(hunk[1]);
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
if (line === 0 || row.startsWith('-') || row.startsWith('\\'))
|
|
79
|
+
continue;
|
|
80
|
+
if (row.startsWith('+'))
|
|
81
|
+
out.add(line);
|
|
82
|
+
line++;
|
|
83
|
+
}
|
|
84
|
+
return out;
|
|
85
|
+
}
|
|
86
|
+
export function changedFiles(files) {
|
|
87
|
+
const out = new Map();
|
|
88
|
+
for (const f of files) {
|
|
89
|
+
if (f.status === 'removed')
|
|
90
|
+
continue;
|
|
91
|
+
if (f.patch !== undefined)
|
|
92
|
+
out.set(f.filename, addedLines(f.patch));
|
|
93
|
+
else if (f.status === 'added')
|
|
94
|
+
out.set(f.filename, 'all');
|
|
95
|
+
else
|
|
96
|
+
out.set(f.filename, new Set());
|
|
97
|
+
}
|
|
98
|
+
return out;
|
|
99
|
+
}
|
|
100
|
+
export function repoPath(prefix, file) {
|
|
101
|
+
return prefix ? `${prefix}/${file}` : file;
|
|
102
|
+
}
|
|
103
|
+
/** Split the report's findings into "added by this pull request" and "already there". */
|
|
104
|
+
export function placeFindings(report, changed, prefix) {
|
|
105
|
+
const placement = { inPr: [], elsewhere: [], baseline: 0 };
|
|
106
|
+
const order = (f) => (f.severity === 'critical' ? 0 : 1);
|
|
107
|
+
const all = report.categories.flatMap((c) => c.findings).sort((a, b) => order(a) - order(b));
|
|
108
|
+
for (const f of all) {
|
|
109
|
+
if (f.baseline) {
|
|
110
|
+
placement.baseline++;
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
const loc = f.location;
|
|
114
|
+
const lines = loc ? changed.get(repoPath(prefix, loc.file)) : undefined;
|
|
115
|
+
if (loc?.line && lines && (lines === 'all' || lines.has(loc.line))) {
|
|
116
|
+
const path = repoPath(prefix, loc.file);
|
|
117
|
+
placement.inPr.push({ finding: f, path, line: loc.line, key: f.fingerprint ?? `${f.id}:${path}:${loc.line}` });
|
|
118
|
+
}
|
|
119
|
+
else {
|
|
120
|
+
placement.elsewhere.push(f);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return placement;
|
|
124
|
+
}
|
|
125
|
+
const label = (f) => (f.severity === 'critical' ? '[CRITICAL]' : '[WARN]');
|
|
126
|
+
/** The body of one inline review comment: what's wrong, why, the fix prompt, and how to silence it. */
|
|
127
|
+
export function renderInlineComment(item) {
|
|
128
|
+
const f = item.finding;
|
|
129
|
+
return [
|
|
130
|
+
`<!-- launch-doctor:finding ${markerKey(item.key)} -->`,
|
|
131
|
+
`**${label(f)} ${md(f.title)}**`,
|
|
132
|
+
'',
|
|
133
|
+
md(f.why, { oneLine: false }),
|
|
134
|
+
'',
|
|
135
|
+
'<details><summary>Fix prompt (paste into Claude Code, Cursor, Lovable or Bolt)</summary>',
|
|
136
|
+
'',
|
|
137
|
+
fence(f.fixPrompt),
|
|
138
|
+
'',
|
|
139
|
+
'</details>',
|
|
140
|
+
'',
|
|
141
|
+
`<sub>Not a problem here? Add a \`launch-doctor-ignore ${f.id}\` comment on this line or the line above.</sub>`,
|
|
142
|
+
].join('\n');
|
|
143
|
+
}
|
|
144
|
+
/** A code fence that can't be closed early by backticks inside the text. */
|
|
145
|
+
function fence(text) {
|
|
146
|
+
const longest = Math.max(2, ...[...text.matchAll(/`+/g)].map((m) => m[0].length));
|
|
147
|
+
const ticks = '`'.repeat(longest + 1);
|
|
148
|
+
return `${ticks}text\n${text}\n${ticks}`;
|
|
149
|
+
}
|
|
150
|
+
/** Where every finding can be seen when a list in the summary comment is cut short. */
|
|
151
|
+
function seeAll(ctx) {
|
|
152
|
+
const summary = ctx.runId
|
|
153
|
+
? `the [job summary](${ctx.serverUrl}/${ctx.repo}/actions/runs/${encodeURIComponent(ctx.runId)}) of this run`
|
|
154
|
+
: "this run's job summary";
|
|
155
|
+
return `Every finding is listed in ${summary}, and \`npx launch-doctor\` writes them all to LAUNCH_FIXES.md.`;
|
|
156
|
+
}
|
|
157
|
+
function listItems(items, line, max, ctx) {
|
|
158
|
+
const out = items.slice(0, max).map(line);
|
|
159
|
+
if (items.length > max)
|
|
160
|
+
out.push(`- ...and ${items.length - max} more. ${seeAll(ctx)}`);
|
|
161
|
+
return out;
|
|
162
|
+
}
|
|
163
|
+
/** A title for a list line, cut to MAX_TITLE_CHARS before it is escaped. */
|
|
164
|
+
function listTitle(title) {
|
|
165
|
+
return escapeCell(title.length > MAX_TITLE_CHARS ? `${title.slice(0, MAX_TITLE_CHARS)}...` : title);
|
|
166
|
+
}
|
|
167
|
+
function countText(findings) {
|
|
168
|
+
const crit = findings.filter((f) => f.severity === 'critical').length;
|
|
169
|
+
const warn = findings.length - crit;
|
|
170
|
+
const parts = [];
|
|
171
|
+
if (crit)
|
|
172
|
+
parts.push(`${crit} critical`);
|
|
173
|
+
if (warn)
|
|
174
|
+
parts.push(`${warn} warning${warn === 1 ? '' : 's'}`);
|
|
175
|
+
return parts.join(', ');
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* The one summary comment on the pull request, edited in place on every run. It always fits GitHub's limit: when
|
|
179
|
+
* the full lists would make it too long, they are cut (fewer and fewer items) and say where to see everything.
|
|
180
|
+
*/
|
|
181
|
+
export function renderPrComment(report, placement, ctx) {
|
|
182
|
+
let max = MAX_LISTED;
|
|
183
|
+
let body = renderPrCommentListing(report, placement, ctx, max);
|
|
184
|
+
while (body.length > MAX_COMMENT_CHARS && max > 0) {
|
|
185
|
+
max = Math.floor(max / 2);
|
|
186
|
+
body = renderPrCommentListing(report, placement, ctx, max);
|
|
187
|
+
}
|
|
188
|
+
// With no list items left it is a few short lines; a cut here is only a last resort (a huge repository name?).
|
|
189
|
+
if (body.length > MAX_COMMENT_CHARS)
|
|
190
|
+
body = `${body.slice(0, MAX_COMMENT_CHARS - 200)}\n\n...cut short. ${seeAll(ctx)}`;
|
|
191
|
+
return body;
|
|
192
|
+
}
|
|
193
|
+
function renderPrCommentListing(report, placement, ctx, max) {
|
|
194
|
+
const link = (path, line) => `${ctx.serverUrl}/${ctx.repo}/blob/${ctx.headSha}/${path.split('/').map(encodeURIComponent).join('/')}${line ? `#L${line}` : ''}`;
|
|
195
|
+
const where = (path, line) => `[${mdCode(line ? `${path}:${line}` : path)}](${link(path, line)})`;
|
|
196
|
+
const out = [
|
|
197
|
+
SUMMARY_MARKER,
|
|
198
|
+
`## Launch Doctor: grade ${report.grade}`,
|
|
199
|
+
'',
|
|
200
|
+
`**${escapeCell(report.verdict)}** · ${report.filesScanned} files checked`,
|
|
201
|
+
'',
|
|
202
|
+
'### This pull request',
|
|
203
|
+
'',
|
|
204
|
+
];
|
|
205
|
+
if (placement.inPr.length) {
|
|
206
|
+
out.push(`${countText(placement.inPr.map((i) => i.finding))} on lines this pull request adds. Each one has an inline comment with a fix prompt.`, '', ...listItems(placement.inPr, (i) => `- ${label(i.finding)} ${listTitle(i.finding.title)} (${where(i.path, i.line)})`, max, ctx));
|
|
207
|
+
}
|
|
208
|
+
else {
|
|
209
|
+
out.push('No problems in the lines this pull request adds.');
|
|
210
|
+
}
|
|
211
|
+
out.push('');
|
|
212
|
+
if (placement.elsewhere.length) {
|
|
213
|
+
out.push(`<details><summary>Already in the project: ${countText(placement.elsewhere)}</summary>`, '', ...listItems(placement.elsewhere, (f) => {
|
|
214
|
+
const loc = f.location ? ` (${where(repoPath(ctx.prefix, f.location.file), f.location.line)})` : '';
|
|
215
|
+
return `- ${label(f)} ${listTitle(f.title)}${loc}`;
|
|
216
|
+
}, max, ctx), '', '</details>', '');
|
|
217
|
+
}
|
|
218
|
+
out.push('<details><summary>Scorecard</summary>', '', ...categoryTable(report), '', '</details>', '');
|
|
219
|
+
const notes = [];
|
|
220
|
+
if (placement.baseline) {
|
|
221
|
+
notes.push(`${placement.baseline} known finding${placement.baseline === 1 ? ' is' : 's are'} in .launchdoctor-baseline.json and not shown.`);
|
|
222
|
+
}
|
|
223
|
+
if (report.counts.manual) {
|
|
224
|
+
notes.push(`${report.counts.manual} thing${report.counts.manual === 1 ? '' : 's'} to check by hand before launch.`);
|
|
225
|
+
}
|
|
226
|
+
notes.push(`Run \`npx launch-doctor\` locally for every fix prompt in LAUNCH_FIXES.md. Updated for ${ctx.headSha.slice(0, 7)}.`);
|
|
227
|
+
out.push(`<sub>${notes.join(' ')}</sub>`);
|
|
228
|
+
return out.join('\n');
|
|
229
|
+
}
|
|
230
|
+
export class GitHubError extends Error {
|
|
231
|
+
status;
|
|
232
|
+
constructor(status, message) {
|
|
233
|
+
super(message);
|
|
234
|
+
this.status = status;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
class GitHub {
|
|
238
|
+
ctx;
|
|
239
|
+
fetchImpl;
|
|
240
|
+
constructor(ctx, fetchImpl) {
|
|
241
|
+
this.ctx = ctx;
|
|
242
|
+
this.fetchImpl = fetchImpl;
|
|
243
|
+
}
|
|
244
|
+
async request(method, path, body) {
|
|
245
|
+
const res = await this.fetchImpl(`${this.ctx.apiUrl}${path}`, {
|
|
246
|
+
method,
|
|
247
|
+
headers: {
|
|
248
|
+
accept: 'application/vnd.github+json',
|
|
249
|
+
authorization: `Bearer ${this.ctx.token}`,
|
|
250
|
+
'user-agent': 'launch-doctor',
|
|
251
|
+
'x-github-api-version': '2022-11-28',
|
|
252
|
+
...(body === undefined ? {} : { 'content-type': 'application/json' }),
|
|
253
|
+
},
|
|
254
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
255
|
+
});
|
|
256
|
+
if (!res.ok) {
|
|
257
|
+
const text = await res.text().catch(() => '');
|
|
258
|
+
throw new GitHubError(res.status, `${method} ${path} returned ${res.status}${text ? `: ${text.slice(0, 300)}` : ''}`);
|
|
259
|
+
}
|
|
260
|
+
return (res.status === 204 ? null : await res.json());
|
|
261
|
+
}
|
|
262
|
+
/** Read every page of a list endpoint (up to 3,000 items). */
|
|
263
|
+
async list(path) {
|
|
264
|
+
const out = [];
|
|
265
|
+
for (let page = 1; page <= 30; page++) {
|
|
266
|
+
const items = await this.request('GET', `${path}?per_page=100&page=${page}`);
|
|
267
|
+
out.push(...items);
|
|
268
|
+
if (items.length < 100)
|
|
269
|
+
break;
|
|
270
|
+
}
|
|
271
|
+
return out;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* Post Launch Doctor's results to a pull request:
|
|
276
|
+
* one summary comment (edited on later runs) and an inline review comment on each new finding.
|
|
277
|
+
*/
|
|
278
|
+
export async function postPrFeedback(report, ctx, fetchImpl = globalThis.fetch) {
|
|
279
|
+
const gh = new GitHub(ctx, fetchImpl);
|
|
280
|
+
const base = `/repos/${ctx.repo}`;
|
|
281
|
+
const files = await gh.list(`${base}/pulls/${ctx.number}/files`);
|
|
282
|
+
const placement = placeFindings(report, changedFiles(files), ctx.prefix);
|
|
283
|
+
// Inline comments: skip findings we already commented on in an earlier run.
|
|
284
|
+
const reviewComments = await gh.list(`${base}/pulls/${ctx.number}/comments`);
|
|
285
|
+
const seen = new Set(reviewComments.map((c) => FINDING_MARKER.exec(c.body ?? '')?.[1]).filter(Boolean));
|
|
286
|
+
const fresh = placement.inPr.filter((i) => !seen.has(markerKey(i.key)));
|
|
287
|
+
const toPost = fresh.slice(0, MAX_INLINE);
|
|
288
|
+
let inlineError;
|
|
289
|
+
if (toPost.length) {
|
|
290
|
+
// Best effort: if the review is rejected (say the commit moved on), still post the summary.
|
|
291
|
+
try {
|
|
292
|
+
await gh.request('POST', `${base}/pulls/${ctx.number}/reviews`, {
|
|
293
|
+
commit_id: ctx.headSha,
|
|
294
|
+
event: 'COMMENT',
|
|
295
|
+
body: `Launch Doctor found ${countText(toPost.map((i) => i.finding))} in this change.`,
|
|
296
|
+
comments: toPost.map((i) => ({ path: i.path, line: i.line, side: 'RIGHT', body: renderInlineComment(i) })),
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
catch (err) {
|
|
300
|
+
inlineError = explainGitHubError(err);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
// The summary comment: edit ours if it's there, otherwise add it.
|
|
304
|
+
const body = renderPrComment(report, placement, ctx);
|
|
305
|
+
const issueComments = await gh.list(`${base}/issues/${ctx.number}/comments`);
|
|
306
|
+
const mine = issueComments.find((c) => (c.body ?? '').startsWith(SUMMARY_MARKER));
|
|
307
|
+
const saved = mine
|
|
308
|
+
? await gh.request('PATCH', `${base}/issues/comments/${mine.id}`, { body })
|
|
309
|
+
: await gh.request('POST', `${base}/issues/${ctx.number}/comments`, { body });
|
|
310
|
+
return {
|
|
311
|
+
inPr: placement.inPr.length,
|
|
312
|
+
elsewhere: placement.elsewhere.length,
|
|
313
|
+
posted: inlineError ? 0 : toPost.length,
|
|
314
|
+
inlineError,
|
|
315
|
+
alreadyPosted: placement.inPr.length - fresh.length,
|
|
316
|
+
overLimit: fresh.length - toPost.length,
|
|
317
|
+
summary: mine ? 'updated' : 'created',
|
|
318
|
+
summaryUrl: saved?.html_url,
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
/** Explain a failed GitHub call in plain words. */
|
|
322
|
+
export function explainGitHubError(err) {
|
|
323
|
+
if (err instanceof GitHubError && (err.status === 403 || err.status === 404)) {
|
|
324
|
+
return `GitHub refused the comment (${err.status}). The workflow needs "permissions: pull-requests: write". Pull requests from forks only get a read-only token, so they can't be commented on; the job summary still has the results.`;
|
|
325
|
+
}
|
|
326
|
+
if (err instanceof GitHubError && err.status === 422) {
|
|
327
|
+
return `GitHub rejected the comment (422). ${err.message}`;
|
|
328
|
+
}
|
|
329
|
+
return `Couldn't comment on the pull request: ${err.message}`;
|
|
330
|
+
}
|
package/dist/src/history.js
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
2
|
import { createInterface } from 'node:readline';
|
|
3
3
|
import { matchKeys } from './checks/secrets.js';
|
|
4
|
-
import { gitArgs,
|
|
4
|
+
import { gitArgs, SAFE_DIFF } from './git.js';
|
|
5
|
+
import { isRealEnvPath } from './project.js';
|
|
5
6
|
import { mask } from './util.js';
|
|
6
7
|
export const DEFAULT_HISTORY_DEPTH = 500;
|
|
7
8
|
/** Stop reading git output after this many bytes, so huge repos don't take forever. */
|
|
8
9
|
export const HISTORY_BYTE_CAP = 64 * 1024 * 1024;
|
|
10
|
+
/** And after this long, whatever has been read by then. */
|
|
11
|
+
const HISTORY_TIMEOUT_MS = 120_000;
|
|
9
12
|
/**
|
|
10
13
|
* Look for API keys that were added in past commits and are no longer in the code.
|
|
11
14
|
* Only added lines ("+" in the diff) are checked. Keys that are still in the working tree are
|
|
@@ -14,7 +17,7 @@ export const HISTORY_BYTE_CAP = 64 * 1024 * 1024;
|
|
|
14
17
|
export async function scanHistory(ctx, depth = DEFAULT_HISTORY_DEPTH) {
|
|
15
18
|
if (!ctx.gitRoot)
|
|
16
19
|
return { findings: [], commitsScanned: 0, truncated: false };
|
|
17
|
-
const args = gitArgs([
|
|
20
|
+
const args = gitArgs(ctx.root, [
|
|
18
21
|
'log',
|
|
19
22
|
'-p',
|
|
20
23
|
'--all',
|
|
@@ -22,10 +25,18 @@ export async function scanHistory(ctx, depth = DEFAULT_HISTORY_DEPTH) {
|
|
|
22
25
|
'-U0',
|
|
23
26
|
`--max-count=${depth}`,
|
|
24
27
|
'--pretty=format:commit %H',
|
|
25
|
-
|
|
28
|
+
...SAFE_DIFF,
|
|
26
29
|
]);
|
|
30
|
+
// null: this repository's config can't be made safe to run git in (see src/git.ts).
|
|
31
|
+
if (!args)
|
|
32
|
+
return { findings: [], commitsScanned: 0, truncated: false };
|
|
27
33
|
const child = spawn('git', args, { cwd: ctx.root, stdio: ['ignore', 'pipe', 'ignore'] });
|
|
28
34
|
const lines = createInterface({ input: child.stdout, crlfDelay: Infinity });
|
|
35
|
+
let timedOut = false;
|
|
36
|
+
const timer = setTimeout(() => {
|
|
37
|
+
timedOut = true;
|
|
38
|
+
child.kill();
|
|
39
|
+
}, HISTORY_TIMEOUT_MS);
|
|
29
40
|
const hits = new Map();
|
|
30
41
|
let commit = '';
|
|
31
42
|
let path = '';
|
|
@@ -56,6 +67,9 @@ export async function scanHistory(ctx, depth = DEFAULT_HISTORY_DEPTH) {
|
|
|
56
67
|
}
|
|
57
68
|
}
|
|
58
69
|
await new Promise((resolve) => (child.exitCode !== null ? resolve(null) : child.once('close', resolve)));
|
|
70
|
+
clearTimeout(timer);
|
|
71
|
+
if (timedOut)
|
|
72
|
+
truncated = true;
|
|
59
73
|
// What's in the code today is reported by the normal scan (real .env files are meant to hold keys).
|
|
60
74
|
const current = ctx.files
|
|
61
75
|
.filter((f) => !isRealEnvPath(f.path))
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { Finding, Report } from './types.js';
|
|
2
|
+
export type HookKind = 'claude' | 'cursor';
|
|
3
|
+
export interface HookResult {
|
|
4
|
+
exitCode: number;
|
|
5
|
+
stdout: string;
|
|
6
|
+
stderr: string;
|
|
7
|
+
}
|
|
8
|
+
/** Findings a hook should bring up: new ones (not in the baseline), worst first. */
|
|
9
|
+
export declare function hookFindings(report: Report): Finding[];
|
|
10
|
+
/** The message an AI coding tool reads: what is wrong, where, and the prompt that fixes it. */
|
|
11
|
+
export declare function renderHookMessage(findings: Finding[], scope: string): string;
|
|
12
|
+
/** Run a hook. `stdin` is the JSON the AI tool sent. Never throws. */
|
|
13
|
+
export declare function runHook(kind: HookKind, stdin: string, env?: NodeJS.ProcessEnv): Promise<HookResult>;
|
package/dist/src/hook.js
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { isAbsolute, relative, resolve } from 'node:path';
|
|
2
|
+
import { changedFiles } from './changed.js';
|
|
3
|
+
import { runDoctor } from './index.js';
|
|
4
|
+
/** How many findings one message carries. More than this is a wall of text the agent skims. */
|
|
5
|
+
const MAX_FINDINGS = 5;
|
|
6
|
+
const NOTHING = {
|
|
7
|
+
claude: { exitCode: 0, stdout: '', stderr: '' },
|
|
8
|
+
cursor: { exitCode: 0, stdout: '{}\n', stderr: '' },
|
|
9
|
+
};
|
|
10
|
+
/** Findings a hook should bring up: new ones (not in the baseline), worst first. */
|
|
11
|
+
export function hookFindings(report) {
|
|
12
|
+
return report.categories
|
|
13
|
+
.flatMap((c) => c.findings)
|
|
14
|
+
.filter((f) => !f.baseline)
|
|
15
|
+
.sort((a, b) => Number(b.severity === 'critical') - Number(a.severity === 'critical'));
|
|
16
|
+
}
|
|
17
|
+
/** The message an AI coding tool reads: what is wrong, where, and the prompt that fixes it. */
|
|
18
|
+
export function renderHookMessage(findings, scope) {
|
|
19
|
+
const lines = [
|
|
20
|
+
`Launch Doctor found ${findings.length === 1 ? 'a problem' : `${findings.length} problems`} in ${scope}:`,
|
|
21
|
+
'',
|
|
22
|
+
];
|
|
23
|
+
findings.slice(0, MAX_FINDINGS).forEach((f, i) => {
|
|
24
|
+
const where = f.location ? ` (${f.location.file}${f.location.line ? `:${f.location.line}` : ''})` : '';
|
|
25
|
+
lines.push(`${i + 1}. [${f.severity}] ${f.title}${where} [id: ${f.id}]`, ` Why: ${f.why}`, ` Fix: ${f.fixPrompt}`, '');
|
|
26
|
+
});
|
|
27
|
+
if (findings.length > MAX_FINDINGS)
|
|
28
|
+
lines.push(`...and ${findings.length - MAX_FINDINGS} more. Run "npx launch-doctor --changed" to see them all.`, '');
|
|
29
|
+
lines.push('Please fix these. If one is a false alarm, do not silence it yourself: tell the user why, and let them decide whether to add a launch-doctor-ignore comment.');
|
|
30
|
+
return lines.join('\n');
|
|
31
|
+
}
|
|
32
|
+
function parse(stdin) {
|
|
33
|
+
try {
|
|
34
|
+
const v = JSON.parse(stdin);
|
|
35
|
+
return v && typeof v === 'object' && !Array.isArray(v) ? v : {};
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return {};
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
const str = (v) => (typeof v === 'string' && v ? v : undefined);
|
|
42
|
+
/**
|
|
43
|
+
* Claude Code PostToolUse hook, run after Claude edits a file. Checks that one file; when it has a
|
|
44
|
+
* problem, exit code 2 sends the message to Claude on stderr (the edit has already happened).
|
|
45
|
+
* Anything unexpected exits 0: a hook must never get in the way of the work.
|
|
46
|
+
*/
|
|
47
|
+
async function claudeHook(input, env) {
|
|
48
|
+
const toolInput = input.tool_input;
|
|
49
|
+
const file = str(toolInput?.file_path);
|
|
50
|
+
if (!file)
|
|
51
|
+
return NOTHING.claude;
|
|
52
|
+
const root = resolve(env.CLAUDE_PROJECT_DIR || str(input.cwd) || process.cwd());
|
|
53
|
+
const rel = relative(root, resolve(root, file));
|
|
54
|
+
// Outside the project (or on another drive): not ours to check.
|
|
55
|
+
if (!rel || rel.startsWith('..') || isAbsolute(rel))
|
|
56
|
+
return NOTHING.claude;
|
|
57
|
+
const report = await runDoctor(root, { onlyFiles: [rel.replace(/\\/g, '/')] });
|
|
58
|
+
const findings = hookFindings(report);
|
|
59
|
+
if (!findings.length)
|
|
60
|
+
return NOTHING.claude;
|
|
61
|
+
return { exitCode: 2, stdout: '', stderr: `${renderHookMessage(findings, rel.replace(/\\/g, '/'))}\n` };
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Cursor stop hook, run when the agent finishes. Checks every file changed since the last commit;
|
|
65
|
+
* a "followup_message" is sent to the agent as its next prompt. (afterFileEdit is not used: Cursor's
|
|
66
|
+
* documentation doesn't say its output reaches the agent.)
|
|
67
|
+
*/
|
|
68
|
+
async function cursorHook(input, env) {
|
|
69
|
+
if (input.status !== undefined && input.status !== 'completed')
|
|
70
|
+
return NOTHING.cursor;
|
|
71
|
+
const roots = Array.isArray(input.workspace_roots) ? input.workspace_roots : [];
|
|
72
|
+
const root = resolve(str(roots[0]) || env.CURSOR_PROJECT_DIR || process.cwd());
|
|
73
|
+
const files = changedFiles(root, 'changed');
|
|
74
|
+
if (!files?.length)
|
|
75
|
+
return NOTHING.cursor;
|
|
76
|
+
const report = await runDoctor(root, { onlyFiles: files });
|
|
77
|
+
const findings = hookFindings(report);
|
|
78
|
+
if (!findings.length)
|
|
79
|
+
return NOTHING.cursor;
|
|
80
|
+
const scope = files.length === 1 ? files[0] : `the ${files.length} files you changed`;
|
|
81
|
+
return {
|
|
82
|
+
exitCode: 0,
|
|
83
|
+
stdout: `${JSON.stringify({ followup_message: renderHookMessage(findings, scope) })}\n`,
|
|
84
|
+
stderr: '',
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
/** Run a hook. `stdin` is the JSON the AI tool sent. Never throws. */
|
|
88
|
+
export async function runHook(kind, stdin, env = process.env) {
|
|
89
|
+
try {
|
|
90
|
+
const input = parse(stdin);
|
|
91
|
+
return kind === 'claude' ? await claudeHook(input, env) : await cursorHook(input, env);
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
return NOTHING[kind];
|
|
95
|
+
}
|
|
96
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export interface HookSetupResult {
|
|
2
|
+
created: string[];
|
|
3
|
+
/** Existing files that a launch-doctor hook was added to. */
|
|
4
|
+
updated: string[];
|
|
5
|
+
/** [file, why] for everything left alone. */
|
|
6
|
+
skipped: [string, string][];
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* The package spec every generated hook runs: the current minor range from package.json ("launch-doctor@^0.4.0"), so a
|
|
10
|
+
* hook never silently picks up a newer minor version (or a new major one) just because it was published to npm.
|
|
11
|
+
*/
|
|
12
|
+
export declare function pinnedPackage(): string;
|
|
13
|
+
/**
|
|
14
|
+
* A value in single quotes for a POSIX shell. Nothing inside single quotes is expanded, so a folder named
|
|
15
|
+
* `app$(curl ...)` stays a folder name; a single quote in the value is written as '\''.
|
|
16
|
+
*/
|
|
17
|
+
export declare function shellQuote(value: string): string;
|
|
18
|
+
/**
|
|
19
|
+
* The block added to the pre-commit hook. Only exit code 1 (critical problems in the staged files)
|
|
20
|
+
* stops the commit. If the tool itself fails (no network for npx, for example) the commit goes ahead.
|
|
21
|
+
*/
|
|
22
|
+
export declare function preCommitBlock(projectDir: string): string;
|
|
23
|
+
/** Set up the Claude Code hook, the Cursor hook and the git pre-commit hook. Existing files are merged into, never replaced. */
|
|
24
|
+
export declare function setupHooks(root: string): HookSetupResult;
|