@kaynooo/cli-probe 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 (3) hide show
  1. package/README.md +17 -2
  2. package/dist/probe.js +418 -63
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -15,7 +15,10 @@ bun add -g @kaynooo/cli-probe
15
15
  | `probe -k https://localhost:8443` | go on with a certificate curl does not trust (it is reported as a warning) |
16
16
  | `probe -H "X-Debug: 1" https://example.com` | a header sent with every request, repeatable |
17
17
  | `probe --resolve example.com:203.0.113.7 https://example.com` | reaches the host at that address instead of the DNS answer (an IPv4 or IPv6 literal), repeatable; the certificate is read from that address, the Host header and the SNI stay the host's, and the addresses reported are that one |
18
- | `probe -t 5s example.com` | longest one request may take (20s by default), a bare number counting seconds |
18
+ | `probe -t 5s example.com` | longest one request may take (20s by default, 3s for a DNS query), a bare number counting seconds |
19
+ | `probe --dns example.com` | no HTTP request: the A, AAAA and CNAME records with their TTL as the system resolver, Cloudflare (1.1.1.1), Google (8.8.8.8), Quad9 (9.9.9.9) and each nameserver of the host's zone answer them, and a warning for each resolver answering otherwise than the zone's nameservers |
20
+ | `probe --cors https://app.example.com https://api.example.com/items` | sends the preflight a browser on that origin sends before a JSON POST, and says whether it would go on: allowed or refused, each reason, the `access-control-*` and `vary` headers |
21
+ | `probe --cors https://app.example.com --method PUT --cors-headers content-type,authorization <url>` | the preflight of another request: its method (POST by default) and the headers it carries (`content-type` by default, empty for none) |
19
22
 
20
23
  ## JSON output
21
24
 
@@ -25,4 +28,16 @@ Redirects are followed hop by hop, at most 10. The HTTP version and timings come
25
28
 
26
29
  Warnings: a certificate with fewer than 14 days left, expired or not trusted, an `http://` twin that does not redirect to https (checked for a bare domain or an https URL on the default port), more than 10 redirects, a site not served over https.
27
30
 
28
- Exits 0 when every site answered, 1 when one could not be reached, 2 on a usage error (a bad URL, header or `--resolve` is refused before any request is made).
31
+ ## DNS comparison
32
+
33
+ `--dns` takes names or URLs, an IP address being refused. The zone is the nearest name up from the host that has NS records, a top-level domain or an alias never counting as one, and a lookup that fails stops the climb rather than take a parent's nameservers; the zone's nameservers are the reference, reached at the address Cloudflare gives for them. Two answers agree when their A records share an address and their AAAA records do too, so a round robin rotating its records is no disagreement while a family one side lacks is one; an alias compares by its target alone, since a zone's nameservers do not follow it out of the zone. A CDN answering by where the question comes from can still show as a disagreement.
34
+
35
+ The system resolver is the one `/etc/resolv.conf` names, asked directly: `/etc/hosts` is not read. The flush advice holds when that is systemd-resolved's stub, `127.0.0.53`. Under Bun a DNS query's `-t` is rounded up to whole seconds, one at least.
36
+
37
+ Warnings: the system resolver behind the zone (`sudo resolvectl flush-caches` drops its copy, the TTL saying how long it may keep it otherwise, left out for an alias whose own TTL is not known), a public resolver giving what none of the zone's nameservers gives, the nameservers disagreeing among themselves, resolvers disagreeing with no nameserver to tell which is right, a resolver not answering, no zone found or the zone lookup failing. `--json` is `{target, zone, answers, agree, warnings}`, each answer `{resolver, server, authoritative, a, aaaa, cname, ttl, error?}`.
38
+
39
+ ## CORS preflight
40
+
41
+ `--cors <origin>` sends `OPTIONS` with `Origin`, `Access-Control-Request-Method` and `Access-Control-Request-Headers`, the way a browser does, then applies the Fetch standard's checks: a 2xx status, `access-control-allow-origin` being `*` or the origin, `access-control-allow-methods` listing a method other than GET, HEAD or POST (or `*`), `access-control-allow-headers` covering every header (`*` covers all but `authorization`). The method is uppercased when it is one of the six fetch normalizes (DELETE, GET, HEAD, OPTIONS, POST, PUT) and otherwise sent and matched as typed, `patch` needing `patch` listed. `accept`, `accept-language` and `content-language` are left out of the preflight, a browser letting them through unlisted. Warnings: credentials allowed alongside a `*`, which a credentialed request does not get, and the request's origin allowed without `vary: origin`. `--json` is `{target, url, status, request, allowed, reasons, warnings, headers}`. `-H`, `--resolve`, `-k` and `-t` apply to the preflight too.
42
+
43
+ Exits 0 when every site answered, 1 when one could not be reached, a CORS preflight was refused or no resolver knows a name, 2 on a usage error (a bad URL, header, origin or `--resolve` is refused before any request is made).
package/dist/probe.js CHANGED
@@ -3,13 +3,14 @@
3
3
 
4
4
  // src/probe.ts
5
5
  import { isIP as isIP2 } from "net";
6
- import process13 from "process";
6
+ import process15 from "process";
7
7
  // ../kit/src/args.ts
8
8
  import process9 from "process";
9
9
  import { parseArgs } from "util";
10
10
 
11
11
  // ../kit/src/format.ts
12
12
  import process7 from "process";
13
+
13
14
  // ../../node_modules/.bun/@kaynooo+utils@3.0.0+4c7ddab9986847c5/node_modules/@kaynooo/utils/dist/chunk-rxztfxgv.js
14
15
  var N = new Map;
15
16
  var Nt = /\s+\S*$/;
@@ -27,6 +28,7 @@ function ko(t, e, r = "...") {
27
28
  }
28
29
  var be = new Map(["\u20AC", "", "\u201A", "\u0192", "\u201E", "\u2026", "\u2020", "\u2021", "\u02C6", "\u2030", "\u0160", "\u2039", "\u0152", "", "\u017D", "", "", "\u2018", "\u2019", "\u201C", "\u201D", "\u2022", "\u2013", "\u2014", "\u02DC", "\u2122", "\u0161", "\u203A", "\u0153", "", "\u017E", "\u0178"].map((t, e) => [t, 128 + e]).filter(([t]) => t));
29
30
  var z = new Map;
31
+
30
32
  // ../kit/src/mode.ts
31
33
  import process2 from "process";
32
34
  var MODES = new Set(["terminal", "ci", "agent", "pipe"]);
@@ -72,7 +74,7 @@ function C(r, e = globalThis.process?.env ?? {}) {
72
74
  return false;
73
75
  return r?.isTTY === true;
74
76
  }
75
- function f2(r, e = []) {
77
+ function f(r, e = []) {
76
78
  let l = "", n = "";
77
79
  for (let t = 0, i = e.length;t < i; t++)
78
80
  l += `\x1B[${e[t][0]}m`, n = `\x1B[${e[t][1]}m${n}`;
@@ -82,7 +84,7 @@ function f2(r, e = []) {
82
84
  if (Array.isArray(a)) {
83
85
  let s = g.get(i);
84
86
  if (s === undefined)
85
- s = f2(r, [...e, a]), g.set(i, s);
87
+ s = f(r, [...e, a]), g.set(i, s);
86
88
  return s;
87
89
  }
88
90
  if (typeof a === "function")
@@ -91,17 +93,17 @@ function f2(r, e = []) {
91
93
  if (u === undefined) {
92
94
  if (g.size >= 64)
93
95
  g.clear();
94
- u = f2(r, [...e, a(...s)]), g.set(y, u);
96
+ u = f(r, [...e, a(...s)]), g.set(y, u);
95
97
  }
96
98
  return u;
97
99
  };
98
100
  throw Error(`Unknown style: ${String(i)}`);
99
101
  } });
100
102
  }
101
- function Fe2(r = {}) {
102
- return f2(r);
103
+ function Fe(r = {}) {
104
+ return f(r);
103
105
  }
104
- var o2 = Fe2();
106
+ var o = Fe();
105
107
 
106
108
  // ../kit/src/theme.ts
107
109
  import { existsSync as existsSync2, readFileSync, statSync } from "fs";
@@ -323,7 +325,7 @@ function takesControlCodes(stream, env = process6.env) {
323
325
  return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb" && outputMode(stream, env) === "terminal";
324
326
  }
325
327
  function paint(stream, env = process6.env) {
326
- return Fe2({ stream: { isTTY: takesControlCodes(stream, env) }, env });
328
+ return Fe({ stream: { isTTY: takesControlCodes(stream, env) }, env });
327
329
  }
328
330
  function marked(mark, text, stream, detail, env = process6.env) {
329
331
  const colors = paint(stream, env);
@@ -348,6 +350,23 @@ var STATUS_WORDS = {
348
350
  var STATUS_OF = new Map(Object.entries(STATUS_WORDS).flatMap(([status, words]) => words.map((word) => [word, status])));
349
351
 
350
352
  // ../kit/src/format.ts
353
+ var UNITS = [["d", 86400], ["h", 3600], ["m", 60], ["s", 1]];
354
+ function formatSeconds(total) {
355
+ let rest = Math.max(0, Math.round(total));
356
+ const amounts = UNITS.map(([unit, size]) => {
357
+ const amount = Math.floor(rest / size);
358
+ rest -= amount * size;
359
+ return `${amount}${unit}`;
360
+ });
361
+ const first = amounts.findIndex((amount) => !amount.startsWith("0"));
362
+ if (first === -1)
363
+ return "0s";
364
+ const next = amounts[first + 1];
365
+ return next === undefined || next.startsWith("0") ? amounts[first] ?? "0s" : `${amounts[first]} ${next}`;
366
+ }
367
+ function formatDuration(ms) {
368
+ return ms < 60000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : formatSeconds(ms / 1000);
369
+ }
351
370
  function upTo(text, separator) {
352
371
  const end = text.indexOf(separator);
353
372
  return end === -1 ? text : text.slice(0, end);
@@ -408,24 +427,20 @@ function printJson(value) {
408
427
 
409
428
  // ../kit/src/help.ts
410
429
  import process8 from "process";
411
- var OPTIONAL = /\[[^\]]+\]/g;
430
+ var OPTIONAL = /(?<!\x1B)\[[^\]]+\]/g;
412
431
  var USAGE_PREFIX = /^usage:\s*/i;
413
432
  var FULL_STOP = /\.$/;
414
433
  function usageLine(usage, colors = paint(process8.stdout)) {
415
434
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
416
435
  }
417
- function helpText(usage, options, colors = paint(process8.stdout), { examples = [], replaces, exits = [] } = {}) {
418
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
436
+ function helpText(usage, options, colors = paint(process8.stdout), { examples = [], exits = [] } = {}) {
437
+ return [usageLine(usage, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
419
438
  `);
420
439
  }
421
440
  function exitRows(exits, colors = paint(process8.stdout)) {
422
441
  if (exits.length === 0)
423
442
  return [];
424
- const width = Math.max(...exits.map(([code]) => String(code).length));
425
- return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
426
- }
427
- function replacesRows(replaces, colors = paint(process8.stdout)) {
428
- return replaces === undefined || outputMode() === "agent" ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
443
+ return ["", `${colors.bold("Exit codes:")} ${exits.map(([code, meaning]) => `${colors.cyan(String(code))} ${meaning}`).join(", ")}`];
429
444
  }
430
445
  function wantsHelpJson(env = process8.env) {
431
446
  return env.KIT_HELP === "json";
@@ -451,29 +466,40 @@ function exampleRows(examples, colors = paint(process8.stdout)) {
451
466
  return [];
452
467
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
453
468
  }
469
+ var MAX_INLINE_CHOICES = 24;
454
470
  function optionRows(options, colors = paint(process8.stdout)) {
455
471
  const rows = Object.entries(options).map(([name, option]) => {
456
472
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
457
- const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
473
+ const choices = option.choices?.join("|");
474
+ const inline = choices !== undefined && choices.length <= MAX_INLINE_CHOICES;
475
+ const named = inline ? `<${choices}>` : "<value>";
458
476
  const placeholder = option.optional === undefined ? named : `[${named}]`;
459
477
  const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
460
- return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
478
+ const described = choices === undefined || inline ? option.description ?? "" : [option.description, `one of ${option.choices.join(", ")}`].filter(Boolean).join("; ");
479
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: described };
461
480
  });
462
481
  const width = Math.max(0, ...rows.map((row) => row.width));
463
482
  return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
464
483
  }
465
484
 
466
485
  // ../kit/src/text.ts
467
- var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
468
486
  function distance(a, b) {
469
- let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
470
- for (const [i, left] of [...a].entries()) {
487
+ const left = [...a];
488
+ const right = [...b];
489
+ let before = [];
490
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
491
+ for (const [i, x] of left.entries()) {
471
492
  const current = [i + 1];
472
- for (const [j, right] of [...b].entries())
473
- current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
493
+ for (const [j, y] of right.entries()) {
494
+ let cost = Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (x === y ? 0 : 1));
495
+ if (i > 0 && j > 0 && x === right[j - 1] && left[i - 1] === y)
496
+ cost = Math.min(cost, (before[j - 1] ?? 0) + 1);
497
+ current.push(cost);
498
+ }
499
+ before = previous;
474
500
  previous = current;
475
501
  }
476
- return previous[b.length] ?? 0;
502
+ return previous[right.length] ?? 0;
477
503
  }
478
504
  function closest(name, names) {
479
505
  const started = names.find((known) => known.startsWith(name));
@@ -712,21 +738,63 @@ function nearestOption(message, options, allowNegative) {
712
738
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
713
739
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
714
740
  }
741
+ // ../kit/src/argv.ts
742
+ import { readFileSync as readFileSync2, realpathSync } from "fs";
743
+ import { resolve as resolve3 } from "path";
744
+ import process10 from "process";
745
+ function commandLine() {
746
+ try {
747
+ return readFileSync2("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
748
+ } catch {
749
+ return;
750
+ }
751
+ }
752
+ function realPath(word) {
753
+ try {
754
+ return realpathSync(resolve3(word));
755
+ } catch {
756
+ return;
757
+ }
758
+ }
759
+ function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
760
+ const target = script === undefined ? undefined : realPath(script) ?? script;
761
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
762
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
763
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
764
+ }
715
765
  // ../kit/src/progress.ts
716
766
  var ESC = String.fromCharCode(27);
717
767
  var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
718
768
  var RESET_STYLE = `${ESC}[0m`;
719
769
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
720
770
  // ../kit/src/cli.ts
721
- import { readFileSync as readFileSync2, realpathSync } from "fs";
771
+ import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
722
772
  import { dirname as dirname3, join as join5 } from "path";
773
+ import process13 from "process";
774
+
775
+ // ../kit/src/notify.ts
723
776
  import process11 from "process";
777
+ var NOTIFY_AFTER_MS = 1e4;
778
+ var CANCELLED = 130;
779
+ function base64(text) {
780
+ return Buffer.from(text).toString("base64");
781
+ }
782
+ function notification(title, body, env = process11.env) {
783
+ const id = `kit${process11.pid}`;
784
+ const codes = [`\x1B]99;i=${id}:d=0:o=unfocused:e=1;${base64(title)}\x1B\\`, `\x1B]99;i=${id}:p=body:e=1;${base64(body)}\x1B\\`];
785
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
786
+ }
787
+ function notifyEnd(command, code, ms, { stream = process11.stderr, env = process11.env } = {}) {
788
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
789
+ return;
790
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
791
+ }
724
792
 
725
793
  // ../kit/src/usage.ts
726
794
  import { appendFileSync, mkdirSync } from "fs";
727
795
  import { homedir as homedir3 } from "os";
728
796
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
729
- import process10 from "process";
797
+ import process12 from "process";
730
798
 
731
799
  // ../kit/src/logs.ts
732
800
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -740,14 +808,14 @@ var usageError;
740
808
  function noteUsageError(message) {
741
809
  usageError = message;
742
810
  }
743
- function stateHome(env = process10.env) {
811
+ function stateHome(env = process12.env) {
744
812
  const dir = env.XDG_STATE_HOME;
745
813
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
746
814
  }
747
- function usagePath(env = process10.env) {
815
+ function usagePath(env = process12.env) {
748
816
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
749
817
  }
750
- function usageRecorded(env = process10.env) {
818
+ function usageRecorded(env = process12.env) {
751
819
  const off = env.KAYNOOO_CLI_NO_USAGE;
752
820
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
753
821
  }
@@ -761,7 +829,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
761
829
  usageError = undefined;
762
830
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
763
831
  }
764
- function recordUsage(entry, env = process10.env) {
832
+ function recordUsage(entry, env = process12.env) {
765
833
  if (!usageRecorded(env))
766
834
  return;
767
835
  try {
@@ -779,8 +847,8 @@ var LEVEL_OPTIONS = {
779
847
  };
780
848
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
781
849
  function printError(prefix, message, hint, cause) {
782
- const colors = paint(process11.stderr);
783
- const styled = takesControlCodes(process11.stderr);
850
+ const colors = paint(process13.stderr);
851
+ const styled = takesControlCodes(process13.stderr);
784
852
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
785
853
  const under = (label, text, tint) => text === undefined ? "" : `
786
854
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -824,24 +892,24 @@ function candidateLine(candidate) {
824
892
  }
825
893
  function positionalBeingTyped(before, { options, positionals }) {
826
894
  const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
827
- let index = 0;
895
+ const typed = [];
828
896
  let at = 0;
829
897
  while (at < before.length) {
830
898
  const word = before[at];
831
899
  if (word === "--") {
832
- index += before.length - at - 1;
900
+ typed.push(...before.slice(at + 1));
833
901
  break;
834
902
  }
835
903
  if (!word.startsWith("-"))
836
- index++;
904
+ typed.push(word);
837
905
  else if (takesValue(word))
838
906
  at++;
839
907
  at++;
840
908
  }
841
909
  const last = positionals.at(-1);
842
- if (index < positionals.length)
843
- return positionals[index];
844
- return last?.replace("]", "").endsWith("...") === true ? last : undefined;
910
+ if (typed.length < positionals.length)
911
+ return { name: positionals[typed.length], typed };
912
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
845
913
  }
846
914
  async function leafCandidates(run, words) {
847
915
  const completing = await completingOf(run);
@@ -849,12 +917,12 @@ async function leafCandidates(run, words) {
849
917
  return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
850
918
  const flag = words.at(-2);
851
919
  const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
920
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
852
921
  if (option?.type === "string") {
853
- const values = option.choices === undefined ? await option.candidates?.() : option.choices;
922
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
854
923
  return values === undefined ? [FILES] : values.map(candidateLine);
855
924
  }
856
- const name = positionalBeingTyped(words.slice(0, -1), completing);
857
- const values = name === undefined ? undefined : await completing.candidates[name]?.();
925
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
858
926
  return values === undefined ? [FILES] : values.map(candidateLine);
859
927
  }
860
928
  async function printCandidates(found) {
@@ -863,9 +931,13 @@ async function printCandidates(found) {
863
931
  return 0;
864
932
  }
865
933
  function packageVersion(entry = Bun.main) {
866
- for (let dir = dirname3(realpathSync(entry));; dir = dirname3(dir)) {
934
+ let resolved = entry;
935
+ try {
936
+ resolved = realpathSync2(entry);
937
+ } catch {}
938
+ for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
867
939
  try {
868
- const { version } = JSON.parse(readFileSync2(join5(dir, "package.json"), "utf8"));
940
+ const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
869
941
  if (typeof version === "string")
870
942
  return version;
871
943
  } catch {}
@@ -873,7 +945,7 @@ function packageVersion(entry = Bun.main) {
873
945
  return "0.0.0";
874
946
  }
875
947
  }
876
- async function runMain({ name, version, run, redact, usage }, argv = process11.argv.slice(2)) {
948
+ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
877
949
  if (argv[0] === COMPLETE)
878
950
  return printCandidates(leafCandidates(run, argv.slice(1)));
879
951
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
@@ -881,11 +953,13 @@ async function runMain({ name, version, run, redact, usage }, argv = process11.a
881
953
  return 0;
882
954
  }
883
955
  let code;
956
+ const started = performance.now();
884
957
  try {
885
958
  code = await run(argv);
886
959
  } catch (error) {
887
960
  code = reportThrown(name, error, redact, wantsJson(argv));
888
961
  }
962
+ notifyEnd(name, code, performance.now() - started);
889
963
  if (usage !== false) {
890
964
  try {
891
965
  recordUsage(usageEntry(name, undefined, argv, code));
@@ -1124,6 +1198,185 @@ function warningsOf(input) {
1124
1198
  return warnings;
1125
1199
  }
1126
1200
 
1201
+ // src/cors.ts
1202
+ var SIMPLE_METHODS = new Set(["GET", "HEAD", "POST"]);
1203
+ var NORMALIZED_METHODS = new Set(["DELETE", "GET", "HEAD", "OPTIONS", "POST", "PUT"]);
1204
+ var SAFELISTED_HEADERS = new Set(["accept", "accept-language", "content-language"]);
1205
+ var LIST = /\s*,\s*/;
1206
+ var HOSTED_SCHEME = /^[a-z][a-z0-9+.-]*:\/\/[^/]/i;
1207
+ function listOf(value) {
1208
+ return value === undefined ? [] : value.trim().split(LIST).filter((item) => item !== "");
1209
+ }
1210
+ function methodOf(input) {
1211
+ return NORMALIZED_METHODS.has(input.toUpperCase()) ? input.toUpperCase() : input;
1212
+ }
1213
+ function requestedHeaders(value) {
1214
+ return listOf(value).map((name) => name.toLowerCase()).filter((name) => !SAFELISTED_HEADERS.has(name));
1215
+ }
1216
+ function originOf(input) {
1217
+ if (input === "null")
1218
+ return input;
1219
+ if (!HOSTED_SCHEME.test(input) || !URL.canParse(input))
1220
+ return;
1221
+ const url = new URL(input);
1222
+ return url.origin === "null" ? `${url.protocol}//${url.host}` : url.origin;
1223
+ }
1224
+ function corsVerdict(status, headers, request) {
1225
+ const reasons = [];
1226
+ const warnings = [];
1227
+ const origin = headers["access-control-allow-origin"];
1228
+ const credentials = headers["access-control-allow-credentials"] === "true";
1229
+ const methods = listOf(headers["access-control-allow-methods"]);
1230
+ const allowedHeaders = new Set(listOf(headers["access-control-allow-headers"]).map((name) => name.toLowerCase()));
1231
+ if (status < 200 || status > 299)
1232
+ reasons.push(`the preflight answered ${status}, a browser wants a 2xx`);
1233
+ if (origin === undefined)
1234
+ reasons.push("no access-control-allow-origin");
1235
+ else if (origin !== "*" && origin !== request.origin)
1236
+ reasons.push(`access-control-allow-origin is ${origin}, not ${request.origin}`);
1237
+ const { method } = request;
1238
+ if (!SIMPLE_METHODS.has(method) && !methods.includes("*") && !methods.includes(method))
1239
+ reasons.push(methods.length === 0 ? `no access-control-allow-methods, which ${method} needs` : `access-control-allow-methods (${methods.join(", ")}) does not list ${method}`);
1240
+ const missing = request.headers.map((name) => name.toLowerCase()).filter((name) => !allowedHeaders.has(name) && (name === "authorization" || !allowedHeaders.has("*")));
1241
+ if (missing.length > 0)
1242
+ reasons.push(`access-control-allow-headers does not cover ${missing.join(", ")}`);
1243
+ if (credentials && (origin === "*" || methods.includes("*") || allowedHeaders.has("*")))
1244
+ warnings.push("access-control-allow-credentials comes with a * wildcard, which a request with cookies or auth does not get");
1245
+ if (origin === request.origin && !listOf(headers.vary).some((name) => name.toLowerCase() === "origin" || name === "*"))
1246
+ warnings.push("if the origin is echoed back from the request, vary lacks origin: a cache may hand this answer to another origin");
1247
+ const shown = Object.fromEntries(Object.entries(headers).filter(([name]) => name.startsWith("access-control-") || name === "vary"));
1248
+ return { allowed: reasons.length === 0, reasons, warnings, headers: shown };
1249
+ }
1250
+
1251
+ // src/dns.ts
1252
+ import { Resolver } from "dns/promises";
1253
+ var TIMEOUT_MS = 3000;
1254
+ var PUBLIC_RESOLVERS = [
1255
+ { name: "cloudflare", address: "1.1.1.1" },
1256
+ { name: "google", address: "8.8.8.8" },
1257
+ { name: "quad9", address: "9.9.9.9" }
1258
+ ];
1259
+ function resolverFor(server, timeoutMs) {
1260
+ const resolver = new Resolver({ timeout: timeoutMs, tries: 1 });
1261
+ if (server.address !== undefined)
1262
+ resolver.setServers([server.address]);
1263
+ return resolver;
1264
+ }
1265
+ function failureOf(error) {
1266
+ const code = error.code;
1267
+ return code === "ETIMEOUT" || code === "ECONNREFUSED" ? "no answer" : String(error.message ?? error);
1268
+ }
1269
+ async function settled(query) {
1270
+ try {
1271
+ return await query;
1272
+ } catch (error) {
1273
+ const code = error.code;
1274
+ if (code === "ENOTFOUND" || code === "ENODATA")
1275
+ return [];
1276
+ throw error;
1277
+ }
1278
+ }
1279
+ function network(timeoutMs = TIMEOUT_MS, upstream = PUBLIC_RESOLVERS[0]) {
1280
+ return {
1281
+ servers: (server) => server.address ?? resolverFor(server, timeoutMs).getServers().join(", "),
1282
+ async records(server, host) {
1283
+ const resolver = resolverFor(server, timeoutMs);
1284
+ try {
1285
+ const [a, aaaa, cname] = await Promise.all([settled(resolver.resolve4(host, { ttl: true })), settled(resolver.resolve6(host, { ttl: true })), settled(resolver.resolveCname(host))]);
1286
+ const ttls = [...a, ...aaaa].map((record) => record.ttl);
1287
+ return { a: a.map((record) => record.address).sort(), aaaa: aaaa.map((record) => record.address).sort(), cname: cname.map((target) => target.toLowerCase()), ttl: ttls.length === 0 ? null : Math.min(...ttls) };
1288
+ } catch (error) {
1289
+ return { a: [], aaaa: [], cname: [], ttl: null, error: failureOf(error) };
1290
+ }
1291
+ },
1292
+ async nameservers(zone) {
1293
+ const resolver = resolverFor(upstream, timeoutMs);
1294
+ const [nameservers, alias] = await Promise.all([settled(resolver.resolveNs(zone)), settled(resolver.resolveCname(zone))]);
1295
+ return alias.length > 0 ? [] : nameservers;
1296
+ },
1297
+ async addressOf(host) {
1298
+ return (await settled(resolverFor(upstream, timeoutMs).resolve4(host)))[0];
1299
+ }
1300
+ };
1301
+ }
1302
+ var NO_ZONE = "no zone with nameservers was found for this name";
1303
+ var ZONE_LOOKUP_FAILED = "the zone of this name could not be looked up, so no nameserver was asked";
1304
+ async function zoneOf(host, client) {
1305
+ const labels = host.split(".");
1306
+ for (let at = 0;at < labels.length - 1; at++) {
1307
+ const zone = labels.slice(at).join(".");
1308
+ const nameservers = await failingToNothing(client.nameservers(zone));
1309
+ if (nameservers === undefined)
1310
+ return { problem: ZONE_LOOKUP_FAILED };
1311
+ if (nameservers.length > 0)
1312
+ return { zone, nameservers: nameservers.sort() };
1313
+ }
1314
+ return { problem: NO_ZONE };
1315
+ }
1316
+ async function failingToNothing(query) {
1317
+ try {
1318
+ return await query;
1319
+ } catch {
1320
+ return;
1321
+ }
1322
+ }
1323
+ function sameFamily(mine, theirs) {
1324
+ if (mine.length === 0 || theirs.length === 0)
1325
+ return mine.length === theirs.length;
1326
+ const other = new Set(theirs);
1327
+ return mine.some((address) => other.has(address));
1328
+ }
1329
+ function sameAnswer(one, other) {
1330
+ if (one.error !== undefined || other.error !== undefined)
1331
+ return one.error === other.error;
1332
+ if (one.cname.length > 0 || other.cname.length > 0)
1333
+ return one.cname.join().toLowerCase() === other.cname.join().toLowerCase();
1334
+ return sameFamily(one.a, other.a) && sameFamily(one.aaaa, other.aaaa);
1335
+ }
1336
+ var TRAILING_DOT = /\.$/;
1337
+ async function dnsReport(target, host, client = network()) {
1338
+ const name = host.replace(TRAILING_DOT, "").toLowerCase();
1339
+ const found = await zoneOf(name, client);
1340
+ const authoritative = await Promise.all(("nameservers" in found ? found.nameservers : []).map(async (nameserver) => {
1341
+ const address = await failingToNothing(client.addressOf(nameserver));
1342
+ return address === undefined ? undefined : { name: nameserver, address };
1343
+ }));
1344
+ const asked = [
1345
+ ...[{ name: "system" }, ...PUBLIC_RESOLVERS].map((server) => ({ server, authoritative: false })),
1346
+ ...authoritative.filter((server) => server !== undefined).map((server) => ({ server, authoritative: true }))
1347
+ ];
1348
+ const answers = await Promise.all(asked.map(async ({ server, authoritative }) => ({ resolver: server.name, server: client.servers(server), authoritative, ...await client.records(server, name) })));
1349
+ return { target, zone: "zone" in found ? found.zone : null, answers, ...verdictOf(answers, "problem" in found ? found.problem : undefined) };
1350
+ }
1351
+ function verdictOf(answers, zoneProblem) {
1352
+ const warnings = zoneProblem === undefined ? [] : [zoneProblem];
1353
+ const answered = answers.filter((answer) => answer.error !== "no answer");
1354
+ const reference = answered.filter((answer) => answer.authoritative);
1355
+ const truth = reference[0] ?? answered[0];
1356
+ const agree = truth === undefined || answered.every((answer) => sameAnswer(answer, truth));
1357
+ if (reference.some((answer) => !sameAnswer(answer, reference[0])))
1358
+ warnings.push("the zone's own nameservers disagree: one of them has not taken the last change yet");
1359
+ for (const answer of answers) {
1360
+ if (answer.error === "no answer")
1361
+ warnings.push(`${answer.resolver} did not answer`);
1362
+ }
1363
+ if (agree)
1364
+ return { agree, warnings };
1365
+ if (reference.length === 0) {
1366
+ warnings.push(`the resolvers disagree, with no nameserver of the zone to tell which is right: ${answered.filter((answer) => !sameAnswer(answer, truth)).map((answer) => answer.resolver).join(", ")} differ from ${truth.resolver}`);
1367
+ return { agree, warnings };
1368
+ }
1369
+ const stale = answered.filter((answer) => !answer.authoritative && !reference.some((ns) => sameAnswer(answer, ns)));
1370
+ for (const answer of stale) {
1371
+ const until = answer.ttl === null || answer.cname.length > 0 ? "" : `, cached for up to ${answer.ttl}s more`;
1372
+ warnings.push(answer.resolver === "system" ? `the system resolver answers differently from the zone's nameservers${until}: \`sudo resolvectl flush-caches\` drops its copy` : `${answer.resolver} answers differently from the zone's nameservers${until}: the change has not reached it yet`);
1373
+ }
1374
+ return { agree, warnings };
1375
+ }
1376
+ function known(report) {
1377
+ return report.answers.some((answer) => answer.error === undefined && answer.a.length + answer.aaaa.length + answer.cname.length > 0);
1378
+ }
1379
+
1127
1380
  // src/net.ts
1128
1381
  import { lookup } from "dns/promises";
1129
1382
  import { isIP } from "net";
@@ -1157,11 +1410,13 @@ function curlResolve(url, resolve) {
1157
1410
  return [];
1158
1411
  return ["--resolve", `${parsed.hostname}:${portOf(parsed)}:${isIP(address) === 6 ? `[${address}]` : address}`];
1159
1412
  }
1160
- async function runCurl(url, { http3: wantsH3, insecure, get, headers = [], resolve, timeoutS = MAX_TIME }) {
1413
+ async function runCurl(url, { http3: wantsH3, insecure, get, method, headers = [], resolve, timeoutS = MAX_TIME }) {
1161
1414
  const args = ["-sS", "-o", "/dev/null", "--connect-timeout", String(Math.min(CONNECT_TIMEOUT, timeoutS)), "--max-time", String(timeoutS), "--write-out", WRITE_OUT, ...curlResolve(url, resolve)];
1162
1415
  for (const header of headers)
1163
1416
  args.push("-H", header);
1164
- if (!get)
1417
+ if (method !== undefined)
1418
+ args.push("-X", method);
1419
+ else if (!get)
1165
1420
  args.push("-I");
1166
1421
  if (wantsH3)
1167
1422
  args.push("--http3");
@@ -1179,10 +1434,14 @@ async function curlHop(url, options) {
1179
1434
  let result = await runCurl(url, options);
1180
1435
  if (result.hop === undefined && options.http3)
1181
1436
  result = await runCurl(url, { ...options, http3: false });
1182
- if (result.hop !== undefined && !options.get && (result.hop.status === 405 || result.hop.status === 501))
1437
+ if (result.hop !== undefined && !options.get && options.method === undefined && result.hop.status >= 400)
1183
1438
  result = await runCurl(url, { ...options, get: true });
1184
1439
  return result;
1185
1440
  }
1441
+ async function curlPreflight(url, request, options) {
1442
+ const asked = [`Origin: ${request.origin}`, `Access-Control-Request-Method: ${request.method}`, ...request.headers.length > 0 ? [`Access-Control-Request-Headers: ${request.headers.join(", ")}`] : []];
1443
+ return runCurl(url, { ...options, headers: [...options.headers ?? [], ...asked], http3: false, get: true, method: "OPTIONS" });
1444
+ }
1186
1445
  async function addressesOf(host, resolve) {
1187
1446
  const bare = resolve?.get(host) ?? host.replace(BRACKETS, "");
1188
1447
  const family = isIP(bare);
@@ -1226,15 +1485,22 @@ By default one line per target: the HTTP version, status, final URL, total time,
1226
1485
  A bare domain is tried over https first and over http when that fails. Redirects are followed hop by hop (at most ${MAX_HOPS}), each hop's status and HTTP version listed. HTTP/3 is spoken only when the installed curl lists it, otherwise it is reported from alt-svc. The certificate is read even when it is not trusted, and --insecure also lets curl go on with it.
1227
1486
  -H adds a header to every request, --resolve host:ip reaches a host at that address instead of the DNS answer (the certificate and the Host header stay the host's), both repeatable.
1228
1487
 
1229
- Warns on a certificate with fewer than 14 days left or not trusted, and on an http:// twin that does not redirect to https (checked for a bare domain or an https URL on the default port).`;
1230
- var EXITS = [[0, "every site answered, warnings or not"], [1, "a site could not be reached"], [2, "a usage error"]];
1488
+ Warns on a certificate with fewer than 14 days left or not trusted, and on an http:// twin that does not redirect to https (checked for a bare domain or an https URL on the default port).
1489
+
1490
+ --dns makes no HTTP request: it asks the system resolver, Cloudflare, Google, Quad9 and each nameserver of the host's zone for its A, AAAA and CNAME records with their TTL, and warns on a resolver answering otherwise than the zone's nameservers, a change not reached it yet.
1491
+ --cors <origin> sends the preflight a browser on that origin would send before a --method request carrying --cors-headers, and says whether the browser would go on, with each reason when it would not.`;
1492
+ var EXITS = [[0, "every site answered, warnings or not"], [1, "a site could not be reached, a CORS preflight was refused, or no resolver knows a name"], [2, "a usage error"]];
1231
1493
  var OPTIONS = {
1232
1494
  insecure: { type: "boolean", short: "k", description: "let curl go on with a certificate it does not trust" },
1233
1495
  header: { type: "string", short: "H", multiple: true, description: "a `Name: value` header sent with every request, repeatable" },
1234
1496
  resolve: { type: "string", multiple: true, description: "host:ip, reach the host at that address instead of the DNS answer, repeatable" },
1235
- timeout: { type: "string", short: "t", description: "longest one request may take (20s): 5s, 1m, a bare number in seconds" },
1497
+ timeout: { type: "string", short: "t", description: "longest one request may take (20s, 3s for a DNS query): 5s, 1m, a bare number in seconds" },
1236
1498
  verbose: { type: "boolean", description: "the whole table for each target instead of one line" },
1237
- json: jsonOption("one object per target {target, url, version, status, chain, timings, addresses, tls, certificate, headers, cdn, offers, httpRedirect, warnings}, an array of them for several targets (an unreachable one is {target, error})")
1499
+ dns: { type: "boolean", description: "compare what each resolver and the zone's nameservers answer for the host, no HTTP request", conflicts: ["cors", "header", "resolve", "insecure", "verbose"] },
1500
+ cors: { type: "string", description: "the origin a browser would call from: whether its CORS preflight lets the request through", conflicts: ["dns", "verbose"] },
1501
+ method: { type: "string", description: "with --cors, the method of the request the preflight asks for (POST)" },
1502
+ "cors-headers": { type: "string", description: "with --cors, the headers it carries, comma separated, empty for none (content-type)" },
1503
+ json: jsonOption("one object per target {target, url, version, status, chain, timings, addresses, tls, certificate, headers, cdn, offers, httpRedirect, warnings}, an array of them for several targets (an unreachable one is {target, error}); with --dns {target, zone, answers, agree, warnings}, with --cors {target, url, status, request, allowed, reasons, warnings, headers}")
1238
1504
  };
1239
1505
  var BRACKETS2 = /^\[|\]$/g;
1240
1506
  var HEADER_LINE = /^[\w!#$%&'*+.^`|~-]+:/;
@@ -1316,9 +1582,9 @@ function ms2(value) {
1316
1582
  return `${value}ms`;
1317
1583
  }
1318
1584
  function compact(report) {
1319
- const { dim } = paint(process13.stdout);
1585
+ const { dim } = paint(process15.stdout);
1320
1586
  const redirects = report.chain.length - 1;
1321
- const parts = [`${role("accent", process13.stdout)(versionLabel(report.version))} ${role("value", process13.stdout)(String(report.status))} ${role("path", process13.stdout)(report.url)}`, ms2(report.timings.total)];
1587
+ const parts = [`${role("accent", process15.stdout)(versionLabel(report.version))} ${role("value", process15.stdout)(String(report.status))} ${role("path", process15.stdout)(report.url)}`, ms2(report.timings.total)];
1322
1588
  const address = report.addresses.a[0] ?? report.addresses.aaaa[0];
1323
1589
  if (redirects > 0)
1324
1590
  parts.push(`${redirects} ${redirects === 1 ? "redirect" : "redirects"}`);
@@ -1327,14 +1593,14 @@ function compact(report) {
1327
1593
  if (address !== undefined)
1328
1594
  parts.push(address);
1329
1595
  const line = parts.join(dim(" "));
1330
- return report.warnings.length === 0 ? line : `${line} ${marked("warn", report.warnings.join("; "), process13.stdout)}`;
1596
+ return report.warnings.length === 0 ? line : `${line} ${marked("warn", report.warnings.join("; "), process15.stdout)}`;
1331
1597
  }
1332
1598
  function print(report) {
1333
- const label = role("label", process13.stdout);
1334
- const value = role("value", process13.stdout);
1335
- const accent = role("accent", process13.stdout);
1599
+ const label = role("label", process15.stdout);
1600
+ const value = role("value", process15.stdout);
1601
+ const accent = role("accent", process15.stdout);
1336
1602
  const row = (name, text) => console.log(`${label(name.padEnd(LABEL_WIDTH))} ${text}`);
1337
- console.log(`${accent(versionLabel(report.version))} ${value(String(report.status))} ${role("path", process13.stdout)(report.url)}`);
1603
+ console.log(`${accent(versionLabel(report.version))} ${value(String(report.status))} ${role("path", process15.stdout)(report.url)}`);
1338
1604
  console.log("");
1339
1605
  if (report.chain.length > 1) {
1340
1606
  console.log(table(report.chain.map((hop) => [String(hop.status), versionLabel(hop.version), ms2(hop.ms), hop.url]), { align: ["right", "left", "right", "left"] }));
@@ -1359,16 +1625,98 @@ function print(report) {
1359
1625
  if (report.httpRedirect !== null)
1360
1626
  row("http://", report.httpRedirect.toHttps ? `redirects to https (${report.httpRedirect.status})` : `answers ${report.httpRedirect.status}`);
1361
1627
  for (const warning of report.warnings)
1362
- console.log(marked("warn", warning, process13.stdout));
1628
+ console.log(marked("warn", warning, process15.stdout));
1629
+ }
1630
+ function printDns(report) {
1631
+ const label = role("label", process15.stdout);
1632
+ const listed = (values) => values.length === 0 ? "-" : values.join(" ");
1633
+ console.log(`${role("path", process15.stdout)(report.target)} ${label(report.zone === null ? "no zone found" : `zone ${report.zone}`)}`);
1634
+ console.log(table([
1635
+ ["RESOLVER", "SERVER", "A", "AAAA", "CNAME", "TTL"],
1636
+ ...report.answers.map((answer) => [
1637
+ answer.authoritative ? `${answer.resolver} (ns)` : answer.resolver,
1638
+ answer.server,
1639
+ ...answer.error === undefined ? [listed(answer.a), listed(answer.aaaa), listed(answer.cname)] : [answer.error, "", ""],
1640
+ answer.ttl === null ? "-" : `${answer.ttl}s`
1641
+ ])
1642
+ ], { header: true }));
1643
+ if (report.agree)
1644
+ console.log(marked("ok", "every resolver gives the same answer", process15.stdout));
1645
+ for (const warning of report.warnings)
1646
+ console.log(marked("warn", warning, process15.stdout));
1647
+ }
1648
+ async function dnsMain(inputs, timeoutMs, json) {
1649
+ const hosts = inputs.map((input) => {
1650
+ const host = parseTarget(input)?.url.hostname;
1651
+ if (host === undefined)
1652
+ badUsage(`not a URL or domain: ${input}`);
1653
+ if (isIP2(host.replace(BRACKETS2, "")) !== 0)
1654
+ badUsage(`--dns takes a name, not the address ${input}`);
1655
+ return { input, host };
1656
+ });
1657
+ const client = network(timeoutMs);
1658
+ const reports = await Promise.all(hosts.map(async ({ input, host }) => dnsReport(input, host, client)));
1659
+ if (json) {
1660
+ printJson(reports.length === 1 ? reports[0] : reports);
1661
+ } else {
1662
+ for (const [at, report] of reports.entries()) {
1663
+ if (at > 0)
1664
+ console.log("");
1665
+ printDns(report);
1666
+ }
1667
+ }
1668
+ return reports.every(known) ? 0 : 1;
1669
+ }
1670
+ function printCors(report) {
1671
+ const label = role("label", process15.stdout);
1672
+ const { request } = report;
1673
+ const asked = `from ${request.origin}, ${request.method}${request.headers.length === 0 ? "" : ` with ${request.headers.join(", ")}`}`;
1674
+ console.log(`${marked(report.allowed ? "ok" : "problem", report.allowed ? "allowed" : "refused", process15.stdout)} ${role("value", process15.stdout)(String(report.status))} ${role("path", process15.stdout)(report.url)} ${label(asked)}`);
1675
+ for (const [name, value] of Object.entries(report.headers))
1676
+ console.log(` ${label(name)} ${value}`);
1677
+ for (const reason of report.reasons)
1678
+ console.log(marked("problem", reason, process15.stdout));
1679
+ for (const warning of report.warnings)
1680
+ console.log(marked("warn", warning, process15.stdout));
1681
+ }
1682
+ async function corsMain(targets, request, { insecure, wire }, json) {
1683
+ const reports = await Promise.all(targets.map(async ({ input, target }) => {
1684
+ const { hop, errormsg } = await curlPreflight(target.url.href, request, { ...wire, insecure });
1685
+ if (hop === undefined)
1686
+ return { target: input, error: `could not reach ${target.url.host}: ${errormsg ?? "no response"}` };
1687
+ return { target: input, url: hop.url, status: hop.status, request, ...corsVerdict(hop.status, hop.headers, request) };
1688
+ }));
1689
+ const [only] = reports;
1690
+ if (reports.length === 1 && only !== undefined && "error" in only)
1691
+ fail(only.error, 1);
1692
+ if (json) {
1693
+ printJson(reports.length === 1 ? only : reports);
1694
+ } else {
1695
+ for (const report of reports) {
1696
+ if ("error" in report)
1697
+ console.error(marked("problem", report.error, process15.stderr));
1698
+ else
1699
+ printCors(report);
1700
+ }
1701
+ }
1702
+ return reports.every((report) => ("allowed" in report) && report.allowed) ? 0 : 1;
1363
1703
  }
1364
1704
  async function main(args) {
1365
- const { values, positionals } = parse(args, USAGE, OPTIONS, { positionals: ["<url|domain>..."], exits: EXITS, replaces: "the httpversion fish function, curl -sI chains and openssl s_client one-liners", examples: ["probe example.com", "probe https://example.com/path --json", ["probe a.test b.test", "one line each"], ['probe https://example.com --resolve example.com:203.0.113.7 -H "Host: example.com" --verbose', "a server before its DNS points at it"]] });
1705
+ const { values, positionals } = parse(args, USAGE, OPTIONS, { positionals: ["<url|domain>..."], exits: EXITS, replaces: "the httpversion fish function, curl -sI chains, openssl s_client and dig @server one-liners", examples: ["probe example.com", "probe https://example.com/path --json", ["probe a.test b.test", "one line each"], ['probe https://example.com --resolve example.com:203.0.113.7 -H "Host: example.com" --verbose', "a server before its DNS points at it"], ["probe --dns example.com", "whether a DNS change has reached every resolver"], ["probe --cors https://app.example.com --method PUT --cors-headers content-type,authorization https://api.example.com/items", "whether the browser would let the call through"]] });
1706
+ if (values.cors === undefined) {
1707
+ if (values.method !== undefined)
1708
+ badUsage("--method goes with --cors");
1709
+ if (values["cors-headers"] !== undefined)
1710
+ badUsage("--cors-headers goes with --cors");
1711
+ }
1366
1712
  const headers = values.header ?? [];
1367
1713
  for (const header of headers) {
1368
1714
  if (!HEADER_LINE.test(header))
1369
1715
  badUsage(`-H takes "Name: value", not ${header}`);
1370
1716
  }
1371
1717
  const timeoutMs = values.timeout === undefined ? undefined : duration(values.timeout, "timeout", 0, "s");
1718
+ if (values.dns === true)
1719
+ return dnsMain(positionals, timeoutMs, values.json === true);
1372
1720
  const wire = { headers, resolve: resolvesOf(values.resolve ?? []), ...timeoutMs === undefined ? {} : { timeoutS: timeoutMs / 1000 } };
1373
1721
  const targets = positionals.map((input) => {
1374
1722
  const target = parseTarget(input);
@@ -1376,6 +1724,13 @@ async function main(args) {
1376
1724
  badUsage(`not a URL or domain: ${input}`);
1377
1725
  return { input, target };
1378
1726
  });
1727
+ if (values.cors !== undefined) {
1728
+ const origin = originOf(values.cors);
1729
+ if (origin === undefined)
1730
+ badUsage(`--cors takes an origin such as https://app.example.com, not ${values.cors}`);
1731
+ const request = { origin, method: methodOf(values.method ?? "POST"), headers: requestedHeaders(values["cors-headers"] ?? "content-type") };
1732
+ return corsMain(targets, request, { insecure: values.insecure === true, wire }, values.json === true);
1733
+ }
1379
1734
  const reports = await Promise.all(targets.map(async ({ input, target }) => probe(target, input, { insecure: values.insecure === true, wire })));
1380
1735
  const [only] = reports;
1381
1736
  if (reports.length === 1 && only !== undefined && "error" in only)
@@ -1387,12 +1742,12 @@ async function main(args) {
1387
1742
  let first = true;
1388
1743
  for (const report of reports) {
1389
1744
  if ("error" in report) {
1390
- console.error(marked("problem", report.error, process13.stderr));
1745
+ console.error(marked("problem", report.error, process15.stderr));
1391
1746
  } else if (values.verbose === true) {
1392
1747
  if (!first)
1393
1748
  console.log("");
1394
1749
  if (reports.length > 1)
1395
- console.log(role("label", process13.stdout)(report.target));
1750
+ console.log(role("label", process15.stdout)(report.target));
1396
1751
  print(report);
1397
1752
  } else {
1398
1753
  console.log(compact(report));
@@ -1401,4 +1756,4 @@ async function main(args) {
1401
1756
  }
1402
1757
  return reports.some((report) => ("error" in report)) ? 1 : 0;
1403
1758
  }
1404
- process13.exitCode = await runMain({ name: "probe", run: main });
1759
+ process15.exitCode = await runMain({ name: "probe", run: main });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-probe",
3
3
  "type": "module",
4
- "version": "0.3.0",
4
+ "version": "0.4.1",
5
5
  "description": "probe: a site's HTTP version, redirect chain, timings, addresses, TLS certificate and notable headers in one call, with warnings.",
6
6
  "author": "Kaynooo <contact@kaynooo.fr>",
7
7
  "license": "MIT",
@@ -35,6 +35,6 @@
35
35
  "probe": "$npm_execpath src/probe.ts"
36
36
  },
37
37
  "devDependencies": {
38
- "@kaynooo/cli-kit": "0.36.0"
38
+ "@kaynooo/cli-kit": "0.39.0"
39
39
  }
40
40
  }