launch-doctor 0.4.0 → 0.4.2

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.
@@ -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
+ }
@@ -1,6 +1,6 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { createInterface } from 'node:readline';
3
- import { matchKeys } from './checks/secrets.js';
3
+ import { leakPlaybook, matchKeys, rotateHint, usageLink } from './checks/secrets.js';
4
4
  import { gitArgs, SAFE_DIFF } from './git.js';
5
5
  import { isRealEnvPath } from './project.js';
6
6
  import { mask } from './util.js';
@@ -94,9 +94,16 @@ function historyFinding(hit) {
94
94
  title: `Secret still in git history: ${hit.pattern.name} (commit ${short}, ${hit.path})`,
95
95
  why: `This ${hit.pattern.name} (${shown}) was removed from your code, but it's still in commit ${short}. Anyone who can clone the repo can dig it out, so it has to be treated as leaked.`,
96
96
  location: { file: hit.path },
97
+ display: {
98
+ title: `Anyone who can clone the repo can use your ${hit.pattern.name}: it is still in git history`,
99
+ reason: `added in commit ${short}`,
100
+ rotate: rotateHint(hit.pattern),
101
+ ...(usageLink(hit.pattern.id) ? { usage: usageLink(hit.pattern.id) } : {}),
102
+ },
97
103
  fixPrompt: `Commit ${short} in my git history added a ${hit.pattern.name} (it starts with "${shown}") to ${hit.path}. The code no longer has it, but the history does. Please:\n` +
98
104
  `1. Walk me through revoking this key and creating a new one (${hit.pattern.rotate}), and make sure the new one lives only in an environment variable.\n` +
99
105
  `2. Optionally, explain how to remove it from the history with git filter-repo (for example "git filter-repo --replace-text replacements.txt"), what that means for everyone else who has a clone, and that I'll need to force-push.\n` +
100
- `Rotating the key matters most: rewriting history doesn't help if someone already copied it.`,
106
+ `Rotating the key matters most: rewriting history doesn't help if someone already copied it.` +
107
+ leakPlaybook({ usage: usageLink(hit.pattern.id), from: 'history' }),
101
108
  };
102
109
  }
@@ -22,3 +22,29 @@ export declare function shellQuote(value: string): string;
22
22
  export declare function preCommitBlock(projectDir: string): string;
23
23
  /** Set up the Claude Code hook, the Cursor hook and the git pre-commit hook. Existing files are merged into, never replaced. */
24
24
  export declare function setupHooks(root: string): HookSetupResult;
25
+ export interface HookChange {
26
+ file: string;
27
+ /** The lines that change, before and after. */
28
+ before: string[];
29
+ after: string[];
30
+ /** The new file contents (written by upgradeHooks unless dryRun). */
31
+ text: string;
32
+ }
33
+ export interface HookUpgradeResult {
34
+ changed: HookChange[];
35
+ /** [file, package spec] already on the current version. */
36
+ current: [string, string][];
37
+ /** Files whose launch-doctor hook has no version: it runs the newest release, so it is reported, not rewritten. */
38
+ unpinned: string[];
39
+ /** [file, why] for files with no launch-doctor hook, or that could not be read. */
40
+ skipped: [string, string][];
41
+ }
42
+ /**
43
+ * `init --hooks --upgrade`: move the hooks that init --hooks installed onto this version's package spec
44
+ * (launch-doctor@^0.4.0 becomes launch-doctor@^0.5.0, say). Only the launch-doctor command changes: other hooks,
45
+ * other settings and the files' formatting are left alone. Hooks installed without a version are reported, not
46
+ * rewritten. With dryRun, nothing is written.
47
+ */
48
+ export declare function upgradeHooks(root: string, { dryRun }?: {
49
+ dryRun?: boolean | undefined;
50
+ }): HookUpgradeResult;
@@ -47,7 +47,9 @@ function writeJson(path, data) {
47
47
  * Does this hook list already run a launch-doctor hook command? Any version counts, including the unpinned commands
48
48
  * older releases wrote: re-running init never adds a second hook, and never rewrites one the user already has.
49
49
  */
50
- const hasOurCommand = (entries, tool) => new RegExp(String.raw `\blaunch-doctor(?:@[^\s"\\]+)?\\?"? hook ${tool}\b`).test(JSON.stringify(entries ?? null));
50
+ const hasOurCommand = (entries, tool) => ourCommand(tool).test(JSON.stringify(entries ?? null));
51
+ /** A launch-doctor hook command for this tool, pinned or not, as it appears in JSON text (quotes escaped). */
52
+ const ourCommand = (tool) => new RegExp(String.raw `\blaunch-doctor(?:@[^\s"\\]+)?\\?"? hook ${tool}\b`);
51
53
  /** .claude/settings.json: a PostToolUse hook that checks every file Claude Code writes or edits. */
52
54
  function setupClaude(root, result) {
53
55
  const rel = '.claude/settings.json';
@@ -185,3 +187,115 @@ export function setupHooks(root) {
185
187
  setupPreCommit(root, result);
186
188
  return result;
187
189
  }
190
+ /** A pinned package spec as init --hooks writes it: launch-doctor@^0.4.0 */
191
+ const PINNED_SPEC = /launch-doctor@\^\d+\.\d+\.\d+/g;
192
+ /**
193
+ * Upgrade one file: replace the pinned package spec on the lines `isOurs` accepts. Every other line, and the
194
+ * file's formatting, stays exactly as it was.
195
+ */
196
+ function upgradeText(file, text, isOurs, result) {
197
+ const target = pinnedPackage();
198
+ const lines = text.split('\n');
199
+ const before = [];
200
+ const after = [];
201
+ let ours = 0;
202
+ let pinned = 0;
203
+ const out = lines.map((line, i) => {
204
+ if (!isOurs(line, i))
205
+ return line;
206
+ ours++;
207
+ if (!PINNED_SPEC.test(line))
208
+ return line;
209
+ PINNED_SPEC.lastIndex = 0;
210
+ pinned++;
211
+ const next = line.replace(PINNED_SPEC, target);
212
+ if (next !== line) {
213
+ before.push(line.trim());
214
+ after.push(next.trim());
215
+ }
216
+ return next;
217
+ });
218
+ if (!ours) {
219
+ result.skipped.push([file, 'no launch-doctor hook in it']);
220
+ return null;
221
+ }
222
+ if (pinned < ours)
223
+ result.unpinned.push(file);
224
+ if (!before.length) {
225
+ if (pinned)
226
+ result.current.push([file, target]);
227
+ return null;
228
+ }
229
+ return { file, before, after, text: out.join('\n') };
230
+ }
231
+ /** The text of a hook file, or a reason it was skipped. */
232
+ function readHookFile(path, rel, result) {
233
+ const kind = entryKind(path);
234
+ if (kind === 'missing') {
235
+ result.skipped.push([rel, 'not found']);
236
+ return null;
237
+ }
238
+ const text = kind === 'file' ? readRegularFile(path, CONFIG_FILE_MAX_BYTES) : null;
239
+ if (text === null)
240
+ result.skipped.push([rel, SPECIAL]);
241
+ return text;
242
+ }
243
+ /**
244
+ * `init --hooks --upgrade`: move the hooks that init --hooks installed onto this version's package spec
245
+ * (launch-doctor@^0.4.0 becomes launch-doctor@^0.5.0, say). Only the launch-doctor command changes: other hooks,
246
+ * other settings and the files' formatting are left alone. Hooks installed without a version are reported, not
247
+ * rewritten. With dryRun, nothing is written.
248
+ */
249
+ export function upgradeHooks(root, { dryRun = false } = {}) {
250
+ const result = { changed: [], current: [], unpinned: [], skipped: [] };
251
+ const changes = [];
252
+ for (const [rel, tool] of [
253
+ ['.claude/settings.json', 'claude'],
254
+ ['.cursor/hooks.json', 'cursor'],
255
+ ]) {
256
+ const path = join(root, rel);
257
+ const text = readHookFile(path, rel, result);
258
+ if (text === null)
259
+ continue;
260
+ // A JSON line holding our hook command: "command": "npx --yes \"launch-doctor@^0.4.0\" hook claude"
261
+ const ours = ourCommand(tool);
262
+ const change = upgradeText(rel, text, (line) => ours.test(line), result);
263
+ if (!change)
264
+ continue;
265
+ try {
266
+ JSON.parse(change.text);
267
+ }
268
+ catch {
269
+ result.skipped.push([rel, 'the upgraded file would not be valid JSON, so it was left alone']);
270
+ continue;
271
+ }
272
+ changes.push([path, change]);
273
+ }
274
+ const gitRoot = findGitRoot(root);
275
+ const hooksPath = gitRoot ? gitHooksDir(root) : null;
276
+ if (!hooksPath) {
277
+ result.skipped.push(['pre-commit hook', gitRoot ? "couldn't find the git hooks folder" : 'not a git repository']);
278
+ }
279
+ else {
280
+ const path = resolve(root, hooksPath, 'pre-commit');
281
+ const shown = relative(root, path).replace(/\\/g, '/');
282
+ const rel = shown.startsWith('..') || isAbsolute(shown) ? path : shown;
283
+ const text = readHookFile(path, rel, result);
284
+ if (text !== null) {
285
+ // Only the lines inside the block init --hooks added.
286
+ const lines = text.split('\n');
287
+ const start = lines.findIndex((l) => l.includes(MARK_START));
288
+ const end = lines.findIndex((l, i) => i > start && l.includes(MARK_END));
289
+ const inBlock = (line, i) => start >= 0 && end > start && i > start && i < end && /\bnpx\b.*\blaunch-doctor\b/.test(line);
290
+ const change = upgradeText(rel, text, inBlock, result);
291
+ if (change)
292
+ changes.push([path, change]);
293
+ }
294
+ }
295
+ for (const [path, change] of changes) {
296
+ if (!dryRun)
297
+ writeRegularFile(path, change.text);
298
+ result.changed.push(change);
299
+ }
300
+ return result;
301
+ }
package/dist/src/index.js CHANGED
@@ -8,7 +8,7 @@ import { legalCheck } from './checks/legal.js';
8
8
  import { monitoringCheck } from './checks/monitoring.js';
9
9
  import { paymentsCheck } from './checks/payments.js';
10
10
  import { secretsCheck } from './checks/secrets.js';
11
- import { overall, scoreCategory, toGrade } from './grade.js';
11
+ import { GRADE_GROUPS, groupGrade, overall, scoreCategory, toGrade } from './grade.js';
12
12
  import { scanHistory } from './history.js';
13
13
  import { ProjectContext } from './project.js';
14
14
  import { sanitizeReport } from './sanitize.js';
@@ -79,6 +79,7 @@ export async function runDoctor(root, options = {}) {
79
79
  });
80
80
  continue;
81
81
  }
82
+ options.onProgress?.(check.name);
82
83
  let out;
83
84
  try {
84
85
  out = await check.run(ctx);
@@ -157,6 +158,10 @@ export async function runDoctor(root, options = {}) {
157
158
  ...(ctx.nestedRepos.length ? { nestedRepos: ctx.nestedRepos } : {}),
158
159
  ...(options.onlyFiles ? { partial: { files: options.onlyFiles } } : {}),
159
160
  ...summary,
161
+ grades: {
162
+ security: groupGrade(categories, GRADE_GROUPS.security),
163
+ launch: groupGrade(categories, GRADE_GROUPS.launch),
164
+ },
160
165
  categories,
161
166
  generatedAt: new Date().toISOString(),
162
167
  };
@@ -1,9 +1,39 @@
1
1
  /** The same workflow as the README's "CI integration" example. */
2
2
  export declare const WORKFLOW_TEMPLATE = "name: Launch Doctor\non: [pull_request]\njobs:\n check:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v7\n - uses: actions/setup-node@v7\n with:\n node-version: 22\n - run: npx launch-doctor --ci\n";
3
3
  export declare const IGNORE_TEMPLATE = "# .launchdoctorignore: things Launch Doctor should leave alone.\n# One entry per line. Lines starting with # are comments.\n\n# Finding ids (each fix in LAUNCH_FIXES.md shows its id). For example:\n# no-error-tracking\n# no-account-deletion\n\n# Folders or files to skip (anything with / * or . is a path):\n# legacy/\n# scripts/seed.ts\n# **/*.fixture.ts\n\n# To silence one finding in one place, add a comment on that line or the line above:\n# // launch-doctor-ignore stripe-test-key\n";
4
+ export declare const MONITOR_WORKFLOW = ".github/workflows/launch-doctor-monitor.yml";
5
+ /**
6
+ * The package spec the monitor runs: at least this version (it needs --record), and no newer major (or, before
7
+ * 1.0, minor) version unless you change it, like the hooks.
8
+ */
9
+ export declare function monitorPackage(): string;
10
+ /** The branch the monitor keeps the grade history and the badge on. */
11
+ export declare const GRADES_BRANCH = "launch-doctor-grades";
12
+ /** Where the README badge points: the badge file on the grades branch. */
13
+ export declare function badgeUrl(repo?: string): string;
14
+ /** "owner/repo" when `origin` is a GitHub repository, otherwise null. */
15
+ export declare function githubRepo(remoteUrl: string | null): string | null;
16
+ /**
17
+ * `init --monitor`: re-check the project every week and keep the grade history and the badge up to date.
18
+ *
19
+ * - The history is read from the launch-doctor-grades branch first, so --record adds to it.
20
+ * - The project scan runs with --record and --ci, so a new critical problem fails the run and GitHub emails you.
21
+ * - With the repository variable LAUNCH_DOCTOR_URL set, the deployed site is checked too (the URL is passed through
22
+ * an environment variable, never pasted into the script).
23
+ * - grades.json and badge.svg are committed to the launch-doctor-grades branch (an orphan branch with only those two
24
+ * files, created on the first run), even when a check failed, so the history shows the bad weeks as well. Nothing
25
+ * is ever committed to the default branch, so this works with a protected main and adds no commits to it. Pushes
26
+ * made with the workflow's token don't start other workflows.
27
+ */
28
+ export declare function monitorTemplate(): string;
4
29
  export interface InitResult {
5
30
  created: string[];
6
31
  skipped: string[];
7
32
  }
8
- /** Create the starter files in `root`. Existing files are never overwritten. */
9
- export declare function runInit(root: string): InitResult;
33
+ /**
34
+ * Create the starter files in `root`, or with `monitor` only the weekly monitoring workflow. Existing files are
35
+ * never overwritten.
36
+ */
37
+ export declare function runInit(root: string, { monitor }?: {
38
+ monitor?: boolean | undefined;
39
+ }): InitResult;
package/dist/src/init.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
2
2
  import { dirname, join } from 'node:path';
3
+ import { version } from './version.js';
3
4
  /** The same workflow as the README's "CI integration" example. */
4
5
  export const WORKFLOW_TEMPLATE = `name: Launch Doctor
5
6
  on: [pull_request]
@@ -28,12 +29,125 @@ export const IGNORE_TEMPLATE = `# .launchdoctorignore: things Launch Doctor shou
28
29
  # To silence one finding in one place, add a comment on that line or the line above:
29
30
  # // launch-doctor-ignore stripe-test-key
30
31
  `;
31
- /** Create the starter files in `root`. Existing files are never overwritten. */
32
- export function runInit(root) {
33
- const files = [
34
- ['.launchdoctorignore', IGNORE_TEMPLATE],
35
- ['.github/workflows/launch-doctor.yml', WORKFLOW_TEMPLATE],
36
- ];
32
+ export const MONITOR_WORKFLOW = '.github/workflows/launch-doctor-monitor.yml';
33
+ /**
34
+ * The package spec the monitor runs: at least this version (it needs --record), and no newer major (or, before
35
+ * 1.0, minor) version unless you change it, like the hooks.
36
+ */
37
+ export function monitorPackage() {
38
+ const [major, minor, patch] = version().split(/[.-]/);
39
+ return `launch-doctor@^${major}.${minor}.${patch}`;
40
+ }
41
+ /** The branch the monitor keeps the grade history and the badge on. */
42
+ export const GRADES_BRANCH = 'launch-doctor-grades';
43
+ /** Where the README badge points: the badge file on the grades branch. */
44
+ export function badgeUrl(repo = '<owner>/<repo>') {
45
+ return `https://raw.githubusercontent.com/${repo}/${GRADES_BRANCH}/badge.svg`;
46
+ }
47
+ /** "owner/repo" when `origin` is a GitHub repository, otherwise null. */
48
+ export function githubRepo(remoteUrl) {
49
+ const m = /github\.com[:/]([A-Za-z0-9-]+)\/([A-Za-z0-9._-]+?)(?:\.git)?\/?$/.exec(remoteUrl?.trim() ?? '');
50
+ return m ? `${m[1]}/${m[2]}` : null;
51
+ }
52
+ /**
53
+ * `init --monitor`: re-check the project every week and keep the grade history and the badge up to date.
54
+ *
55
+ * - The history is read from the launch-doctor-grades branch first, so --record adds to it.
56
+ * - The project scan runs with --record and --ci, so a new critical problem fails the run and GitHub emails you.
57
+ * - With the repository variable LAUNCH_DOCTOR_URL set, the deployed site is checked too (the URL is passed through
58
+ * an environment variable, never pasted into the script).
59
+ * - grades.json and badge.svg are committed to the launch-doctor-grades branch (an orphan branch with only those two
60
+ * files, created on the first run), even when a check failed, so the history shows the bad weeks as well. Nothing
61
+ * is ever committed to the default branch, so this works with a protected main and adds no commits to it. Pushes
62
+ * made with the workflow's token don't start other workflows.
63
+ */
64
+ export function monitorTemplate() {
65
+ const pkg = monitorPackage();
66
+ return `name: Launch Doctor monitor
67
+
68
+ # Re-checks this project every Monday and keeps its grade history (grades.json) and README badge
69
+ # (badge.svg) on the ${GRADES_BRANCH} branch, which holds only those two files. Nothing is
70
+ # committed to your default branch. A critical problem fails the run, so GitHub emails you.
71
+ # To also check your deployed site, add a repository variable named LAUNCH_DOCTOR_URL
72
+ # (Settings > Secrets and variables > Actions > Variables).
73
+ on:
74
+ schedule:
75
+ - cron: '17 6 * * 1'
76
+ workflow_dispatch:
77
+
78
+ permissions:
79
+ contents: write # push the grade history and the badge to the ${GRADES_BRANCH} branch
80
+
81
+ concurrency:
82
+ group: launch-doctor-monitor
83
+ cancel-in-progress: false
84
+
85
+ jobs:
86
+ monitor:
87
+ runs-on: ubuntu-latest
88
+ env:
89
+ GRADES_BRANCH: ${GRADES_BRANCH}
90
+ steps:
91
+ - uses: actions/checkout@v7
92
+ - uses: actions/setup-node@v7
93
+ with:
94
+ node-version: 22
95
+ - name: Load the grade history
96
+ run: |
97
+ if git ls-remote --exit-code --heads origin "$GRADES_BRANCH" > /dev/null; then
98
+ git fetch --quiet --depth=1 origin "refs/heads/$GRADES_BRANCH"
99
+ mkdir -p .launchdoctor
100
+ git show FETCH_HEAD:grades.json > .launchdoctor/grades.json || rm -f .launchdoctor/grades.json
101
+ else
102
+ echo "There is no $GRADES_BRANCH branch yet, so this run starts the history."
103
+ fi
104
+ - name: Check the project
105
+ run: npx --yes "${pkg}" --record --ci
106
+ - name: Check the deployed site
107
+ if: \${{ !cancelled() && vars.LAUNCH_DOCTOR_URL != '' }}
108
+ env:
109
+ LAUNCH_DOCTOR_URL: \${{ vars.LAUNCH_DOCTOR_URL }}
110
+ run: npx --yes "${pkg}" scan "$LAUNCH_DOCTOR_URL" --ci --no-file
111
+ - name: Save the grade history to its branch
112
+ if: \${{ !cancelled() }}
113
+ run: |
114
+ if [ ! -f .launchdoctor/grades.json ] || [ ! -f .launchdoctor/badge.svg ]; then
115
+ echo "No grade was recorded, so there is nothing to save."
116
+ exit 0
117
+ fi
118
+ dir="$RUNNER_TEMP/launch-doctor-grades"
119
+ if git ls-remote --exit-code --heads origin "$GRADES_BRANCH" > /dev/null; then
120
+ git fetch --quiet --depth=1 origin "refs/heads/$GRADES_BRANCH"
121
+ git worktree add --quiet --detach "$dir" FETCH_HEAD
122
+ else
123
+ # A new branch with no history and no files from the default branch.
124
+ git worktree add --quiet --detach "$dir"
125
+ git -C "$dir" checkout --quiet --orphan "$GRADES_BRANCH"
126
+ git -C "$dir" rm -r --quiet --force --ignore-unmatch .
127
+ fi
128
+ cp .launchdoctor/grades.json .launchdoctor/badge.svg "$dir/"
129
+ git -C "$dir" add -- grades.json badge.svg
130
+ if git -C "$dir" diff --cached --quiet; then
131
+ echo "The grade history is unchanged."
132
+ exit 0
133
+ fi
134
+ git -C "$dir" -c user.name="github-actions[bot]" \\
135
+ -c user.email="41898282+github-actions[bot]@users.noreply.github.com" \\
136
+ commit --quiet -m "Launch Doctor: record this week's grade"
137
+ git -C "$dir" push --quiet origin "HEAD:refs/heads/$GRADES_BRANCH"
138
+ `;
139
+ }
140
+ /**
141
+ * Create the starter files in `root`, or with `monitor` only the weekly monitoring workflow. Existing files are
142
+ * never overwritten.
143
+ */
144
+ export function runInit(root, { monitor = false } = {}) {
145
+ const files = monitor
146
+ ? [[MONITOR_WORKFLOW, monitorTemplate()]]
147
+ : [
148
+ ['.launchdoctorignore', IGNORE_TEMPLATE],
149
+ ['.github/workflows/launch-doctor.yml', WORKFLOW_TEMPLATE],
150
+ ];
37
151
  const result = { created: [], skipped: [] };
38
152
  for (const [rel, content] of files) {
39
153
  const full = join(root, rel);
@@ -9,7 +9,10 @@ export interface LiveOptions {
9
9
  maxBytes?: number;
10
10
  /** Don't send the anonymous-key requests to Supabase (default false). */
11
11
  skipDatabase?: boolean;
12
- /** Replacement for fetch (used by tests to fake a Supabase project). */
12
+ /**
13
+ * Tests only: send requests with this instead of the pinned node:http transport (to fake a Supabase project, for
14
+ * example). Every host is still checked first, but the connection is not pinned to the checked address.
15
+ */
13
16
  fetch?: typeof fetch;
14
17
  /** Replacement for the DNS lookup used to check each host before a request (tests). */
15
18
  lookup?: Lookup;