launch-doctor 0.4.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 CHANGED
@@ -7,6 +7,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.4.1] - 2026-12-04
11
+
12
+ ### Added
13
+
14
+ - **Grade history:** `--record` saves the grade of a full scan to `.launchdoctor/grades.json` (date, grade, score, counts, Launch Doctor version and the commit scanned; no finding text, file names or keys; the newest 200 entries). Every full scan then shows the last recorded grade under the overall grade, and `launch-doctor grades [folder]` lists the history (`--json` for the raw list). `--record` is refused with `--changed`, `--staged`, `--only`, `--skip` and `--demo`, whose grades aren't comparable. The file is read like the baseline (a regular file only) and every entry is checked before use.
15
+ - **README badge:** `--record` also draws `.launchdoctor/badge.svg` locally (no badge service), with the grade in a color that keeps 4.5:1 contrast with its white text. With scheduled monitoring, the README points at the copy on the `launch-doctor-grades` branch: `![Launch Doctor grade](https://raw.githubusercontent.com/<owner>/<repo>/launch-doctor-grades/badge.svg)`.
16
+ - **Scheduled monitoring:** `launch-doctor init --monitor` adds `.github/workflows/launch-doctor-monitor.yml`. Every Monday (or when started by hand) it reads the grade history from the `launch-doctor-grades` branch, runs `--record --ci`, so a new critical problem fails the run and GitHub emails you; checks the deployed site too when the repository variable `LAUNCH_DOCTOR_URL` is set (passed through an environment variable, never pasted into the script); and commits `grades.json` and `badge.svg` to the `launch-doctor-grades` branch, also after a failed check. That branch is created on the first run as an orphan branch holding only those two files; nothing is committed to the default branch, so it works with a protected `main` and adds no commits to it. It runs Launch Doctor pinned to the version that created it, and `init --monitor` prints the badge line with your repository filled in when `origin` is on GitHub.
17
+
18
+ ### Security
19
+
20
+ - `scan <url>` is no longer open to DNS rebinding. Requests are made with `node:http` and `node:https` instead of `fetch`, and each one connects only to the addresses that were checked for it, so DNS can't hand the connection a private address after the check said public. The host name is still used for the `Host` header and for HTTPS (the server name and the certificate check). Redirects (one hop at a time, at most 5), the per-request timeout, the 3 MB body cap (now counted after decompression) and gzip, deflate and Brotli bodies work as before.
21
+
22
+ ### Changed
23
+
24
+ - Releases are published to npm with trusted publishing: the Release workflow proves who it is to npm with a short-lived GitHub token, so no npm token is stored anywhere, and every version gets a provenance statement linking it to its tag and workflow run. A version that is already on npm is skipped, so a re-run is safe. CONTRIBUTING.md has the one-time npm setup.
25
+ - `docs/roadmap.md` lists the milestones planned after the 0.5.0 engine rewrite, the rules every milestone follows (local-first, opt-in network access, no secrets in output, approval for new dependencies), and what is deliberately not planned, with the reasons. CONTRIBUTING.md, the README and `docs/architecture.md` link to it.
26
+
10
27
  ## [0.4.0] - 2026-12-02
11
28
 
12
29
  ### Added
@@ -51,6 +68,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
51
68
 
52
69
  - An Express route registered before `app.use(requireAuth)` counted as protected, but Express runs middleware in the order it is registered, so the route was open. Sign-in middleware added with `app.use` now only covers the routes registered after it in the same file, so such a route is reported by the access-control checks (`api-write-no-auth`). Middleware registered in another file is still not tracked; that comes with the 0.5.0 engine. Scanning the 50 corpus apps shows no change.
53
70
  - A sign-in helper that was only imported (`import { getServerSession } from 'next-auth'`, never called) counted as a sign-in check, so an unprotected AI route (`ai-endpoint-no-auth`) or data-changing endpoint (`api-write-no-auth`) in that file, or in a file that imports such a module, went unreported. Import and `require` lines no longer count; the helper has to appear in the code. A call whose result is never checked still counts; that needs the 0.5.0 engine. Scanning the 50 corpus apps shows no change.
71
+ - CLI tools that contain web-like sample code were misclassified as web apps. A project whose package.json declares a `bin` no longer counts as a website just because its source contains text like `"use server"` or `app.get(`, unless it depends on a server framework (Express, Fastify, Hono, Koa, NestJS or hapi), a frontend package or has an `index.html`. This removes the "No error tracking" warning from Launch Doctor's own scan.
72
+ - Public forms are matched by their whole name, not their first letters. `subscribe\w*` and `contact\w*` also exempted admin actions such as `subscribers_delete`, `contacts_export` and `contact_admin`, so a missing sign-in or ownership check on them went unreported. Now only the action itself is treated as public (`subscribe`, `unsubscribe`, `contact`, `contact_form`, `contact_submit`, `newsletter_signup`, `join_waitlist`, feedback, inquiry, `consume_link`, bounces, ping), and a name or URL that also says delete, update, edit, export, list, admin, remove or all is checked like any other endpoint. The same rule applies to URLs (`/api/contact/export`, `/api/contact_admin/:id`). Scanning the 50 corpus apps shows no other change.
73
+ - The pull request summary comment could go over GitHub's 65,536-character limit (with long paths, it reached 162,000 characters), and then GitHub refused it and no summary was posted. Its lists now get shorter until the comment fits (under 60,000 characters), long titles are cut at 300 characters, and a cut list says how many findings were left out and links to the run's job summary, which lists them all.
54
74
 
55
75
  False alarms found by running Launch Doctor on 50 real open-source apps:
56
76
 
@@ -71,12 +91,6 @@ False alarms found by running Launch Doctor on 50 real open-source apps:
71
91
  - SECURITY.md lists every network request Launch Doctor is expected to make: email DNS lookups, the `scan <url>` requests (including Supabase), the GitHub API calls for pull request comments, and the MCP server's tools.
72
92
  - LICENSE, README and package.json credit Namay Singh for early development.
73
93
 
74
- ### Fixed
75
-
76
- - Fix: CLI tools that contain web-like sample code were misclassified as web apps. A project whose package.json declares a `bin` no longer counts as a website just because its source contains text like `"use server"` or `app.get(`, unless it depends on a server framework (Express, Fastify, Hono, Koa, NestJS or hapi), a frontend package or has an `index.html`. This removes the "No error tracking" warning from Launch Doctor's own scan.
77
- - Public forms are matched by their whole name, not their first letters. `subscribe\w*` and `contact\w*` also exempted admin actions such as `subscribers_delete`, `contacts_export` and `contact_admin`, so a missing sign-in or ownership check on them went unreported. Now only the action itself is treated as public (`subscribe`, `unsubscribe`, `contact`, `contact_form`, `contact_submit`, `newsletter_signup`, `join_waitlist`, feedback, inquiry, `consume_link`, bounces, ping), and a name or URL that also says delete, update, edit, export, list, admin, remove or all is checked like any other endpoint. The same rule applies to URLs (`/api/contact/export`, `/api/contact_admin/:id`). Scanning the 50 corpus apps shows no other change.
78
- - The pull request summary comment could go over GitHub's 65,536-character limit (with long paths, it reached 162,000 characters), and then GitHub refused it and no summary was posted. Its lists now get shorter until the comment fits (under 60,000 characters), long titles are cut at 300 characters, and a cut list says how many findings were left out and links to the run's job summary, which lists them all.
79
-
80
94
  ## [0.3.0] - 2026-11-27
81
95
 
82
96
  ### Added
@@ -170,7 +184,8 @@ First release.
170
184
  - `.launchdoctorignore` for silencing findings by id or skipping paths.
171
185
  - Support for JavaScript / TypeScript and Python projects.
172
186
 
173
- [Unreleased]: https://github.com/SHARAJ379/Launch-Doctor/compare/v0.4.0...HEAD
187
+ [Unreleased]: https://github.com/SHARAJ379/Launch-Doctor/compare/v0.4.1...HEAD
188
+ [0.4.1]: https://github.com/SHARAJ379/Launch-Doctor/compare/v0.4.0...v0.4.1
174
189
  [0.4.0]: https://github.com/SHARAJ379/Launch-Doctor/compare/v0.3.0...v0.4.0
175
190
  [0.3.0]: https://github.com/SHARAJ379/Launch-Doctor/compare/v0.2.1...v0.3.0
176
191
  [0.2.1]: https://github.com/SHARAJ379/Launch-Doctor/compare/v0.2.0...v0.2.1
package/README.md CHANGED
@@ -49,7 +49,7 @@ Requires Node.js 22 or newer. That is the version range the automated tests cove
49
49
  This is the `--demo` report, shortened. On a real project the last line tells you where `LAUNCH_FIXES.md` was saved (the demo doesn't write it).
50
50
 
51
51
  ```
52
- Launch Doctor v0.4.0
52
+ Launch Doctor v0.4.1
53
53
  Checked my-weekend-saas · 13 files · Vite, React, Supabase, Stripe, OpenAI
54
54
 
55
55
  Overall grade F Not ready to launch: fix 6 critical issues first
@@ -218,7 +218,8 @@ The report uses the same grades and `--json`, `--ci`, `--fail-on`, `--out` and `
218
218
 
219
219
  ```
220
220
  npx launch-doctor [folder] [options]
221
- npx launch-doctor init [folder] [--hooks]
221
+ npx launch-doctor init [folder] [--hooks | --monitor]
222
+ npx launch-doctor grades [folder] [--json]
222
223
  npx launch-doctor scan <url> [options]
223
224
  npx launch-doctor mcp
224
225
  npx launch-doctor hook <claude|cursor>
@@ -242,6 +243,7 @@ npx launch-doctor hook <claude|cursor>
242
243
  | `--history-depth <n>` | `500` | How many commits `--history` reads |
243
244
  | `--update-baseline` | off | Save today's findings to `.launchdoctor-baseline.json` as accepted |
244
245
  | `--no-baseline` | off | Ignore `.launchdoctor-baseline.json` and show every finding |
246
+ | `--record` | off | Save the grade to `.launchdoctor/grades.json` and redraw `.launchdoctor/badge.svg` (see [Grade history and badge](#grade-history-and-badge)). Not with `--changed`, `--staged`, `--only`, `--skip` or `--demo` |
245
247
  | `--config-from <ref>` | off | Read `.launchdoctorignore` and `.launchdoctor-baseline.json` from this git ref (branch, tag or commit) instead of the folder, and ignore inline `launch-doctor-ignore` comments on lines changed since that ref. The GitHub Action passes the pull request's base commit |
246
248
  | `--changed` | off | Only report on files changed since the last commit (edited, staged or new). Fast, for hooks. See [Hooks and fast mode](#hooks-and-fast-mode) |
247
249
  | `--staged` | off | Only report on files staged for the next commit. For a pre-commit hook |
@@ -250,6 +252,8 @@ npx launch-doctor hook <claude|cursor>
250
252
  | `-v`, `--version` | | Show the version |
251
253
  | `init [folder]` | `.` | Create `.launchdoctorignore` and `.github/workflows/launch-doctor.yml` (never overwrites) |
252
254
  | `init --hooks` | `.` | Set up the Claude Code, Cursor and git pre-commit hooks (merges into existing files, never overwrites) |
255
+ | `init --monitor` | `.` | Create `.github/workflows/launch-doctor-monitor.yml`, which re-checks the project every week (see [Scheduled monitoring](#scheduled-monitoring)). Never overwrites |
256
+ | `grades [folder]` | `.` | Show the grades saved with `--record`, newest first (`--json` for the raw list) |
253
257
  | `hook <claude|cursor>` | | What the Claude Code and Cursor hooks run. Reads the tool's JSON from stdin; you don't run it yourself |
254
258
  | `scan <url>` | | Check your deployed site from the outside (see [Live site scan](#live-site-scan)) |
255
259
  | `mcp` | | Start an MCP server so AI coding tools can run checks themselves (see [MCP server](#mcp-server)) |
@@ -305,6 +309,29 @@ On subsequent runs:
305
309
 
306
310
  Findings are tracked by check ID, file path, and a fingerprint of the offending line, preserving baseline matches even as line numbers shift. Run with `--no-baseline` to display all suppressed findings.
307
311
 
312
+ ### Grade history and badge
313
+
314
+ `--record` saves the grade of a full scan so you can see whether the project is getting better or worse:
315
+
316
+ ```bash
317
+ npx launch-doctor --record
318
+ npx launch-doctor grades # the saved grades, newest first
319
+ ```
320
+
321
+ - **History:** each run adds one entry to `.launchdoctor/grades.json`: the date, grade, score, the number of critical issues, warnings and things to check yourself, the Launch Doctor version, and the commit that was scanned. Nothing else is saved (no finding text, file names or keys), and only the newest 200 entries are kept.
322
+ - **Comparison:** once a grade is saved, every full scan shows it under the overall grade ("Last recorded grade: B (82) on 30 Nov 2026").
323
+ - **Badge:** `--record` also redraws `.launchdoctor/badge.svg`. It is drawn locally, not by a badge service.
324
+
325
+ `--record` only works on a full scan of a real project: it is refused with `--changed`, `--staged`, `--only`, `--skip` and `--demo`, because their grades aren't comparable. Like other hidden folders, `.launchdoctor/` is never scanned.
326
+
327
+ **On GitHub, let [scheduled monitoring](#scheduled-monitoring) keep the history.** It stores `grades.json` and `badge.svg` on a separate `launch-doctor-grades` branch, never on your default branch, so you don't need to commit `.launchdoctor/` yourself (you can add it to `.gitignore`). Point your README badge at the file on that branch, replacing `<owner>/<repo>` with your repository (`init --monitor` prints the line with them filled in):
328
+
329
+ ```markdown
330
+ ![Launch Doctor grade](https://raw.githubusercontent.com/<owner>/<repo>/launch-doctor-grades/badge.svg)
331
+ ```
332
+
333
+ The badge shows the grade from the last monitoring run. In a private repository, `raw.githubusercontent.com` addresses need a sign-in, so the badge may not show for visitors.
334
+
308
335
  ## CI integration
309
336
 
310
337
  The `npx launch-doctor init` command creates this GitHub Actions workflow:
@@ -341,6 +368,17 @@ jobs:
341
368
  sarif_file: launch-doctor.sarif
342
369
  ```
343
370
 
371
+ ### Scheduled monitoring
372
+
373
+ A project can get worse without anyone opening a pull request. `npx launch-doctor init --monitor` adds `.github/workflows/launch-doctor-monitor.yml`, which every Monday (and whenever you start it from the Actions tab):
374
+
375
+ 1. reads the grade history from the `launch-doctor-grades` branch, if it exists;
376
+ 2. scans the project with `--record --ci`, so a critical problem fails the run and GitHub emails you;
377
+ 3. if you have set a repository variable named `LAUNCH_DOCTOR_URL` (Settings → Secrets and variables → Actions → Variables), also runs `scan` on that address;
378
+ 4. commits the updated `grades.json` and `badge.svg` to the `launch-doctor-grades` branch, also after a failed check, so the history shows the bad weeks too.
379
+
380
+ `launch-doctor-grades` is created on the first run as an orphan branch: it shares no history with your code and holds only those two files. Nothing is ever committed to your default branch, so the monitor works when `main` is protected and doesn't add weekly commits to it. The workflow needs `contents: write` to push to the grades branch; if a branch rule (for example one matching every branch) stops the workflow's token from pushing there, the save step fails and the checks still run. The workflow runs Launch Doctor pinned to the version that created it, like the hooks (see [Hooks and fast mode](#hooks-and-fast-mode)).
381
+
344
382
  ### Pull request comments
345
383
 
346
384
  The Launch Doctor GitHub Action reviews each pull request like a teammate would:
@@ -466,12 +504,14 @@ The tools only read: nothing is written to your project, and results also come b
466
504
  Launch Doctor analyzes your codebase locally on your device. Your source code, findings, and credentials are never uploaded to any remote server. Detected secrets are masked in reports (for example, `sk_live_…exe9`).
467
505
 
468
506
  - **Email DNS validation:** This is the only network check a folder scan performs. When your project sends transactional email and a domain is identified (either discovered in code or specified via `--domain`), Launch Doctor queries your system DNS resolver for NS and TXT records (including root SPF, `send.<domain>`, `_dmarc.<domain>`, and common DKIM selectors). No code or private data is transmitted. Pass `--offline` to disable DNS lookups entirely. The `--demo` command never touches the network.
469
- - **Live site scan (`scan <url>`):** sends ordinary `GET` requests to the address you give, to the JavaScript files and source maps that page loads (which may be on another domain, such as a CDN), and to your Supabase project when the page uses one. For the Supabase test it sends the public anon key it found in your page back to your own Supabase project. Nothing else is sent, and nothing is uploaded. When the address you give is a public site, the scan never sends a request to a private or local network address (your router, the cloud metadata address, `localhost`), even if the page or a redirect points there; you can still scan your own dev server by giving its address. See [SECURITY.md](SECURITY.md) for the details and one known gap.
507
+ - **Live site scan (`scan <url>`):** sends ordinary `GET` requests to the address you give, to the JavaScript files and source maps that page loads (which may be on another domain, such as a CDN), and to your Supabase project when the page uses one. For the Supabase test it sends the public anon key it found in your page back to your own Supabase project. Nothing else is sent, and nothing is uploaded. When the address you give is a public site, the scan never sends a request to a private or local network address (your router, the cloud metadata address, `localhost`), even if the page or a redirect points there; you can still scan your own dev server by giving its address. Each request connects only to the address that was checked for it, so a DNS server can't switch it to a private one afterwards (DNS rebinding). See [SECURITY.md](SECURITY.md) for the details.
470
508
  - **No telemetry:** Launch Doctor does not collect usage data or phone home.
471
509
  - **Git history analysis (`--history`):** Runs local `git log` commands directly on your system without network requests.
472
510
  - **Pull request comments (`--pr-comment`):** calls the GitHub API with the workflow's token to read the pull request's changed files and post comments. It only runs on GitHub Actions and sends finding titles, explanations, fix prompts and file paths, never your source code.
473
511
  - **MCP server (`mcp`):** talks to your AI tool over stdin and stdout only; it opens no port. Its tools make the same network calls as the CLI: email DNS lookups for `scan_project` (unless `offline`), and the requests to the site you name for `scan_url`, which only accepts public sites.
474
512
  - **Hooks (`init --hooks`):** the hooks themselves make no network requests beyond `npx --yes "launch-doctor@^X.Y.0"`, which downloads the package from the npm registry the first time if it isn't installed. `--changed` and `--staged` skip the email DNS lookups.
513
+ - **Grade history and badge (`--record`):** written to `.launchdoctor/` in your project. No badge service is involved and nothing is sent anywhere.
514
+ - **Scheduled monitoring (`init --monitor`):** the workflow runs on GitHub's servers and makes the same requests as the commands it runs (`npx`, the email DNS lookups, and `scan` when `LAUNCH_DOCTOR_URL` is set), then pushes its commit to the `launch-doctor-grades` branch of your repository.
475
515
  - **Package installation:** standard `npx` retrieval via the npm registry.
476
516
 
477
517
  ## What it cannot do
@@ -505,7 +545,7 @@ Launch Doctor is useful because it is fast and specific. That also means it has
505
545
  - **Basic:** Ruby, PHP and Go are scanned for hard-coded secrets and a few patterns, but their frameworks and dependency files are not understood.
506
546
 
507
547
  **It skips some files**
508
- - `node_modules`, `dist`, `build`, `out`, `coverage`, `vendor`, `venv`, `target`, `generated` and a few other build or dependency folders, and hidden folders other than `.github` (such as `.venv` and `.next`).
548
+ - `node_modules`, `dist`, `build`, `out`, `coverage`, `vendor`, `venv`, `target`, `generated` and a few other build or dependency folders, and hidden folders other than `.github` (such as `.venv`, `.next` and Launch Doctor's own `.launchdoctor`).
509
549
  - Files over 1 MB, minified `.min.js` files, source maps and binary files.
510
550
  - Everything after the first 20,000 files, or after 128 MB of text in total (the report says when either happens).
511
551
  - Symlinks, FIFOs and other special files.
@@ -514,7 +554,7 @@ For apps that handle significant money or sensitive personal or health data, use
514
554
 
515
555
  ## How it is tested
516
556
 
517
- - 334 automated tests run on every change, on Windows, macOS and Linux, with Node.js 22 and 24.
557
+ - 353 automated tests run on every change, on Windows, macOS and Linux, with Node.js 22 and 24.
518
558
  - A stress-test harness (`scripts/stress/`, see [CONTRIBUTING.md](CONTRIBUTING.md#stress-tests)) runs Launch Doctor against hostile inputs: repositories whose git settings try to run programs, symlink loops and FIFOs, files built to make a regular expression backtrack, terminal escape sequences, hostile servers for `scan`, and MCP requests to private addresses. Before 0.4.0 it found 10 security problems; each is fixed and has a regression test, and the whole suite now passes on Windows and Linux.
519
559
  - Every check that existed in 0.2 has been confirmed against a small project (or fake site) that contains exactly that problem, and every command in this README has been run (the `scan` examples against a local test site rather than a real one).
520
560
  - The features new in 0.3.0 (the GitHub Action, the MCP server, mobile apps, and Clerk, Convex, Appwrite, Paddle and Lemon Squeezy) have their own tests and were spot-checked by hand, which found and fixed two bugs before release. They have been tried less than the older checks. Posting pull request comments is tested against a fake GitHub API; it has not yet run on many real pull requests.
@@ -531,13 +571,14 @@ Meanwhile you can silence a finding with `.launchdoctorignore` or an inline `lau
531
571
 
532
572
  ## Roadmap
533
573
 
534
- Planned work, in no fixed order and without dates:
574
+ What comes next (the 0.5.0 engine rewrite, then milestones such as coverage reporting, more rules for the mistakes AI tools make, opt-in supply-chain and production-settings checks), and what is deliberately not planned, is in [docs/roadmap.md](docs/roadmap.md). Done so far:
535
575
 
536
576
  - [x] Live URL inspection (`launch-doctor scan <url>`: exposed `.env`, source maps, security headers, open Supabase tables via anonymous key)
537
577
  - [x] GitHub Action that posts a summary and inline fix prompts on pull requests ([Pull request comments](#pull-request-comments))
538
578
  - [x] Model Context Protocol (MCP) server for direct Claude Code and Cursor integration ([MCP server](#mcp-server))
539
579
  - [x] Extended provider coverage (Clerk, Convex, Appwrite, Lemon Squeezy, Paddle)
540
580
  - [x] Mobile framework support (Expo, React Native)
581
+ - [x] Grade history, a README badge and weekly monitoring ([Grade history and badge](#grade-history-and-badge), [Scheduled monitoring](#scheduled-monitoring))
541
582
 
542
583
  ## Using it as a library (experimental)
543
584
 
package/dist/src/cli.js CHANGED
@@ -6,12 +6,14 @@ import { changedFiles } from './changed.js';
6
6
  import { createDemoProject, removeOnSignal } from './demo.js';
7
7
  import { renderFixes } from './fixes.js';
8
8
  import { explainGitHubError, postPrFeedback, prContextFromEnv } from './github.js';
9
+ import { git } from './git.js';
9
10
  import { failingFindings } from './grade.js';
11
+ import { BADGE_FILE, describeEntry, entryFor, GRADES_FILE, headCommit, loadGrades, recordGrade, renderGradeTable, } from './grades.js';
10
12
  import { DEFAULT_HISTORY_DEPTH } from './history.js';
11
13
  import { runHook } from './hook.js';
12
14
  import { setupHooks } from './hooks-setup.js';
13
15
  import { CATEGORY_IDS, runDoctor } from './index.js';
14
- import { runInit } from './init.js';
16
+ import { badgeUrl, GRADES_BRANCH, githubRepo, runInit } from './init.js';
15
17
  import { runLiveScan } from './live.js';
16
18
  import { runMcpServer } from './mcp.js';
17
19
  import { assertConfigRef } from './project.js';
@@ -27,6 +29,8 @@ const HELP = `
27
29
  npx launch-doctor [folder] [options]
28
30
  npx launch-doctor init [folder] Create .launchdoctorignore and a GitHub Actions workflow
29
31
  npx launch-doctor init --hooks Set up hooks that check every AI edit and every commit
32
+ npx launch-doctor init --monitor Add a GitHub Actions workflow that re-checks the project every week
33
+ npx launch-doctor grades [folder] Show the grades saved with --record
30
34
  npx launch-doctor scan <url> Check your deployed site (exposed files, source maps, open Supabase tables, headers)
31
35
  npx launch-doctor mcp Start an MCP server so Claude Code, Cursor and other AI tools can run checks
32
36
 
@@ -46,6 +50,7 @@ const HELP = `
46
50
  --history-depth <n> How many commits --history reads (default 500)
47
51
  --update-baseline Save today's findings to .launchdoctor-baseline.json as accepted
48
52
  --no-baseline Ignore .launchdoctor-baseline.json and show every finding
53
+ --record Save the grade to .launchdoctor/grades.json and redraw .launchdoctor/badge.svg
49
54
  --config-from <ref> Read .launchdoctorignore and the baseline from this git ref (a branch,
50
55
  tag or commit) instead of the folder, and ignore inline ignore comments on
51
56
  lines changed since then. The GitHub Action uses it so a pull request
@@ -93,6 +98,7 @@ function parseArgs(argv) {
93
98
  baseline: true,
94
99
  history: false,
95
100
  historyDepth: DEFAULT_HISTORY_DEPTH,
101
+ record: false,
96
102
  demo: false,
97
103
  help: false,
98
104
  version: false,
@@ -125,6 +131,8 @@ function parseArgs(argv) {
125
131
  args.updateBaseline = true;
126
132
  else if (a === '--no-baseline')
127
133
  args.baseline = false;
134
+ else if (a === '--record')
135
+ args.record = true;
128
136
  else if (a === '--changed')
129
137
  args.changeMode = setChangeMode(args.changeMode, 'changed');
130
138
  else if (a === '--staged')
@@ -215,10 +223,13 @@ function fail(message) {
215
223
  }
216
224
  function init(argv) {
217
225
  const hooks = argv.includes('--hooks');
218
- const rest = argv.filter((a) => a !== '--hooks');
226
+ const monitor = argv.includes('--monitor');
227
+ const rest = argv.filter((a) => a !== '--hooks' && a !== '--monitor');
219
228
  const extra = rest.filter((a) => a.startsWith('-'));
220
229
  if (extra.length)
221
- fail(`init only takes --hooks (got ${extra.join(' ')})`);
230
+ fail(`init only takes --hooks or --monitor (got ${extra.join(' ')})`);
231
+ if (hooks && monitor)
232
+ fail('Run "init --hooks" and "init --monitor" one at a time');
222
233
  if (rest.length > 1)
223
234
  fail('init takes at most one folder');
224
235
  const root = resolve(rest[0] ?? '.');
@@ -237,11 +248,36 @@ function init(argv) {
237
248
  `);
238
249
  return;
239
250
  }
240
- const { created, skipped } = runInit(root);
251
+ const { created, skipped } = runInit(root, { monitor });
241
252
  for (const f of created)
242
253
  process.stdout.write(` created ${f}\n`);
243
254
  for (const f of skipped)
244
255
  process.stdout.write(` skipped ${f} ${dim('(already exists)')}\n`);
256
+ if (monitor && created.length) {
257
+ const repo = githubRepo(git(root, ['remote', 'get-url', 'origin'])) ?? undefined;
258
+ process.stdout.write(`\n It runs every Monday and keeps grades.json and badge.svg on the ${GRADES_BRANCH} branch\n` +
259
+ ` (never on your default branch). Show the grade in your README:\n` +
260
+ ` ![Launch Doctor grade](${badgeUrl(repo)})\n` +
261
+ ` ${dim('To check your deployed site too, add a repository variable named LAUNCH_DOCTOR_URL.')}\n`);
262
+ }
263
+ }
264
+ /** `launch-doctor grades [folder] [--json]`: the grades saved with --record, newest first. */
265
+ function grades(argv) {
266
+ const json = argv.includes('--json');
267
+ const rest = argv.filter((a) => a !== '--json');
268
+ const extra = rest.filter((a) => a.startsWith('-'));
269
+ if (extra.length)
270
+ fail(`grades only takes --json (got ${extra.join(' ')})`);
271
+ if (rest.length > 1)
272
+ fail('grades takes at most one folder');
273
+ const root = resolve(rest[0] ?? '.');
274
+ if (!existsSync(root) || !statSync(root).isDirectory())
275
+ fail(`Folder not found: ${root}`);
276
+ const entries = loadGrades(root);
277
+ if (json)
278
+ process.stdout.write(`${JSON.stringify(entries, null, 2)}\n`);
279
+ else
280
+ process.stdout.write(renderGradeTable(entries));
245
281
  }
246
282
  /** The JSON an AI tool sends to a hook on stdin. A terminal has nothing to send. */
247
283
  async function readStdin() {
@@ -443,6 +479,8 @@ async function main() {
443
479
  return mcp(process.argv.slice(3));
444
480
  if (process.argv[2] === 'hook')
445
481
  return hook(process.argv.slice(3));
482
+ if (process.argv[2] === 'grades')
483
+ return grades(process.argv.slice(3));
446
484
  const args = parseArgs(process.argv.slice(2));
447
485
  if (args.help) {
448
486
  process.stdout.write(HELP);
@@ -470,6 +508,13 @@ async function main() {
470
508
  const root = resolve(args.path ?? '.');
471
509
  if (!existsSync(root) || !statSync(root).isDirectory())
472
510
  fail(`Folder not found: ${root}`);
511
+ if (args.record) {
512
+ // A recorded grade is compared with the next one, so it has to be for the whole project.
513
+ if (args.demo)
514
+ fail('--record needs a real project folder, not --demo');
515
+ if (args.only || args.skip)
516
+ fail('--record saves the grade for the whole project, so leave out --only and --skip');
517
+ }
473
518
  if (args.configFrom) {
474
519
  if (args.updateBaseline)
475
520
  fail('--config-from reads the baseline from git, so it cannot be used with --update-baseline');
@@ -489,6 +534,7 @@ async function main() {
489
534
  [args.updateBaseline, '--update-baseline'],
490
535
  [args.prComment, '--pr-comment'],
491
536
  [args.history, '--history'],
537
+ [args.record, '--record'],
492
538
  ]) {
493
539
  if (on)
494
540
  fail(`${flag} reports on some files only, so it can't be used with ${name}`);
@@ -580,10 +626,25 @@ async function main() {
580
626
  writeStepOutputs(report);
581
627
  if (args.prComment)
582
628
  await commentOnPr(report, root);
629
+ // The last recorded grade, read before this run adds one. Not for a partial report or the demo.
630
+ const last = args.demo || onlyFiles || args.only || args.skip ? undefined : loadGrades(root).at(-1);
631
+ let recorded;
632
+ if (args.record) {
633
+ try {
634
+ recordGrade(root, entryFor(report, headCommit(root)));
635
+ recorded = `Recorded grade ${report.grade} in ${GRADES_FILE} and ${BADGE_FILE}.`;
636
+ }
637
+ catch (err) {
638
+ process.stderr.write(`\n ${dim(`Couldn't record the grade: ${err.message}`)}\n`);
639
+ process.exitCode = 2;
640
+ }
641
+ }
583
642
  if (args.json)
584
643
  process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
585
644
  else
586
- process.stdout.write(renderReport(report, { fixFile }));
645
+ process.stdout.write(renderReport(report, { fixFile, lastRecorded: last && describeEntry(last) }));
646
+ if (recorded)
647
+ (args.json ? process.stderr : process.stdout).write(` ${dim(recorded)}\n\n`);
587
648
  if (args.ci && failingFindings(report, args.failOn).length > 0)
588
649
  process.exitCode = 1;
589
650
  }
@@ -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
+ }
@@ -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;
package/dist/src/live.js CHANGED
@@ -2,6 +2,7 @@ import { emptyOutput, notApplicable } from './checks/common.js';
2
2
  import { matchKeys } from './checks/secrets.js';
3
3
  import { overall, scoreCategory, toGrade } from './grade.js';
4
4
  import { checkHost, defaultLookup } from './net-guard.js';
5
+ import { pinnedGet } from './pinned-http.js';
5
6
  import { sanitizeReport } from './sanitize.js';
6
7
  import { decodeJwtPayload, mask, plural } from './util.js';
7
8
  import { version } from './version.js';
@@ -46,13 +47,56 @@ export function parseTarget(input) {
46
47
  function isLocal(url) {
47
48
  return /^(localhost|127\.\d+\.\d+\.\d+|\[::1\]|0\.0\.0\.0)$/.test(url.hostname);
48
49
  }
50
+ function fetchTransport(f) {
51
+ return async (req) => {
52
+ const res = await f(req.url.href, {
53
+ method: 'GET',
54
+ redirect: 'manual',
55
+ signal: AbortSignal.timeout(req.timeoutMs),
56
+ headers: req.headers,
57
+ });
58
+ if (req.skipRedirectBody && res.status >= 300 && res.status < 400 && res.headers.get('location')) {
59
+ await res.body?.cancel().catch(() => { });
60
+ return { status: res.status, headers: res.headers, body: '' };
61
+ }
62
+ return { status: res.status, headers: res.headers, body: await readCapped(res, req.maxBytes) };
63
+ };
64
+ }
49
65
  class Fetcher {
50
66
  opts;
51
67
  requests = 0;
52
68
  /** Requests not sent because they would have reached a private or local address. */
53
69
  blocked = [];
70
+ transport;
54
71
  constructor(opts) {
55
72
  this.opts = opts;
73
+ this.transport = opts.fetch ? fetchTransport(opts.fetch) : pinnedGet;
74
+ }
75
+ /**
76
+ * The addresses a request to `url` may connect to, or null when it must not be sent. Each hop is checked once and
77
+ * the connection is pinned to what was checked, so DNS can't hand the connection a different address.
78
+ */
79
+ async addressesFor(url) {
80
+ const host = await checkHost(url, this.opts.lookup);
81
+ if (host.kind === 'unresolved')
82
+ return null;
83
+ if (host.kind === 'private') {
84
+ if (!this.opts.allowPrivate) {
85
+ this.blocked.push(host.reason);
86
+ return null;
87
+ }
88
+ if (host.addresses)
89
+ return host.addresses;
90
+ // localhost and friends: you chose to scan this computer, so ask DNS (or the hosts file) where it is.
91
+ try {
92
+ const local = await this.opts.lookup(url.hostname);
93
+ return local.length ? local : null;
94
+ }
95
+ catch {
96
+ return null;
97
+ }
98
+ }
99
+ return host.addresses;
56
100
  }
57
101
  /**
58
102
  * One GET. Returns null when the site can't be reached. Never throws. Redirects are followed here, one hop at a
@@ -70,33 +114,26 @@ class Fetcher {
70
114
  }
71
115
  if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')
72
116
  return null;
73
- if (!this.opts.allowPrivate) {
74
- const host = await checkHost(parsed, this.opts.lookup);
75
- if (host.kind === 'private')
76
- this.blocked.push(host.reason);
77
- if (host.kind !== 'public')
78
- return null;
79
- }
117
+ const addresses = await this.addressesFor(parsed);
118
+ if (!addresses)
119
+ return null;
80
120
  this.requests++;
81
121
  try {
82
- const res = await this.opts.fetch(current, {
83
- method: 'GET',
84
- redirect: 'manual',
85
- signal: AbortSignal.timeout(this.opts.timeoutMs),
122
+ const follow = init.follow !== false;
123
+ const res = await this.transport({
124
+ url: parsed,
125
+ addresses,
86
126
  headers: { 'user-agent': USER_AGENT, accept: '*/*', ...init.headers },
127
+ timeoutMs: this.opts.timeoutMs,
128
+ maxBytes: this.opts.maxBytes,
129
+ skipRedirectBody: follow,
87
130
  });
88
131
  const location = res.headers.get('location');
89
- if (init.follow !== false && res.status >= 300 && res.status < 400 && location) {
90
- await res.body?.cancel().catch(() => { });
132
+ if (follow && res.status >= 300 && res.status < 400 && location) {
91
133
  current = new URL(location, current).href;
92
134
  continue;
93
135
  }
94
- return {
95
- url: current,
96
- status: res.status,
97
- headers: res.headers,
98
- body: await readCapped(res, this.opts.maxBytes),
99
- };
136
+ return { url: current, status: res.status, headers: res.headers, body: res.body };
100
137
  }
101
138
  catch {
102
139
  return null;
@@ -498,7 +535,7 @@ export async function runLiveScan(input, options = {}) {
498
535
  const fetcher = new Fetcher({
499
536
  timeoutMs: options.timeoutMs ?? 10_000,
500
537
  maxBytes: options.maxBytes ?? 3_000_000,
501
- fetch: options.fetch ?? fetch,
538
+ fetch: options.fetch,
502
539
  lookup,
503
540
  // A scan you start at a private address (your own dev server) stays usable; one that starts on a public site
504
541
  // never reaches a private address.
@@ -9,21 +9,29 @@
9
9
  * Alternate spellings of an IPv4 address (2130706433, 0x7f000001, 0177.0.0.1, 127.1) need no extra handling here:
10
10
  * the URL parser turns them all into "127.0.0.1" before this code sees the host.
11
11
  *
12
- * Known gap (see SECURITY.md): fetch resolves the name again when it connects, so a DNS server that answers with a
13
- * public address to the check and a private one to the connection (DNS rebinding) can get past it.
12
+ * The check returns the addresses it approved, and the live scan connects only to those (see pinned-http.ts), so a
13
+ * DNS server that answers with a public address to the check and a private one to the connection (DNS rebinding)
14
+ * gets nowhere: the name is never resolved a second time.
14
15
  */
15
- export type Lookup = (host: string) => Promise<{
16
+ export interface ResolvedAddress {
16
17
  address: string;
17
18
  family: number;
18
- }[]>;
19
+ }
20
+ export type Lookup = (host: string) => Promise<ResolvedAddress[]>;
19
21
  export declare const defaultLookup: Lookup;
20
22
  /** Is this literal IP address one anyone on the internet could reach? Null when `text` isn't an IP address. */
21
23
  export declare function isPublicAddress(text: string): boolean | null;
22
- export type HostCheck = {
24
+ export type HostCheck =
25
+ /** `addresses` are the ones that were checked: a request must connect to one of them and nothing else. */
26
+ {
23
27
  kind: 'public';
24
- } | {
28
+ addresses: ResolvedAddress[];
29
+ }
30
+ /** `addresses` is missing for names that always mean this computer (localhost), which are not looked up. */
31
+ | {
25
32
  kind: 'private';
26
33
  reason: string;
34
+ addresses?: ResolvedAddress[];
27
35
  }
28
36
  /** The name doesn't resolve, so no request can reach it. */
29
37
  | {
@@ -124,10 +124,13 @@ export async function checkHost(url, lookup = defaultLookup) {
124
124
  if (isLocalName(host))
125
125
  return { kind: 'private', reason: `${host} is this computer` };
126
126
  const literal = isPublicAddress(host);
127
- if (literal === false)
128
- return { kind: 'private', reason: `${host} is a private or local network address` };
129
- if (literal === true)
130
- return { kind: 'public' };
127
+ if (literal !== null) {
128
+ const bare = host.replace(/^\[|\]$/g, '');
129
+ const addresses = [{ address: bare, family: bare.includes(':') ? 6 : 4 }];
130
+ return literal
131
+ ? { kind: 'public', addresses }
132
+ : { kind: 'private', reason: `${host} is a private or local network address`, addresses };
133
+ }
131
134
  let addresses;
132
135
  try {
133
136
  addresses = await lookup(host);
@@ -139,6 +142,6 @@ export async function checkHost(url, lookup = defaultLookup) {
139
142
  return { kind: 'unresolved', reason: `${host} could not be resolved` };
140
143
  const bad = addresses.find((a) => isPublicAddress(a.address) !== true);
141
144
  return bad
142
- ? { kind: 'private', reason: `${host} resolves to ${bad.address}, a private or local network address` }
143
- : { kind: 'public' };
145
+ ? { kind: 'private', reason: `${host} resolves to ${bad.address}, a private or local network address`, addresses }
146
+ : { kind: 'public', addresses };
144
147
  }
@@ -0,0 +1,31 @@
1
+ import { type LookupFunction } from 'node:net';
2
+ import type { ResolvedAddress } from './net-guard.js';
3
+ /**
4
+ * One GET for the live scan, connecting only to addresses that were already checked.
5
+ *
6
+ * `fetch` resolves a host name again when it connects, so a DNS server could answer the check with a public address
7
+ * and the connection with a private one (DNS rebinding). Here the request is made with node:http or node:https and a
8
+ * `lookup` that never asks DNS: it hands back the checked addresses and nothing else. The URL's host name is still
9
+ * used for the Host header, and for TLS (the server name and the certificate check), so HTTPS works as before.
10
+ */
11
+ export interface PinnedRequest {
12
+ url: URL;
13
+ /** The checked addresses for `url`'s host. The connection goes to one of these, never anywhere else. */
14
+ addresses: ResolvedAddress[];
15
+ headers: Record<string, string>;
16
+ /** For the whole request, body included. */
17
+ timeoutMs: number;
18
+ /** Stop reading the (decompressed) body after this many bytes. */
19
+ maxBytes: number;
20
+ /** Don't read the body of a redirect that will be followed. */
21
+ skipRedirectBody: boolean;
22
+ }
23
+ export interface RawReply {
24
+ status: number;
25
+ headers: Headers;
26
+ body: string;
27
+ }
28
+ /** A `lookup` for one request that only ever returns `addresses`. */
29
+ export declare function pinnedLookup(addresses: ResolvedAddress[]): LookupFunction;
30
+ /** Rejects when the site can't be reached, times out or sends a broken body. */
31
+ export declare function pinnedGet(req: PinnedRequest): Promise<RawReply>;
@@ -0,0 +1,104 @@
1
+ import { request as httpRequest } from 'node:http';
2
+ import { request as httpsRequest } from 'node:https';
3
+ import { isIP } from 'node:net';
4
+ import { createBrotliDecompress, createGunzip, createInflate } from 'node:zlib';
5
+ /** A `lookup` for one request that only ever returns `addresses`. */
6
+ export function pinnedLookup(addresses) {
7
+ return (_hostname, options, callback) => {
8
+ const family = options?.family === 4 || options?.family === 6 ? options.family : undefined;
9
+ const list = family ? addresses.filter((a) => a.family === family) : addresses;
10
+ if (!list.length) {
11
+ const err = new Error('No checked address for this request');
12
+ err.code = 'ENOTFOUND';
13
+ callback(err, '', 0);
14
+ return;
15
+ }
16
+ if (options?.all)
17
+ callback(null, list);
18
+ else
19
+ callback(null, list[0].address, list[0].family);
20
+ };
21
+ }
22
+ function toHeaders(res) {
23
+ const headers = new Headers();
24
+ for (const [name, value] of Object.entries(res.headers)) {
25
+ for (const v of Array.isArray(value) ? value : value === undefined ? [] : [value]) {
26
+ try {
27
+ headers.append(name, v);
28
+ }
29
+ catch {
30
+ // a value the Headers class refuses is left out
31
+ }
32
+ }
33
+ }
34
+ return headers;
35
+ }
36
+ function decoded(res) {
37
+ const encoding = (res.headers['content-encoding'] ?? '').trim().toLowerCase();
38
+ if (encoding === 'gzip' || encoding === 'x-gzip')
39
+ return res.pipe(createGunzip());
40
+ if (encoding === 'deflate')
41
+ return res.pipe(createInflate());
42
+ if (encoding === 'br')
43
+ return res.pipe(createBrotliDecompress());
44
+ return res;
45
+ }
46
+ /** Rejects when the site can't be reached, times out or sends a broken body. */
47
+ export function pinnedGet(req) {
48
+ const { url } = req;
49
+ const host = url.hostname.replace(/^\[|\]$/g, '');
50
+ const send = url.protocol === 'https:' ? httpsRequest : httpRequest;
51
+ return new Promise((resolve, reject) => {
52
+ let settled = false;
53
+ const finish = (err, reply) => {
54
+ if (settled)
55
+ return;
56
+ settled = true;
57
+ clearTimeout(timer);
58
+ if (err)
59
+ reject(err);
60
+ else
61
+ resolve(reply);
62
+ };
63
+ const request = send({
64
+ protocol: url.protocol,
65
+ host,
66
+ port: url.port || undefined,
67
+ path: `${url.pathname}${url.search}`,
68
+ method: 'GET',
69
+ headers: { ...req.headers, 'accept-encoding': 'gzip, deflate, br' },
70
+ lookup: pinnedLookup(req.addresses),
71
+ // No shared agent: a pooled connection could have been made to another address for the same name.
72
+ agent: false,
73
+ // TLS checks the certificate against the host name, never the address. An IP address has no server name.
74
+ servername: isIP(host) ? undefined : host,
75
+ }, (res) => {
76
+ const status = res.statusCode ?? 0;
77
+ const headers = toHeaders(res);
78
+ if (req.skipRedirectBody && status >= 300 && status < 400 && res.headers.location) {
79
+ res.destroy();
80
+ finish(null, { status, headers, body: '' });
81
+ return;
82
+ }
83
+ const body = decoded(res);
84
+ const chunks = [];
85
+ let size = 0;
86
+ const done = () => finish(null, { status, headers, body: Buffer.concat(chunks).toString('utf8') });
87
+ body.on('data', (chunk) => {
88
+ chunks.push(chunk);
89
+ size += chunk.length;
90
+ if (size >= req.maxBytes) {
91
+ done();
92
+ res.destroy();
93
+ body.destroy();
94
+ }
95
+ });
96
+ body.on('end', done);
97
+ body.on('error', (err) => finish(err));
98
+ res.on('error', (err) => finish(err));
99
+ });
100
+ const timer = setTimeout(() => request.destroy(new Error('The request timed out')), req.timeoutMs);
101
+ request.on('error', (err) => finish(err));
102
+ request.end();
103
+ });
104
+ }
@@ -7,4 +7,6 @@ export declare const BYTE_LIMIT_NOTE = "Very large project: only the first 128 M
7
7
  export declare function nestedReposNote(repos: string[]): string;
8
8
  export declare function renderReport(report: Report, opts?: {
9
9
  fixFile?: string;
10
+ /** The last recorded grade ("B (82) on 30 Nov 2026"), shown under the overall grade. */
11
+ lastRecorded?: string;
10
12
  }): string;
@@ -98,6 +98,8 @@ export function renderReport(report, opts = {}) {
98
98
  lines.push(` ${dim(nestedReposNote(report.nestedRepos))}`);
99
99
  lines.push('');
100
100
  lines.push(` ${bold('Overall grade')} ${badge(report.grade)} ${report.verdict}`);
101
+ if (opts.lastRecorded)
102
+ lines.push(` ${dim(`Last recorded grade: ${opts.lastRecorded}`)}`);
101
103
  lines.push('');
102
104
  const nameWidth = Math.max(...report.categories.map((c) => c.name.length)) + 2;
103
105
  for (const c of report.categories) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "launch-doctor",
3
- "version": "0.4.0",
3
+ "version": "0.4.1",
4
4
  "description": "A pre-launch checkup for vibe-coded apps. Grades your project A-F on secrets, database safety, payments, AI costs, email, error tracking, legal pages and first impressions, with a copy-paste fix prompt for every issue.",
5
5
  "type": "module",
6
6
  "bin": {