launch-doctor 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/CHANGELOG.md +92 -6
  2. package/LICENSE +1 -0
  3. package/README.md +138 -22
  4. package/dist/src/access.d.ts +52 -0
  5. package/dist/src/access.js +482 -0
  6. package/dist/src/baseline.d.ts +6 -3
  7. package/dist/src/baseline.js +15 -8
  8. package/dist/src/changed.d.ts +12 -0
  9. package/dist/src/changed.js +34 -0
  10. package/dist/src/checks/access.d.ts +7 -0
  11. package/dist/src/checks/access.js +868 -0
  12. package/dist/src/checks/costs.d.ts +7 -0
  13. package/dist/src/checks/costs.js +14 -6
  14. package/dist/src/checks/database.js +79 -3
  15. package/dist/src/checks/first-impressions.js +22 -2
  16. package/dist/src/checks/legal.js +3 -1
  17. package/dist/src/checks/monitoring.js +8 -5
  18. package/dist/src/checks/payments.js +10 -2
  19. package/dist/src/checks/secrets.d.ts +8 -0
  20. package/dist/src/checks/secrets.js +82 -9
  21. package/dist/src/checks/supabase-storage.d.ts +31 -0
  22. package/dist/src/checks/supabase-storage.js +216 -0
  23. package/dist/src/cli.js +175 -12
  24. package/dist/src/demo.js +1 -0
  25. package/dist/src/detect.d.ts +1 -1
  26. package/dist/src/detect.js +1 -1
  27. package/dist/src/fixes.js +8 -5
  28. package/dist/src/git.d.ts +25 -0
  29. package/dist/src/git.js +121 -0
  30. package/dist/src/github.d.ts +11 -1
  31. package/dist/src/github.js +56 -14
  32. package/dist/src/grades.d.ts +42 -0
  33. package/dist/src/grades.js +163 -0
  34. package/dist/src/history.js +17 -3
  35. package/dist/src/hook.d.ts +13 -0
  36. package/dist/src/hook.js +96 -0
  37. package/dist/src/hooks-setup.d.ts +24 -0
  38. package/dist/src/hooks-setup.js +187 -0
  39. package/dist/src/ignore.d.ts +36 -0
  40. package/dist/src/ignore.js +164 -0
  41. package/dist/src/index.js +28 -3
  42. package/dist/src/init.d.ts +32 -2
  43. package/dist/src/init.js +120 -6
  44. package/dist/src/live.d.ts +13 -1
  45. package/dist/src/live.js +111 -23
  46. package/dist/src/mcp.js +7 -2
  47. package/dist/src/net-guard.d.ts +42 -0
  48. package/dist/src/net-guard.js +147 -0
  49. package/dist/src/pinned-http.d.ts +31 -0
  50. package/dist/src/pinned-http.js +104 -0
  51. package/dist/src/project.d.ts +34 -5
  52. package/dist/src/project.js +145 -111
  53. package/dist/src/report.d.ts +4 -0
  54. package/dist/src/report.js +13 -0
  55. package/dist/src/routes.d.ts +10 -0
  56. package/dist/src/routes.js +21 -4
  57. package/dist/src/safe-fs.d.ts +19 -0
  58. package/dist/src/safe-fs.js +77 -0
  59. package/dist/src/sanitize.d.ts +17 -0
  60. package/dist/src/sanitize.js +90 -0
  61. package/dist/src/sarif.js +1 -1
  62. package/dist/src/summary.d.ts +4 -0
  63. package/dist/src/summary.js +9 -4
  64. package/dist/src/types.d.ts +24 -0
  65. package/dist/src/util.d.ts +1 -1
  66. package/dist/src/util.js +1 -1
  67. package/package.json +9 -5
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);
@@ -1,3 +1,4 @@
1
+ import { type Lookup } from './net-guard.js';
1
2
  import type { Report } from './types.js';
2
3
  /** Ids of every finding a live scan can produce (for docs and tests). */
3
4
  export declare const LIVE_IDS: readonly ['live-unreachable-https', 'live-no-https', 'live-http-no-redirect', 'live-exposed-env', 'live-exposed-git', 'live-exposed-backup', 'live-source-maps', 'live-secret-in-bundle', 'live-supabase-service-role', 'live-supabase-open-table', 'live-missing-hsts', 'live-missing-csp', 'live-missing-basic-headers'];
@@ -8,8 +9,19 @@ export interface LiveOptions {
8
9
  maxBytes?: number;
9
10
  /** Don't send the anonymous-key requests to Supabase (default false). */
10
11
  skipDatabase?: boolean;
11
- /** 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
+ */
12
16
  fetch?: typeof fetch;
17
+ /** Replacement for the DNS lookup used to check each host before a request (tests). */
18
+ lookup?: Lookup;
19
+ /**
20
+ * May the address you give be on a private or local network (your own dev server, for example)? Default true,
21
+ * as for the CLI. The MCP server sets it to false. Either way, a scan that starts on a public site never sends
22
+ * a request to a private address, through a script, a source map or a redirect.
23
+ */
24
+ allowPrivateTarget?: boolean;
13
25
  }
14
26
  /** "myapp.com" or "https://myapp.com/x" -> a URL object. Throws a friendly error for anything else. */
15
27
  export declare function parseTarget(input: string): URL;
package/dist/src/live.js CHANGED
@@ -1,6 +1,9 @@
1
1
  import { emptyOutput, notApplicable } from './checks/common.js';
2
2
  import { matchKeys } from './checks/secrets.js';
3
3
  import { overall, scoreCategory, toGrade } from './grade.js';
4
+ import { checkHost, defaultLookup } from './net-guard.js';
5
+ import { pinnedGet } from './pinned-http.js';
6
+ import { sanitizeReport } from './sanitize.js';
4
7
  import { decodeJwtPayload, mask, plural } from './util.js';
5
8
  import { version } from './version.js';
6
9
  /** Ids of every finding a live scan can produce (for docs and tests). */
@@ -19,9 +22,11 @@ export const LIVE_IDS = [
19
22
  'live-missing-csp',
20
23
  'live-missing-basic-headers',
21
24
  ];
25
+ /** Redirects followed for one request. */
26
+ const MAX_REDIRECTS = 5;
22
27
  const MAX_SCRIPTS = 20;
23
28
  const MAX_TABLES = 25;
24
- const USER_AGENT = `launch-doctor/${version()} (+https://github.com/SHARAJ379/launch-doctor)`;
29
+ const USER_AGENT = `launch-doctor/${version()} (+https://github.com/SHARAJ379/Launch-Doctor)`;
25
30
  /** "myapp.com" or "https://myapp.com/x" -> a URL object. Throws a friendly error for anything else. */
26
31
  export function parseTarget(input) {
27
32
  const text = input.trim();
@@ -42,32 +47,99 @@ export function parseTarget(input) {
42
47
  function isLocal(url) {
43
48
  return /^(localhost|127\.\d+\.\d+\.\d+|\[::1\]|0\.0\.0\.0)$/.test(url.hostname);
44
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
+ }
45
65
  class Fetcher {
46
66
  opts;
47
67
  requests = 0;
68
+ /** Requests not sent because they would have reached a private or local address. */
69
+ blocked = [];
70
+ transport;
48
71
  constructor(opts) {
49
72
  this.opts = opts;
73
+ this.transport = opts.fetch ? fetchTransport(opts.fetch) : pinnedGet;
50
74
  }
51
- /** One GET. Returns null when the site can't be reached. Never throws. */
52
- async get(url, init = {}) {
53
- this.requests++;
54
- try {
55
- const res = await this.opts.fetch(url, {
56
- method: 'GET',
57
- redirect: init.follow === false ? 'manual' : 'follow',
58
- signal: AbortSignal.timeout(this.opts.timeoutMs),
59
- headers: { 'user-agent': USER_AGENT, accept: '*/*', ...init.headers },
60
- });
61
- return {
62
- url: res.url || url,
63
- status: res.status,
64
- headers: res.headers,
65
- body: await readCapped(res, this.opts.maxBytes),
66
- };
67
- }
68
- catch {
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')
69
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;
100
+ }
101
+ /**
102
+ * One GET. Returns null when the site can't be reached. Never throws. Redirects are followed here, one hop at a
103
+ * time, so every address is checked before anything is sent to it.
104
+ */
105
+ async get(url, init = {}) {
106
+ let current = url;
107
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
108
+ let parsed;
109
+ try {
110
+ parsed = new URL(current);
111
+ }
112
+ catch {
113
+ return null;
114
+ }
115
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')
116
+ return null;
117
+ const addresses = await this.addressesFor(parsed);
118
+ if (!addresses)
119
+ return null;
120
+ this.requests++;
121
+ try {
122
+ const follow = init.follow !== false;
123
+ const res = await this.transport({
124
+ url: parsed,
125
+ addresses,
126
+ headers: { 'user-agent': USER_AGENT, accept: '*/*', ...init.headers },
127
+ timeoutMs: this.opts.timeoutMs,
128
+ maxBytes: this.opts.maxBytes,
129
+ skipRedirectBody: follow,
130
+ });
131
+ const location = res.headers.get('location');
132
+ if (follow && res.status >= 300 && res.status < 400 && location) {
133
+ current = new URL(location, current).href;
134
+ continue;
135
+ }
136
+ return { url: current, status: res.status, headers: res.headers, body: res.body };
137
+ }
138
+ catch {
139
+ return null;
140
+ }
70
141
  }
142
+ return null; // too many redirects
71
143
  }
72
144
  }
73
145
  async function readCapped(res, maxBytes) {
@@ -201,7 +273,7 @@ const PROBES = [
201
273
  path: '/.git/config',
202
274
  id: 'live-exposed-git',
203
275
  what: 'your git settings (.git/config)',
204
- valid: (b) => /^\s*\[core\]/m.test(b),
276
+ valid: (b) => /^[ \t]*\[core\]/m.test(b),
205
277
  },
206
278
  {
207
279
  path: '/.git/HEAD',
@@ -455,13 +527,24 @@ function capitalize(s) {
455
527
  // ---------------------------------------------------------------------------
456
528
  export async function runLiveScan(input, options = {}) {
457
529
  const target = parseTarget(input);
530
+ const lookup = options.lookup ?? defaultLookup;
531
+ const targetHost = await checkHost(target, lookup);
532
+ if (targetHost.kind === 'private' && options.allowPrivateTarget === false) {
533
+ throw new Error(`Only public sites can be scanned here: ${targetHost.reason}.`);
534
+ }
458
535
  const fetcher = new Fetcher({
459
536
  timeoutMs: options.timeoutMs ?? 10_000,
460
537
  maxBytes: options.maxBytes ?? 3_000_000,
461
- fetch: options.fetch ?? fetch,
538
+ fetch: options.fetch,
539
+ lookup,
540
+ // A scan you start at a private address (your own dev server) stays usable; one that starts on a public site
541
+ // never reaches a private address.
542
+ allowPrivate: targetHost.kind === 'private',
462
543
  });
463
544
  const home = await fetcher.get(target.href);
464
545
  if (!home) {
546
+ if (fetcher.blocked.length)
547
+ throw new Error(`${target.origin} redirected to ${fetcher.blocked[0]}, so it wasn't scanned.`);
465
548
  throw new Error(`Couldn't reach ${target.origin}. Check the address and that the site is online.`);
466
549
  }
467
550
  if (home.status >= 500)
@@ -491,7 +574,12 @@ export async function runLiveScan(input, options = {}) {
491
574
  grade: score === null ? null : toGrade(score),
492
575
  });
493
576
  }
494
- return {
577
+ if (fetcher.blocked.length) {
578
+ const hosts = [...new Set(fetcher.blocked.map((b) => b.split(' ')[0]))].slice(0, 3).join(', ');
579
+ categories[0].passed.push(`Skipped ${plural(fetcher.blocked.length, 'request')} to private or local network addresses (${hosts}) that this public site pointed to`);
580
+ }
581
+ // Text from the site (table names, paths) can hold terminal escape sequences; none reach any output.
582
+ return sanitizeReport({
495
583
  tool: 'launch-doctor',
496
584
  version: version(),
497
585
  mode: 'live',
@@ -505,5 +593,5 @@ export async function runLiveScan(input, options = {}) {
505
593
  ...overall(categories),
506
594
  categories,
507
595
  generatedAt: new Date().toISOString(),
508
- };
596
+ });
509
597
  }
package/dist/src/mcp.js CHANGED
@@ -5,7 +5,7 @@ import { shortWhere } from './checks/common.js';
5
5
  import { DEFAULT_HISTORY_DEPTH } from './history.js';
6
6
  import { CHECKS, runDoctor } from './index.js';
7
7
  import { runLiveScan } from './live.js';
8
- import { nestedReposNote } from './report.js';
8
+ import { BYTE_LIMIT_NOTE, nestedReposNote } from './report.js';
9
9
  import { plural } from './util.js';
10
10
  import { version } from './version.js';
11
11
  /**
@@ -140,6 +140,8 @@ export function reportText(report, includeBaseline = false) {
140
140
  lines.push(nestedReposNote(report.nestedRepos));
141
141
  if (report.truncated)
142
142
  lines.push('Very large project: only the first 20,000 files were checked.');
143
+ if (report.byteLimitReached)
144
+ lines.push(BYTE_LIMIT_NOTE);
143
145
  lines.push(...listSection('Critical', shown.filter((f) => f.severity === 'critical'), (f, n) => findingEntry(n, f)), ...listSection('Warnings', shown.filter((f) => f.severity === 'warning'), (f, n) => findingEntry(n, f)), ...listSection('Check by hand, outside the code', manual, (m, n) => `${n}. ${m.title} · id: ${m.id}\n${indent(m.how)}`));
144
146
  if (!shown.length) {
145
147
  lines.push('', hiddenBaseline
@@ -256,7 +258,10 @@ async function scanUrl(args) {
256
258
  if (typeof args.url !== 'string' || !args.url.trim())
257
259
  return toolError('"url" is required, for example https://myapp.com.');
258
260
  try {
259
- return reportResult(await runLiveScan(args.url, { skipDatabase: args.skipDatabase === true }), false);
261
+ // An AI tool decides what to scan here, and a prompt injection could aim it at your network, so only public
262
+ // sites are allowed. The CLI (where you type the address yourself) also accepts your own dev server.
263
+ const report = await runLiveScan(args.url, { skipDatabase: args.skipDatabase === true, allowPrivateTarget: false });
264
+ return reportResult(report, false);
260
265
  }
261
266
  catch (err) {
262
267
  return toolError(err.message);
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Which addresses a live scan may connect to.
3
+ *
4
+ * A deployed site decides which URLs the scanner requests next (its script tags, source maps and redirects), so a
5
+ * public site could otherwise point the scanner at the cloud metadata address, a router or a service on your own
6
+ * machine. Every request is checked first: its host name is resolved, and the request is refused unless every
7
+ * address it resolves to is public.
8
+ *
9
+ * Alternate spellings of an IPv4 address (2130706433, 0x7f000001, 0177.0.0.1, 127.1) need no extra handling here:
10
+ * the URL parser turns them all into "127.0.0.1" before this code sees the host.
11
+ *
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.
15
+ */
16
+ export interface ResolvedAddress {
17
+ address: string;
18
+ family: number;
19
+ }
20
+ export type Lookup = (host: string) => Promise<ResolvedAddress[]>;
21
+ export declare const defaultLookup: Lookup;
22
+ /** Is this literal IP address one anyone on the internet could reach? Null when `text` isn't an IP address. */
23
+ export declare function isPublicAddress(text: string): boolean | null;
24
+ export type HostCheck =
25
+ /** `addresses` are the ones that were checked: a request must connect to one of them and nothing else. */
26
+ {
27
+ kind: 'public';
28
+ addresses: ResolvedAddress[];
29
+ }
30
+ /** `addresses` is missing for names that always mean this computer (localhost), which are not looked up. */
31
+ | {
32
+ kind: 'private';
33
+ reason: string;
34
+ addresses?: ResolvedAddress[];
35
+ }
36
+ /** The name doesn't resolve, so no request can reach it. */
37
+ | {
38
+ kind: 'unresolved';
39
+ reason: string;
40
+ };
41
+ /** Is `url`'s host public (every address it resolves to is public), private, or not resolvable? Never throws. */
42
+ export declare function checkHost(url: URL, lookup?: Lookup): Promise<HostCheck>;
@@ -0,0 +1,147 @@
1
+ import { lookup as dnsLookup } from 'node:dns/promises';
2
+ export const defaultLookup = (host) => dnsLookup(host, { all: true, verbatim: true });
3
+ function parseIPv4(text) {
4
+ const parts = text.split('.');
5
+ if (parts.length !== 4)
6
+ return null;
7
+ const out = [];
8
+ for (const p of parts) {
9
+ if (!/^\d{1,3}$/.test(p))
10
+ return null;
11
+ const n = Number(p);
12
+ if (n > 255)
13
+ return null;
14
+ out.push(n);
15
+ }
16
+ return out;
17
+ }
18
+ /** The 8 groups of an IPv6 address (a trailing dotted IPv4 part included), or null if it isn't one. */
19
+ function parseIPv6(text) {
20
+ let s = text.replace(/^\[|\]$/g, '').toLowerCase();
21
+ const zone = s.indexOf('%');
22
+ if (zone >= 0)
23
+ s = s.slice(0, zone);
24
+ if (!s.includes(':'))
25
+ return null;
26
+ let tail = [];
27
+ const lastColon = s.lastIndexOf(':');
28
+ if (s.slice(lastColon + 1).includes('.')) {
29
+ const v4 = parseIPv4(s.slice(lastColon + 1));
30
+ if (!v4)
31
+ return null;
32
+ tail = [(v4[0] << 8) | v4[1], (v4[2] << 8) | v4[3]];
33
+ s = `${s.slice(0, lastColon + 1)}0:0`;
34
+ }
35
+ const halves = s.split('::');
36
+ if (halves.length > 2)
37
+ return null;
38
+ const group = (h) => (h ? h.split(':') : []);
39
+ const head = group(halves[0]);
40
+ const rest = halves.length === 2 ? group(halves[1]) : [];
41
+ const missing = 8 - head.length - rest.length;
42
+ if (halves.length === 2 ? missing < 1 : missing !== 0)
43
+ return null;
44
+ const all = [...head, ...Array(halves.length === 2 ? missing : 0).fill('0'), ...rest];
45
+ const out = [];
46
+ for (const g of all) {
47
+ if (!/^[0-9a-f]{1,4}$/.test(g))
48
+ return null;
49
+ out.push(Number.parseInt(g, 16));
50
+ }
51
+ if (tail.length)
52
+ out.splice(6, 2, ...tail);
53
+ return out;
54
+ }
55
+ function isPublicIPv4([a, b, c]) {
56
+ if (a === 0 || a === 10 || a === 127)
57
+ return false; // "this network", private, loopback
58
+ if (a === 100 && b >= 64 && b <= 127)
59
+ return false; // carrier-grade NAT (100.64.0.0/10)
60
+ if (a === 169 && b === 254)
61
+ return false; // link-local, including the cloud metadata address
62
+ if (a === 172 && b >= 16 && b <= 31)
63
+ return false; // private
64
+ if (a === 192 && b === 168)
65
+ return false; // private
66
+ if (a === 192 && b === 0 && (c === 0 || c === 2))
67
+ return false; // IETF protocol assignments, documentation
68
+ if (a === 198 && (b === 18 || b === 19))
69
+ return false; // benchmarking
70
+ if (a === 198 && b === 51 && c === 100)
71
+ return false; // documentation
72
+ if (a === 203 && b === 0 && c === 113)
73
+ return false; // documentation
74
+ if (a >= 224)
75
+ return false; // multicast, reserved, broadcast
76
+ return true;
77
+ }
78
+ function isPublicIPv6(g) {
79
+ const v4 = (hi, lo) => [hi >> 8, hi & 255, lo >> 8, lo & 255];
80
+ if (g.every((x) => x === 0))
81
+ return false; // ::
82
+ if (g.slice(0, 7).every((x) => x === 0) && g[7] === 1)
83
+ return false; // ::1
84
+ if (g.slice(0, 5).every((x) => x === 0) && g[5] === 0xffff)
85
+ return isPublicIPv4(v4(g[6], g[7])); // ::ffff:a.b.c.d
86
+ if (g.slice(0, 6).every((x) => x === 0))
87
+ return isPublicIPv4(v4(g[6], g[7])); // ::a.b.c.d (deprecated)
88
+ if (g[0] === 0x64 && g[1] === 0xff9b && g.slice(2, 6).every((x) => x === 0))
89
+ return isPublicIPv4(v4(g[6], g[7])); // NAT64
90
+ if (g[0] === 0x2002)
91
+ return isPublicIPv4(v4(g[1], g[2])); // 6to4
92
+ if ((g[0] & 0xfe00) === 0xfc00)
93
+ return false; // unique local (fc00::/7)
94
+ if ((g[0] & 0xffc0) === 0xfe80)
95
+ return false; // link-local
96
+ if ((g[0] & 0xffc0) === 0xfec0)
97
+ return false; // site-local (deprecated)
98
+ if ((g[0] & 0xff00) === 0xff00)
99
+ return false; // multicast
100
+ if (g[0] === 0x2001 && g[1] === 0xdb8)
101
+ return false; // documentation
102
+ if (g[0] === 0x100 && g.slice(1, 4).every((x) => x === 0))
103
+ return false; // discard-only
104
+ return true;
105
+ }
106
+ /** Is this literal IP address one anyone on the internet could reach? Null when `text` isn't an IP address. */
107
+ export function isPublicAddress(text) {
108
+ const v4 = parseIPv4(text);
109
+ if (v4)
110
+ return isPublicIPv4(v4);
111
+ const v6 = parseIPv6(text);
112
+ if (v6)
113
+ return isPublicIPv6(v6);
114
+ return null;
115
+ }
116
+ /** Names that always mean this machine, whatever DNS says. */
117
+ function isLocalName(host) {
118
+ const h = host.toLowerCase().replace(/\.$/, '');
119
+ return h === 'localhost' || h.endsWith('.localhost') || h === 'localhost.localdomain';
120
+ }
121
+ /** Is `url`'s host public (every address it resolves to is public), private, or not resolvable? Never throws. */
122
+ export async function checkHost(url, lookup = defaultLookup) {
123
+ const host = url.hostname;
124
+ if (isLocalName(host))
125
+ return { kind: 'private', reason: `${host} is this computer` };
126
+ const literal = isPublicAddress(host);
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
+ }
134
+ let addresses;
135
+ try {
136
+ addresses = await lookup(host);
137
+ }
138
+ catch {
139
+ return { kind: 'unresolved', reason: `${host} could not be resolved` };
140
+ }
141
+ if (!addresses.length)
142
+ return { kind: 'unresolved', reason: `${host} could not be resolved` };
143
+ const bad = addresses.find((a) => isPublicAddress(a.address) !== true);
144
+ return bad
145
+ ? { kind: 'private', reason: `${host} resolves to ${bad.address}, a private or local network address`, addresses }
146
+ : { kind: 'public', addresses };
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>;