launch-doctor 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/CHANGELOG.md +77 -6
  2. package/LICENSE +1 -0
  3. package/README.md +95 -20
  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 +111 -9
  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/history.js +17 -3
  33. package/dist/src/hook.d.ts +13 -0
  34. package/dist/src/hook.js +96 -0
  35. package/dist/src/hooks-setup.d.ts +24 -0
  36. package/dist/src/hooks-setup.js +187 -0
  37. package/dist/src/ignore.d.ts +36 -0
  38. package/dist/src/ignore.js +164 -0
  39. package/dist/src/index.js +28 -3
  40. package/dist/src/live.d.ts +9 -0
  41. package/dist/src/live.js +73 -22
  42. package/dist/src/mcp.js +7 -2
  43. package/dist/src/net-guard.d.ts +34 -0
  44. package/dist/src/net-guard.js +144 -0
  45. package/dist/src/project.d.ts +34 -5
  46. package/dist/src/project.js +145 -111
  47. package/dist/src/report.d.ts +2 -0
  48. package/dist/src/report.js +11 -0
  49. package/dist/src/routes.d.ts +10 -0
  50. package/dist/src/routes.js +21 -4
  51. package/dist/src/safe-fs.d.ts +19 -0
  52. package/dist/src/safe-fs.js +77 -0
  53. package/dist/src/sanitize.d.ts +17 -0
  54. package/dist/src/sanitize.js +90 -0
  55. package/dist/src/sarif.js +1 -1
  56. package/dist/src/summary.d.ts +4 -0
  57. package/dist/src/summary.js +9 -4
  58. package/dist/src/types.d.ts +24 -0
  59. package/dist/src/util.d.ts +1 -1
  60. package/dist/src/util.js +1 -1
  61. package/package.json +9 -5
@@ -0,0 +1,164 @@
1
+ import { basename } from 'node:path';
2
+ /** `*` matches inside one folder name, `**` across folders, `?` one character. Runs of stars collapse. */
3
+ function compileGlob(text) {
4
+ const tokens = [];
5
+ for (let i = 0; i < text.length; i++) {
6
+ const ch = text[i];
7
+ if (ch === '*') {
8
+ let n = 1;
9
+ while (text[i + 1] === '*') {
10
+ n++;
11
+ i++;
12
+ }
13
+ const tok = { kind: n >= 2 ? 'globstar' : 'star' };
14
+ const prev = tokens.at(-1);
15
+ // "**" next to "*" or "**" (also "**/**", which only adds an optional folder) is just "**".
16
+ if (prev?.kind === 'globstar' || prev?.kind === 'star') {
17
+ if (tok.kind === 'globstar')
18
+ prev.kind = 'globstar';
19
+ continue;
20
+ }
21
+ if (tok.kind === 'globstar' && prev?.kind === 'char' && prev.c === '/' && tokens.at(-2)?.kind === 'globstar') {
22
+ tokens.pop();
23
+ continue;
24
+ }
25
+ tokens.push(tok);
26
+ }
27
+ else if (ch === '?') {
28
+ tokens.push({ kind: 'one' });
29
+ }
30
+ else {
31
+ tokens.push({ kind: 'char', c: ch });
32
+ }
33
+ }
34
+ let mustContain = '';
35
+ let run = '';
36
+ for (const t of [...tokens, { kind: 'one' }]) {
37
+ if (t.kind === 'char')
38
+ run += t.c;
39
+ else {
40
+ if (run.length > mustContain.length)
41
+ mustContain = run;
42
+ run = '';
43
+ }
44
+ }
45
+ return { tokens, mustContain };
46
+ }
47
+ /** Does `s` match the whole glob? */
48
+ function globMatch(glob, s) {
49
+ if (glob.mustContain && !s.includes(glob.mustContain))
50
+ return false;
51
+ const toks = glob.tokens;
52
+ const m = toks.length;
53
+ let cur = new Uint8Array(m + 1);
54
+ let next = new Uint8Array(m + 1);
55
+ const close = (set) => {
56
+ // A star can match nothing, so being before it also means being after it.
57
+ for (let i = 0; i < m; i++) {
58
+ const k = toks[i].kind;
59
+ if (set[i] && (k === 'star' || k === 'globstar'))
60
+ set[i + 1] = 1;
61
+ }
62
+ };
63
+ cur[0] = 1;
64
+ close(cur);
65
+ for (let p = 0; p < s.length; p++) {
66
+ const ch = s[p];
67
+ next.fill(0);
68
+ let any = false;
69
+ for (let i = 0; i < m; i++) {
70
+ if (!cur[i])
71
+ continue;
72
+ const t = toks[i];
73
+ if (t.kind === 'char') {
74
+ if (t.c === ch)
75
+ next[i + 1] = 1;
76
+ }
77
+ else if (t.kind === 'one') {
78
+ if (ch !== '/')
79
+ next[i + 1] = 1;
80
+ }
81
+ else if (t.kind === 'star') {
82
+ if (ch !== '/')
83
+ next[i] = 1;
84
+ }
85
+ else {
86
+ next[i] = 1;
87
+ }
88
+ }
89
+ close(next);
90
+ for (let i = 0; i <= m; i++) {
91
+ if (next[i]) {
92
+ any = true;
93
+ break;
94
+ }
95
+ }
96
+ if (!any)
97
+ return false;
98
+ [cur, next] = [next, cur];
99
+ }
100
+ return cur[m] === 1;
101
+ }
102
+ /** Parse gitignore-style text into rules. */
103
+ export function compileIgnore(text) {
104
+ const rules = [];
105
+ for (const raw of text.split(/\r?\n/)) {
106
+ let line = raw.trim();
107
+ if (!line || line.startsWith('#'))
108
+ continue;
109
+ const negate = line.startsWith('!');
110
+ if (negate)
111
+ line = line.slice(1);
112
+ line = line.replace(/\/+$/, '');
113
+ // "**/x" means "x in any folder".
114
+ let anyDepth = false;
115
+ while (line.startsWith('**/')) {
116
+ line = line.slice(3);
117
+ anyDepth = true;
118
+ }
119
+ const anchored = line.startsWith('/') || line.includes('/');
120
+ line = line.replace(/^\//, '');
121
+ if (!line)
122
+ continue;
123
+ rules.push({ glob: compileGlob(line), negate, anchored, anyDepth });
124
+ }
125
+ return rules;
126
+ }
127
+ /** Is `path` (relative, with "/") ignored by these rules? The last matching rule wins, as in git. */
128
+ export function matchesIgnore(rules, path) {
129
+ let ignored = false;
130
+ let segments = null;
131
+ for (const rule of rules) {
132
+ // A later rule can only change the answer if it is the opposite kind.
133
+ if (rule.negate !== ignored)
134
+ continue;
135
+ let hit;
136
+ if (!rule.anchored) {
137
+ segments ??= path.split('/');
138
+ hit = globMatch(rule.glob, basename(path)) || segments.some((seg) => globMatch(rule.glob, seg));
139
+ }
140
+ else if (rule.anyDepth) {
141
+ segments ??= path.split('/');
142
+ const segs = segments;
143
+ hit = segs.some((_, i) => globMatch(rule.glob, segs.slice(i).join('/')));
144
+ }
145
+ else {
146
+ hit = globMatch(rule.glob, path);
147
+ }
148
+ if (hit)
149
+ ignored = !rule.negate;
150
+ }
151
+ return ignored;
152
+ }
153
+ const compiled = new Map();
154
+ /** Minimal .gitignore matching for one path, used when git isn't available. Compiles each distinct text once. */
155
+ export function matchesGitignore(gitignore, path) {
156
+ let rules = compiled.get(gitignore);
157
+ if (!rules) {
158
+ rules = compileIgnore(gitignore);
159
+ if (compiled.size > 32)
160
+ compiled.clear();
161
+ compiled.set(gitignore, rules);
162
+ }
163
+ return matchesIgnore(rules, path);
164
+ }
package/dist/src/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { applyBaseline, fingerprint, loadBaseline } from './baseline.js';
2
+ import { accessCheck } from './checks/access.js';
2
3
  import { costsCheck } from './checks/costs.js';
3
4
  import { databaseCheck } from './checks/database.js';
4
5
  import { emailCheck } from './checks/email.js';
@@ -10,6 +11,7 @@ import { secretsCheck } from './checks/secrets.js';
10
11
  import { overall, scoreCategory, toGrade } from './grade.js';
11
12
  import { scanHistory } from './history.js';
12
13
  import { ProjectContext } from './project.js';
14
+ import { sanitizeReport } from './sanitize.js';
13
15
  import { plural } from './util.js';
14
16
  import { version } from './version.js';
15
17
  function notRun(note) {
@@ -18,6 +20,7 @@ function notRun(note) {
18
20
  export const CHECKS = [
19
21
  secretsCheck,
20
22
  databaseCheck,
23
+ accessCheck,
21
24
  paymentsCheck,
22
25
  costsCheck,
23
26
  emailCheck,
@@ -35,9 +38,13 @@ export function isInlineIgnored(ctx, f) {
35
38
  if (!file)
36
39
  return false;
37
40
  const lines = file.content.split(/\r?\n/);
38
- for (const text of [lines[loc.line - 1], lines[loc.line - 2]]) {
41
+ for (const lineNo of [loc.line, loc.line - 1]) {
42
+ const text = lines[lineNo - 1];
39
43
  if (!text)
40
44
  continue;
45
+ // With --config-from, a comment on a line added since that ref is not trusted (a pull request could add it).
46
+ if (ctx.addedSinceConfigRef(loc.file, lineNo))
47
+ continue;
41
48
  for (const m of text.matchAll(INLINE_IGNORE)) {
42
49
  if (m[1].split(/\s*,\s*/).includes(f.id))
43
50
  return true;
@@ -51,6 +58,10 @@ export async function runDoctor(root, options = {}) {
51
58
  const unknown = [...(options.only ?? []), ...(options.skip ?? [])].filter((id) => !CATEGORY_IDS().includes(id));
52
59
  if (unknown.length)
53
60
  throw new Error(`Unknown category: ${unknown.join(', ')}. Use one of: ${CATEGORY_IDS().join(', ')}`);
61
+ // Reporting on a few files is for quick checks, so it never waits for DNS.
62
+ if (options.onlyFiles)
63
+ options = { ...options, offline: true };
64
+ const only = options.onlyFiles ? new Set(options.onlyFiles) : null;
54
65
  const ctx = new ProjectContext(root, options);
55
66
  const categories = [];
56
67
  let ignored = 0;
@@ -90,6 +101,16 @@ export async function runDoctor(root, options = {}) {
90
101
  out.passed.push('Git history scan stopped early because the history is very large');
91
102
  }
92
103
  }
104
+ // Reporting on some files only: keep findings in those files. "Passed" lines and the checklist describe
105
+ // the whole project, so they would mislead here.
106
+ if (only) {
107
+ out = {
108
+ ...out,
109
+ findings: out.findings.filter((f) => f.location && only.has(f.location.file)),
110
+ manual: [],
111
+ passed: [],
112
+ };
113
+ }
93
114
  // Inline: a "launch-doctor-ignore <id>" comment on the finding's line or the line above.
94
115
  const inline = out.findings.filter((f) => isInlineIgnored(ctx, f));
95
116
  if (inline.length) {
@@ -129,19 +150,23 @@ export async function runDoctor(root, options = {}) {
129
150
  stack: ctx.stack(),
130
151
  filesScanned: ctx.files.length,
131
152
  truncated: ctx.truncated,
153
+ ...(ctx.byteLimitReached ? { byteLimitReached: true } : {}),
132
154
  ignored,
133
155
  unknownIgnoreIds,
156
+ ...(ctx.ignoreLinesSkipped ? { ignoreLinesSkipped: ctx.ignoreLinesSkipped } : {}),
134
157
  ...(ctx.nestedRepos.length ? { nestedRepos: ctx.nestedRepos } : {}),
158
+ ...(options.onlyFiles ? { partial: { files: options.onlyFiles } } : {}),
135
159
  ...summary,
136
160
  categories,
137
161
  generatedAt: new Date().toISOString(),
138
162
  };
139
163
  if (options.baseline !== false) {
140
- const baseline = loadBaseline(ctx.root);
164
+ const baseline = loadBaseline(ctx.root, options.configFrom);
141
165
  if (baseline)
142
166
  applyBaseline(report, baseline);
143
167
  }
144
- return report;
168
+ // Text from the scanned files (names, paths) can hold terminal escape sequences; none reach any output.
169
+ return sanitizeReport(report);
145
170
  }
146
171
  export { renderFixes } from './fixes.js';
147
172
  export { postPrFeedback, prContextFromEnv, renderPrComment } from './github.js';
@@ -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'];
@@ -10,6 +11,14 @@ export interface LiveOptions {
10
11
  skipDatabase?: boolean;
11
12
  /** Replacement for fetch (used by tests to fake a Supabase project). */
12
13
  fetch?: typeof fetch;
14
+ /** Replacement for the DNS lookup used to check each host before a request (tests). */
15
+ lookup?: Lookup;
16
+ /**
17
+ * May the address you give be on a private or local network (your own dev server, for example)? Default true,
18
+ * as for the CLI. The MCP server sets it to false. Either way, a scan that starts on a public site never sends
19
+ * a request to a private address, through a script, a source map or a redirect.
20
+ */
21
+ allowPrivateTarget?: boolean;
13
22
  }
14
23
  /** "myapp.com" or "https://myapp.com/x" -> a URL object. Throws a friendly error for anything else. */
15
24
  export declare function parseTarget(input: string): URL;
package/dist/src/live.js CHANGED
@@ -1,6 +1,8 @@
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 { sanitizeReport } from './sanitize.js';
4
6
  import { decodeJwtPayload, mask, plural } from './util.js';
5
7
  import { version } from './version.js';
6
8
  /** Ids of every finding a live scan can produce (for docs and tests). */
@@ -19,9 +21,11 @@ export const LIVE_IDS = [
19
21
  'live-missing-csp',
20
22
  'live-missing-basic-headers',
21
23
  ];
24
+ /** Redirects followed for one request. */
25
+ const MAX_REDIRECTS = 5;
22
26
  const MAX_SCRIPTS = 20;
23
27
  const MAX_TABLES = 25;
24
- const USER_AGENT = `launch-doctor/${version()} (+https://github.com/SHARAJ379/launch-doctor)`;
28
+ const USER_AGENT = `launch-doctor/${version()} (+https://github.com/SHARAJ379/Launch-Doctor)`;
25
29
  /** "myapp.com" or "https://myapp.com/x" -> a URL object. Throws a friendly error for anything else. */
26
30
  export function parseTarget(input) {
27
31
  const text = input.trim();
@@ -45,29 +49,60 @@ function isLocal(url) {
45
49
  class Fetcher {
46
50
  opts;
47
51
  requests = 0;
52
+ /** Requests not sent because they would have reached a private or local address. */
53
+ blocked = [];
48
54
  constructor(opts) {
49
55
  this.opts = opts;
50
56
  }
51
- /** One GET. Returns null when the site can't be reached. Never throws. */
57
+ /**
58
+ * One GET. Returns null when the site can't be reached. Never throws. Redirects are followed here, one hop at a
59
+ * time, so every address is checked before anything is sent to it.
60
+ */
52
61
  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 {
69
- return null;
62
+ let current = url;
63
+ for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
64
+ let parsed;
65
+ try {
66
+ parsed = new URL(current);
67
+ }
68
+ catch {
69
+ return null;
70
+ }
71
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')
72
+ 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
+ }
80
+ this.requests++;
81
+ try {
82
+ const res = await this.opts.fetch(current, {
83
+ method: 'GET',
84
+ redirect: 'manual',
85
+ signal: AbortSignal.timeout(this.opts.timeoutMs),
86
+ headers: { 'user-agent': USER_AGENT, accept: '*/*', ...init.headers },
87
+ });
88
+ const location = res.headers.get('location');
89
+ if (init.follow !== false && res.status >= 300 && res.status < 400 && location) {
90
+ await res.body?.cancel().catch(() => { });
91
+ current = new URL(location, current).href;
92
+ continue;
93
+ }
94
+ return {
95
+ url: current,
96
+ status: res.status,
97
+ headers: res.headers,
98
+ body: await readCapped(res, this.opts.maxBytes),
99
+ };
100
+ }
101
+ catch {
102
+ return null;
103
+ }
70
104
  }
105
+ return null; // too many redirects
71
106
  }
72
107
  }
73
108
  async function readCapped(res, maxBytes) {
@@ -201,7 +236,7 @@ const PROBES = [
201
236
  path: '/.git/config',
202
237
  id: 'live-exposed-git',
203
238
  what: 'your git settings (.git/config)',
204
- valid: (b) => /^\s*\[core\]/m.test(b),
239
+ valid: (b) => /^[ \t]*\[core\]/m.test(b),
205
240
  },
206
241
  {
207
242
  path: '/.git/HEAD',
@@ -455,13 +490,24 @@ function capitalize(s) {
455
490
  // ---------------------------------------------------------------------------
456
491
  export async function runLiveScan(input, options = {}) {
457
492
  const target = parseTarget(input);
493
+ const lookup = options.lookup ?? defaultLookup;
494
+ const targetHost = await checkHost(target, lookup);
495
+ if (targetHost.kind === 'private' && options.allowPrivateTarget === false) {
496
+ throw new Error(`Only public sites can be scanned here: ${targetHost.reason}.`);
497
+ }
458
498
  const fetcher = new Fetcher({
459
499
  timeoutMs: options.timeoutMs ?? 10_000,
460
500
  maxBytes: options.maxBytes ?? 3_000_000,
461
501
  fetch: options.fetch ?? fetch,
502
+ lookup,
503
+ // A scan you start at a private address (your own dev server) stays usable; one that starts on a public site
504
+ // never reaches a private address.
505
+ allowPrivate: targetHost.kind === 'private',
462
506
  });
463
507
  const home = await fetcher.get(target.href);
464
508
  if (!home) {
509
+ if (fetcher.blocked.length)
510
+ throw new Error(`${target.origin} redirected to ${fetcher.blocked[0]}, so it wasn't scanned.`);
465
511
  throw new Error(`Couldn't reach ${target.origin}. Check the address and that the site is online.`);
466
512
  }
467
513
  if (home.status >= 500)
@@ -491,7 +537,12 @@ export async function runLiveScan(input, options = {}) {
491
537
  grade: score === null ? null : toGrade(score),
492
538
  });
493
539
  }
494
- return {
540
+ if (fetcher.blocked.length) {
541
+ const hosts = [...new Set(fetcher.blocked.map((b) => b.split(' ')[0]))].slice(0, 3).join(', ');
542
+ categories[0].passed.push(`Skipped ${plural(fetcher.blocked.length, 'request')} to private or local network addresses (${hosts}) that this public site pointed to`);
543
+ }
544
+ // Text from the site (table names, paths) can hold terminal escape sequences; none reach any output.
545
+ return sanitizeReport({
495
546
  tool: 'launch-doctor',
496
547
  version: version(),
497
548
  mode: 'live',
@@ -505,5 +556,5 @@ export async function runLiveScan(input, options = {}) {
505
556
  ...overall(categories),
506
557
  categories,
507
558
  generatedAt: new Date().toISOString(),
508
- };
559
+ });
509
560
  }
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,34 @@
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
+ * 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.
14
+ */
15
+ export type Lookup = (host: string) => Promise<{
16
+ address: string;
17
+ family: number;
18
+ }[]>;
19
+ export declare const defaultLookup: Lookup;
20
+ /** Is this literal IP address one anyone on the internet could reach? Null when `text` isn't an IP address. */
21
+ export declare function isPublicAddress(text: string): boolean | null;
22
+ export type HostCheck = {
23
+ kind: 'public';
24
+ } | {
25
+ kind: 'private';
26
+ reason: string;
27
+ }
28
+ /** The name doesn't resolve, so no request can reach it. */
29
+ | {
30
+ kind: 'unresolved';
31
+ reason: string;
32
+ };
33
+ /** Is `url`'s host public (every address it resolves to is public), private, or not resolvable? Never throws. */
34
+ export declare function checkHost(url: URL, lookup?: Lookup): Promise<HostCheck>;
@@ -0,0 +1,144 @@
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 === false)
128
+ return { kind: 'private', reason: `${host} is a private or local network address` };
129
+ if (literal === true)
130
+ return { kind: 'public' };
131
+ let addresses;
132
+ try {
133
+ addresses = await lookup(host);
134
+ }
135
+ catch {
136
+ return { kind: 'unresolved', reason: `${host} could not be resolved` };
137
+ }
138
+ if (!addresses.length)
139
+ return { kind: 'unresolved', reason: `${host} could not be resolved` };
140
+ const bad = addresses.find((a) => isPublicAddress(a.address) !== true);
141
+ return bad
142
+ ? { kind: 'private', reason: `${host} resolves to ${bad.address}, a private or local network address` }
143
+ : { kind: 'public' };
144
+ }