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.
- package/CHANGELOG.md +92 -6
- package/LICENSE +1 -0
- package/README.md +138 -22
- 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 +7 -0
- package/dist/src/checks/costs.js +14 -6
- package/dist/src/checks/database.js +79 -3
- package/dist/src/checks/first-impressions.js +22 -2
- package/dist/src/checks/legal.js +3 -1
- package/dist/src/checks/monitoring.js +8 -5
- package/dist/src/checks/payments.js +10 -2
- package/dist/src/checks/secrets.d.ts +8 -0
- package/dist/src/checks/secrets.js +82 -9
- package/dist/src/checks/supabase-storage.d.ts +31 -0
- package/dist/src/checks/supabase-storage.js +216 -0
- package/dist/src/cli.js +175 -12
- package/dist/src/demo.js +1 -0
- package/dist/src/detect.d.ts +1 -1
- package/dist/src/detect.js +1 -1
- package/dist/src/fixes.js +8 -5
- package/dist/src/git.d.ts +25 -0
- package/dist/src/git.js +121 -0
- package/dist/src/github.d.ts +11 -1
- package/dist/src/github.js +56 -14
- package/dist/src/grades.d.ts +42 -0
- package/dist/src/grades.js +163 -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.js +28 -3
- package/dist/src/init.d.ts +32 -2
- package/dist/src/init.js +120 -6
- package/dist/src/live.d.ts +13 -1
- package/dist/src/live.js +111 -23
- package/dist/src/mcp.js +7 -2
- package/dist/src/net-guard.d.ts +42 -0
- package/dist/src/net-guard.js +147 -0
- package/dist/src/pinned-http.d.ts +31 -0
- package/dist/src/pinned-http.js +104 -0
- package/dist/src/project.d.ts +34 -5
- package/dist/src/project.js +145 -111
- package/dist/src/report.d.ts +4 -0
- package/dist/src/report.js +13 -0
- 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 +4 -0
- package/dist/src/summary.js +9 -4
- package/dist/src/types.d.ts +24 -0
- package/dist/src/util.d.ts +1 -1
- package/dist/src/util.js +1 -1
- package/package.json +9 -5
package/dist/src/git.js
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { devNull } from 'node:os';
|
|
3
|
+
/**
|
|
4
|
+
* Running git safely inside a folder we don't trust.
|
|
5
|
+
*
|
|
6
|
+
* A project downloaded with its .git folder (a zip, a tarball, a copied folder; a plain `git clone` never copies
|
|
7
|
+
* .git/config) can set git options that run programs: core.fsmonitor, filter drivers (clean, smudge, process),
|
|
8
|
+
* diff drivers (textconv, command), diff.external, the pager, signature checks and hooks. Every git command
|
|
9
|
+
* Launch Doctor runs gets these settings, so none of them can run:
|
|
10
|
+
*
|
|
11
|
+
* - core.fsmonitor=false, no pager, no signature checks, hooks looked up in the null device (except for the one
|
|
12
|
+
* read-only lookup of the hooks folder that `init --hooks` makes, see gitHooksDir);
|
|
13
|
+
* - every filter driver the configuration names gets an empty clean, smudge and process command (git runs
|
|
14
|
+
* nothing for an empty one), wherever the attributes that select it come from (.gitattributes,
|
|
15
|
+
* .git/info/attributes or core.attributesFile);
|
|
16
|
+
* - log and diff calls also pass --no-textconv and --no-ext-diff (see SAFE_DIFF).
|
|
17
|
+
*
|
|
18
|
+
* When a driver name can't be overridden on the command line, git is treated as unavailable.
|
|
19
|
+
*/
|
|
20
|
+
/** Settings every git command gets. */
|
|
21
|
+
const FIXED = ['--no-pager', '-c', 'core.fsmonitor=false', '-c', 'log.showSignature=false'];
|
|
22
|
+
/** Hooks are looked up in the null device, so none can run (git status-like commands run post-index-change). */
|
|
23
|
+
const NO_HOOKS = ['-c', `core.hooksPath=${devNull}`];
|
|
24
|
+
/** Flags for every command that prints a diff or compares files (log -p, diff). */
|
|
25
|
+
export const SAFE_DIFF = ['--no-textconv', '--no-ext-diff'];
|
|
26
|
+
/** No git command we run should take this long; a hang (a FIFO for a config file, for example) is cut off. */
|
|
27
|
+
export const GIT_TIMEOUT_MS = 60_000;
|
|
28
|
+
const overrideCache = new Map();
|
|
29
|
+
/**
|
|
30
|
+
* `-c` settings that empty every filter driver the configuration seen from `cwd` defines, or null when one
|
|
31
|
+
* can't be overridden safely. Reading the configuration runs nothing.
|
|
32
|
+
*/
|
|
33
|
+
function driverOverrides(cwd) {
|
|
34
|
+
const cached = overrideCache.get(cwd);
|
|
35
|
+
if (cached !== undefined)
|
|
36
|
+
return cached;
|
|
37
|
+
let names;
|
|
38
|
+
try {
|
|
39
|
+
const out = execFileSync('git', [...FIXED, 'config', '-z', '--name-only', '--get-regexp', '^filter\\.'], {
|
|
40
|
+
cwd,
|
|
41
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
42
|
+
timeout: GIT_TIMEOUT_MS,
|
|
43
|
+
maxBuffer: 16 * 1024 * 1024,
|
|
44
|
+
}).toString();
|
|
45
|
+
names = out.split('\0').filter(Boolean);
|
|
46
|
+
}
|
|
47
|
+
catch (err) {
|
|
48
|
+
// Exit code 1 means no filter is configured. Any other failure (no git, a broken config, a timeout) means we
|
|
49
|
+
// can't know which drivers exist, so git isn't run at all.
|
|
50
|
+
if (err.status !== 1) {
|
|
51
|
+
overrideCache.set(cwd, null);
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
names = [];
|
|
55
|
+
}
|
|
56
|
+
const drivers = new Set();
|
|
57
|
+
let unsafe = false;
|
|
58
|
+
for (const name of names) {
|
|
59
|
+
const m = /^filter\.(.+)\.[^.]+$/s.exec(name);
|
|
60
|
+
if (!m)
|
|
61
|
+
continue;
|
|
62
|
+
const driver = m[1];
|
|
63
|
+
// "-c" splits the setting at its first "="; such a name can't be overridden, so refuse to run git at all.
|
|
64
|
+
if (/[=\n\0]/.test(driver))
|
|
65
|
+
unsafe = true;
|
|
66
|
+
drivers.add(driver);
|
|
67
|
+
}
|
|
68
|
+
const result = unsafe
|
|
69
|
+
? null
|
|
70
|
+
: [...drivers].flatMap((d) => [
|
|
71
|
+
'-c',
|
|
72
|
+
`filter.${d}.clean=`,
|
|
73
|
+
'-c',
|
|
74
|
+
`filter.${d}.smudge=`,
|
|
75
|
+
'-c',
|
|
76
|
+
`filter.${d}.process=`,
|
|
77
|
+
'-c',
|
|
78
|
+
`filter.${d}.required=false`,
|
|
79
|
+
]);
|
|
80
|
+
overrideCache.set(cwd, result);
|
|
81
|
+
return result;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* The full argument list for a git command run in `cwd`, or null when it isn't safe to run git there.
|
|
85
|
+
* Every git call goes through here (a test checks this).
|
|
86
|
+
*/
|
|
87
|
+
export function gitArgs(cwd, args, { ownHooks = false } = {}) {
|
|
88
|
+
const overrides = driverOverrides(cwd);
|
|
89
|
+
if (overrides === null)
|
|
90
|
+
return null;
|
|
91
|
+
return [...FIXED, ...(ownHooks ? [] : NO_HOOKS), ...overrides, ...args];
|
|
92
|
+
}
|
|
93
|
+
/** Run git in `cwd`. Returns stdout, or null when git fails, isn't installed, times out or isn't safe to run. */
|
|
94
|
+
export function git(cwd, args) {
|
|
95
|
+
return gitStatus(cwd, args).stdout;
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* The repository's own hooks folder (core.hooksPath, or .git/hooks), for `init --hooks`, which you run on your own
|
|
99
|
+
* project to install a hook there. The only git command that sees the repository's hooks setting; it runs nothing.
|
|
100
|
+
*/
|
|
101
|
+
export function gitHooksDir(cwd) {
|
|
102
|
+
return gitStatus(cwd, ['rev-parse', '--git-path', 'hooks'], { ownHooks: true }).stdout?.trim() || null;
|
|
103
|
+
}
|
|
104
|
+
/** Like git(), but also reports the exit code, for commands where exit code 1 is an answer, not a failure. */
|
|
105
|
+
export function gitStatus(cwd, args, opts = {}) {
|
|
106
|
+
const full = gitArgs(cwd, args, opts);
|
|
107
|
+
if (!full)
|
|
108
|
+
return { stdout: null, status: null };
|
|
109
|
+
try {
|
|
110
|
+
const stdout = execFileSync('git', full, {
|
|
111
|
+
cwd,
|
|
112
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
113
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
114
|
+
timeout: GIT_TIMEOUT_MS,
|
|
115
|
+
}).toString();
|
|
116
|
+
return { stdout, status: 0 };
|
|
117
|
+
}
|
|
118
|
+
catch (err) {
|
|
119
|
+
return { stdout: null, status: err.status ?? null };
|
|
120
|
+
}
|
|
121
|
+
}
|
package/dist/src/github.d.ts
CHANGED
|
@@ -3,6 +3,11 @@ import type { Finding, Report } from './types.js';
|
|
|
3
3
|
export declare const SUMMARY_MARKER = "<!-- launch-doctor:summary -->";
|
|
4
4
|
/** At most this many inline comments per run, so a big pull request isn't buried. */
|
|
5
5
|
export declare const MAX_INLINE = 20;
|
|
6
|
+
/**
|
|
7
|
+
* GitHub rejects a comment longer than 65,536 characters (and then no summary is posted at all). The summary comment
|
|
8
|
+
* is kept under this, with room to spare: lists get shorter until it fits.
|
|
9
|
+
*/
|
|
10
|
+
export declare const MAX_COMMENT_CHARS = 60000;
|
|
6
11
|
export interface PrContext {
|
|
7
12
|
apiUrl: string;
|
|
8
13
|
serverUrl: string;
|
|
@@ -13,6 +18,8 @@ export interface PrContext {
|
|
|
13
18
|
token: string;
|
|
14
19
|
/** Where the scanned folder sits inside the repository ("" for the repository root, "web" for ./web). */
|
|
15
20
|
prefix: string;
|
|
21
|
+
/** The workflow run (GITHUB_RUN_ID), to link to its job summary, which lists every finding. */
|
|
22
|
+
runId?: string;
|
|
16
23
|
}
|
|
17
24
|
/**
|
|
18
25
|
* Work out which pull request we're running for from the GitHub Actions environment.
|
|
@@ -49,7 +56,10 @@ export declare function repoPath(prefix: string, file: string): string;
|
|
|
49
56
|
export declare function placeFindings(report: Report, changed: Map<string, ChangedLines>, prefix: string): Placement;
|
|
50
57
|
/** The body of one inline review comment: what's wrong, why, the fix prompt, and how to silence it. */
|
|
51
58
|
export declare function renderInlineComment(item: InlineFinding): string;
|
|
52
|
-
/**
|
|
59
|
+
/**
|
|
60
|
+
* The one summary comment on the pull request, edited in place on every run. It always fits GitHub's limit: when
|
|
61
|
+
* the full lists would make it too long, they are cut (fewer and fewer items) and say where to see everything.
|
|
62
|
+
*/
|
|
53
63
|
export declare function renderPrComment(report: Report, placement: Placement, ctx: PrContext): string;
|
|
54
64
|
export declare class GitHubError extends Error {
|
|
55
65
|
readonly status: number;
|
package/dist/src/github.js
CHANGED
|
@@ -1,13 +1,28 @@
|
|
|
1
1
|
import { readFileSync } from 'node:fs';
|
|
2
2
|
import { isAbsolute, relative } from 'node:path';
|
|
3
|
+
import { htmlCommentSafe, md, mdCode } from './sanitize.js';
|
|
3
4
|
import { categoryTable, escapeCell } from './summary.js';
|
|
4
5
|
/** Marks our one summary comment on a pull request, so later runs edit it instead of adding another. */
|
|
5
6
|
export const SUMMARY_MARKER = '<!-- launch-doctor:summary -->';
|
|
6
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
|
+
}
|
|
7
15
|
/** At most this many inline comments per run, so a big pull request isn't buried. */
|
|
8
16
|
export const MAX_INLINE = 20;
|
|
9
|
-
/** At most this many findings per list in the summary comment
|
|
17
|
+
/** At most this many findings per list in the summary comment. */
|
|
10
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;
|
|
11
26
|
/**
|
|
12
27
|
* Work out which pull request we're running for from the GitHub Actions environment.
|
|
13
28
|
* Returns a reason string instead when there's nothing to comment on.
|
|
@@ -47,6 +62,7 @@ export function prContextFromEnv(root, env = process.env) {
|
|
|
47
62
|
headSha,
|
|
48
63
|
token,
|
|
49
64
|
prefix,
|
|
65
|
+
...(env.GITHUB_RUN_ID ? { runId: env.GITHUB_RUN_ID } : {}),
|
|
50
66
|
};
|
|
51
67
|
}
|
|
52
68
|
/** Line numbers (in the new version of the file) that a unified diff patch adds. */
|
|
@@ -111,10 +127,10 @@ const label = (f) => (f.severity === 'critical' ? '[CRITICAL]' : '[WARN]');
|
|
|
111
127
|
export function renderInlineComment(item) {
|
|
112
128
|
const f = item.finding;
|
|
113
129
|
return [
|
|
114
|
-
`<!-- launch-doctor:finding ${item.key} -->`,
|
|
115
|
-
`**${label(f)} ${f.title}**`,
|
|
130
|
+
`<!-- launch-doctor:finding ${markerKey(item.key)} -->`,
|
|
131
|
+
`**${label(f)} ${md(f.title)}**`,
|
|
116
132
|
'',
|
|
117
|
-
f.why,
|
|
133
|
+
md(f.why, { oneLine: false }),
|
|
118
134
|
'',
|
|
119
135
|
'<details><summary>Fix prompt (paste into Claude Code, Cursor, Lovable or Bolt)</summary>',
|
|
120
136
|
'',
|
|
@@ -131,12 +147,23 @@ function fence(text) {
|
|
|
131
147
|
const ticks = '`'.repeat(longest + 1);
|
|
132
148
|
return `${ticks}text\n${text}\n${ticks}`;
|
|
133
149
|
}
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
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)}`);
|
|
138
161
|
return out;
|
|
139
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
|
+
}
|
|
140
167
|
function countText(findings) {
|
|
141
168
|
const crit = findings.filter((f) => f.severity === 'critical').length;
|
|
142
169
|
const warn = findings.length - crit;
|
|
@@ -147,10 +174,25 @@ function countText(findings) {
|
|
|
147
174
|
parts.push(`${warn} warning${warn === 1 ? '' : 's'}`);
|
|
148
175
|
return parts.join(', ');
|
|
149
176
|
}
|
|
150
|
-
/**
|
|
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
|
+
*/
|
|
151
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) {
|
|
152
194
|
const link = (path, line) => `${ctx.serverUrl}/${ctx.repo}/blob/${ctx.headSha}/${path.split('/').map(encodeURIComponent).join('/')}${line ? `#L${line}` : ''}`;
|
|
153
|
-
const where = (path, line) => `[
|
|
195
|
+
const where = (path, line) => `[${mdCode(line ? `${path}:${line}` : path)}](${link(path, line)})`;
|
|
154
196
|
const out = [
|
|
155
197
|
SUMMARY_MARKER,
|
|
156
198
|
`## Launch Doctor: grade ${report.grade}`,
|
|
@@ -161,7 +203,7 @@ export function renderPrComment(report, placement, ctx) {
|
|
|
161
203
|
'',
|
|
162
204
|
];
|
|
163
205
|
if (placement.inPr.length) {
|
|
164
|
-
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)} ${
|
|
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));
|
|
165
207
|
}
|
|
166
208
|
else {
|
|
167
209
|
out.push('No problems in the lines this pull request adds.');
|
|
@@ -170,8 +212,8 @@ export function renderPrComment(report, placement, ctx) {
|
|
|
170
212
|
if (placement.elsewhere.length) {
|
|
171
213
|
out.push(`<details><summary>Already in the project: ${countText(placement.elsewhere)}</summary>`, '', ...listItems(placement.elsewhere, (f) => {
|
|
172
214
|
const loc = f.location ? ` (${where(repoPath(ctx.prefix, f.location.file), f.location.line)})` : '';
|
|
173
|
-
return `- ${label(f)} ${
|
|
174
|
-
}), '', '</details>', '');
|
|
215
|
+
return `- ${label(f)} ${listTitle(f.title)}${loc}`;
|
|
216
|
+
}, max, ctx), '', '</details>', '');
|
|
175
217
|
}
|
|
176
218
|
out.push('<details><summary>Scorecard</summary>', '', ...categoryTable(report), '', '</details>', '');
|
|
177
219
|
const notes = [];
|
|
@@ -241,7 +283,7 @@ export async function postPrFeedback(report, ctx, fetchImpl = globalThis.fetch)
|
|
|
241
283
|
// Inline comments: skip findings we already commented on in an earlier run.
|
|
242
284
|
const reviewComments = await gh.list(`${base}/pulls/${ctx.number}/comments`);
|
|
243
285
|
const seen = new Set(reviewComments.map((c) => FINDING_MARKER.exec(c.body ?? '')?.[1]).filter(Boolean));
|
|
244
|
-
const fresh = placement.inPr.filter((i) => !seen.has(i.key));
|
|
286
|
+
const fresh = placement.inPr.filter((i) => !seen.has(markerKey(i.key)));
|
|
245
287
|
const toPost = fresh.slice(0, MAX_INLINE);
|
|
246
288
|
let inlineError;
|
|
247
289
|
if (toPost.length) {
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { Grade, Report } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Grade history and the README badge (`--record`).
|
|
4
|
+
*
|
|
5
|
+
* Each recorded scan adds one line to .launchdoctor/grades.json (the date, grade, score, counts, the Launch Doctor
|
|
6
|
+
* version and the commit), and redraws .launchdoctor/badge.svg. Both are meant to be committed, so the history and
|
|
7
|
+
* the badge travel with the repository and nothing is sent anywhere. (history.ts is the git history secret scan.)
|
|
8
|
+
*/
|
|
9
|
+
export declare const STATE_DIR = ".launchdoctor";
|
|
10
|
+
export declare const GRADES_FILE = ".launchdoctor/grades.json";
|
|
11
|
+
export declare const BADGE_FILE = ".launchdoctor/badge.svg";
|
|
12
|
+
/** Older entries are dropped, so the file stays small however often it is recorded. */
|
|
13
|
+
export declare const MAX_GRADE_ENTRIES = 200;
|
|
14
|
+
export interface GradeEntry {
|
|
15
|
+
/** When the scan ran (ISO 8601). */
|
|
16
|
+
date: string;
|
|
17
|
+
grade: Grade;
|
|
18
|
+
score: number;
|
|
19
|
+
critical: number;
|
|
20
|
+
warning: number;
|
|
21
|
+
manual: number;
|
|
22
|
+
/** The Launch Doctor version that produced it: grades from different versions aren't always comparable. */
|
|
23
|
+
version: string;
|
|
24
|
+
/** The commit that was scanned (short hash), when the folder is a git repository. */
|
|
25
|
+
commit?: string;
|
|
26
|
+
}
|
|
27
|
+
/** Recorded grades, oldest first. Empty when there is no file or it can't be read. */
|
|
28
|
+
export declare function loadGrades(root: string): GradeEntry[];
|
|
29
|
+
export declare function entryFor(report: Report, commit?: string): GradeEntry;
|
|
30
|
+
/** The short hash of HEAD, or undefined outside a git repository (or when git can't run safely there). */
|
|
31
|
+
export declare function headCommit(root: string): string | undefined;
|
|
32
|
+
/** Add `entry` to the history and redraw the badge. Returns the history, oldest first, with the new entry last. */
|
|
33
|
+
export declare function recordGrade(root: string, entry: GradeEntry): GradeEntry[];
|
|
34
|
+
/**
|
|
35
|
+
* A small SVG in the usual "label | value" badge shape, drawn locally: no badge service is asked, so the README
|
|
36
|
+
* shows the grade that was last recorded and committed. Every color has at least 4.5:1 contrast with white text.
|
|
37
|
+
*/
|
|
38
|
+
export declare function renderBadge(grade: Grade): string;
|
|
39
|
+
/** "B (82) on 30 Nov 2026" for the line under the overall grade. */
|
|
40
|
+
export declare function describeEntry(e: GradeEntry): string;
|
|
41
|
+
/** The table `launch-doctor grades` prints, newest first. */
|
|
42
|
+
export declare function renderGradeTable(entries: GradeEntry[], limit?: number): string;
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { mkdirSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { git } from './git.js';
|
|
4
|
+
import { CONFIG_FILE_MAX_BYTES } from './project.js';
|
|
5
|
+
import { entryKind, readRegularFile, writeRegularFile } from './safe-fs.js';
|
|
6
|
+
/**
|
|
7
|
+
* Grade history and the README badge (`--record`).
|
|
8
|
+
*
|
|
9
|
+
* Each recorded scan adds one line to .launchdoctor/grades.json (the date, grade, score, counts, the Launch Doctor
|
|
10
|
+
* version and the commit), and redraws .launchdoctor/badge.svg. Both are meant to be committed, so the history and
|
|
11
|
+
* the badge travel with the repository and nothing is sent anywhere. (history.ts is the git history secret scan.)
|
|
12
|
+
*/
|
|
13
|
+
export const STATE_DIR = '.launchdoctor';
|
|
14
|
+
export const GRADES_FILE = `${STATE_DIR}/grades.json`;
|
|
15
|
+
export const BADGE_FILE = `${STATE_DIR}/badge.svg`;
|
|
16
|
+
/** Older entries are dropped, so the file stays small however often it is recorded. */
|
|
17
|
+
export const MAX_GRADE_ENTRIES = 200;
|
|
18
|
+
const GRADES = new Set(['A', 'B', 'C', 'D', 'F']);
|
|
19
|
+
const count = (v) => Number.isInteger(v) && v >= 0 && v <= 1_000_000;
|
|
20
|
+
/** The file is in a repository that may not be yours, so every field is checked and anything odd is dropped. */
|
|
21
|
+
function validEntry(e) {
|
|
22
|
+
if (!e || typeof e !== 'object')
|
|
23
|
+
return null;
|
|
24
|
+
const r = e;
|
|
25
|
+
if (typeof r.grade !== 'string' || !GRADES.has(r.grade))
|
|
26
|
+
return null;
|
|
27
|
+
if (!count(r.score) || r.score > 100)
|
|
28
|
+
return null;
|
|
29
|
+
if (!count(r.critical) || !count(r.warning) || !count(r.manual))
|
|
30
|
+
return null;
|
|
31
|
+
if (typeof r.date !== 'string' || r.date.length > 40 || Number.isNaN(Date.parse(r.date)))
|
|
32
|
+
return null;
|
|
33
|
+
if (typeof r.version !== 'string' || !/^\d{1,4}\.\d{1,4}\.\d{1,6}(?:-[0-9A-Za-z.-]{1,40})?$/.test(r.version))
|
|
34
|
+
return null;
|
|
35
|
+
if (r.commit !== undefined && (typeof r.commit !== 'string' || !/^[0-9a-f]{7,40}$/.test(r.commit)))
|
|
36
|
+
return null;
|
|
37
|
+
return {
|
|
38
|
+
date: new Date(r.date).toISOString(),
|
|
39
|
+
grade: r.grade,
|
|
40
|
+
score: r.score,
|
|
41
|
+
critical: r.critical,
|
|
42
|
+
warning: r.warning,
|
|
43
|
+
manual: r.manual,
|
|
44
|
+
version: r.version,
|
|
45
|
+
...(r.commit ? { commit: r.commit } : {}),
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
/** Recorded grades, oldest first. Empty when there is no file or it can't be read. */
|
|
49
|
+
export function loadGrades(root) {
|
|
50
|
+
// Only a regular file in the project: a symlink or a FIFO counts as no history.
|
|
51
|
+
const raw = readRegularFile(join(root, GRADES_FILE), CONFIG_FILE_MAX_BYTES);
|
|
52
|
+
if (raw === null)
|
|
53
|
+
return [];
|
|
54
|
+
try {
|
|
55
|
+
const data = JSON.parse(raw);
|
|
56
|
+
if (!Array.isArray(data.entries))
|
|
57
|
+
return [];
|
|
58
|
+
return data.entries
|
|
59
|
+
.map(validEntry)
|
|
60
|
+
.filter((e) => e !== null)
|
|
61
|
+
.slice(-MAX_GRADE_ENTRIES);
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
return [];
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
export function entryFor(report, commit) {
|
|
68
|
+
return {
|
|
69
|
+
date: report.generatedAt,
|
|
70
|
+
grade: report.grade,
|
|
71
|
+
score: report.score,
|
|
72
|
+
critical: report.counts.critical,
|
|
73
|
+
warning: report.counts.warning,
|
|
74
|
+
manual: report.counts.manual,
|
|
75
|
+
version: report.version,
|
|
76
|
+
...(commit ? { commit } : {}),
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
/** The short hash of HEAD, or undefined outside a git repository (or when git can't run safely there). */
|
|
80
|
+
export function headCommit(root) {
|
|
81
|
+
const out = git(root, ['rev-parse', '--short=12', 'HEAD'])?.trim();
|
|
82
|
+
return out && /^[0-9a-f]{7,40}$/.test(out) ? out : undefined;
|
|
83
|
+
}
|
|
84
|
+
/** Make .launchdoctor/ if needed. A symlink or special file in its place is refused, like every file we write. */
|
|
85
|
+
function stateDir(root) {
|
|
86
|
+
const dir = join(root, STATE_DIR);
|
|
87
|
+
const kind = entryKind(dir);
|
|
88
|
+
if (kind === 'missing')
|
|
89
|
+
mkdirSync(dir);
|
|
90
|
+
else if (kind !== 'dir')
|
|
91
|
+
throw new Error(`${STATE_DIR} is a link or a special file, not a folder, so nothing was written`);
|
|
92
|
+
return dir;
|
|
93
|
+
}
|
|
94
|
+
/** Add `entry` to the history and redraw the badge. Returns the history, oldest first, with the new entry last. */
|
|
95
|
+
export function recordGrade(root, entry) {
|
|
96
|
+
const entries = [...loadGrades(root), entry].slice(-MAX_GRADE_ENTRIES);
|
|
97
|
+
stateDir(root);
|
|
98
|
+
const file = { tool: 'launch-doctor', version: 1, entries };
|
|
99
|
+
writeRegularFile(join(root, GRADES_FILE), `${JSON.stringify(file, null, 2)}\n`);
|
|
100
|
+
writeRegularFile(join(root, BADGE_FILE), renderBadge(entry.grade));
|
|
101
|
+
return entries;
|
|
102
|
+
}
|
|
103
|
+
// ---------------------------------------------------------------------------
|
|
104
|
+
// The badge
|
|
105
|
+
// ---------------------------------------------------------------------------
|
|
106
|
+
const BADGE_COLORS = {
|
|
107
|
+
A: '#1a7f37',
|
|
108
|
+
B: '#4d7c0f',
|
|
109
|
+
C: '#9a6700',
|
|
110
|
+
D: '#c2410c',
|
|
111
|
+
F: '#b91c1c',
|
|
112
|
+
};
|
|
113
|
+
/**
|
|
114
|
+
* A small SVG in the usual "label | value" badge shape, drawn locally: no badge service is asked, so the README
|
|
115
|
+
* shows the grade that was last recorded and committed. Every color has at least 4.5:1 contrast with white text.
|
|
116
|
+
*/
|
|
117
|
+
export function renderBadge(grade) {
|
|
118
|
+
const label = 'launch doctor';
|
|
119
|
+
const labelWidth = 96;
|
|
120
|
+
const valueWidth = 24;
|
|
121
|
+
const width = labelWidth + valueWidth;
|
|
122
|
+
const color = BADGE_COLORS[grade];
|
|
123
|
+
return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="20" role="img" aria-label="${label}: ${grade}">
|
|
124
|
+
<title>${label}: ${grade}</title>
|
|
125
|
+
<clipPath id="r"><rect width="${width}" height="20" rx="3"/></clipPath>
|
|
126
|
+
<g clip-path="url(#r)">
|
|
127
|
+
<rect width="${labelWidth}" height="20" fill="#444d56"/>
|
|
128
|
+
<rect x="${labelWidth}" width="${valueWidth}" height="20" fill="${color}"/>
|
|
129
|
+
</g>
|
|
130
|
+
<g fill="#fff" text-anchor="middle" font-family="Verdana,DejaVu Sans,sans-serif" font-size="11">
|
|
131
|
+
<text x="${labelWidth / 2}" y="14">${label}</text>
|
|
132
|
+
<text x="${labelWidth + valueWidth / 2}" y="14" font-weight="bold">${grade}</text>
|
|
133
|
+
</g>
|
|
134
|
+
</svg>
|
|
135
|
+
`;
|
|
136
|
+
}
|
|
137
|
+
// ---------------------------------------------------------------------------
|
|
138
|
+
// Showing the history
|
|
139
|
+
// ---------------------------------------------------------------------------
|
|
140
|
+
/** "B (82) on 30 Nov 2026" for the line under the overall grade. */
|
|
141
|
+
export function describeEntry(e) {
|
|
142
|
+
const day = new Date(e.date).toLocaleDateString('en-GB', {
|
|
143
|
+
day: 'numeric',
|
|
144
|
+
month: 'short',
|
|
145
|
+
year: 'numeric',
|
|
146
|
+
timeZone: 'UTC',
|
|
147
|
+
});
|
|
148
|
+
return `${e.grade} (${e.score}) on ${day}`;
|
|
149
|
+
}
|
|
150
|
+
/** The table `launch-doctor grades` prints, newest first. */
|
|
151
|
+
export function renderGradeTable(entries, limit = 20) {
|
|
152
|
+
if (!entries.length) {
|
|
153
|
+
return `\n No grades recorded yet. Run "launch-doctor --record" to save one to ${GRADES_FILE}.\n\n`;
|
|
154
|
+
}
|
|
155
|
+
const shown = entries.slice(-limit).reverse();
|
|
156
|
+
const lines = ['', ' Date Grade Score Critical Warnings Commit Version'];
|
|
157
|
+
for (const e of shown) {
|
|
158
|
+
lines.push(` ${e.date.slice(0, 10)} ${e.grade.padEnd(5)} ${String(e.score).padStart(5)} ${String(e.critical).padStart(8)} ${String(e.warning).padStart(8)} ${(e.commit ?? '-').padEnd(12)} ${e.version}`);
|
|
159
|
+
}
|
|
160
|
+
if (entries.length > shown.length)
|
|
161
|
+
lines.push('', ` ${entries.length - shown.length} older entries not shown.`);
|
|
162
|
+
return `${lines.join('\n')}\n\n`;
|
|
163
|
+
}
|
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
|
+
}
|