@kaynooo/cli-probe 0.3.0 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +17 -2
  2. package/dist/probe.js +499 -65
  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));
@@ -540,7 +566,7 @@ class Completing {
540
566
  }
541
567
  var completion = { active: false };
542
568
  var OUTPUT_OPTIONS = {
543
- color: { type: "string", description: "auto (on a terminal alone), always or never" },
569
+ color: { type: "string", choices: ["auto", "always", "never"], description: "auto (the default) colours on a terminal alone" },
544
570
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
545
571
  };
546
572
  function applyOutput(color, plain, env = process9.env) {
@@ -712,21 +738,123 @@ 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/completions.ts
776
+ var COMPLETION_SHELLS = ["fish", "bash", "zsh"];
777
+ var FISH_FUNCTION = `functions -q __kaynooo_cli_complete; or function __kaynooo_cli_complete --argument-names bin --description 'what a @kaynooo/cli-kit bin offers for the word being typed'
778
+ set -l tokens (commandline -xpc 2>/dev/null; or commandline -opc)
779
+ set -l current (commandline -ct)
780
+ for line in ($bin __complete $tokens[2..-1] $current 2>/dev/null)
781
+ if test "$line" = __files__
782
+ __fish_complete_path $current
783
+ else
784
+ echo $line
785
+ end
786
+ end
787
+ end`;
788
+ var BASH_FUNCTION = `__kaynooo_cli_complete() {
789
+ local IFS=$'\\n' cur=\${COMP_WORDS[COMP_CWORD]} line words=
790
+ local -a lines
791
+ COMPREPLY=()
792
+ lines=($("\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1:COMP_CWORD}" 2>/dev/null))
793
+ for line in "\${lines[@]}"; do
794
+ if [[ $line == __files__ ]]; then
795
+ COMPREPLY+=($(compgen -f -- "$cur"))
796
+ else
797
+ words+="\${line%%$'\\t'*}"$'\\n'
798
+ fi
799
+ done
800
+ COMPREPLY+=($(compgen -W "$words" -- "$cur"))
801
+ }`;
802
+ var ZSH_FUNCTION = `__kaynooo_cli_complete() {
803
+ local line
804
+ local -a described plain
805
+ for line in \${(f)"$("\${words[1]}" __complete "\${(@)words[2,CURRENT]}" 2>/dev/null)"}; do
806
+ if [[ $line == __files__ ]]; then
807
+ _files
808
+ elif [[ $line == *$'\\t'* ]]; then
809
+ described+=("\${\${line%%$'\\t'*}//:/\\\\:}:\${line#*$'\\t'}")
810
+ else
811
+ plain+=("$line")
812
+ fi
813
+ done
814
+ (( \${#described} )) && _describe -V value described
815
+ (( \${#plain} )) && compadd -- "\${plain[@]}"
816
+ return 0
817
+ }`;
818
+ function completionScript(shell, bins, header = `# Generated by \`${bins[0]} --completions ${shell}\``) {
819
+ if (shell === "fish")
820
+ return `${header}
821
+ ${FISH_FUNCTION}
822
+ ${bins.map((bin) => `complete -c ${bin} -f -a '(__kaynooo_cli_complete ${bin})'
823
+ `).join("")}`;
824
+ if (shell === "bash")
825
+ return `${header}
826
+ ${BASH_FUNCTION}
827
+ complete -F __kaynooo_cli_complete ${bins.join(" ")}
828
+ `;
829
+ return `${header}
830
+ ${ZSH_FUNCTION}
831
+ compdef __kaynooo_cli_complete ${bins.join(" ")}
832
+ `;
833
+ }
834
+
835
+ // ../kit/src/notify.ts
723
836
  import process11 from "process";
837
+ var NOTIFY_AFTER_MS = 1e4;
838
+ var CANCELLED = 130;
839
+ function base64(text) {
840
+ return Buffer.from(text).toString("base64");
841
+ }
842
+ function notification(title, body, env = process11.env) {
843
+ const id = `kit${process11.pid}`;
844
+ 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\\`];
845
+ return codes.map((code) => env.TMUX === undefined || env.TMUX === "" ? code : `\x1BPtmux;${code.replaceAll("\x1B", "\x1B\x1B")}\x1B\\`).join("");
846
+ }
847
+ function notifyEnd(command, code, ms, { stream = process11.stderr, env = process11.env } = {}) {
848
+ if (ms < NOTIFY_AFTER_MS || code === CANCELLED || outputMode(stream, env) !== "terminal")
849
+ return;
850
+ stream.write(notification(command, code === 0 ? `done in ${formatDuration(ms)}` : `failed with exit ${code} after ${formatDuration(ms)}`, env));
851
+ }
724
852
 
725
853
  // ../kit/src/usage.ts
726
854
  import { appendFileSync, mkdirSync } from "fs";
727
855
  import { homedir as homedir3 } from "os";
728
856
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
729
- import process10 from "process";
857
+ import process12 from "process";
730
858
 
731
859
  // ../kit/src/logs.ts
732
860
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -740,14 +868,14 @@ var usageError;
740
868
  function noteUsageError(message) {
741
869
  usageError = message;
742
870
  }
743
- function stateHome(env = process10.env) {
871
+ function stateHome(env = process12.env) {
744
872
  const dir = env.XDG_STATE_HOME;
745
873
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
746
874
  }
747
- function usagePath(env = process10.env) {
875
+ function usagePath(env = process12.env) {
748
876
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
749
877
  }
750
- function usageRecorded(env = process10.env) {
878
+ function usageRecorded(env = process12.env) {
751
879
  const off = env.KAYNOOO_CLI_NO_USAGE;
752
880
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
753
881
  }
@@ -761,7 +889,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
761
889
  usageError = undefined;
762
890
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
763
891
  }
764
- function recordUsage(entry, env = process10.env) {
892
+ function recordUsage(entry, env = process12.env) {
765
893
  if (!usageRecorded(env))
766
894
  return;
767
895
  try {
@@ -777,10 +905,14 @@ var LEVEL_OPTIONS = {
777
905
  ...OUTPUT_OPTIONS,
778
906
  help: { type: "boolean", short: "h", description: "show this help" }
779
907
  };
780
- var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
908
+ var TOP_OPTIONS = {
909
+ ...LEVEL_OPTIONS,
910
+ version: { type: "boolean", short: "v", description: "print the version" },
911
+ completions: { type: "string", choices: COMPLETION_SHELLS, description: "print the shell completion script" }
912
+ };
781
913
  function printError(prefix, message, hint, cause) {
782
- const colors = paint(process11.stderr);
783
- const styled = takesControlCodes(process11.stderr);
914
+ const colors = paint(process13.stderr);
915
+ const styled = takesControlCodes(process13.stderr);
784
916
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
785
917
  const under = (label, text, tint) => text === undefined ? "" : `
786
918
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -824,24 +956,24 @@ function candidateLine(candidate) {
824
956
  }
825
957
  function positionalBeingTyped(before, { options, positionals }) {
826
958
  const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
827
- let index = 0;
959
+ const typed = [];
828
960
  let at = 0;
829
961
  while (at < before.length) {
830
962
  const word = before[at];
831
963
  if (word === "--") {
832
- index += before.length - at - 1;
964
+ typed.push(...before.slice(at + 1));
833
965
  break;
834
966
  }
835
967
  if (!word.startsWith("-"))
836
- index++;
968
+ typed.push(word);
837
969
  else if (takesValue(word))
838
970
  at++;
839
971
  at++;
840
972
  }
841
973
  const last = positionals.at(-1);
842
- if (index < positionals.length)
843
- return positionals[index];
844
- return last?.replace("]", "").endsWith("...") === true ? last : undefined;
974
+ if (typed.length < positionals.length)
975
+ return { name: positionals[typed.length], typed };
976
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
845
977
  }
846
978
  async function leafCandidates(run, words) {
847
979
  const completing = await completingOf(run);
@@ -849,23 +981,40 @@ async function leafCandidates(run, words) {
849
981
  return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
850
982
  const flag = words.at(-2);
851
983
  const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
984
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
852
985
  if (option?.type === "string") {
853
- const values = option.choices === undefined ? await option.candidates?.() : option.choices;
986
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
854
987
  return values === undefined ? [FILES] : values.map(candidateLine);
855
988
  }
856
- const name = positionalBeingTyped(words.slice(0, -1), completing);
857
- const values = name === undefined ? undefined : await completing.candidates[name]?.();
989
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
858
990
  return values === undefined ? [FILES] : values.map(candidateLine);
859
991
  }
992
+ var COMPLETIONS = "--completions";
993
+ function flagValue([flag = "", ...rest]) {
994
+ return flag.includes("=") ? [flag.slice(flag.indexOf("=") + 1), ...rest] : rest;
995
+ }
996
+ function printCompletionScript(name, args) {
997
+ const shell = COMPLETION_SHELLS.find((each) => each === args[0]);
998
+ if (shell === undefined || args.length !== 1) {
999
+ printError(name, `${COMPLETIONS} takes one of ${COMPLETION_SHELLS.join(", ")}`, `${name} ${COMPLETIONS} fish`);
1000
+ return 2;
1001
+ }
1002
+ console.log(completionScript(shell, [name]).trimEnd());
1003
+ return 0;
1004
+ }
860
1005
  async function printCandidates(found) {
861
1006
  for (const line of await found)
862
1007
  console.log(line);
863
1008
  return 0;
864
1009
  }
865
1010
  function packageVersion(entry = Bun.main) {
866
- for (let dir = dirname3(realpathSync(entry));; dir = dirname3(dir)) {
1011
+ let resolved = entry;
1012
+ try {
1013
+ resolved = realpathSync2(entry);
1014
+ } catch {}
1015
+ for (let dir = dirname3(resolved);; dir = dirname3(dir)) {
867
1016
  try {
868
- const { version } = JSON.parse(readFileSync2(join5(dir, "package.json"), "utf8"));
1017
+ const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
869
1018
  if (typeof version === "string")
870
1019
  return version;
871
1020
  } catch {}
@@ -873,19 +1022,23 @@ function packageVersion(entry = Bun.main) {
873
1022
  return "0.0.0";
874
1023
  }
875
1024
  }
876
- async function runMain({ name, version, run, redact, usage }, argv = process11.argv.slice(2)) {
1025
+ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
877
1026
  if (argv[0] === COMPLETE)
878
1027
  return printCandidates(leafCandidates(run, argv.slice(1)));
1028
+ if (argv[0] === COMPLETIONS || argv[0]?.startsWith(`${COMPLETIONS}=`) === true)
1029
+ return printCompletionScript(name, flagValue(argv));
879
1030
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
880
1031
  console.log(version ?? packageVersion());
881
1032
  return 0;
882
1033
  }
883
1034
  let code;
1035
+ const started = performance.now();
884
1036
  try {
885
1037
  code = await run(argv);
886
1038
  } catch (error) {
887
1039
  code = reportThrown(name, error, redact, wantsJson(argv));
888
1040
  }
1041
+ notifyEnd(name, code, performance.now() - started);
889
1042
  if (usage !== false) {
890
1043
  try {
891
1044
  recordUsage(usageEntry(name, undefined, argv, code));
@@ -1124,6 +1277,185 @@ function warningsOf(input) {
1124
1277
  return warnings;
1125
1278
  }
1126
1279
 
1280
+ // src/cors.ts
1281
+ var SIMPLE_METHODS = new Set(["GET", "HEAD", "POST"]);
1282
+ var NORMALIZED_METHODS = new Set(["DELETE", "GET", "HEAD", "OPTIONS", "POST", "PUT"]);
1283
+ var SAFELISTED_HEADERS = new Set(["accept", "accept-language", "content-language"]);
1284
+ var LIST = /\s*,\s*/;
1285
+ var HOSTED_SCHEME = /^[a-z][a-z0-9+.-]*:\/\/[^/]/i;
1286
+ function listOf(value) {
1287
+ return value === undefined ? [] : value.trim().split(LIST).filter((item) => item !== "");
1288
+ }
1289
+ function methodOf(input) {
1290
+ return NORMALIZED_METHODS.has(input.toUpperCase()) ? input.toUpperCase() : input;
1291
+ }
1292
+ function requestedHeaders(value) {
1293
+ return listOf(value).map((name) => name.toLowerCase()).filter((name) => !SAFELISTED_HEADERS.has(name));
1294
+ }
1295
+ function originOf(input) {
1296
+ if (input === "null")
1297
+ return input;
1298
+ if (!HOSTED_SCHEME.test(input) || !URL.canParse(input))
1299
+ return;
1300
+ const url = new URL(input);
1301
+ return url.origin === "null" ? `${url.protocol}//${url.host}` : url.origin;
1302
+ }
1303
+ function corsVerdict(status, headers, request) {
1304
+ const reasons = [];
1305
+ const warnings = [];
1306
+ const origin = headers["access-control-allow-origin"];
1307
+ const credentials = headers["access-control-allow-credentials"] === "true";
1308
+ const methods = listOf(headers["access-control-allow-methods"]);
1309
+ const allowedHeaders = new Set(listOf(headers["access-control-allow-headers"]).map((name) => name.toLowerCase()));
1310
+ if (status < 200 || status > 299)
1311
+ reasons.push(`the preflight answered ${status}, a browser wants a 2xx`);
1312
+ if (origin === undefined)
1313
+ reasons.push("no access-control-allow-origin");
1314
+ else if (origin !== "*" && origin !== request.origin)
1315
+ reasons.push(`access-control-allow-origin is ${origin}, not ${request.origin}`);
1316
+ const { method } = request;
1317
+ if (!SIMPLE_METHODS.has(method) && !methods.includes("*") && !methods.includes(method))
1318
+ reasons.push(methods.length === 0 ? `no access-control-allow-methods, which ${method} needs` : `access-control-allow-methods (${methods.join(", ")}) does not list ${method}`);
1319
+ const missing = request.headers.map((name) => name.toLowerCase()).filter((name) => !allowedHeaders.has(name) && (name === "authorization" || !allowedHeaders.has("*")));
1320
+ if (missing.length > 0)
1321
+ reasons.push(`access-control-allow-headers does not cover ${missing.join(", ")}`);
1322
+ if (credentials && (origin === "*" || methods.includes("*") || allowedHeaders.has("*")))
1323
+ warnings.push("access-control-allow-credentials comes with a * wildcard, which a request with cookies or auth does not get");
1324
+ if (origin === request.origin && !listOf(headers.vary).some((name) => name.toLowerCase() === "origin" || name === "*"))
1325
+ warnings.push("if the origin is echoed back from the request, vary lacks origin: a cache may hand this answer to another origin");
1326
+ const shown = Object.fromEntries(Object.entries(headers).filter(([name]) => name.startsWith("access-control-") || name === "vary"));
1327
+ return { allowed: reasons.length === 0, reasons, warnings, headers: shown };
1328
+ }
1329
+
1330
+ // src/dns.ts
1331
+ import { Resolver } from "dns/promises";
1332
+ var TIMEOUT_MS = 3000;
1333
+ var PUBLIC_RESOLVERS = [
1334
+ { name: "cloudflare", address: "1.1.1.1" },
1335
+ { name: "google", address: "8.8.8.8" },
1336
+ { name: "quad9", address: "9.9.9.9" }
1337
+ ];
1338
+ function resolverFor(server, timeoutMs) {
1339
+ const resolver = new Resolver({ timeout: timeoutMs, tries: 1 });
1340
+ if (server.address !== undefined)
1341
+ resolver.setServers([server.address]);
1342
+ return resolver;
1343
+ }
1344
+ function failureOf(error) {
1345
+ const code = error.code;
1346
+ return code === "ETIMEOUT" || code === "ECONNREFUSED" ? "no answer" : String(error.message ?? error);
1347
+ }
1348
+ async function settled(query) {
1349
+ try {
1350
+ return await query;
1351
+ } catch (error) {
1352
+ const code = error.code;
1353
+ if (code === "ENOTFOUND" || code === "ENODATA")
1354
+ return [];
1355
+ throw error;
1356
+ }
1357
+ }
1358
+ function network(timeoutMs = TIMEOUT_MS, upstream = PUBLIC_RESOLVERS[0]) {
1359
+ return {
1360
+ servers: (server) => server.address ?? resolverFor(server, timeoutMs).getServers().join(", "),
1361
+ async records(server, host) {
1362
+ const resolver = resolverFor(server, timeoutMs);
1363
+ try {
1364
+ const [a, aaaa, cname] = await Promise.all([settled(resolver.resolve4(host, { ttl: true })), settled(resolver.resolve6(host, { ttl: true })), settled(resolver.resolveCname(host))]);
1365
+ const ttls = [...a, ...aaaa].map((record) => record.ttl);
1366
+ 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) };
1367
+ } catch (error) {
1368
+ return { a: [], aaaa: [], cname: [], ttl: null, error: failureOf(error) };
1369
+ }
1370
+ },
1371
+ async nameservers(zone) {
1372
+ const resolver = resolverFor(upstream, timeoutMs);
1373
+ const [nameservers, alias] = await Promise.all([settled(resolver.resolveNs(zone)), settled(resolver.resolveCname(zone))]);
1374
+ return alias.length > 0 ? [] : nameservers;
1375
+ },
1376
+ async addressOf(host) {
1377
+ return (await settled(resolverFor(upstream, timeoutMs).resolve4(host)))[0];
1378
+ }
1379
+ };
1380
+ }
1381
+ var NO_ZONE = "no zone with nameservers was found for this name";
1382
+ var ZONE_LOOKUP_FAILED = "the zone of this name could not be looked up, so no nameserver was asked";
1383
+ async function zoneOf(host, client) {
1384
+ const labels = host.split(".");
1385
+ for (let at = 0;at < labels.length - 1; at++) {
1386
+ const zone = labels.slice(at).join(".");
1387
+ const nameservers = await failingToNothing(client.nameservers(zone));
1388
+ if (nameservers === undefined)
1389
+ return { problem: ZONE_LOOKUP_FAILED };
1390
+ if (nameservers.length > 0)
1391
+ return { zone, nameservers: nameservers.sort() };
1392
+ }
1393
+ return { problem: NO_ZONE };
1394
+ }
1395
+ async function failingToNothing(query) {
1396
+ try {
1397
+ return await query;
1398
+ } catch {
1399
+ return;
1400
+ }
1401
+ }
1402
+ function sameFamily(mine, theirs) {
1403
+ if (mine.length === 0 || theirs.length === 0)
1404
+ return mine.length === theirs.length;
1405
+ const other = new Set(theirs);
1406
+ return mine.some((address) => other.has(address));
1407
+ }
1408
+ function sameAnswer(one, other) {
1409
+ if (one.error !== undefined || other.error !== undefined)
1410
+ return one.error === other.error;
1411
+ if (one.cname.length > 0 || other.cname.length > 0)
1412
+ return one.cname.join().toLowerCase() === other.cname.join().toLowerCase();
1413
+ return sameFamily(one.a, other.a) && sameFamily(one.aaaa, other.aaaa);
1414
+ }
1415
+ var TRAILING_DOT = /\.$/;
1416
+ async function dnsReport(target, host, client = network()) {
1417
+ const name = host.replace(TRAILING_DOT, "").toLowerCase();
1418
+ const found = await zoneOf(name, client);
1419
+ const authoritative = await Promise.all(("nameservers" in found ? found.nameservers : []).map(async (nameserver) => {
1420
+ const address = await failingToNothing(client.addressOf(nameserver));
1421
+ return address === undefined ? undefined : { name: nameserver, address };
1422
+ }));
1423
+ const asked = [
1424
+ ...[{ name: "system" }, ...PUBLIC_RESOLVERS].map((server) => ({ server, authoritative: false })),
1425
+ ...authoritative.filter((server) => server !== undefined).map((server) => ({ server, authoritative: true }))
1426
+ ];
1427
+ const answers = await Promise.all(asked.map(async ({ server, authoritative }) => ({ resolver: server.name, server: client.servers(server), authoritative, ...await client.records(server, name) })));
1428
+ return { target, zone: "zone" in found ? found.zone : null, answers, ...verdictOf(answers, "problem" in found ? found.problem : undefined) };
1429
+ }
1430
+ function verdictOf(answers, zoneProblem) {
1431
+ const warnings = zoneProblem === undefined ? [] : [zoneProblem];
1432
+ const answered = answers.filter((answer) => answer.error !== "no answer");
1433
+ const reference = answered.filter((answer) => answer.authoritative);
1434
+ const truth = reference[0] ?? answered[0];
1435
+ const agree = truth === undefined || answered.every((answer) => sameAnswer(answer, truth));
1436
+ if (reference.some((answer) => !sameAnswer(answer, reference[0])))
1437
+ warnings.push("the zone's own nameservers disagree: one of them has not taken the last change yet");
1438
+ for (const answer of answers) {
1439
+ if (answer.error === "no answer")
1440
+ warnings.push(`${answer.resolver} did not answer`);
1441
+ }
1442
+ if (agree)
1443
+ return { agree, warnings };
1444
+ if (reference.length === 0) {
1445
+ 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}`);
1446
+ return { agree, warnings };
1447
+ }
1448
+ const stale = answered.filter((answer) => !answer.authoritative && !reference.some((ns) => sameAnswer(answer, ns)));
1449
+ for (const answer of stale) {
1450
+ const until = answer.ttl === null || answer.cname.length > 0 ? "" : `, cached for up to ${answer.ttl}s more`;
1451
+ 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`);
1452
+ }
1453
+ return { agree, warnings };
1454
+ }
1455
+ function known(report) {
1456
+ return report.answers.some((answer) => answer.error === undefined && answer.a.length + answer.aaaa.length + answer.cname.length > 0);
1457
+ }
1458
+
1127
1459
  // src/net.ts
1128
1460
  import { lookup } from "dns/promises";
1129
1461
  import { isIP } from "net";
@@ -1157,11 +1489,13 @@ function curlResolve(url, resolve) {
1157
1489
  return [];
1158
1490
  return ["--resolve", `${parsed.hostname}:${portOf(parsed)}:${isIP(address) === 6 ? `[${address}]` : address}`];
1159
1491
  }
1160
- async function runCurl(url, { http3: wantsH3, insecure, get, headers = [], resolve, timeoutS = MAX_TIME }) {
1492
+ async function runCurl(url, { http3: wantsH3, insecure, get, method, headers = [], resolve, timeoutS = MAX_TIME }) {
1161
1493
  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
1494
  for (const header of headers)
1163
1495
  args.push("-H", header);
1164
- if (!get)
1496
+ if (method !== undefined)
1497
+ args.push("-X", method);
1498
+ else if (!get)
1165
1499
  args.push("-I");
1166
1500
  if (wantsH3)
1167
1501
  args.push("--http3");
@@ -1179,10 +1513,14 @@ async function curlHop(url, options) {
1179
1513
  let result = await runCurl(url, options);
1180
1514
  if (result.hop === undefined && options.http3)
1181
1515
  result = await runCurl(url, { ...options, http3: false });
1182
- if (result.hop !== undefined && !options.get && (result.hop.status === 405 || result.hop.status === 501))
1516
+ if (result.hop !== undefined && !options.get && options.method === undefined && result.hop.status >= 400)
1183
1517
  result = await runCurl(url, { ...options, get: true });
1184
1518
  return result;
1185
1519
  }
1520
+ async function curlPreflight(url, request, options) {
1521
+ const asked = [`Origin: ${request.origin}`, `Access-Control-Request-Method: ${request.method}`, ...request.headers.length > 0 ? [`Access-Control-Request-Headers: ${request.headers.join(", ")}`] : []];
1522
+ return runCurl(url, { ...options, headers: [...options.headers ?? [], ...asked], http3: false, get: true, method: "OPTIONS" });
1523
+ }
1186
1524
  async function addressesOf(host, resolve) {
1187
1525
  const bare = resolve?.get(host) ?? host.replace(BRACKETS, "");
1188
1526
  const family = isIP(bare);
@@ -1226,15 +1564,22 @@ By default one line per target: the HTTP version, status, final URL, total time,
1226
1564
  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
1565
  -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
1566
 
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"]];
1567
+ 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).
1568
+
1569
+ --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.
1570
+ --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.`;
1571
+ 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
1572
  var OPTIONS = {
1232
1573
  insecure: { type: "boolean", short: "k", description: "let curl go on with a certificate it does not trust" },
1233
1574
  header: { type: "string", short: "H", multiple: true, description: "a `Name: value` header sent with every request, repeatable" },
1234
1575
  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" },
1576
+ 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
1577
  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})")
1578
+ 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"] },
1579
+ cors: { type: "string", description: "the origin a browser would call from: whether its CORS preflight lets the request through", conflicts: ["dns", "verbose"] },
1580
+ method: { type: "string", description: "with --cors, the method of the request the preflight asks for (POST)" },
1581
+ "cors-headers": { type: "string", description: "with --cors, the headers it carries, comma separated, empty for none (content-type)" },
1582
+ 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
1583
  };
1239
1584
  var BRACKETS2 = /^\[|\]$/g;
1240
1585
  var HEADER_LINE = /^[\w!#$%&'*+.^`|~-]+:/;
@@ -1316,9 +1661,9 @@ function ms2(value) {
1316
1661
  return `${value}ms`;
1317
1662
  }
1318
1663
  function compact(report) {
1319
- const { dim } = paint(process13.stdout);
1664
+ const { dim } = paint(process15.stdout);
1320
1665
  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)];
1666
+ 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
1667
  const address = report.addresses.a[0] ?? report.addresses.aaaa[0];
1323
1668
  if (redirects > 0)
1324
1669
  parts.push(`${redirects} ${redirects === 1 ? "redirect" : "redirects"}`);
@@ -1327,14 +1672,14 @@ function compact(report) {
1327
1672
  if (address !== undefined)
1328
1673
  parts.push(address);
1329
1674
  const line = parts.join(dim(" "));
1330
- return report.warnings.length === 0 ? line : `${line} ${marked("warn", report.warnings.join("; "), process13.stdout)}`;
1675
+ return report.warnings.length === 0 ? line : `${line} ${marked("warn", report.warnings.join("; "), process15.stdout)}`;
1331
1676
  }
1332
1677
  function print(report) {
1333
- const label = role("label", process13.stdout);
1334
- const value = role("value", process13.stdout);
1335
- const accent = role("accent", process13.stdout);
1678
+ const label = role("label", process15.stdout);
1679
+ const value = role("value", process15.stdout);
1680
+ const accent = role("accent", process15.stdout);
1336
1681
  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)}`);
1682
+ console.log(`${accent(versionLabel(report.version))} ${value(String(report.status))} ${role("path", process15.stdout)(report.url)}`);
1338
1683
  console.log("");
1339
1684
  if (report.chain.length > 1) {
1340
1685
  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 +1704,98 @@ function print(report) {
1359
1704
  if (report.httpRedirect !== null)
1360
1705
  row("http://", report.httpRedirect.toHttps ? `redirects to https (${report.httpRedirect.status})` : `answers ${report.httpRedirect.status}`);
1361
1706
  for (const warning of report.warnings)
1362
- console.log(marked("warn", warning, process13.stdout));
1707
+ console.log(marked("warn", warning, process15.stdout));
1708
+ }
1709
+ function printDns(report) {
1710
+ const label = role("label", process15.stdout);
1711
+ const listed = (values) => values.length === 0 ? "-" : values.join(" ");
1712
+ console.log(`${role("path", process15.stdout)(report.target)} ${label(report.zone === null ? "no zone found" : `zone ${report.zone}`)}`);
1713
+ console.log(table([
1714
+ ["RESOLVER", "SERVER", "A", "AAAA", "CNAME", "TTL"],
1715
+ ...report.answers.map((answer) => [
1716
+ answer.authoritative ? `${answer.resolver} (ns)` : answer.resolver,
1717
+ answer.server,
1718
+ ...answer.error === undefined ? [listed(answer.a), listed(answer.aaaa), listed(answer.cname)] : [answer.error, "", ""],
1719
+ answer.ttl === null ? "-" : `${answer.ttl}s`
1720
+ ])
1721
+ ], { header: true }));
1722
+ if (report.agree)
1723
+ console.log(marked("ok", "every resolver gives the same answer", process15.stdout));
1724
+ for (const warning of report.warnings)
1725
+ console.log(marked("warn", warning, process15.stdout));
1726
+ }
1727
+ async function dnsMain(inputs, timeoutMs, json) {
1728
+ const hosts = inputs.map((input) => {
1729
+ const host = parseTarget(input)?.url.hostname;
1730
+ if (host === undefined)
1731
+ badUsage(`not a URL or domain: ${input}`);
1732
+ if (isIP2(host.replace(BRACKETS2, "")) !== 0)
1733
+ badUsage(`--dns takes a name, not the address ${input}`);
1734
+ return { input, host };
1735
+ });
1736
+ const client = network(timeoutMs);
1737
+ const reports = await Promise.all(hosts.map(async ({ input, host }) => dnsReport(input, host, client)));
1738
+ if (json) {
1739
+ printJson(reports.length === 1 ? reports[0] : reports);
1740
+ } else {
1741
+ for (const [at, report] of reports.entries()) {
1742
+ if (at > 0)
1743
+ console.log("");
1744
+ printDns(report);
1745
+ }
1746
+ }
1747
+ return reports.every(known) ? 0 : 1;
1748
+ }
1749
+ function printCors(report) {
1750
+ const label = role("label", process15.stdout);
1751
+ const { request } = report;
1752
+ const asked = `from ${request.origin}, ${request.method}${request.headers.length === 0 ? "" : ` with ${request.headers.join(", ")}`}`;
1753
+ 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)}`);
1754
+ for (const [name, value] of Object.entries(report.headers))
1755
+ console.log(` ${label(name)} ${value}`);
1756
+ for (const reason of report.reasons)
1757
+ console.log(marked("problem", reason, process15.stdout));
1758
+ for (const warning of report.warnings)
1759
+ console.log(marked("warn", warning, process15.stdout));
1760
+ }
1761
+ async function corsMain(targets, request, { insecure, wire }, json) {
1762
+ const reports = await Promise.all(targets.map(async ({ input, target }) => {
1763
+ const { hop, errormsg } = await curlPreflight(target.url.href, request, { ...wire, insecure });
1764
+ if (hop === undefined)
1765
+ return { target: input, error: `could not reach ${target.url.host}: ${errormsg ?? "no response"}` };
1766
+ return { target: input, url: hop.url, status: hop.status, request, ...corsVerdict(hop.status, hop.headers, request) };
1767
+ }));
1768
+ const [only] = reports;
1769
+ if (reports.length === 1 && only !== undefined && "error" in only)
1770
+ fail(only.error, 1);
1771
+ if (json) {
1772
+ printJson(reports.length === 1 ? only : reports);
1773
+ } else {
1774
+ for (const report of reports) {
1775
+ if ("error" in report)
1776
+ console.error(marked("problem", report.error, process15.stderr));
1777
+ else
1778
+ printCors(report);
1779
+ }
1780
+ }
1781
+ return reports.every((report) => ("allowed" in report) && report.allowed) ? 0 : 1;
1363
1782
  }
1364
1783
  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"]] });
1784
+ 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"]] });
1785
+ if (values.cors === undefined) {
1786
+ if (values.method !== undefined)
1787
+ badUsage("--method goes with --cors");
1788
+ if (values["cors-headers"] !== undefined)
1789
+ badUsage("--cors-headers goes with --cors");
1790
+ }
1366
1791
  const headers = values.header ?? [];
1367
1792
  for (const header of headers) {
1368
1793
  if (!HEADER_LINE.test(header))
1369
1794
  badUsage(`-H takes "Name: value", not ${header}`);
1370
1795
  }
1371
1796
  const timeoutMs = values.timeout === undefined ? undefined : duration(values.timeout, "timeout", 0, "s");
1797
+ if (values.dns === true)
1798
+ return dnsMain(positionals, timeoutMs, values.json === true);
1372
1799
  const wire = { headers, resolve: resolvesOf(values.resolve ?? []), ...timeoutMs === undefined ? {} : { timeoutS: timeoutMs / 1000 } };
1373
1800
  const targets = positionals.map((input) => {
1374
1801
  const target = parseTarget(input);
@@ -1376,6 +1803,13 @@ async function main(args) {
1376
1803
  badUsage(`not a URL or domain: ${input}`);
1377
1804
  return { input, target };
1378
1805
  });
1806
+ if (values.cors !== undefined) {
1807
+ const origin = originOf(values.cors);
1808
+ if (origin === undefined)
1809
+ badUsage(`--cors takes an origin such as https://app.example.com, not ${values.cors}`);
1810
+ const request = { origin, method: methodOf(values.method ?? "POST"), headers: requestedHeaders(values["cors-headers"] ?? "content-type") };
1811
+ return corsMain(targets, request, { insecure: values.insecure === true, wire }, values.json === true);
1812
+ }
1379
1813
  const reports = await Promise.all(targets.map(async ({ input, target }) => probe(target, input, { insecure: values.insecure === true, wire })));
1380
1814
  const [only] = reports;
1381
1815
  if (reports.length === 1 && only !== undefined && "error" in only)
@@ -1387,12 +1821,12 @@ async function main(args) {
1387
1821
  let first = true;
1388
1822
  for (const report of reports) {
1389
1823
  if ("error" in report) {
1390
- console.error(marked("problem", report.error, process13.stderr));
1824
+ console.error(marked("problem", report.error, process15.stderr));
1391
1825
  } else if (values.verbose === true) {
1392
1826
  if (!first)
1393
1827
  console.log("");
1394
1828
  if (reports.length > 1)
1395
- console.log(role("label", process13.stdout)(report.target));
1829
+ console.log(role("label", process15.stdout)(report.target));
1396
1830
  print(report);
1397
1831
  } else {
1398
1832
  console.log(compact(report));
@@ -1401,4 +1835,4 @@ async function main(args) {
1401
1835
  }
1402
1836
  return reports.some((report) => ("error" in report)) ? 1 : 0;
1403
1837
  }
1404
- process13.exitCode = await runMain({ name: "probe", run: main });
1838
+ 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.2",
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.41.0"
39
39
  }
40
40
  }