@kaynooo/cli-probe 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +11 -2
  2. package/dist/probe.js +206 -88
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -8,12 +8,21 @@ bun add -g @kaynooo/cli-probe
8
8
 
9
9
  | Command | What it does |
10
10
  | --- | --- |
11
- | `probe example.com` | a bare domain tries https first, then http; prints the HTTP version, status chain, timings (dns, connect, tls, first byte, total), A and AAAA addresses, TLS version and cipher, certificate issuer, expiry and names, server, content type and encoding, cache control, hsts, a CDN hint, and whether h2 and h3 are offered |
11
+ | `probe example.com` | a bare domain tries https first, then http; one line: HTTP version, status, final URL, total time, redirects, certificate expiry, first address and the warnings |
12
+ | `probe example.com --verbose` | the whole table: the status chain, timings (dns, connect, tls, first byte, total), A and AAAA addresses, TLS version and cipher, certificate issuer, expiry and names, server, content type and encoding, cache control, hsts, a CDN hint, and whether h2 and h3 are offered |
13
+ | `probe a.test b.test` | several targets, probed together, one line (or table) each in the order given |
12
14
  | `probe https://example.com/path --json` | the same as one JSON object |
13
15
  | `probe -k https://localhost:8443` | go on with a certificate curl does not trust (it is reported as a warning) |
16
+ | `probe -H "X-Debug: 1" https://example.com` | a header sent with every request, repeatable |
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 |
19
+
20
+ ## JSON output
21
+
22
+ One target prints one object, `{target, url, version, status, chain, timings, addresses, tls, certificate, headers, cdn, offers, httpRedirect, warnings}`, unchanged by the other options (`--json` is always the full report). Several targets print an array of those in the order given, an unreachable one being `{target, error}`.
14
23
 
15
24
  Redirects are followed hop by hop, at most 10. The HTTP version and timings come from `curl --write-out '%{json}'`, the certificate from `node:tls`, which Bun's fetch exposes neither of. HTTP/3 is spoken only when `curl --version` lists it, otherwise h3 is reported from `alt-svc` alone.
16
25
 
17
26
  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.
18
27
 
19
- Exits 0 when the site answered, 1 when it could not be reached, 2 on a usage error.
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).
package/dist/probe.js CHANGED
@@ -2,17 +2,17 @@
2
2
  // @bun
3
3
 
4
4
  // src/probe.ts
5
- import process8 from "process";
6
-
5
+ import { isIP as isIP2 } from "net";
6
+ import process9 from "process";
7
7
  // ../kit/src/args.ts
8
- import process4 from "process";
8
+ import process5 from "process";
9
9
  import { parseArgs } from "util";
10
10
 
11
11
  // ../kit/src/format.ts
12
- import process2 from "process";
12
+ import process3 from "process";
13
13
 
14
14
  // ../kit/src/style.ts
15
- import process from "process";
15
+ import process2 from "process";
16
16
 
17
17
  // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
18
18
  function x(s) {
@@ -282,13 +282,13 @@ var MARKS = {
282
282
  problem: { symbol: "\u2717", word: "error:", paint: (colors) => colors.red },
283
283
  note: { symbol: "\xB7", word: "note:", paint: (colors) => colors.dim }
284
284
  };
285
- function takesControlCodes(stream, env = process.env) {
285
+ function takesControlCodes(stream, env = process2.env) {
286
286
  return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
287
287
  }
288
- function paint(stream, env = process.env) {
288
+ function paint(stream, env = process2.env) {
289
289
  return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
290
290
  }
291
- function marked(mark, text, stream, detail, env = process.env) {
291
+ function marked(mark, text, stream, detail, env = process2.env) {
292
292
  const colors = paint(stream, env);
293
293
  const { symbol, word, paint: tint } = MARKS[mark];
294
294
  const head = takesControlCodes(stream, env) ? tint(colors)(symbol) : word;
@@ -301,7 +301,7 @@ var ROLES = {
301
301
  label: (colors) => colors.dim,
302
302
  value: (colors) => colors.bold
303
303
  };
304
- function role(name, stream, env = process.env) {
304
+ function role(name, stream, env = process2.env) {
305
305
  return ROLES[name](paint(stream, env));
306
306
  }
307
307
  var STATUSES = {
@@ -334,7 +334,7 @@ function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
334
334
  widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
335
335
  }
336
336
  const shown = fit === undefined ? cells : narrow(cells, widths, fit);
337
- const colors = paint(process2.stdout);
337
+ const colors = paint(process3.stdout);
338
338
  const lines = shown.map((row) => row.map((cell, index) => {
339
339
  const width = widths[index] ?? 0;
340
340
  const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
@@ -366,24 +366,30 @@ function printJson(value) {
366
366
  }
367
367
 
368
368
  // ../kit/src/help.ts
369
- import process3 from "process";
369
+ import process4 from "process";
370
370
  var OPTIONAL = /\[[^\]]+\]/g;
371
371
  var USAGE_PREFIX = /^usage:\s*/i;
372
372
  var FULL_STOP = /\.$/;
373
- function usageLine(usage, colors = paint(process3.stdout)) {
373
+ function usageLine(usage, colors = paint(process4.stdout)) {
374
374
  return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
375
375
  }
376
- function helpText(usage, options, colors = paint(process3.stdout), { examples = [], replaces } = {}) {
377
- return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exampleRows(examples, colors)].join(`
376
+ function helpText(usage, options, colors = paint(process4.stdout), { examples = [], replaces, exits = [] } = {}) {
377
+ return [usageLine(usage, colors), ...replacesRows(replaces, colors), "", colors.bold("Options:"), ...optionRows(options, colors), ...exitRows(exits, colors), ...exampleRows(examples, colors)].join(`
378
378
  `);
379
379
  }
380
- function replacesRows(replaces, colors = paint(process3.stdout)) {
380
+ function exitRows(exits, colors = paint(process4.stdout)) {
381
+ if (exits.length === 0)
382
+ return [];
383
+ const width = Math.max(...exits.map(([code]) => String(code).length));
384
+ return ["", colors.bold("Exits:"), ...exits.map(([code, meaning]) => ` ${colors.cyan(String(code).padEnd(width))} ${meaning}`)];
385
+ }
386
+ function replacesRows(replaces, colors = paint(process4.stdout)) {
381
387
  return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
382
388
  }
383
- function wantsHelpJson(env = process3.env) {
389
+ function wantsHelpJson(env = process4.env) {
384
390
  return env.KIT_HELP === "json";
385
391
  }
386
- function description(usage, { examples = [], replaces } = {}) {
392
+ function description(usage, { examples = [], replaces, exits } = {}, options) {
387
393
  const lines = usage.replace(USAGE_PREFIX, "").split(`
388
394
  `);
389
395
  const first = lines[0];
@@ -394,15 +400,17 @@ function description(usage, { examples = [], replaces } = {}) {
394
400
  synopsis: colon === -1 ? first : first.slice(0, colon),
395
401
  summary: colon === -1 ? fallback : first.slice(colon + 2),
396
402
  ...replaces === undefined ? {} : { replaces },
397
- examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
403
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] }),
404
+ ...exits === undefined ? {} : { exits: exits.map(([code, meaning]) => ({ code, meaning })) },
405
+ ...options === undefined ? {} : { options: Object.entries(options).map(([name, { short, description }]) => ({ name, ...short === undefined ? {} : { short }, ...description === undefined ? {} : { description } })) }
398
406
  };
399
407
  }
400
- function exampleRows(examples, colors = paint(process3.stdout)) {
408
+ function exampleRows(examples, colors = paint(process4.stdout)) {
401
409
  if (examples.length === 0)
402
410
  return [];
403
411
  return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
404
412
  }
405
- function optionRows(options, colors = paint(process3.stdout)) {
413
+ function optionRows(options, colors = paint(process4.stdout)) {
406
414
  const rows = Object.entries(options).map(([name, option]) => {
407
415
  const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
408
416
  const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
@@ -433,6 +441,18 @@ function closest(name, names) {
433
441
  const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
434
442
  return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
435
443
  }
444
+ // ../kit/src/input.ts
445
+ var DURATION = /^(\d+(?:\.\d+)?)(ms|[smhd])?$/;
446
+ var UNIT_MS = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
447
+ function duration(value, name, fallback, unit = "s") {
448
+ if (value === undefined)
449
+ return fallback;
450
+ const match = DURATION.exec(value.trim());
451
+ const ms = match === null ? 0 : Number(match[1]) * UNIT_MS[match[2] ?? unit];
452
+ if (ms < 1)
453
+ badUsage(`--${name} takes a duration such as 30s, 5m, 1h or 7d, not ${value}`);
454
+ return ms;
455
+ }
436
456
 
437
457
  // ../kit/src/args.ts
438
458
  var DASHES = /^-+/;
@@ -483,7 +503,7 @@ var OUTPUT_OPTIONS = {
483
503
  color: { type: "string", description: "auto (on a terminal alone), always or never" },
484
504
  plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
485
505
  };
486
- function applyOutput(color, plain, env = process4.env) {
506
+ function applyOutput(color, plain, env = process5.env) {
487
507
  const when = plain === true ? "never" : color ?? "auto";
488
508
  if (when === "auto")
489
509
  return;
@@ -506,7 +526,7 @@ function parse(args, usage, options, settings = {}) {
506
526
  const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
507
527
  let parsed;
508
528
  try {
509
- parsed = parseArgs({ args: joinDashValues(withBare(own, all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
529
+ parsed = parseArgs({ args: joinDashValues(withBare(withAliases(own, all), all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
510
530
  } catch (error) {
511
531
  const message = parseError(error);
512
532
  throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
@@ -514,7 +534,7 @@ function parse(args, usage, options, settings = {}) {
514
534
  const values = parsed.values;
515
535
  applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
516
536
  if (values.help === true) {
517
- console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, listing, undefined, settings));
537
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings, listing)) : helpText(usage, listing, undefined, settings));
518
538
  throw new HelpShown;
519
539
  }
520
540
  checkChoices(parsed.values, all);
@@ -556,6 +576,18 @@ function listed(options, allowNegative) {
556
576
  return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
557
577
  }));
558
578
  }
579
+ function withAliases(args, options) {
580
+ const named = new Map(Object.entries(options).flatMap(([name, { aliases = [] }]) => aliases.map((alias) => [`--${alias}`, `--${name}`])));
581
+ if (named.size === 0)
582
+ return args;
583
+ const separator = args.indexOf("--");
584
+ const own = separator === -1 ? args : args.slice(0, separator);
585
+ return [...own.map((arg) => {
586
+ const at = arg.indexOf("=");
587
+ const current = named.get(at === -1 ? arg : arg.slice(0, at));
588
+ return current === undefined ? arg : `${current}${at === -1 ? "" : arg.slice(at)}`;
589
+ }), ...separator === -1 ? [] : args.slice(separator)];
590
+ }
559
591
  function withBare(args, options) {
560
592
  const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
561
593
  if (bare.size === 0)
@@ -646,13 +678,15 @@ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x
646
678
  var RESET_STYLE = `${ESC}[0m`;
647
679
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
648
680
  // ../kit/src/cli.ts
649
- import process6 from "process";
681
+ import { readFileSync, realpathSync } from "fs";
682
+ import { dirname as dirname2, join as join2 } from "path";
683
+ import process7 from "process";
650
684
 
651
685
  // ../kit/src/usage.ts
652
686
  import { appendFileSync, mkdirSync } from "fs";
653
687
  import { homedir } from "os";
654
688
  import { dirname, isAbsolute, join } from "path";
655
- import process5 from "process";
689
+ import process6 from "process";
656
690
 
657
691
  // ../kit/src/logs.ts
658
692
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -666,14 +700,14 @@ var usageError;
666
700
  function noteUsageError(message) {
667
701
  usageError = message;
668
702
  }
669
- function stateHome(env = process5.env) {
703
+ function stateHome(env = process6.env) {
670
704
  const dir = env.XDG_STATE_HOME;
671
705
  return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
672
706
  }
673
- function usagePath(env = process5.env) {
707
+ function usagePath(env = process6.env) {
674
708
  return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
675
709
  }
676
- function usageRecorded(env = process5.env) {
710
+ function usageRecorded(env = process6.env) {
677
711
  const off = env.KAYNOOO_CLI_NO_USAGE;
678
712
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
679
713
  }
@@ -687,7 +721,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
687
721
  usageError = undefined;
688
722
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
689
723
  }
690
- function recordUsage(entry, env = process5.env) {
724
+ function recordUsage(entry, env = process6.env) {
691
725
  if (!usageRecorded(env))
692
726
  return;
693
727
  try {
@@ -705,8 +739,8 @@ var LEVEL_OPTIONS = {
705
739
  };
706
740
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
707
741
  function printError(prefix, message, hint, cause) {
708
- const colors = paint(process6.stderr);
709
- const styled = takesControlCodes(process6.stderr);
742
+ const colors = paint(process7.stderr);
743
+ const styled = takesControlCodes(process7.stderr);
710
744
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
711
745
  const under = (label, text, tint) => text === undefined ? "" : `
712
746
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -788,11 +822,22 @@ async function printCandidates(found) {
788
822
  console.log(line);
789
823
  return 0;
790
824
  }
791
- async function runMain({ name, version, run, redact, usage }, argv = process6.argv.slice(2)) {
825
+ function packageVersion(entry = Bun.main) {
826
+ for (let dir = dirname2(realpathSync(entry));; dir = dirname2(dir)) {
827
+ try {
828
+ const { version } = JSON.parse(readFileSync(join2(dir, "package.json"), "utf8"));
829
+ if (typeof version === "string")
830
+ return version;
831
+ } catch {}
832
+ if (dirname2(dir) === dir)
833
+ return "0.0.0";
834
+ }
835
+ }
836
+ async function runMain({ name, version, run, redact, usage }, argv = process7.argv.slice(2)) {
792
837
  if (argv[0] === COMPLETE)
793
838
  return printCandidates(leafCandidates(run, argv.slice(1)));
794
839
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
795
- console.log(version);
840
+ console.log(version ?? packageVersion());
796
841
  return 0;
797
842
  }
798
843
  let code;
@@ -801,8 +846,11 @@ async function runMain({ name, version, run, redact, usage }, argv = process6.ar
801
846
  } catch (error) {
802
847
  code = reportThrown(name, error, redact, wantsJson(argv));
803
848
  }
804
- if (usage !== false)
805
- recordUsage(usageEntry(name, undefined, argv, code));
849
+ if (usage !== false) {
850
+ try {
851
+ recordUsage(usageEntry(name, undefined, argv, code));
852
+ } catch {}
853
+ }
806
854
  return code;
807
855
  }
808
856
  // ../kit/src/secrets.ts
@@ -811,9 +859,6 @@ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "ses
811
859
  var {Glob } = globalThis.Bun;
812
860
  var SESSION_FILES = new Glob("*.json");
813
861
  var ACCOUNT_DIRS = new Glob("*/sessions");
814
- // package.json
815
- var version = "0.1.0";
816
-
817
862
  // src/analyze.ts
818
863
  var SOON_DAYS = 14;
819
864
  var MAX_HOPS = 10;
@@ -822,7 +867,7 @@ var SEPARATOR = `
822
867
  ---HEADERS---
823
868
  `;
824
869
  var CERT_PREFIX = /^(?:DNS|IP Address|IP|email|URI):/;
825
- var CACHE_NODE = /cache-/i;
870
+ var CACHE_NODE = /^cache-/i;
826
871
  var ALT_VALUE = /=.*$/;
827
872
  function parseTarget(input) {
828
873
  const bare = !SCHEME.test(input);
@@ -933,7 +978,7 @@ var KNOWN_SERVERS = [
933
978
  [/vercel/i, "Vercel"],
934
979
  [/netlify/i, "Netlify"],
935
980
  [/bunnycdn/i, "BunnyCDN"],
936
- [/gws|esf|google frontend|gse/i, "Google"]
981
+ [/^(?:gws|esf|gse)$|google frontend/i, "Google"]
937
982
  ];
938
983
  function cdnHint(headers) {
939
984
  const served = headers["x-served-by"];
@@ -986,6 +1031,9 @@ function namesOf(subjectaltname) {
986
1031
  return [];
987
1032
  return subjectaltname.split(",").map((entry) => entry.trim().replace(CERT_PREFIX, "")).filter((name) => name !== "");
988
1033
  }
1034
+ function daysLeftLabel(days) {
1035
+ return `${days} ${days === 1 ? "day" : "days"} left`;
1036
+ }
989
1037
  function certInfo(raw, now = Date.now()) {
990
1038
  if (raw.valid_to === undefined || raw.valid_from === undefined)
991
1039
  return;
@@ -1018,10 +1066,12 @@ function warningsOf(input) {
1018
1066
  const warnings = [];
1019
1067
  const { cert, httpRedirect } = input;
1020
1068
  if (cert !== undefined) {
1021
- if (cert.daysLeft < 0)
1069
+ if (cert.daysLeft === -1)
1070
+ warnings.push("certificate expired within the last day");
1071
+ else if (cert.daysLeft < 0)
1022
1072
  warnings.push(`certificate expired ${-cert.daysLeft} days ago`);
1023
1073
  else if (cert.daysLeft < SOON_DAYS)
1024
- warnings.push(`certificate expires in ${cert.daysLeft} days`);
1074
+ warnings.push(`certificate expires in ${cert.daysLeft} ${cert.daysLeft === 1 ? "day" : "days"}`);
1025
1075
  }
1026
1076
  if (input.authorizationError !== undefined)
1027
1077
  warnings.push(`certificate not trusted: ${input.authorizationError}`);
@@ -1053,8 +1103,22 @@ async function curlHasHttp3() {
1053
1103
  }
1054
1104
  return http3;
1055
1105
  }
1056
- async function runCurl(url, { http3: wantsH3, insecure, get }) {
1057
- const args = ["-sS", "-o", "/dev/null", "--connect-timeout", String(CONNECT_TIMEOUT), "--max-time", String(MAX_TIME), "--write-out", WRITE_OUT];
1106
+ function portOf(url) {
1107
+ if (url.port !== "")
1108
+ return Number(url.port);
1109
+ return url.protocol === "https:" ? 443 : 80;
1110
+ }
1111
+ function curlResolve(url, resolve) {
1112
+ const parsed = URL.canParse(url) ? new URL(url) : undefined;
1113
+ const address = parsed === undefined ? undefined : resolve?.get(parsed.hostname);
1114
+ if (parsed === undefined || address === undefined)
1115
+ return [];
1116
+ return ["--resolve", `${parsed.hostname}:${portOf(parsed)}:${isIP(address) === 6 ? `[${address}]` : address}`];
1117
+ }
1118
+ async function runCurl(url, { http3: wantsH3, insecure, get, headers = [], resolve, timeoutS = MAX_TIME }) {
1119
+ 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)];
1120
+ for (const header of headers)
1121
+ args.push("-H", header);
1058
1122
  if (!get)
1059
1123
  args.push("-I");
1060
1124
  if (wantsH3)
@@ -1077,8 +1141,8 @@ async function curlHop(url, options) {
1077
1141
  result = await runCurl(url, { ...options, get: true });
1078
1142
  return result;
1079
1143
  }
1080
- async function addressesOf(host) {
1081
- const bare = host.replace(BRACKETS, "");
1144
+ async function addressesOf(host, resolve) {
1145
+ const bare = resolve?.get(host) ?? host.replace(BRACKETS, "");
1082
1146
  const family = isIP(bare);
1083
1147
  if (family !== 0)
1084
1148
  return family === 4 ? { a: [bare], aaaa: [] } : { a: [], aaaa: [bare] };
@@ -1089,10 +1153,10 @@ async function addressesOf(host) {
1089
1153
  return { a: [], aaaa: [] };
1090
1154
  }
1091
1155
  }
1092
- async function tlsInfo(host, port) {
1156
+ async function tlsInfo(host, port, { address, timeoutS = CONNECT_TIMEOUT } = {}) {
1093
1157
  const bare = host.replace(BRACKETS, "");
1094
1158
  return new Promise((resolve) => {
1095
- const socket = connect({ host: bare, port, servername: isIP(bare) === 0 ? bare : "", ALPNProtocols: ["h2", "http/1.1"], rejectUnauthorized: false, timeout: CONNECT_TIMEOUT * 1000 });
1159
+ const socket = connect({ host: address ?? bare, port, servername: isIP(bare) === 0 ? bare : "", ALPNProtocols: ["h2", "http/1.1"], rejectUnauthorized: false, timeout: Math.min(CONNECT_TIMEOUT, timeoutS) * 1000 });
1096
1160
  socket.on("secureConnect", () => {
1097
1161
  const error = socket.authorizationError;
1098
1162
  resolve({
@@ -1114,22 +1178,29 @@ async function tlsInfo(host, port) {
1114
1178
 
1115
1179
  // src/probe.ts
1116
1180
  var LABEL_WIDTH = 13;
1117
- var USAGE = `probe [options] <url|domain>: reports a site's negotiated HTTP version, redirect chain, timings, addresses, TLS and certificate, the headers worth knowing and what warrants a warning
1181
+ var USAGE = `probe [options] <url|domain>...: reports each site's negotiated HTTP version, redirect chain, timings, addresses, TLS and certificate, the headers worth knowing and what warrants a warning
1118
1182
 
1183
+ By default one line per target: the HTTP version, status, final URL, total time, redirects, certificate expiry, first address and the warnings. --verbose prints the whole table.
1119
1184
  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.
1185
+ -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.
1120
1186
 
1121
- 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).
1122
-
1123
- Exits 0 when the site answered, 1 when it could not be reached, 2 on a usage error.`;
1187
+ 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).`;
1188
+ var EXITS = [[0, "every site answered, warnings or not"], [1, "a site could not be reached"], [2, "a usage error"]];
1124
1189
  var OPTIONS = {
1125
1190
  insecure: { type: "boolean", short: "k", description: "let curl go on with a certificate it does not trust" },
1126
- json: jsonOption("{target, url, version, status, chain, timings, addresses, tls, certificate, headers, cdn, offers, httpRedirect, warnings}")
1191
+ header: { type: "string", short: "H", multiple: true, description: "a `Name: value` header sent with every request, repeatable" },
1192
+ resolve: { type: "string", multiple: true, description: "host:ip, reach the host at that address instead of the DNS answer, repeatable" },
1193
+ timeout: { type: "string", short: "t", description: "longest one request may take (20s): 5s, 1m, a bare number in seconds" },
1194
+ verbose: { type: "boolean", description: "the whole table for each target instead of one line" },
1195
+ 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})")
1127
1196
  };
1128
- async function follow(start, insecure, http3) {
1197
+ var BRACKETS2 = /^\[|\]$/g;
1198
+ var HEADER_LINE = /^[\w!#$%&'*+.^`|~-]+:/;
1199
+ async function follow(start, { insecure, wire }, http3) {
1129
1200
  const chain = [];
1130
1201
  let url = start;
1131
1202
  while (chain.length < MAX_HOPS) {
1132
- const { hop, errormsg } = await curlHop(url, { http3: http3 && url.startsWith("https:"), insecure, get: false });
1203
+ const { hop, errormsg } = await curlHop(url, { ...wire, http3: http3 && url.startsWith("https:"), insecure, get: false });
1133
1204
  if (hop === undefined)
1134
1205
  return { chain, error: errormsg ?? "no response", tooMany: false };
1135
1206
  chain.push(hop);
@@ -1140,33 +1211,26 @@ async function follow(start, insecure, http3) {
1140
1211
  }
1141
1212
  return { chain, tooMany: true };
1142
1213
  }
1143
- function portOf(url) {
1144
- if (url.port !== "")
1145
- return Number(url.port);
1146
- return url.protocol === "https:" ? 443 : 80;
1147
- }
1148
- async function probe(input, insecure) {
1149
- const target = parseTarget(input);
1150
- if (target === undefined)
1151
- badUsage(`not a URL or domain: ${input}`);
1214
+ async function probe(target, input, settings) {
1215
+ const { wire } = settings;
1152
1216
  const http3 = await curlHasHttp3();
1153
- let followed = await follow(target.url.href, insecure, http3);
1217
+ let followed = await follow(target.url.href, settings, http3);
1154
1218
  if (followed.chain.length === 0 && target.bare) {
1155
1219
  const plain = new URL(target.url.href);
1156
1220
  plain.protocol = "http:";
1157
- const second = await follow(plain.href, insecure, http3);
1221
+ const second = await follow(plain.href, settings, http3);
1158
1222
  if (second.chain.length > 0)
1159
1223
  followed = second;
1160
1224
  }
1161
1225
  const final = followed.chain.at(-1);
1162
1226
  if (final === undefined)
1163
- return { error: `could not reach ${target.url.host}: ${followed.error ?? "no response"}` };
1227
+ return { target: input, error: `could not reach ${target.url.host}: ${followed.error ?? "no response"}` };
1164
1228
  const finalUrl = new URL(final.url);
1165
1229
  const secure = finalUrl.protocol === "https:";
1166
1230
  const [addresses, tls, twin] = await Promise.all([
1167
- addressesOf(target.url.hostname),
1168
- secure ? tlsInfo(finalUrl.hostname, portOf(finalUrl)) : Promise.resolve(undefined),
1169
- wantsHttpCheck(target) && secure ? twinOf(target.url, insecure) : Promise.resolve(undefined)
1231
+ addressesOf(target.url.hostname, wire.resolve),
1232
+ secure ? tlsInfo(finalUrl.hostname, portOf(finalUrl), { address: wire.resolve?.get(finalUrl.hostname), ...wire.timeoutS === undefined ? {} : { timeoutS: wire.timeoutS } }) : Promise.resolve(undefined),
1233
+ wantsHttpCheck(target) && secure ? twinOf(target.url, settings) : Promise.resolve(undefined)
1170
1234
  ]);
1171
1235
  const httpRedirect = httpRedirectOf(twin);
1172
1236
  const offers = offersOf({ alpn: tls?.alpn, version: final.version, altSvc: final.headers["alt-svc"] });
@@ -1190,20 +1254,45 @@ async function probe(input, insecure) {
1190
1254
  warnings
1191
1255
  };
1192
1256
  }
1193
- async function twinOf(url, insecure) {
1257
+ async function twinOf(url, { insecure, wire }) {
1194
1258
  const plain = new URL(url.href);
1195
1259
  plain.protocol = "http:";
1196
- return (await curlHop(plain.href, { http3: false, insecure, get: false })).hop;
1260
+ return (await curlHop(plain.href, { ...wire, http3: false, insecure, get: false })).hop;
1261
+ }
1262
+ function resolvesOf(entries) {
1263
+ const resolve = new Map;
1264
+ for (const entry of entries) {
1265
+ const at = entry.indexOf(":");
1266
+ const address = entry.slice(at + 1).replace(BRACKETS2, "");
1267
+ if (at < 1 || isIP2(address) === 0)
1268
+ badUsage(`--resolve takes host:ip, not ${entry}`);
1269
+ resolve.set(entry.slice(0, at).toLowerCase(), address);
1270
+ }
1271
+ return resolve;
1197
1272
  }
1198
1273
  function ms2(value) {
1199
1274
  return `${value}ms`;
1200
1275
  }
1276
+ function compact(report) {
1277
+ const { dim } = paint(process9.stdout);
1278
+ const redirects = report.chain.length - 1;
1279
+ const parts = [`${role("accent", process9.stdout)(versionLabel(report.version))} ${role("value", process9.stdout)(String(report.status))} ${role("path", process9.stdout)(report.url)}`, ms2(report.timings.total)];
1280
+ const address = report.addresses.a[0] ?? report.addresses.aaaa[0];
1281
+ if (redirects > 0)
1282
+ parts.push(`${redirects} ${redirects === 1 ? "redirect" : "redirects"}`);
1283
+ if (report.certificate !== null)
1284
+ parts.push(`cert ${daysLeftLabel(report.certificate.daysLeft)}`);
1285
+ if (address !== undefined)
1286
+ parts.push(address);
1287
+ const line = parts.join(dim(" "));
1288
+ return report.warnings.length === 0 ? line : `${line} ${marked("warn", report.warnings.join("; "), process9.stdout)}`;
1289
+ }
1201
1290
  function print(report) {
1202
- const label = role("label", process8.stdout);
1203
- const value = role("value", process8.stdout);
1204
- const accent = role("accent", process8.stdout);
1291
+ const label = role("label", process9.stdout);
1292
+ const value = role("value", process9.stdout);
1293
+ const accent = role("accent", process9.stdout);
1205
1294
  const row = (name, text) => console.log(`${label(name.padEnd(LABEL_WIDTH))} ${text}`);
1206
- console.log(`${accent(versionLabel(report.version))} ${value(String(report.status))} ${role("path", process8.stdout)(report.url)}`);
1295
+ console.log(`${accent(versionLabel(report.version))} ${value(String(report.status))} ${role("path", process9.stdout)(report.url)}`);
1207
1296
  console.log("");
1208
1297
  if (report.chain.length > 1) {
1209
1298
  console.log(table(report.chain.map((hop) => [String(hop.status), versionLabel(hop.version), ms2(hop.ms), hop.url]), { align: ["right", "left", "right", "left"] }));
@@ -1217,7 +1306,7 @@ function print(report) {
1217
1306
  const cert = report.certificate;
1218
1307
  if (cert !== null) {
1219
1308
  row("issuer", cert.issuer);
1220
- row("expires", `${cert.validTo.slice(0, 10)} (${cert.daysLeft} days left)`);
1309
+ row("expires", `${cert.validTo.slice(0, 10)} (${daysLeftLabel(cert.daysLeft)})`);
1221
1310
  row("names", cert.names.join(", "));
1222
1311
  }
1223
1312
  row("offers", `h2 ${report.offers.h2 ? "yes" : "no"}, h3 ${report.offers.h3 ? "yes" : "no"}${report.offers.altSvc.length === 0 ? "" : ` (alt-svc ${report.offers.altSvc.join(" ")})`}`);
@@ -1228,17 +1317,46 @@ function print(report) {
1228
1317
  if (report.httpRedirect !== null)
1229
1318
  row("http://", report.httpRedirect.toHttps ? `redirects to https (${report.httpRedirect.status})` : `answers ${report.httpRedirect.status}`);
1230
1319
  for (const warning of report.warnings)
1231
- console.log(marked("warn", warning, process8.stdout));
1320
+ console.log(marked("warn", warning, process9.stdout));
1232
1321
  }
1233
1322
  async function main(args) {
1234
- const { values, positionals } = parse(args, USAGE, OPTIONS, { positionals: ["<url|domain>"], replaces: "the httpversion fish function, curl -sI chains and openssl s_client one-liners", examples: ["probe example.com", "probe https://example.com/path --json"] });
1235
- const report = await probe(positionals[0], values.insecure === true);
1236
- if ("error" in report)
1237
- fail(report.error, 1);
1238
- if (values.json === true)
1239
- printJson(report);
1240
- else
1241
- print(report);
1242
- return 0;
1323
+ 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"]] });
1324
+ const headers = values.header ?? [];
1325
+ for (const header of headers) {
1326
+ if (!HEADER_LINE.test(header))
1327
+ badUsage(`-H takes "Name: value", not ${header}`);
1328
+ }
1329
+ const timeoutMs = values.timeout === undefined ? undefined : duration(values.timeout, "timeout", 0, "s");
1330
+ const wire = { headers, resolve: resolvesOf(values.resolve ?? []), ...timeoutMs === undefined ? {} : { timeoutS: timeoutMs / 1000 } };
1331
+ const targets = positionals.map((input) => {
1332
+ const target = parseTarget(input);
1333
+ if (target === undefined)
1334
+ badUsage(`not a URL or domain: ${input}`);
1335
+ return { input, target };
1336
+ });
1337
+ const reports = await Promise.all(targets.map(async ({ input, target }) => probe(target, input, { insecure: values.insecure === true, wire })));
1338
+ const [only] = reports;
1339
+ if (reports.length === 1 && only !== undefined && "error" in only)
1340
+ fail(only.error, 1);
1341
+ if (values.json === true) {
1342
+ printJson(reports.length === 1 ? only : reports);
1343
+ return reports.some((report) => ("error" in report)) ? 1 : 0;
1344
+ }
1345
+ let first = true;
1346
+ for (const report of reports) {
1347
+ if ("error" in report) {
1348
+ console.error(marked("problem", report.error, process9.stderr));
1349
+ } else if (values.verbose === true) {
1350
+ if (!first)
1351
+ console.log("");
1352
+ if (reports.length > 1)
1353
+ console.log(role("label", process9.stdout)(report.target));
1354
+ print(report);
1355
+ } else {
1356
+ console.log(compact(report));
1357
+ }
1358
+ first = false;
1359
+ }
1360
+ return reports.some((report) => ("error" in report)) ? 1 : 0;
1243
1361
  }
1244
- process8.exitCode = await runMain({ name: "probe", version, run: main });
1362
+ process9.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.1.0",
4
+ "version": "0.2.0",
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.19.0"
38
+ "@kaynooo/cli-kit": "0.21.0"
39
39
  }
40
40
  }