@kaynooo/cli-probe 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +17 -2
  2. package/dist/probe.js +354 -47
  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 process14 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);
@@ -712,21 +714,45 @@ function nearestOption(message, options, allowNegative) {
712
714
  const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
713
715
  return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
714
716
  }
717
+ // ../kit/src/argv.ts
718
+ import { readFileSync as readFileSync2, realpathSync } from "fs";
719
+ import { resolve as resolve3 } from "path";
720
+ import process10 from "process";
721
+ function commandLine() {
722
+ try {
723
+ return readFileSync2("/proc/self/cmdline", "utf8").split("\x00").slice(0, -1);
724
+ } catch {
725
+ return;
726
+ }
727
+ }
728
+ function realPath(word) {
729
+ try {
730
+ return realpathSync(resolve3(word));
731
+ } catch {
732
+ return;
733
+ }
734
+ }
735
+ function scriptArgs(argv = process10.argv.slice(2), cmdline = commandLine(), script = process10.argv[1]) {
736
+ const target = script === undefined ? undefined : realPath(script) ?? script;
737
+ const at = cmdline === undefined || target === undefined ? -1 : cmdline.findIndex((word, index) => index > 0 && (resolve3(word) === script || realPath(word) === target));
738
+ const after = at === -1 ? [] : cmdline.slice(at + 1);
739
+ return after[0] === "--" && after.length === argv.length + 1 && argv.every((word, index) => word === after[index + 1]) ? after : argv;
740
+ }
715
741
  // ../kit/src/progress.ts
716
742
  var ESC = String.fromCharCode(27);
717
743
  var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
718
744
  var RESET_STYLE = `${ESC}[0m`;
719
745
  var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
720
746
  // ../kit/src/cli.ts
721
- import { readFileSync as readFileSync2, realpathSync } from "fs";
747
+ import { readFileSync as readFileSync3, realpathSync as realpathSync2 } from "fs";
722
748
  import { dirname as dirname3, join as join5 } from "path";
723
- import process11 from "process";
749
+ import process12 from "process";
724
750
 
725
751
  // ../kit/src/usage.ts
726
752
  import { appendFileSync, mkdirSync } from "fs";
727
753
  import { homedir as homedir3 } from "os";
728
754
  import { dirname as dirname2, isAbsolute, join as join4 } from "path";
729
- import process10 from "process";
755
+ import process11 from "process";
730
756
 
731
757
  // ../kit/src/logs.ts
732
758
  var DAY_MS = 24 * 60 * 60 * 1000;
@@ -740,14 +766,14 @@ var usageError;
740
766
  function noteUsageError(message) {
741
767
  usageError = message;
742
768
  }
743
- function stateHome(env = process10.env) {
769
+ function stateHome(env = process11.env) {
744
770
  const dir = env.XDG_STATE_HOME;
745
771
  return dir !== undefined && isAbsolute(dir) ? dir : join4(homedir3(), ".local", "state");
746
772
  }
747
- function usagePath(env = process10.env) {
773
+ function usagePath(env = process11.env) {
748
774
  return join4(stateHome(env), CLI_FOLDER, "usage.jsonl");
749
775
  }
750
- function usageRecorded(env = process10.env) {
776
+ function usageRecorded(env = process11.env) {
751
777
  const off = env.KAYNOOO_CLI_NO_USAGE;
752
778
  return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
753
779
  }
@@ -761,7 +787,7 @@ function usageEntry(bin, command, argv, code, now = new Date) {
761
787
  usageError = undefined;
762
788
  return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
763
789
  }
764
- function recordUsage(entry, env = process10.env) {
790
+ function recordUsage(entry, env = process11.env) {
765
791
  if (!usageRecorded(env))
766
792
  return;
767
793
  try {
@@ -779,8 +805,8 @@ var LEVEL_OPTIONS = {
779
805
  };
780
806
  var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
781
807
  function printError(prefix, message, hint, cause) {
782
- const colors = paint(process11.stderr);
783
- const styled = takesControlCodes(process11.stderr);
808
+ const colors = paint(process12.stderr);
809
+ const styled = takesControlCodes(process12.stderr);
784
810
  const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
785
811
  const under = (label, text, tint) => text === undefined ? "" : `
786
812
  ${styled ? tint(label) : `${label}:`} ${text}`;
@@ -824,24 +850,24 @@ function candidateLine(candidate) {
824
850
  }
825
851
  function positionalBeingTyped(before, { options, positionals }) {
826
852
  const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
827
- let index = 0;
853
+ const typed = [];
828
854
  let at = 0;
829
855
  while (at < before.length) {
830
856
  const word = before[at];
831
857
  if (word === "--") {
832
- index += before.length - at - 1;
858
+ typed.push(...before.slice(at + 1));
833
859
  break;
834
860
  }
835
861
  if (!word.startsWith("-"))
836
- index++;
862
+ typed.push(word);
837
863
  else if (takesValue(word))
838
864
  at++;
839
865
  at++;
840
866
  }
841
867
  const last = positionals.at(-1);
842
- if (index < positionals.length)
843
- return positionals[index];
844
- return last?.replace("]", "").endsWith("...") === true ? last : undefined;
868
+ if (typed.length < positionals.length)
869
+ return { name: positionals[typed.length], typed };
870
+ return { name: last?.replace("]", "").endsWith("...") === true ? last : undefined, typed };
845
871
  }
846
872
  async function leafCandidates(run, words) {
847
873
  const completing = await completingOf(run);
@@ -849,12 +875,12 @@ async function leafCandidates(run, words) {
849
875
  return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
850
876
  const flag = words.at(-2);
851
877
  const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
878
+ const { name, typed } = positionalBeingTyped(words.slice(0, -1), completing);
852
879
  if (option?.type === "string") {
853
- const values = option.choices === undefined ? await option.candidates?.() : option.choices;
880
+ const values = option.choices === undefined ? await option.candidates?.(typed) : option.choices;
854
881
  return values === undefined ? [FILES] : values.map(candidateLine);
855
882
  }
856
- const name = positionalBeingTyped(words.slice(0, -1), completing);
857
- const values = name === undefined ? undefined : await completing.candidates[name]?.();
883
+ const values = name === undefined ? undefined : await completing.candidates[name]?.(typed);
858
884
  return values === undefined ? [FILES] : values.map(candidateLine);
859
885
  }
860
886
  async function printCandidates(found) {
@@ -863,9 +889,9 @@ async function printCandidates(found) {
863
889
  return 0;
864
890
  }
865
891
  function packageVersion(entry = Bun.main) {
866
- for (let dir = dirname3(realpathSync(entry));; dir = dirname3(dir)) {
892
+ for (let dir = dirname3(realpathSync2(entry));; dir = dirname3(dir)) {
867
893
  try {
868
- const { version } = JSON.parse(readFileSync2(join5(dir, "package.json"), "utf8"));
894
+ const { version } = JSON.parse(readFileSync3(join5(dir, "package.json"), "utf8"));
869
895
  if (typeof version === "string")
870
896
  return version;
871
897
  } catch {}
@@ -873,7 +899,7 @@ function packageVersion(entry = Bun.main) {
873
899
  return "0.0.0";
874
900
  }
875
901
  }
876
- async function runMain({ name, version, run, redact, usage }, argv = process11.argv.slice(2)) {
902
+ async function runMain({ name, version, run, redact, usage }, argv = scriptArgs()) {
877
903
  if (argv[0] === COMPLETE)
878
904
  return printCandidates(leafCandidates(run, argv.slice(1)));
879
905
  if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
@@ -1124,6 +1150,185 @@ function warningsOf(input) {
1124
1150
  return warnings;
1125
1151
  }
1126
1152
 
1153
+ // src/cors.ts
1154
+ var SIMPLE_METHODS = new Set(["GET", "HEAD", "POST"]);
1155
+ var NORMALIZED_METHODS = new Set(["DELETE", "GET", "HEAD", "OPTIONS", "POST", "PUT"]);
1156
+ var SAFELISTED_HEADERS = new Set(["accept", "accept-language", "content-language"]);
1157
+ var LIST = /\s*,\s*/;
1158
+ var HOSTED_SCHEME = /^[a-z][a-z0-9+.-]*:\/\/[^/]/i;
1159
+ function listOf(value) {
1160
+ return value === undefined ? [] : value.trim().split(LIST).filter((item) => item !== "");
1161
+ }
1162
+ function methodOf(input) {
1163
+ return NORMALIZED_METHODS.has(input.toUpperCase()) ? input.toUpperCase() : input;
1164
+ }
1165
+ function requestedHeaders(value) {
1166
+ return listOf(value).map((name) => name.toLowerCase()).filter((name) => !SAFELISTED_HEADERS.has(name));
1167
+ }
1168
+ function originOf(input) {
1169
+ if (input === "null")
1170
+ return input;
1171
+ if (!HOSTED_SCHEME.test(input) || !URL.canParse(input))
1172
+ return;
1173
+ const url = new URL(input);
1174
+ return url.origin === "null" ? `${url.protocol}//${url.host}` : url.origin;
1175
+ }
1176
+ function corsVerdict(status, headers, request) {
1177
+ const reasons = [];
1178
+ const warnings = [];
1179
+ const origin = headers["access-control-allow-origin"];
1180
+ const credentials = headers["access-control-allow-credentials"] === "true";
1181
+ const methods = listOf(headers["access-control-allow-methods"]);
1182
+ const allowedHeaders = new Set(listOf(headers["access-control-allow-headers"]).map((name) => name.toLowerCase()));
1183
+ if (status < 200 || status > 299)
1184
+ reasons.push(`the preflight answered ${status}, a browser wants a 2xx`);
1185
+ if (origin === undefined)
1186
+ reasons.push("no access-control-allow-origin");
1187
+ else if (origin !== "*" && origin !== request.origin)
1188
+ reasons.push(`access-control-allow-origin is ${origin}, not ${request.origin}`);
1189
+ const { method } = request;
1190
+ if (!SIMPLE_METHODS.has(method) && !methods.includes("*") && !methods.includes(method))
1191
+ reasons.push(methods.length === 0 ? `no access-control-allow-methods, which ${method} needs` : `access-control-allow-methods (${methods.join(", ")}) does not list ${method}`);
1192
+ const missing = request.headers.map((name) => name.toLowerCase()).filter((name) => !allowedHeaders.has(name) && (name === "authorization" || !allowedHeaders.has("*")));
1193
+ if (missing.length > 0)
1194
+ reasons.push(`access-control-allow-headers does not cover ${missing.join(", ")}`);
1195
+ if (credentials && (origin === "*" || methods.includes("*") || allowedHeaders.has("*")))
1196
+ warnings.push("access-control-allow-credentials comes with a * wildcard, which a request with cookies or auth does not get");
1197
+ if (origin === request.origin && !listOf(headers.vary).some((name) => name.toLowerCase() === "origin" || name === "*"))
1198
+ warnings.push("if the origin is echoed back from the request, vary lacks origin: a cache may hand this answer to another origin");
1199
+ const shown = Object.fromEntries(Object.entries(headers).filter(([name]) => name.startsWith("access-control-") || name === "vary"));
1200
+ return { allowed: reasons.length === 0, reasons, warnings, headers: shown };
1201
+ }
1202
+
1203
+ // src/dns.ts
1204
+ import { Resolver } from "dns/promises";
1205
+ var TIMEOUT_MS = 3000;
1206
+ var PUBLIC_RESOLVERS = [
1207
+ { name: "cloudflare", address: "1.1.1.1" },
1208
+ { name: "google", address: "8.8.8.8" },
1209
+ { name: "quad9", address: "9.9.9.9" }
1210
+ ];
1211
+ function resolverFor(server, timeoutMs) {
1212
+ const resolver = new Resolver({ timeout: timeoutMs, tries: 1 });
1213
+ if (server.address !== undefined)
1214
+ resolver.setServers([server.address]);
1215
+ return resolver;
1216
+ }
1217
+ function failureOf(error) {
1218
+ const code = error.code;
1219
+ return code === "ETIMEOUT" || code === "ECONNREFUSED" ? "no answer" : String(error.message ?? error);
1220
+ }
1221
+ async function settled(query) {
1222
+ try {
1223
+ return await query;
1224
+ } catch (error) {
1225
+ const code = error.code;
1226
+ if (code === "ENOTFOUND" || code === "ENODATA")
1227
+ return [];
1228
+ throw error;
1229
+ }
1230
+ }
1231
+ function network(timeoutMs = TIMEOUT_MS, upstream = PUBLIC_RESOLVERS[0]) {
1232
+ return {
1233
+ servers: (server) => server.address ?? resolverFor(server, timeoutMs).getServers().join(", "),
1234
+ async records(server, host) {
1235
+ const resolver = resolverFor(server, timeoutMs);
1236
+ try {
1237
+ const [a, aaaa, cname] = await Promise.all([settled(resolver.resolve4(host, { ttl: true })), settled(resolver.resolve6(host, { ttl: true })), settled(resolver.resolveCname(host))]);
1238
+ const ttls = [...a, ...aaaa].map((record) => record.ttl);
1239
+ 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) };
1240
+ } catch (error) {
1241
+ return { a: [], aaaa: [], cname: [], ttl: null, error: failureOf(error) };
1242
+ }
1243
+ },
1244
+ async nameservers(zone) {
1245
+ const resolver = resolverFor(upstream, timeoutMs);
1246
+ const [nameservers, alias] = await Promise.all([settled(resolver.resolveNs(zone)), settled(resolver.resolveCname(zone))]);
1247
+ return alias.length > 0 ? [] : nameservers;
1248
+ },
1249
+ async addressOf(host) {
1250
+ return (await settled(resolverFor(upstream, timeoutMs).resolve4(host)))[0];
1251
+ }
1252
+ };
1253
+ }
1254
+ var NO_ZONE = "no zone with nameservers was found for this name";
1255
+ var ZONE_LOOKUP_FAILED = "the zone of this name could not be looked up, so no nameserver was asked";
1256
+ async function zoneOf(host, client) {
1257
+ const labels = host.split(".");
1258
+ for (let at = 0;at < labels.length - 1; at++) {
1259
+ const zone = labels.slice(at).join(".");
1260
+ const nameservers = await failingToNothing(client.nameservers(zone));
1261
+ if (nameservers === undefined)
1262
+ return { problem: ZONE_LOOKUP_FAILED };
1263
+ if (nameservers.length > 0)
1264
+ return { zone, nameservers: nameservers.sort() };
1265
+ }
1266
+ return { problem: NO_ZONE };
1267
+ }
1268
+ async function failingToNothing(query) {
1269
+ try {
1270
+ return await query;
1271
+ } catch {
1272
+ return;
1273
+ }
1274
+ }
1275
+ function sameFamily(mine, theirs) {
1276
+ if (mine.length === 0 || theirs.length === 0)
1277
+ return mine.length === theirs.length;
1278
+ const other = new Set(theirs);
1279
+ return mine.some((address) => other.has(address));
1280
+ }
1281
+ function sameAnswer(one, other) {
1282
+ if (one.error !== undefined || other.error !== undefined)
1283
+ return one.error === other.error;
1284
+ if (one.cname.length > 0 || other.cname.length > 0)
1285
+ return one.cname.join().toLowerCase() === other.cname.join().toLowerCase();
1286
+ return sameFamily(one.a, other.a) && sameFamily(one.aaaa, other.aaaa);
1287
+ }
1288
+ var TRAILING_DOT = /\.$/;
1289
+ async function dnsReport(target, host, client = network()) {
1290
+ const name = host.replace(TRAILING_DOT, "").toLowerCase();
1291
+ const found = await zoneOf(name, client);
1292
+ const authoritative = await Promise.all(("nameservers" in found ? found.nameservers : []).map(async (nameserver) => {
1293
+ const address = await failingToNothing(client.addressOf(nameserver));
1294
+ return address === undefined ? undefined : { name: nameserver, address };
1295
+ }));
1296
+ const asked = [
1297
+ ...[{ name: "system" }, ...PUBLIC_RESOLVERS].map((server) => ({ server, authoritative: false })),
1298
+ ...authoritative.filter((server) => server !== undefined).map((server) => ({ server, authoritative: true }))
1299
+ ];
1300
+ const answers = await Promise.all(asked.map(async ({ server, authoritative }) => ({ resolver: server.name, server: client.servers(server), authoritative, ...await client.records(server, name) })));
1301
+ return { target, zone: "zone" in found ? found.zone : null, answers, ...verdictOf(answers, "problem" in found ? found.problem : undefined) };
1302
+ }
1303
+ function verdictOf(answers, zoneProblem) {
1304
+ const warnings = zoneProblem === undefined ? [] : [zoneProblem];
1305
+ const answered = answers.filter((answer) => answer.error !== "no answer");
1306
+ const reference = answered.filter((answer) => answer.authoritative);
1307
+ const truth = reference[0] ?? answered[0];
1308
+ const agree = truth === undefined || answered.every((answer) => sameAnswer(answer, truth));
1309
+ if (reference.some((answer) => !sameAnswer(answer, reference[0])))
1310
+ warnings.push("the zone's own nameservers disagree: one of them has not taken the last change yet");
1311
+ for (const answer of answers) {
1312
+ if (answer.error === "no answer")
1313
+ warnings.push(`${answer.resolver} did not answer`);
1314
+ }
1315
+ if (agree)
1316
+ return { agree, warnings };
1317
+ if (reference.length === 0) {
1318
+ 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}`);
1319
+ return { agree, warnings };
1320
+ }
1321
+ const stale = answered.filter((answer) => !answer.authoritative && !reference.some((ns) => sameAnswer(answer, ns)));
1322
+ for (const answer of stale) {
1323
+ const until = answer.ttl === null || answer.cname.length > 0 ? "" : `, cached for up to ${answer.ttl}s more`;
1324
+ 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`);
1325
+ }
1326
+ return { agree, warnings };
1327
+ }
1328
+ function known(report) {
1329
+ return report.answers.some((answer) => answer.error === undefined && answer.a.length + answer.aaaa.length + answer.cname.length > 0);
1330
+ }
1331
+
1127
1332
  // src/net.ts
1128
1333
  import { lookup } from "dns/promises";
1129
1334
  import { isIP } from "net";
@@ -1157,11 +1362,13 @@ function curlResolve(url, resolve) {
1157
1362
  return [];
1158
1363
  return ["--resolve", `${parsed.hostname}:${portOf(parsed)}:${isIP(address) === 6 ? `[${address}]` : address}`];
1159
1364
  }
1160
- async function runCurl(url, { http3: wantsH3, insecure, get, headers = [], resolve, timeoutS = MAX_TIME }) {
1365
+ async function runCurl(url, { http3: wantsH3, insecure, get, method, headers = [], resolve, timeoutS = MAX_TIME }) {
1161
1366
  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
1367
  for (const header of headers)
1163
1368
  args.push("-H", header);
1164
- if (!get)
1369
+ if (method !== undefined)
1370
+ args.push("-X", method);
1371
+ else if (!get)
1165
1372
  args.push("-I");
1166
1373
  if (wantsH3)
1167
1374
  args.push("--http3");
@@ -1183,6 +1390,10 @@ async function curlHop(url, options) {
1183
1390
  result = await runCurl(url, { ...options, get: true });
1184
1391
  return result;
1185
1392
  }
1393
+ async function curlPreflight(url, request, options) {
1394
+ const asked = [`Origin: ${request.origin}`, `Access-Control-Request-Method: ${request.method}`, ...request.headers.length > 0 ? [`Access-Control-Request-Headers: ${request.headers.join(", ")}`] : []];
1395
+ return runCurl(url, { ...options, headers: [...options.headers ?? [], ...asked], http3: false, get: true, method: "OPTIONS" });
1396
+ }
1186
1397
  async function addressesOf(host, resolve) {
1187
1398
  const bare = resolve?.get(host) ?? host.replace(BRACKETS, "");
1188
1399
  const family = isIP(bare);
@@ -1226,15 +1437,22 @@ By default one line per target: the HTTP version, status, final URL, total time,
1226
1437
  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
1438
  -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
1439
 
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"]];
1440
+ 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).
1441
+
1442
+ --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.
1443
+ --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.`;
1444
+ 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
1445
  var OPTIONS = {
1232
1446
  insecure: { type: "boolean", short: "k", description: "let curl go on with a certificate it does not trust" },
1233
1447
  header: { type: "string", short: "H", multiple: true, description: "a `Name: value` header sent with every request, repeatable" },
1234
1448
  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" },
1449
+ 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
1450
  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})")
1451
+ 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"] },
1452
+ cors: { type: "string", description: "the origin a browser would call from: whether its CORS preflight lets the request through", conflicts: ["dns", "verbose"] },
1453
+ method: { type: "string", description: "with --cors, the method of the request the preflight asks for (POST)" },
1454
+ "cors-headers": { type: "string", description: "with --cors, the headers it carries, comma separated, empty for none (content-type)" },
1455
+ 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
1456
  };
1239
1457
  var BRACKETS2 = /^\[|\]$/g;
1240
1458
  var HEADER_LINE = /^[\w!#$%&'*+.^`|~-]+:/;
@@ -1316,9 +1534,9 @@ function ms2(value) {
1316
1534
  return `${value}ms`;
1317
1535
  }
1318
1536
  function compact(report) {
1319
- const { dim } = paint(process13.stdout);
1537
+ const { dim } = paint(process14.stdout);
1320
1538
  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)];
1539
+ const parts = [`${role("accent", process14.stdout)(versionLabel(report.version))} ${role("value", process14.stdout)(String(report.status))} ${role("path", process14.stdout)(report.url)}`, ms2(report.timings.total)];
1322
1540
  const address = report.addresses.a[0] ?? report.addresses.aaaa[0];
1323
1541
  if (redirects > 0)
1324
1542
  parts.push(`${redirects} ${redirects === 1 ? "redirect" : "redirects"}`);
@@ -1327,14 +1545,14 @@ function compact(report) {
1327
1545
  if (address !== undefined)
1328
1546
  parts.push(address);
1329
1547
  const line = parts.join(dim(" "));
1330
- return report.warnings.length === 0 ? line : `${line} ${marked("warn", report.warnings.join("; "), process13.stdout)}`;
1548
+ return report.warnings.length === 0 ? line : `${line} ${marked("warn", report.warnings.join("; "), process14.stdout)}`;
1331
1549
  }
1332
1550
  function print(report) {
1333
- const label = role("label", process13.stdout);
1334
- const value = role("value", process13.stdout);
1335
- const accent = role("accent", process13.stdout);
1551
+ const label = role("label", process14.stdout);
1552
+ const value = role("value", process14.stdout);
1553
+ const accent = role("accent", process14.stdout);
1336
1554
  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)}`);
1555
+ console.log(`${accent(versionLabel(report.version))} ${value(String(report.status))} ${role("path", process14.stdout)(report.url)}`);
1338
1556
  console.log("");
1339
1557
  if (report.chain.length > 1) {
1340
1558
  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 +1577,98 @@ function print(report) {
1359
1577
  if (report.httpRedirect !== null)
1360
1578
  row("http://", report.httpRedirect.toHttps ? `redirects to https (${report.httpRedirect.status})` : `answers ${report.httpRedirect.status}`);
1361
1579
  for (const warning of report.warnings)
1362
- console.log(marked("warn", warning, process13.stdout));
1580
+ console.log(marked("warn", warning, process14.stdout));
1581
+ }
1582
+ function printDns(report) {
1583
+ const label = role("label", process14.stdout);
1584
+ const listed = (values) => values.length === 0 ? "-" : values.join(" ");
1585
+ console.log(`${role("path", process14.stdout)(report.target)} ${label(report.zone === null ? "no zone found" : `zone ${report.zone}`)}`);
1586
+ console.log(table([
1587
+ ["RESOLVER", "SERVER", "A", "AAAA", "CNAME", "TTL"],
1588
+ ...report.answers.map((answer) => [
1589
+ answer.authoritative ? `${answer.resolver} (ns)` : answer.resolver,
1590
+ answer.server,
1591
+ ...answer.error === undefined ? [listed(answer.a), listed(answer.aaaa), listed(answer.cname)] : [answer.error, "", ""],
1592
+ answer.ttl === null ? "-" : `${answer.ttl}s`
1593
+ ])
1594
+ ], { header: true }));
1595
+ if (report.agree)
1596
+ console.log(marked("ok", "every resolver gives the same answer", process14.stdout));
1597
+ for (const warning of report.warnings)
1598
+ console.log(marked("warn", warning, process14.stdout));
1599
+ }
1600
+ async function dnsMain(inputs, timeoutMs, json) {
1601
+ const hosts = inputs.map((input) => {
1602
+ const host = parseTarget(input)?.url.hostname;
1603
+ if (host === undefined)
1604
+ badUsage(`not a URL or domain: ${input}`);
1605
+ if (isIP2(host.replace(BRACKETS2, "")) !== 0)
1606
+ badUsage(`--dns takes a name, not the address ${input}`);
1607
+ return { input, host };
1608
+ });
1609
+ const client = network(timeoutMs);
1610
+ const reports = await Promise.all(hosts.map(async ({ input, host }) => dnsReport(input, host, client)));
1611
+ if (json) {
1612
+ printJson(reports.length === 1 ? reports[0] : reports);
1613
+ } else {
1614
+ for (const [at, report] of reports.entries()) {
1615
+ if (at > 0)
1616
+ console.log("");
1617
+ printDns(report);
1618
+ }
1619
+ }
1620
+ return reports.every(known) ? 0 : 1;
1621
+ }
1622
+ function printCors(report) {
1623
+ const label = role("label", process14.stdout);
1624
+ const { request } = report;
1625
+ const asked = `from ${request.origin}, ${request.method}${request.headers.length === 0 ? "" : ` with ${request.headers.join(", ")}`}`;
1626
+ console.log(`${marked(report.allowed ? "ok" : "problem", report.allowed ? "allowed" : "refused", process14.stdout)} ${role("value", process14.stdout)(String(report.status))} ${role("path", process14.stdout)(report.url)} ${label(asked)}`);
1627
+ for (const [name, value] of Object.entries(report.headers))
1628
+ console.log(` ${label(name)} ${value}`);
1629
+ for (const reason of report.reasons)
1630
+ console.log(marked("problem", reason, process14.stdout));
1631
+ for (const warning of report.warnings)
1632
+ console.log(marked("warn", warning, process14.stdout));
1633
+ }
1634
+ async function corsMain(targets, request, { insecure, wire }, json) {
1635
+ const reports = await Promise.all(targets.map(async ({ input, target }) => {
1636
+ const { hop, errormsg } = await curlPreflight(target.url.href, request, { ...wire, insecure });
1637
+ if (hop === undefined)
1638
+ return { target: input, error: `could not reach ${target.url.host}: ${errormsg ?? "no response"}` };
1639
+ return { target: input, url: hop.url, status: hop.status, request, ...corsVerdict(hop.status, hop.headers, request) };
1640
+ }));
1641
+ const [only] = reports;
1642
+ if (reports.length === 1 && only !== undefined && "error" in only)
1643
+ fail(only.error, 1);
1644
+ if (json) {
1645
+ printJson(reports.length === 1 ? only : reports);
1646
+ } else {
1647
+ for (const report of reports) {
1648
+ if ("error" in report)
1649
+ console.error(marked("problem", report.error, process14.stderr));
1650
+ else
1651
+ printCors(report);
1652
+ }
1653
+ }
1654
+ return reports.every((report) => ("allowed" in report) && report.allowed) ? 0 : 1;
1363
1655
  }
1364
1656
  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"]] });
1657
+ 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"]] });
1658
+ if (values.cors === undefined) {
1659
+ if (values.method !== undefined)
1660
+ badUsage("--method goes with --cors");
1661
+ if (values["cors-headers"] !== undefined)
1662
+ badUsage("--cors-headers goes with --cors");
1663
+ }
1366
1664
  const headers = values.header ?? [];
1367
1665
  for (const header of headers) {
1368
1666
  if (!HEADER_LINE.test(header))
1369
1667
  badUsage(`-H takes "Name: value", not ${header}`);
1370
1668
  }
1371
1669
  const timeoutMs = values.timeout === undefined ? undefined : duration(values.timeout, "timeout", 0, "s");
1670
+ if (values.dns === true)
1671
+ return dnsMain(positionals, timeoutMs, values.json === true);
1372
1672
  const wire = { headers, resolve: resolvesOf(values.resolve ?? []), ...timeoutMs === undefined ? {} : { timeoutS: timeoutMs / 1000 } };
1373
1673
  const targets = positionals.map((input) => {
1374
1674
  const target = parseTarget(input);
@@ -1376,6 +1676,13 @@ async function main(args) {
1376
1676
  badUsage(`not a URL or domain: ${input}`);
1377
1677
  return { input, target };
1378
1678
  });
1679
+ if (values.cors !== undefined) {
1680
+ const origin = originOf(values.cors);
1681
+ if (origin === undefined)
1682
+ badUsage(`--cors takes an origin such as https://app.example.com, not ${values.cors}`);
1683
+ const request = { origin, method: methodOf(values.method ?? "POST"), headers: requestedHeaders(values["cors-headers"] ?? "content-type") };
1684
+ return corsMain(targets, request, { insecure: values.insecure === true, wire }, values.json === true);
1685
+ }
1379
1686
  const reports = await Promise.all(targets.map(async ({ input, target }) => probe(target, input, { insecure: values.insecure === true, wire })));
1380
1687
  const [only] = reports;
1381
1688
  if (reports.length === 1 && only !== undefined && "error" in only)
@@ -1387,12 +1694,12 @@ async function main(args) {
1387
1694
  let first = true;
1388
1695
  for (const report of reports) {
1389
1696
  if ("error" in report) {
1390
- console.error(marked("problem", report.error, process13.stderr));
1697
+ console.error(marked("problem", report.error, process14.stderr));
1391
1698
  } else if (values.verbose === true) {
1392
1699
  if (!first)
1393
1700
  console.log("");
1394
1701
  if (reports.length > 1)
1395
- console.log(role("label", process13.stdout)(report.target));
1702
+ console.log(role("label", process14.stdout)(report.target));
1396
1703
  print(report);
1397
1704
  } else {
1398
1705
  console.log(compact(report));
@@ -1401,4 +1708,4 @@ async function main(args) {
1401
1708
  }
1402
1709
  return reports.some((report) => ("error" in report)) ? 1 : 0;
1403
1710
  }
1404
- process13.exitCode = await runMain({ name: "probe", run: main });
1711
+ process14.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.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.36.0"
38
+ "@kaynooo/cli-kit": "0.38.1"
39
39
  }
40
40
  }