@kaynooo/cli-probe 0.0.0-stage → 0.1.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 (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +18 -2
  3. package/dist/probe.js +1244 -0
  4. package/package.json +38 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kaynooo <contact@kaynooo.fr>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,19 @@
1
- # Temporary Holding Version
1
+ # @kaynooo/cli-probe
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `probe` reports what a site answers in one call: the negotiated HTTP version, the redirect chain, timings, addresses, TLS and certificate, the headers worth knowing, and a warning mark for what needs attention.
4
+
5
+ ```sh
6
+ bun add -g @kaynooo/cli-probe
7
+ ```
8
+
9
+ | Command | What it does |
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 |
12
+ | `probe https://example.com/path --json` | the same as one JSON object |
13
+ | `probe -k https://localhost:8443` | go on with a certificate curl does not trust (it is reported as a warning) |
14
+
15
+ 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
+
17
+ 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
+
19
+ Exits 0 when the site answered, 1 when it could not be reached, 2 on a usage error.
package/dist/probe.js ADDED
@@ -0,0 +1,1244 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+
4
+ // src/probe.ts
5
+ import process8 from "process";
6
+
7
+ // ../kit/src/args.ts
8
+ import process4 from "process";
9
+ import { parseArgs } from "util";
10
+
11
+ // ../kit/src/format.ts
12
+ import process2 from "process";
13
+
14
+ // ../kit/src/style.ts
15
+ import process from "process";
16
+
17
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-mtetydvc.js
18
+ function x(s) {
19
+ let r = s.startsWith("#") ? s.slice(1).toLowerCase() : s.toLowerCase();
20
+ if (!/^[a-f0-9]+$/.test(r))
21
+ return [0, 0, 0];
22
+ let t = r.length, n = (c) => Number.parseInt(c, 16);
23
+ if (t === 3 || t === 4) {
24
+ let c = n(r[0] + r[0]), u = n(r[1] + r[1]), h = n(r[2] + r[2]), g = t === 4 ? n(r[3] + r[3]) : undefined;
25
+ return g !== undefined ? [c, u, h, g] : [c, u, h];
26
+ }
27
+ if (t !== 6 && t !== 8)
28
+ throw Error(`Invalid hex color length: ${t}`);
29
+ let a = n(r.slice(0, 2)), b = n(r.slice(2, 4)), o = n(r.slice(4, 6)), y = t === 8 ? n(r.slice(6, 8)) : undefined;
30
+ if ([a, b, o].some(Number.isNaN) || y !== undefined && Number.isNaN(y))
31
+ throw Error(`Invalid hex color value: ${s}`);
32
+ return y !== undefined ? [a, b, o, y] : [a, b, o];
33
+ }
34
+ function A(s) {
35
+ let [r, t, n, a] = s;
36
+ if (a)
37
+ return `#${(r << 24 | t << 16 | n << 8 | Math.round((a ?? 1) * 255)).toString(16).padStart(8, "0").toUpperCase()}`;
38
+ return `#${(r << 16 | t << 8 | n).toString(16).padStart(6, "0").toUpperCase()}`;
39
+ }
40
+ function R(s, r, t) {
41
+ s = (s % 360 + 360) % 360, t /= 100;
42
+ let n = r * Math.min(t, 1 - t) / 100, a = (b) => {
43
+ let o = (b + s / 30) % 12, y = t - n * Math.max(Math.min(o - 3, 9 - o, 1), -1);
44
+ return Math.round(255 * y);
45
+ };
46
+ return [a(0), a(8), a(4)];
47
+ }
48
+ function k(s) {
49
+ let [r, t, n] = s;
50
+ r /= 255, t /= 255, n /= 255;
51
+ let a = Math.max(r, t, n), b = Math.min(r, t, n), o = 0, y = 0, c = (a + b) / 2;
52
+ if (a !== b) {
53
+ let u = a - b;
54
+ if (y = c > 0 && c < 1 ? u / (1 - Math.abs(2 * c - 1)) : 0, a === r)
55
+ o = (t - n) / u + (t < n ? 6 : 0);
56
+ else if (a === t)
57
+ o = (n - r) / u + 2;
58
+ else
59
+ o = (r - t) / u + 4;
60
+ o /= 6;
61
+ }
62
+ return [Math.round(o * 360), Math.round(y * 100), Math.round(c * 100)];
63
+ }
64
+ function H(s, r, t) {
65
+ s = (s % 360 + 360) % 360, r /= 100, t /= 100;
66
+ let n = (a) => {
67
+ let b = (a + s / 60) % 6, o = t - t * r * Math.max(Math.min(b, 4 - b, 1), 0);
68
+ return Math.round(255 * o);
69
+ };
70
+ return [n(5), n(3), n(1)];
71
+ }
72
+ function f(s) {
73
+ let [r, t, n] = s;
74
+ r /= 255, t /= 255, n /= 255;
75
+ let a = Math.max(r, t, n), b = Math.min(r, t, n), o = a - b, y = 0, c = a === 0 ? 0 : o / a, u = a;
76
+ if (o !== 0) {
77
+ if (a === r)
78
+ y = (t - n) / o + (t < n ? 6 : 0);
79
+ else if (a === t)
80
+ y = (n - r) / o + 2;
81
+ else
82
+ y = (r - t) / o + 4;
83
+ y /= 6;
84
+ }
85
+ return [Math.round(y * 360), Math.round(c * 100), Math.round(u * 100)];
86
+ }
87
+ function O(s) {
88
+ let r = s[0] / 255, t = s[1] / 255, n = s[2] / 255, a = 1 - Math.max(r, t, n);
89
+ if (a === 1)
90
+ return [0, 0, 0, 100];
91
+ let b = (1 - r - a) / (1 - a), o = (1 - t - a) / (1 - a), y = (1 - n - a) / (1 - a);
92
+ return [Math.round(b * 100), Math.round(o * 100), Math.round(y * 100), Math.round(a * 100)];
93
+ }
94
+ function v(s, r, t, n) {
95
+ return s /= 100, r /= 100, t /= 100, n /= 100, [Math.round(255 * (1 - s) * (1 - n)), Math.round(255 * (1 - r) * (1 - n)), Math.round(255 * (1 - t) * (1 - n))];
96
+ }
97
+ var m = (s) => s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
98
+ var p = (s) => s <= 0.0031308 ? 12.92 * s : 1.055 * s ** 0.4166666666666667 - 0.055;
99
+ var i = (s, r) => Math.round(s * 10 ** r) / 10 ** r;
100
+ function T(s) {
101
+ let r = m(s[0] / 255), t = m(s[1] / 255), n = m(s[2] / 255), a = Math.cbrt(0.4122214708 * r + 0.5363325363 * t + 0.0514459929 * n), b = Math.cbrt(0.2119034982 * r + 0.6806995451 * t + 0.1073969566 * n), o = Math.cbrt(0.0883024619 * r + 0.2817188376 * t + 0.6299787005 * n);
102
+ return [i(0.2104542553 * a + 0.793617785 * b - 0.0040720468 * o, 4), i(1.9779984951 * a - 2.428592205 * b + 0.4505937099 * o, 4), i(0.0259040371 * a + 0.7827717662 * b - 0.808675766 * o, 4)];
103
+ }
104
+ function M(s, r, t) {
105
+ let n = (s + 0.3963377774 * r + 0.2158037573 * t) ** 3, a = (s - 0.1055613458 * r - 0.0638541728 * t) ** 3, b = (s - 0.0894841775 * r - 1.291485548 * t) ** 3, o = p(4.0767416621 * n - 3.3077115913 * a + 0.2309699292 * b), y = p(-1.2684380046 * n + 2.6097574011 * a - 0.3413193965 * b), c = p(-0.0041960863 * n - 0.7034186147 * a + 1.707614701 * b), u = (h) => Math.min(255, Math.max(0, Math.round(h * 255)));
106
+ return [u(o), u(y), u(c)];
107
+ }
108
+ function d(s) {
109
+ let [r, t, n] = T(s), a = Math.sqrt(t * t + n * n), b = (Math.atan2(n, t) * 180 / Math.PI + 360) % 360;
110
+ return [i(r, 4), i(a, 4), i(b, 2)];
111
+ }
112
+ function C(s, r, t) {
113
+ let n = t * Math.PI / 180;
114
+ return M(s, r * Math.cos(n), r * Math.sin(n));
115
+ }
116
+ function l(s) {
117
+ let r = s / 255;
118
+ return r <= 0.03928 ? r / 12.92 : ((r + 0.055) / 1.055) ** 2.4;
119
+ }
120
+
121
+ class e {
122
+ r;
123
+ g;
124
+ b;
125
+ a;
126
+ constructor(s, r, t, n = 1) {
127
+ this.r = s, this.g = r, this.b = t, this.a = n;
128
+ }
129
+ static from(s, r) {
130
+ if (s === "hex") {
131
+ let [t, n, a, b] = x(r);
132
+ return new e(t, n, a, b);
133
+ }
134
+ if (s === "rgb") {
135
+ if (Array.isArray(r)) {
136
+ let [o, y, c, u] = r;
137
+ return new e(o, y, c, u);
138
+ }
139
+ let { r: t, g: n, b: a, a: b } = r;
140
+ return new e(t, n, a, b);
141
+ }
142
+ if (s === "hsl") {
143
+ let t, n, a, b;
144
+ if (Array.isArray(r))
145
+ [t, n, a, b] = r;
146
+ else
147
+ ({ h: t, s: n, l: a, a: b } = r);
148
+ let [o, y, c] = R(t, n, a);
149
+ return new e(o, y, c, b);
150
+ }
151
+ if (s === "hsv") {
152
+ let t, n, a, b;
153
+ if (Array.isArray(r))
154
+ [t, n, a, b] = r;
155
+ else
156
+ ({ h: t, s: n, v: a, a: b } = r);
157
+ let [o, y, c] = H(t, n, a);
158
+ return new e(o, y, c, b);
159
+ }
160
+ if (s === "cmyk") {
161
+ let t, n, a, b, o;
162
+ if (Array.isArray(r))
163
+ [t, n, a, b, o] = r;
164
+ else
165
+ ({ c: t, m: n, y: a, k: b, a: o } = r);
166
+ let [y, c, u] = v(t, n, a, b);
167
+ return new e(y, c, u, o);
168
+ }
169
+ if (s === "oklch") {
170
+ let t, n, a, b;
171
+ if (Array.isArray(r))
172
+ [t, n, a, b] = r;
173
+ else
174
+ ({ l: t, c: n, h: a, a: b } = r);
175
+ let [o, y, c] = C(t, n, a);
176
+ return new e(o, y, c, b);
177
+ }
178
+ if (s === "oklab") {
179
+ let t, n, a, b;
180
+ if (Array.isArray(r))
181
+ [t, n, a, b] = r;
182
+ else
183
+ ({ l: t, a: n, b: a, alpha: b } = r);
184
+ let [o, y, c] = M(t, n, a);
185
+ return new e(o, y, c, b);
186
+ }
187
+ throw Error("Invalid input");
188
+ }
189
+ to(s) {
190
+ switch (s) {
191
+ case "rgb":
192
+ return [this.r, this.g, this.b];
193
+ case "rgba":
194
+ return [this.r, this.g, this.b, this.a];
195
+ case "hex":
196
+ return A([this.r, this.g, this.b]);
197
+ case "hexa":
198
+ return A([this.r, this.g, this.b, this.a]);
199
+ case "hsl":
200
+ return k([this.r, this.g, this.b]);
201
+ case "hsla":
202
+ return [...k([this.r, this.g, this.b]), this.a];
203
+ case "hsv":
204
+ return f([this.r, this.g, this.b]);
205
+ case "hsva":
206
+ return [...f([this.r, this.g, this.b]), this.a];
207
+ case "cmyk":
208
+ return O([this.r, this.g, this.b]);
209
+ case "cmyka":
210
+ return [...O([this.r, this.g, this.b]), this.a];
211
+ case "oklch":
212
+ return d([this.r, this.g, this.b]);
213
+ case "oklcha":
214
+ return [...d([this.r, this.g, this.b]), this.a];
215
+ case "oklab":
216
+ return T([this.r, this.g, this.b]);
217
+ case "oklaba":
218
+ return [...T([this.r, this.g, this.b]), this.a];
219
+ default:
220
+ return [this.r, this.g, this.b];
221
+ }
222
+ }
223
+ getLuminance() {
224
+ let s = l(this.r), r = l(this.g), t = l(this.b);
225
+ return 0.2126 * s + 0.7152 * r + 0.0722 * t;
226
+ }
227
+ contrastRatio(s) {
228
+ let r = this.getLuminance(), t = s.getLuminance(), [n, a] = r >= t ? [r, t] : [t, r];
229
+ return (n + 0.05) / (a + 0.05);
230
+ }
231
+ bestContrastForeground() {
232
+ let s = new e(255, 255, 255, 1), r = new e(0, 0, 0, 1), t = this.contrastRatio(s), n = this.contrastRatio(r);
233
+ return t >= n ? s : r;
234
+ }
235
+ }
236
+
237
+ // ../../node_modules/.bun/@kaynooo+utils@2.31.2+d0769e28dc4dad16/node_modules/@kaynooo/utils/dist/chunk-y1msbssb.js
238
+ var r = 39;
239
+ var o = 49;
240
+ var f2 = "\x1B[";
241
+ var C2 = { reset: [0, 0], bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29], black: [30, r], red: [31, r], green: [32, r], yellow: [33, r], blue: [34, r], magenta: [35, r], cyan: [36, r], white: [37, r], gray: [90, r], grey: [90, r], blackBright: [90, r], redBright: [91, r], greenBright: [92, r], yellowBright: [93, r], blueBright: [94, r], magentaBright: [95, r], cyanBright: [96, r], whiteBright: [97, r], bgBlack: [40, o], bgRed: [41, o], bgGreen: [42, o], bgYellow: [43, o], bgBlue: [44, o], bgMagenta: [45, o], bgCyan: [46, o], bgWhite: [47, o], bgBlackBright: [100, o], bgRedBright: [101, o], bgGreenBright: [102, o], bgYellowBright: [103, o], bgBlueBright: [104, o], bgMagentaBright: [105, o], bgCyanBright: [106, o], bgWhiteBright: [107, o], rgb: (i, n, a, l = "fg") => [`${l === "fg" ? 38 : 48};2;${i};${n};${a}`, l === "fg" ? r : o], hex: (i, n = "fg") => {
242
+ let [a, l, s] = e.from("hex", i).to("rgb");
243
+ return [`${n === "fg" ? 38 : 48};2;${a};${l};${s}`, n === "fg" ? r : o];
244
+ }, ansi256: (i, n = "fg") => [`${n === "fg" ? 38 : 48};5;${i}`, n === "fg" ? r : o] };
245
+ var b = new Set(["", "1", "2", "3", "true"]);
246
+ function h(i, n = globalThis.process?.env ?? {}) {
247
+ if (n.FORCE_COLOR !== undefined)
248
+ return b.has(n.FORCE_COLOR);
249
+ if (n.NO_COLOR !== undefined || n.NODE_DISABLE_COLORS !== undefined || n.TERM === "dumb")
250
+ return false;
251
+ return i?.isTTY === true;
252
+ }
253
+ function d2(i, n, a) {
254
+ if (!h(a.stream ?? globalThis.process?.stdout, a.env))
255
+ return n;
256
+ let l = "", s = "";
257
+ for (let g = 0, y = i.length;g < y; g++) {
258
+ let [c, p] = i[g];
259
+ l += `${f2}${c}m`, s = `${f2}${p}m${s}`;
260
+ }
261
+ return l + n + s;
262
+ }
263
+ function u(i, n = []) {
264
+ return new Proxy((l) => d2(n, l, i), { get(l, s) {
265
+ let g = C2[s];
266
+ if (Array.isArray(g))
267
+ return u(i, [...n, g]);
268
+ if (typeof g === "function")
269
+ return (...y) => u(i, [...n, g(...y)]);
270
+ throw Error(`Unknown style: ${String(s)}`);
271
+ } });
272
+ }
273
+ function le(i = {}) {
274
+ return u(i);
275
+ }
276
+ var t = le();
277
+
278
+ // ../kit/src/style.ts
279
+ var MARKS = {
280
+ ok: { symbol: "\u2713", word: "ok:", paint: (colors) => colors.green },
281
+ warn: { symbol: "!", word: "warning:", paint: (colors) => colors.yellow },
282
+ problem: { symbol: "\u2717", word: "error:", paint: (colors) => colors.red },
283
+ note: { symbol: "\xB7", word: "note:", paint: (colors) => colors.dim }
284
+ };
285
+ function takesControlCodes(stream, env = process.env) {
286
+ return stream.isTTY === true && env.NO_COLOR === undefined && env.NODE_DISABLE_COLORS === undefined && env.TERM !== "dumb";
287
+ }
288
+ function paint(stream, env = process.env) {
289
+ return le({ stream: { isTTY: takesControlCodes(stream, env) }, env });
290
+ }
291
+ function marked(mark, text, stream, detail, env = process.env) {
292
+ const colors = paint(stream, env);
293
+ const { symbol, word, paint: tint } = MARKS[mark];
294
+ const head = takesControlCodes(stream, env) ? tint(colors)(symbol) : word;
295
+ return `${head} ${text}${detail === undefined ? "" : ` ${colors.dim(detail)}`}`;
296
+ }
297
+ var ROLES = {
298
+ accent: (colors) => colors.cyan,
299
+ id: (colors) => colors.yellow,
300
+ path: (colors) => colors.blue,
301
+ label: (colors) => colors.dim,
302
+ value: (colors) => colors.bold
303
+ };
304
+ function role(name, stream, env = process.env) {
305
+ return ROLES[name](paint(stream, env));
306
+ }
307
+ var STATUSES = {
308
+ passed: { symbol: "\u2713", words: ["passed", "success", "succeeded", "ok"], paint: (colors) => colors.green },
309
+ failed: { symbol: "\u2717", words: ["failed", "failure", "error", "errored"], paint: (colors) => colors.red },
310
+ running: { symbol: "\u25CF", words: ["running", "in_progress", "started"], paint: (colors) => colors.cyan },
311
+ queued: { symbol: "\u25CB", words: ["queued", "waiting", "pending", "created", "blocked", "scheduled"], paint: (colors) => colors.yellow },
312
+ skipped: { symbol: "-", words: ["skipped", "cancelled", "canceled", "manual"], paint: (colors) => colors.dim }
313
+ };
314
+ var STATUS_OF = new Map(Object.entries(STATUSES).flatMap(([status, { words }]) => words.map((word) => [word, status])));
315
+
316
+ // ../kit/src/format.ts
317
+ function upTo(text, separator) {
318
+ const end = text.indexOf(separator);
319
+ return end === -1 ? text : text.slice(0, end);
320
+ }
321
+ function truncate(text, width) {
322
+ return text.length <= width ? text : `${text.slice(0, Math.max(0, width - 1))}\u2026`;
323
+ }
324
+ var LINE_BREAKS = /\s*\n\s*/g;
325
+ var ESCAPE = String.fromCharCode(27);
326
+ function textWidth(text) {
327
+ return Bun.stringWidth(text);
328
+ }
329
+ function table(rows, { cellWidth, header = false, align = [], fit } = {}) {
330
+ const cells = cellWidth === undefined ? rows : rows.map((row) => row.map((cell) => truncate(cell.replaceAll(LINE_BREAKS, " "), cellWidth)));
331
+ const widths = [];
332
+ for (const row of cells) {
333
+ for (const [index, cell] of row.entries())
334
+ widths[index] = Math.max(widths[index] ?? 0, textWidth(cell));
335
+ }
336
+ const shown = fit === undefined ? cells : narrow(cells, widths, fit);
337
+ const colors = paint(process2.stdout);
338
+ const lines = shown.map((row) => row.map((cell, index) => {
339
+ const width = widths[index] ?? 0;
340
+ const gap = " ".repeat(Math.max(0, width - textWidth(cell)));
341
+ if (align[index] === "right")
342
+ return `${gap}${cell}`;
343
+ return index === row.length - 1 ? cell : `${cell}${gap}`;
344
+ }).join(" ").trimEnd());
345
+ return lines.map((line, index) => header && index === 0 ? colors.bold(line) : line).join(`
346
+ `);
347
+ }
348
+ function narrow(rows, widths, limit) {
349
+ const used = () => widths.reduce((sum, width) => sum + width, 0) + 2 * Math.max(0, widths.length - 1);
350
+ const cuttable = (index) => rows.every((row) => !(row[index] ?? "").includes(ESCAPE));
351
+ const floor = 8;
352
+ while (used() > limit) {
353
+ let widest = -1;
354
+ for (const [index, width] of widths.entries()) {
355
+ if (cuttable(index) && width > floor && width > (widths[widest] ?? 0))
356
+ widest = index;
357
+ }
358
+ if (widest === -1)
359
+ break;
360
+ widths[widest] = Math.max(floor, (widths[widest] ?? 0) - (used() - limit));
361
+ }
362
+ return rows.map((row) => row.map((cell, index) => textWidth(cell) > (widths[index] ?? 0) ? truncate(cell, widths[index] ?? 0) : cell));
363
+ }
364
+ function printJson(value) {
365
+ console.log(JSON.stringify(value, undefined, 2));
366
+ }
367
+
368
+ // ../kit/src/help.ts
369
+ import process3 from "process";
370
+ var OPTIONAL = /\[[^\]]+\]/g;
371
+ var USAGE_PREFIX = /^usage:\s*/i;
372
+ var FULL_STOP = /\.$/;
373
+ function usageLine(usage, colors = paint(process3.stdout)) {
374
+ return `${colors.bold("Usage:")} ${usage.replace(USAGE_PREFIX, "").replaceAll(OPTIONAL, (part) => colors.dim(part))}`;
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(`
378
+ `);
379
+ }
380
+ function replacesRows(replaces, colors = paint(process3.stdout)) {
381
+ return replaces === undefined ? [] : ["", `${colors.bold("Instead of:")} ${replaces}`];
382
+ }
383
+ function wantsHelpJson(env = process3.env) {
384
+ return env.KIT_HELP === "json";
385
+ }
386
+ function description(usage, { examples = [], replaces } = {}) {
387
+ const lines = usage.replace(USAGE_PREFIX, "").split(`
388
+ `);
389
+ const first = lines[0];
390
+ const colon = first.indexOf(": ");
391
+ const prose = lines[lines.indexOf("") + 1] ?? "";
392
+ const fallback = lines.includes("") ? `${prose.charAt(0).toLowerCase()}${prose.slice(1)}`.replace(FULL_STOP, "") : "";
393
+ return {
394
+ synopsis: colon === -1 ? first : first.slice(0, colon),
395
+ summary: colon === -1 ? fallback : first.slice(colon + 2),
396
+ ...replaces === undefined ? {} : { replaces },
397
+ examples: examples.map((example) => typeof example === "string" ? { line: example } : { line: example[0], note: example[1] })
398
+ };
399
+ }
400
+ function exampleRows(examples, colors = paint(process3.stdout)) {
401
+ if (examples.length === 0)
402
+ return [];
403
+ return ["", colors.bold("Examples:"), ...examples.map((example) => typeof example === "string" ? ` ${example}` : ` ${example[0]} ${colors.dim(`# ${example[1]}`)}`)];
404
+ }
405
+ function optionRows(options, colors = paint(process3.stdout)) {
406
+ const rows = Object.entries(options).map(([name, option]) => {
407
+ const short = option.short === undefined ? " " : `${colors.cyan(`-${option.short}`)}, `;
408
+ const named = option.choices === undefined ? "<value>" : `<${option.choices.join("|")}>`;
409
+ const placeholder = option.optional === undefined ? named : `[${named}]`;
410
+ const value = option.type === "string" ? ` ${colors.dim(placeholder)}` : "";
411
+ return { flag: `${short}${colors.cyan(`--${name}`)}${value}`, width: `-x, --${name}`.length + (option.type === "string" ? placeholder.length + 1 : 0), description: option.description ?? "" };
412
+ });
413
+ const width = Math.max(0, ...rows.map((row) => row.width));
414
+ return rows.map((row) => row.description === "" ? ` ${row.flag}` : ` ${row.flag}${" ".repeat(width - row.width)} ${colors.dim(row.description)}`);
415
+ }
416
+
417
+ // ../kit/src/text.ts
418
+ var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[\\d;?]*[a-z]`, "gi");
419
+ function distance(a, b) {
420
+ let previous = Array.from({ length: b.length + 1 }, (_, index) => index);
421
+ for (const [i, left] of [...a].entries()) {
422
+ const current = [i + 1];
423
+ for (const [j, right] of [...b].entries())
424
+ current.push(Math.min((previous[j + 1] ?? 0) + 1, (current[j] ?? 0) + 1, (previous[j] ?? 0) + (left === right ? 0 : 1)));
425
+ previous = current;
426
+ }
427
+ return previous[b.length] ?? 0;
428
+ }
429
+ function closest(name, names) {
430
+ const started = names.find((known) => known.startsWith(name));
431
+ if (started !== undefined)
432
+ return started;
433
+ const [best] = names.map((known) => ({ known, far: distance(name, known) })).sort((a, b) => a.far - b.far);
434
+ return best !== undefined && best.far <= (name.length < 4 ? 1 : 2) ? best.known : undefined;
435
+ }
436
+
437
+ // ../kit/src/args.ts
438
+ var DASHES = /^-+/;
439
+ function jsonOption(holds) {
440
+ return { type: "boolean", description: holds === undefined ? "print JSON" : `print JSON: ${holds}` };
441
+ }
442
+
443
+ class Exit extends Error {
444
+ code;
445
+ hint;
446
+ constructor(message, code, hint) {
447
+ super(message);
448
+ this.code = code;
449
+ this.hint = hint;
450
+ }
451
+ }
452
+ function fail(message, code = 2, hint) {
453
+ throw new Exit(message, code, hint);
454
+ }
455
+
456
+ class UsageError extends Exit {
457
+ constructor(message, hint) {
458
+ super(message, 2, hint);
459
+ }
460
+ }
461
+ function badUsage(message) {
462
+ throw new UsageError(message);
463
+ }
464
+
465
+ class HelpShown extends Exit {
466
+ constructor() {
467
+ super("help shown", 0);
468
+ }
469
+ }
470
+
471
+ class Completing {
472
+ options;
473
+ positionals;
474
+ candidates;
475
+ constructor(options, positionals = [], candidates = {}) {
476
+ this.options = options;
477
+ this.positionals = positionals;
478
+ this.candidates = candidates;
479
+ }
480
+ }
481
+ var completion = { active: false };
482
+ var OUTPUT_OPTIONS = {
483
+ color: { type: "string", description: "auto (on a terminal alone), always or never" },
484
+ plain: { type: "boolean", description: "plain text, no colour or spinner: --color never" }
485
+ };
486
+ function applyOutput(color, plain, env = process4.env) {
487
+ const when = plain === true ? "never" : color ?? "auto";
488
+ if (when === "auto")
489
+ return;
490
+ if (when !== "always" && when !== "never")
491
+ badUsage(`--color takes auto, always or never, not ${when}`);
492
+ if (when === "always") {
493
+ env.FORCE_COLOR = "1";
494
+ delete env.NO_COLOR;
495
+ } else {
496
+ env.NO_COLOR = "1";
497
+ delete env.FORCE_COLOR;
498
+ }
499
+ }
500
+ function parse(args, usage, options, settings = {}) {
501
+ const output = Object.fromEntries(Object.entries(OUTPUT_OPTIONS).filter(([name]) => !(name in options)));
502
+ const all = { ...options, ...output, help: { type: "boolean", short: "h", description: "show this help" } };
503
+ const listing = listed(all, settings.allowNegative === true);
504
+ if (completion.active)
505
+ throw new Completing(listing, settings.positionals, settings.candidates);
506
+ const { own, rest } = settings.trailing === true ? splitTrailing(args, all, settings.positionals?.length ?? 0) : splitRest(args, settings.rest === true);
507
+ let parsed;
508
+ try {
509
+ parsed = parseArgs({ args: joinDashValues(withBare(own, all), all), options: all, allowPositionals: true, allowNegative: settings.allowNegative === true, strict: true });
510
+ } catch (error) {
511
+ const message = parseError(error);
512
+ throw new UsageError(message, nearestOption(message, all, settings.allowNegative === true));
513
+ }
514
+ const values = parsed.values;
515
+ applyOutput("color" in output ? values.color : undefined, "plain" in output ? values.plain : undefined);
516
+ if (values.help === true) {
517
+ console.log(wantsHelpJson() ? JSON.stringify(description(usage, settings)) : helpText(usage, listing, undefined, settings));
518
+ throw new HelpShown;
519
+ }
520
+ checkChoices(parsed.values, all);
521
+ checkConflicts(parsed.values, all);
522
+ if (settings.positionals !== undefined)
523
+ checkPositionals(parsed.positionals, settings.positionals);
524
+ return { ...parsed, values: parsed.values, positionals: parsed.positionals, rest };
525
+ }
526
+ function splitRest(args, passes) {
527
+ const separator = passes ? args.indexOf("--") : -1;
528
+ return { own: separator === -1 ? args : args.slice(0, separator), rest: separator === -1 ? undefined : args.slice(separator + 1) };
529
+ }
530
+ function splitTrailing(args, options, count) {
531
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
532
+ let seen = 0;
533
+ if (count === 0)
534
+ return { own: args, rest: undefined };
535
+ for (let at = 0;at < args.length; at++) {
536
+ const word = args[at];
537
+ if (word === "--")
538
+ break;
539
+ if (word.startsWith("-")) {
540
+ if (takesValue(word))
541
+ at++;
542
+ continue;
543
+ }
544
+ seen++;
545
+ if (seen === count)
546
+ return { own: args.slice(0, at + 1), rest: args.slice(at + 1) };
547
+ }
548
+ return { own: args, rest: undefined };
549
+ }
550
+ function listed(options, allowNegative) {
551
+ if (!allowNegative)
552
+ return options;
553
+ return Object.fromEntries(Object.entries(options).flatMap(([name, option]) => {
554
+ if (option.type !== "boolean" || option.negative === undefined)
555
+ return [[name, option]];
556
+ return [...option.description === undefined ? [] : [[name, option]], [`no-${name}`, { type: "boolean", description: option.negative }]];
557
+ }));
558
+ }
559
+ function withBare(args, options) {
560
+ const bare = new Map(Object.entries(options).flatMap(([name, { short, optional }]) => optional === undefined ? [] : [[`--${name}`, optional], ...short === undefined ? [] : [[`-${short}`, optional]]]));
561
+ if (bare.size === 0)
562
+ return args;
563
+ const separator = args.indexOf("--");
564
+ const own = separator === -1 ? args : args.slice(0, separator);
565
+ return [...own.flatMap((arg, index) => {
566
+ const optional = bare.get(arg);
567
+ const next = own[index + 1];
568
+ const value = next !== undefined && (optional?.accepts === undefined ? !next.startsWith("-") : optional.accepts.test(next));
569
+ return optional === undefined || value ? [arg] : [arg, optional.bare];
570
+ }), ...separator === -1 ? [] : args.slice(separator)];
571
+ }
572
+ function checkConflicts(values, options) {
573
+ const given = (name) => values[name] !== undefined && values[name] !== false;
574
+ for (const [name, { conflicts = [] }] of Object.entries(options)) {
575
+ const other = given(name) ? conflicts.find(given) : undefined;
576
+ if (other !== undefined)
577
+ badUsage(`--${name} cannot be used with --${other}`);
578
+ }
579
+ }
580
+ function checkChoices(values, options) {
581
+ for (const [name, option] of Object.entries(options)) {
582
+ if (option.choices === undefined)
583
+ continue;
584
+ const given = values[name];
585
+ for (const value of Array.isArray(given) ? given : [given]) {
586
+ if (typeof value === "string")
587
+ oneOf(value, name, option.choices);
588
+ }
589
+ }
590
+ }
591
+ function oneOf(value, name, choices) {
592
+ if (!choices.includes(value))
593
+ badUsage(`${name.startsWith("<") ? name : `--${name}`} takes one of ${choices.join(", ")}, not ${value}`);
594
+ return value;
595
+ }
596
+ function checkPositionals(given, names) {
597
+ const variadic = names.at(-1)?.replace("]", "").endsWith("...") === true;
598
+ const required = names.filter((name) => !name.startsWith("[")).length;
599
+ if (given.length < required)
600
+ badUsage(`missing ${names[given.length]}`);
601
+ if (!variadic && given.length > names.length)
602
+ badUsage(`unexpected argument ${given[names.length]}`);
603
+ }
604
+ function joinDashValues(args, options) {
605
+ const longOf = new Map(Object.entries(options).flatMap(([name, option]) => option.short === undefined ? [[`--${name}`, name]] : [[`--${name}`, name], [`-${option.short}`, name]]));
606
+ const isOption = (arg) => arg === "--" || longOf.has(arg.includes("=") ? arg.slice(0, arg.indexOf("=")) : arg);
607
+ const joined = [];
608
+ for (let i = 0;i < args.length; i++) {
609
+ const arg = args[i] ?? "";
610
+ if (arg === "--")
611
+ return [...joined, ...args.slice(i)];
612
+ const name = longOf.get(arg);
613
+ const next = args[i + 1];
614
+ if (name !== undefined && options[name]?.type === "string" && next !== undefined && next.startsWith("-") && next !== "-" && !isOption(next)) {
615
+ joined.push(`--${name}=${next}`);
616
+ i++;
617
+ } else {
618
+ joined.push(arg);
619
+ }
620
+ }
621
+ return joined;
622
+ }
623
+ function parseError(error) {
624
+ const message = upTo(error instanceof Error ? error.message : String(error), ". ");
625
+ return `${message.charAt(0).toLowerCase()}${message.slice(1)}`;
626
+ }
627
+ var UNKNOWN_OPTION = /^unknown option '(-[^']+)'/;
628
+ function nearestOption(message, options, allowNegative) {
629
+ const typed = UNKNOWN_OPTION.exec(message)?.[1];
630
+ if (typed === undefined)
631
+ return;
632
+ const word = typed.replace(DASHES, "");
633
+ if (word.length < 2 && !typed.startsWith("--"))
634
+ return;
635
+ const known = Object.entries(options).flatMap(([name, option]) => [
636
+ ...option.short === undefined ? [] : [`-${option.short}`],
637
+ `--${name}`,
638
+ ...allowNegative && option.type === "boolean" ? [`--no-${name}`] : []
639
+ ]);
640
+ const meant = closest(word, known.map((flag) => flag.replace(DASHES, "")));
641
+ return meant === undefined ? undefined : `did you mean ${known.find((flag) => flag.replace(DASHES, "") === meant)}?`;
642
+ }
643
+ // ../kit/src/progress.ts
644
+ var ESC = String.fromCharCode(27);
645
+ var ESCAPE_CODE = new RegExp(`${ESC}(?:\\[[\\x30-\\x3F]*[\\x20-\\x2F]*[\\x40-\\x7E]|\\][^\\u0007${ESC}]*(?:\\u0007|${ESC}\\\\))`, "y");
646
+ var RESET_STYLE = `${ESC}[0m`;
647
+ var CLOSE_LINK = `${ESC}]8;;${ESC}\\`;
648
+ // ../kit/src/cli.ts
649
+ import process6 from "process";
650
+
651
+ // ../kit/src/usage.ts
652
+ import { appendFileSync, mkdirSync } from "fs";
653
+ import { homedir } from "os";
654
+ import { dirname, isAbsolute, join } from "path";
655
+ import process5 from "process";
656
+
657
+ // ../kit/src/logs.ts
658
+ var DAY_MS = 24 * 60 * 60 * 1000;
659
+ var CLI_FOLDER = "kaynooo-cli";
660
+
661
+ // ../kit/src/usage.ts
662
+ var UNKNOWN_OPTION2 = /unknown option '(--[a-z][a-z0-9-]*)[=']/;
663
+ var FLAG_NAME = /^(?:--[a-z][a-z0-9-]*|-[a-zA-Z])$/;
664
+ var LONGEST_NAME = 40;
665
+ var usageError;
666
+ function noteUsageError(message) {
667
+ usageError = message;
668
+ }
669
+ function stateHome(env = process5.env) {
670
+ const dir = env.XDG_STATE_HOME;
671
+ return dir !== undefined && isAbsolute(dir) ? dir : join(homedir(), ".local", "state");
672
+ }
673
+ function usagePath(env = process5.env) {
674
+ return join(stateHome(env), CLI_FOLDER, "usage.jsonl");
675
+ }
676
+ function usageRecorded(env = process5.env) {
677
+ const off = env.KAYNOOO_CLI_NO_USAGE;
678
+ return env.NODE_ENV !== "test" && (off === undefined || off === "" || off === "0");
679
+ }
680
+ function flagNames(argv) {
681
+ const end = argv.indexOf("--");
682
+ const names = (end === -1 ? argv : argv.slice(0, end)).filter((word) => word.startsWith("-") && word !== "-").map((word) => word.includes("=") ? word.slice(0, word.indexOf("=")) : word);
683
+ return [...new Set(names)].filter((name) => name.length <= LONGEST_NAME && FLAG_NAME.test(name));
684
+ }
685
+ function usageEntry(bin, command, argv, code, now = new Date) {
686
+ const unknown = code === 2 && usageError !== undefined ? UNKNOWN_OPTION2.exec(usageError)?.[1] : undefined;
687
+ usageError = undefined;
688
+ return { at: now.toISOString(), bin, ...command === undefined ? {} : { command }, flags: flagNames(argv), code, ...unknown === undefined ? {} : { unknown } };
689
+ }
690
+ function recordUsage(entry, env = process5.env) {
691
+ if (!usageRecorded(env))
692
+ return;
693
+ try {
694
+ const path = usagePath(env);
695
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
696
+ appendFileSync(path, `${JSON.stringify(entry)}
697
+ `, { mode: 384 });
698
+ } catch {}
699
+ }
700
+
701
+ // ../kit/src/cli.ts
702
+ var LEVEL_OPTIONS = {
703
+ ...OUTPUT_OPTIONS,
704
+ help: { type: "boolean", short: "h", description: "show this help" }
705
+ };
706
+ var TOP_OPTIONS = { ...LEVEL_OPTIONS, version: { type: "boolean", short: "v", description: "print the version" } };
707
+ function printError(prefix, message, hint, cause) {
708
+ const colors = paint(process6.stderr);
709
+ const styled = takesControlCodes(process6.stderr);
710
+ const head = styled ? `${colors.red.bold("error")} ${colors.dim(`${prefix}:`)}` : `error: ${prefix}:`;
711
+ const under = (label, text, tint) => text === undefined ? "" : `
712
+ ${styled ? tint(label) : `${label}:`} ${text}`;
713
+ console.error(`${head} ${message}${under("cause", cause, colors.dim)}${under("hint", hint, colors.yellow)}`);
714
+ }
715
+ function printJsonError(message, hint, cause) {
716
+ console.error(JSON.stringify({ error: message, ...hint === undefined ? {} : { hint }, ...cause === undefined ? {} : { cause } }));
717
+ }
718
+ function wantsJson(argv) {
719
+ const end = argv.indexOf("--");
720
+ return (end === -1 ? argv : argv.slice(0, end)).includes("--json");
721
+ }
722
+ function reportThrown(prefix, error, redact = (text) => text, json = false) {
723
+ if (error instanceof HelpShown)
724
+ return 0;
725
+ const help = error instanceof UsageError ? `run ${prefix} --help for its options` : undefined;
726
+ const named = error instanceof Error && !(error instanceof Exit) && error.name !== "Error" ? `${error.name}: ${error.message}` : undefined;
727
+ const cause = error instanceof Error && error.cause instanceof Error ? redact(error.cause.message) : undefined;
728
+ if (error instanceof UsageError)
729
+ noteUsageError(error.message);
730
+ const report = json ? printJsonError : (message, hint, causeText) => printError(prefix, message, hint, causeText);
731
+ report(redact(named ?? (error instanceof Error ? error.message : String(error))), error instanceof Exit ? error.hint ?? help : undefined, cause);
732
+ return error instanceof Exit ? error.code : 1;
733
+ }
734
+ var COMPLETE = "__complete";
735
+ var FILES = "__files__";
736
+ async function completingOf(run) {
737
+ completion.active = true;
738
+ try {
739
+ await run([]);
740
+ } catch (error) {
741
+ if (error instanceof Completing)
742
+ return error;
743
+ } finally {
744
+ completion.active = false;
745
+ }
746
+ return new Completing({});
747
+ }
748
+ function candidateLine(candidate) {
749
+ return typeof candidate === "string" ? candidate : candidate.join("\t");
750
+ }
751
+ function positionalBeingTyped(before, { options, positionals }) {
752
+ const takesValue = (word) => !word.includes("=") && Object.entries(options).some(([name, { short, type }]) => type === "string" && (word === `--${name}` || word === `-${short}`));
753
+ let index = 0;
754
+ let at = 0;
755
+ while (at < before.length) {
756
+ const word = before[at];
757
+ if (word === "--") {
758
+ index += before.length - at - 1;
759
+ break;
760
+ }
761
+ if (!word.startsWith("-"))
762
+ index++;
763
+ else if (takesValue(word))
764
+ at++;
765
+ at++;
766
+ }
767
+ const last = positionals.at(-1);
768
+ if (index < positionals.length)
769
+ return positionals[index];
770
+ return last?.replace("]", "").endsWith("...") === true ? last : undefined;
771
+ }
772
+ async function leafCandidates(run, words) {
773
+ const completing = await completingOf(run);
774
+ if ((words.at(-1) ?? "").startsWith("-"))
775
+ return Object.entries(completing.options).map(([name, option]) => option.description === undefined ? `--${name}` : `--${name} ${option.description}`);
776
+ const flag = words.at(-2);
777
+ const option = flag?.startsWith("-") === true ? Object.entries(completing.options).find(([name, { short }]) => flag === `--${name}` || flag === `-${short}`)?.[1] : undefined;
778
+ if (option?.type === "string") {
779
+ const values = option.choices === undefined ? await option.candidates?.() : option.choices;
780
+ return values === undefined ? [FILES] : values.map(candidateLine);
781
+ }
782
+ const name = positionalBeingTyped(words.slice(0, -1), completing);
783
+ const values = name === undefined ? undefined : await completing.candidates[name]?.();
784
+ return values === undefined ? [FILES] : values.map(candidateLine);
785
+ }
786
+ async function printCandidates(found) {
787
+ for (const line of await found)
788
+ console.log(line);
789
+ return 0;
790
+ }
791
+ async function runMain({ name, version, run, redact, usage }, argv = process6.argv.slice(2)) {
792
+ if (argv[0] === COMPLETE)
793
+ return printCandidates(leafCandidates(run, argv.slice(1)));
794
+ if (argv.length === 1 && (argv[0] === "--version" || argv[0] === "-v")) {
795
+ console.log(version);
796
+ return 0;
797
+ }
798
+ let code;
799
+ try {
800
+ code = await run(argv);
801
+ } catch (error) {
802
+ code = reportThrown(name, error, redact, wantsJson(argv));
803
+ }
804
+ if (usage !== false)
805
+ recordUsage(usageEntry(name, undefined, argv, code));
806
+ return code;
807
+ }
808
+ // ../kit/src/secrets.ts
809
+ var SECRET_WORDS = new Set(["key", "pass", "pwd", "auth", "salt", "cookie", "session", "jwt", "ssn", "iban", "card", "cvv", "otp"]);
810
+ // ../kit/src/sessions.ts
811
+ var {Glob } = globalThis.Bun;
812
+ var SESSION_FILES = new Glob("*.json");
813
+ var ACCOUNT_DIRS = new Glob("*/sessions");
814
+ // package.json
815
+ var version = "0.1.0";
816
+
817
+ // src/analyze.ts
818
+ var SOON_DAYS = 14;
819
+ var MAX_HOPS = 10;
820
+ var SCHEME = /^[a-z][a-z0-9+.-]*:\/\//i;
821
+ var SEPARATOR = `
822
+ ---HEADERS---
823
+ `;
824
+ var CERT_PREFIX = /^(?:DNS|IP Address|IP|email|URI):/;
825
+ var CACHE_NODE = /cache-/i;
826
+ var ALT_VALUE = /=.*$/;
827
+ function parseTarget(input) {
828
+ const bare = !SCHEME.test(input);
829
+ try {
830
+ const url = new URL(bare ? `https://${input}` : input);
831
+ return url.protocol !== "http:" && url.protocol !== "https:" || url.hostname === "" ? undefined : { url, bare };
832
+ } catch {
833
+ return;
834
+ }
835
+ }
836
+ var WRITE_OUT = `%{json}${SEPARATOR}%{header_json}`;
837
+ function seconds(value) {
838
+ return typeof value === "number" ? value : 0;
839
+ }
840
+ function ms(value) {
841
+ return Math.round(value * 1000);
842
+ }
843
+ function timingsOf(info) {
844
+ const lookup = seconds(info.time_namelookup);
845
+ const connect = seconds(info.time_connect);
846
+ const secure = seconds(info.time_appconnect);
847
+ const ready = secure > 0 ? secure : connect;
848
+ const first = seconds(info.time_starttransfer);
849
+ return {
850
+ dns: ms(lookup),
851
+ connect: ms(Math.max(0, connect - lookup)),
852
+ tls: secure > 0 ? ms(Math.max(0, secure - connect)) : 0,
853
+ firstByte: ms(Math.max(0, first - ready)),
854
+ total: ms(seconds(info.time_total))
855
+ };
856
+ }
857
+ function headersOf(json) {
858
+ const headers = {};
859
+ try {
860
+ const parsed = JSON.parse(json);
861
+ if (typeof parsed !== "object" || parsed === null)
862
+ return headers;
863
+ for (const [name, value] of Object.entries(parsed)) {
864
+ const values = Array.isArray(value) ? value.map(String) : [String(value)];
865
+ headers[name.toLowerCase()] = values.join(", ");
866
+ }
867
+ } catch {}
868
+ return headers;
869
+ }
870
+ function parseCurl(stdout) {
871
+ const at = stdout.indexOf(SEPARATOR);
872
+ const infoText = at === -1 ? stdout : stdout.slice(0, at);
873
+ let info;
874
+ try {
875
+ info = JSON.parse(infoText);
876
+ } catch {
877
+ return { exitcode: 1, errormsg: "curl printed no result" };
878
+ }
879
+ const exitcode = typeof info.exitcode === "number" ? info.exitcode : 1;
880
+ const errormsg = typeof info.errormsg === "string" ? info.errormsg : null;
881
+ const status = typeof info.response_code === "number" ? info.response_code : 0;
882
+ if (exitcode !== 0 || status === 0)
883
+ return { exitcode: exitcode === 0 ? 1 : exitcode, errormsg: errormsg ?? "no response" };
884
+ const headers = headersOf(at === -1 ? "" : stdout.slice(at + SEPARATOR.length));
885
+ const hop = {
886
+ url: String(info.url_effective ?? info.url ?? ""),
887
+ status,
888
+ version: String(info.http_version ?? ""),
889
+ timings: timingsOf(info),
890
+ headers
891
+ };
892
+ if (typeof info.redirect_url === "string" && info.redirect_url !== "")
893
+ hop.location = info.redirect_url;
894
+ else if (headers.location !== undefined)
895
+ hop.location = headers.location;
896
+ if (typeof info.remote_ip === "string" && info.remote_ip !== "")
897
+ hop.remoteIp = info.remote_ip;
898
+ return { exitcode, errormsg, hop };
899
+ }
900
+ function isRedirect(status) {
901
+ return status === 301 || status === 302 || status === 303 || status === 307 || status === 308;
902
+ }
903
+ function nextUrl(current, location) {
904
+ try {
905
+ const next = new URL(location, current);
906
+ return next.protocol === "http:" || next.protocol === "https:" ? next.href : undefined;
907
+ } catch {
908
+ return;
909
+ }
910
+ }
911
+ function versionLabel(version) {
912
+ return version === "" ? "unknown" : `HTTP/${version}`;
913
+ }
914
+ function altSvcProtocols(altSvc) {
915
+ if (altSvc === undefined || altSvc.trim() === "clear")
916
+ return [];
917
+ const ids = altSvc.split(",").map((entry) => entry.trim().replace(ALT_VALUE, "")).filter((id) => id !== "");
918
+ return [...new Set(ids)];
919
+ }
920
+ function offersOf(options) {
921
+ const altSvc = altSvcProtocols(options.altSvc);
922
+ return {
923
+ h2: options.alpn === "h2" || options.version === "2" || options.version === "3",
924
+ h3: options.version === "3" || altSvc.some((id) => id === "h3" || id.startsWith("h3-")),
925
+ altSvc
926
+ };
927
+ }
928
+ var KNOWN_SERVERS = [
929
+ [/cloudflare/i, "Cloudflare"],
930
+ [/cloudfront/i, "CloudFront"],
931
+ [/akamai/i, "Akamai"],
932
+ [/fastly/i, "Fastly"],
933
+ [/vercel/i, "Vercel"],
934
+ [/netlify/i, "Netlify"],
935
+ [/bunnycdn/i, "BunnyCDN"],
936
+ [/gws|esf|google frontend|gse/i, "Google"]
937
+ ];
938
+ function cdnHint(headers) {
939
+ const served = headers["x-served-by"];
940
+ if (headers["cf-ray"] !== undefined)
941
+ return "Cloudflare (cf-ray)";
942
+ if (served !== undefined)
943
+ return `${CACHE_NODE.test(served) ? "Fastly" : served} (x-served-by)`;
944
+ if (headers["x-amz-cf-id"] !== undefined)
945
+ return "CloudFront (x-amz-cf-id)";
946
+ if (headers["x-vercel-id"] !== undefined)
947
+ return "Vercel (x-vercel-id)";
948
+ if (headers.via !== undefined)
949
+ return `${headers.via} (via)`;
950
+ if (headers["x-cache"] !== undefined)
951
+ return `${headers["x-cache"]} (x-cache)`;
952
+ const server = headers.server;
953
+ if (server !== undefined) {
954
+ const known = KNOWN_SERVERS.find(([pattern]) => pattern.test(server));
955
+ if (known !== undefined)
956
+ return `${known[1]} (server)`;
957
+ }
958
+ return;
959
+ }
960
+ var WORTH_KNOWING = ["server", "content-type", "content-encoding", "cache-control", "strict-transport-security"];
961
+ function worthKnowing(headers) {
962
+ const kept = {};
963
+ for (const name of WORTH_KNOWING) {
964
+ const value = headers[name];
965
+ if (value !== undefined)
966
+ kept[name] = value;
967
+ }
968
+ return kept;
969
+ }
970
+ function field(value) {
971
+ if (typeof value === "string")
972
+ return value;
973
+ return Array.isArray(value) ? value.join(", ") : "";
974
+ }
975
+ function nameOf(entry) {
976
+ if (entry === undefined)
977
+ return "";
978
+ const common = field(entry.CN);
979
+ const organization = field(entry.O);
980
+ if (common !== "" && organization !== "" && common !== organization)
981
+ return `${common} (${organization})`;
982
+ return common === "" ? organization : common;
983
+ }
984
+ function namesOf(subjectaltname) {
985
+ if (subjectaltname === undefined)
986
+ return [];
987
+ return subjectaltname.split(",").map((entry) => entry.trim().replace(CERT_PREFIX, "")).filter((name) => name !== "");
988
+ }
989
+ function certInfo(raw, now = Date.now()) {
990
+ if (raw.valid_to === undefined || raw.valid_from === undefined)
991
+ return;
992
+ const end = Date.parse(raw.valid_to);
993
+ const start = Date.parse(raw.valid_from);
994
+ if (Number.isNaN(end) || Number.isNaN(start))
995
+ return;
996
+ return {
997
+ subject: nameOf(raw.subject),
998
+ issuer: nameOf(raw.issuer),
999
+ names: namesOf(raw.subjectaltname),
1000
+ validFrom: new Date(start).toISOString(),
1001
+ validTo: new Date(end).toISOString(),
1002
+ daysLeft: Math.floor((end - now) / 86400000)
1003
+ };
1004
+ }
1005
+ function httpRedirectOf(hop) {
1006
+ if (hop === undefined)
1007
+ return;
1008
+ const next = hop.location === undefined ? undefined : nextUrl(hop.url, hop.location);
1009
+ const redirect = { status: hop.status, toHttps: isRedirect(hop.status) && next !== undefined && new URL(next).protocol === "https:" };
1010
+ if (hop.location !== undefined)
1011
+ redirect.location = hop.location;
1012
+ return redirect;
1013
+ }
1014
+ function wantsHttpCheck(target) {
1015
+ return target.url.protocol === "https:" && target.url.port === "";
1016
+ }
1017
+ function warningsOf(input) {
1018
+ const warnings = [];
1019
+ const { cert, httpRedirect } = input;
1020
+ if (cert !== undefined) {
1021
+ if (cert.daysLeft < 0)
1022
+ warnings.push(`certificate expired ${-cert.daysLeft} days ago`);
1023
+ else if (cert.daysLeft < SOON_DAYS)
1024
+ warnings.push(`certificate expires in ${cert.daysLeft} days`);
1025
+ }
1026
+ if (input.authorizationError !== undefined)
1027
+ warnings.push(`certificate not trusted: ${input.authorizationError}`);
1028
+ if (httpRedirect !== undefined && !httpRedirect.toHttps)
1029
+ warnings.push(`http:// answers ${httpRedirect.status} and does not redirect to https`);
1030
+ if (input.tooManyRedirects)
1031
+ warnings.push(`more than ${MAX_HOPS} redirects`);
1032
+ return warnings;
1033
+ }
1034
+
1035
+ // src/net.ts
1036
+ import { lookup } from "dns/promises";
1037
+ import { isIP } from "net";
1038
+ import { connect } from "tls";
1039
+ var CONNECT_TIMEOUT = 10;
1040
+ var MAX_TIME = 20;
1041
+ var HTTP3_FEATURE = /^Features:.*\bHTTP3\b/m;
1042
+ var BRACKETS = /^\[|\]$/g;
1043
+ var http3;
1044
+ async function curlHasHttp3() {
1045
+ if (http3 !== undefined)
1046
+ return http3;
1047
+ try {
1048
+ const result = Bun.spawn(["curl", "--version"], { stdout: "pipe", stderr: "ignore" });
1049
+ const text = await new Response(result.stdout).text();
1050
+ http3 = HTTP3_FEATURE.test(text);
1051
+ } catch {
1052
+ http3 = false;
1053
+ }
1054
+ return http3;
1055
+ }
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];
1058
+ if (!get)
1059
+ args.push("-I");
1060
+ if (wantsH3)
1061
+ args.push("--http3");
1062
+ if (insecure)
1063
+ args.push("--insecure");
1064
+ try {
1065
+ const result = Bun.spawn(["curl", ...args, url], { stdout: "pipe", stderr: "pipe" });
1066
+ const [stdout] = await Promise.all([new Response(result.stdout).text(), new Response(result.stderr).text(), result.exited]);
1067
+ return parseCurl(stdout);
1068
+ } catch {
1069
+ return { exitcode: 127, errormsg: "curl is not installed" };
1070
+ }
1071
+ }
1072
+ async function curlHop(url, options) {
1073
+ let result = await runCurl(url, options);
1074
+ if (result.hop === undefined && options.http3)
1075
+ result = await runCurl(url, { ...options, http3: false });
1076
+ if (result.hop !== undefined && !options.get && (result.hop.status === 405 || result.hop.status === 501))
1077
+ result = await runCurl(url, { ...options, get: true });
1078
+ return result;
1079
+ }
1080
+ async function addressesOf(host) {
1081
+ const bare = host.replace(BRACKETS, "");
1082
+ const family = isIP(bare);
1083
+ if (family !== 0)
1084
+ return family === 4 ? { a: [bare], aaaa: [] } : { a: [], aaaa: [bare] };
1085
+ try {
1086
+ const found = await lookup(bare, { all: true });
1087
+ return { a: found.filter((entry) => entry.family === 4).map((entry) => entry.address), aaaa: found.filter((entry) => entry.family === 6).map((entry) => entry.address) };
1088
+ } catch {
1089
+ return { a: [], aaaa: [] };
1090
+ }
1091
+ }
1092
+ async function tlsInfo(host, port) {
1093
+ const bare = host.replace(BRACKETS, "");
1094
+ 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 });
1096
+ socket.on("secureConnect", () => {
1097
+ const error = socket.authorizationError;
1098
+ resolve({
1099
+ protocol: socket.getProtocol() ?? "",
1100
+ cipher: socket.getCipher().name,
1101
+ alpn: typeof socket.alpnProtocol === "string" ? socket.alpnProtocol : undefined,
1102
+ authorizationError: error === null || error === undefined || error === false ? undefined : String(error),
1103
+ cert: certInfo(socket.getPeerCertificate())
1104
+ });
1105
+ socket.end();
1106
+ });
1107
+ socket.on("error", () => resolve(undefined));
1108
+ socket.on("timeout", () => {
1109
+ socket.destroy();
1110
+ resolve(undefined);
1111
+ });
1112
+ });
1113
+ }
1114
+
1115
+ // src/probe.ts
1116
+ 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
1118
+
1119
+ 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.
1120
+
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.`;
1124
+ var OPTIONS = {
1125
+ 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}")
1127
+ };
1128
+ async function follow(start, insecure, http3) {
1129
+ const chain = [];
1130
+ let url = start;
1131
+ while (chain.length < MAX_HOPS) {
1132
+ const { hop, errormsg } = await curlHop(url, { http3: http3 && url.startsWith("https:"), insecure, get: false });
1133
+ if (hop === undefined)
1134
+ return { chain, error: errormsg ?? "no response", tooMany: false };
1135
+ chain.push(hop);
1136
+ const next = hop.location === undefined ? undefined : nextUrl(hop.url, hop.location);
1137
+ if (!isRedirect(hop.status) || next === undefined)
1138
+ return { chain, tooMany: false };
1139
+ url = next;
1140
+ }
1141
+ return { chain, tooMany: true };
1142
+ }
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}`);
1152
+ const http3 = await curlHasHttp3();
1153
+ let followed = await follow(target.url.href, insecure, http3);
1154
+ if (followed.chain.length === 0 && target.bare) {
1155
+ const plain = new URL(target.url.href);
1156
+ plain.protocol = "http:";
1157
+ const second = await follow(plain.href, insecure, http3);
1158
+ if (second.chain.length > 0)
1159
+ followed = second;
1160
+ }
1161
+ const final = followed.chain.at(-1);
1162
+ if (final === undefined)
1163
+ return { error: `could not reach ${target.url.host}: ${followed.error ?? "no response"}` };
1164
+ const finalUrl = new URL(final.url);
1165
+ const secure = finalUrl.protocol === "https:";
1166
+ 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)
1170
+ ]);
1171
+ const httpRedirect = httpRedirectOf(twin);
1172
+ const offers = offersOf({ alpn: tls?.alpn, version: final.version, altSvc: final.headers["alt-svc"] });
1173
+ const warnings = warningsOf({ cert: tls?.cert, authorizationError: tls?.authorizationError, httpRedirect, tooManyRedirects: followed.tooMany });
1174
+ if (!secure)
1175
+ warnings.push("the site is not served over https");
1176
+ return {
1177
+ target: input,
1178
+ url: final.url,
1179
+ version: final.version,
1180
+ status: final.status,
1181
+ chain: followed.chain.map((hop) => ({ url: hop.url, status: hop.status, version: hop.version, ...hop.location === undefined ? {} : { location: hop.location }, ms: hop.timings.total })),
1182
+ timings: final.timings,
1183
+ addresses,
1184
+ tls: tls === undefined ? null : { protocol: tls.protocol, cipher: tls.cipher, ...tls.alpn === undefined ? {} : { alpn: tls.alpn } },
1185
+ certificate: tls?.cert ?? null,
1186
+ headers: worthKnowing(final.headers),
1187
+ cdn: cdnHint(final.headers) ?? null,
1188
+ offers,
1189
+ httpRedirect: httpRedirect ?? null,
1190
+ warnings
1191
+ };
1192
+ }
1193
+ async function twinOf(url, insecure) {
1194
+ const plain = new URL(url.href);
1195
+ plain.protocol = "http:";
1196
+ return (await curlHop(plain.href, { http3: false, insecure, get: false })).hop;
1197
+ }
1198
+ function ms2(value) {
1199
+ return `${value}ms`;
1200
+ }
1201
+ function print(report) {
1202
+ const label = role("label", process8.stdout);
1203
+ const value = role("value", process8.stdout);
1204
+ const accent = role("accent", process8.stdout);
1205
+ 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)}`);
1207
+ console.log("");
1208
+ if (report.chain.length > 1) {
1209
+ console.log(table(report.chain.map((hop) => [String(hop.status), versionLabel(hop.version), ms2(hop.ms), hop.url]), { align: ["right", "left", "right", "left"] }));
1210
+ console.log("");
1211
+ }
1212
+ const { timings } = report;
1213
+ row("timings", `dns ${ms2(timings.dns)}, connect ${ms2(timings.connect)}, tls ${ms2(timings.tls)}, first byte ${ms2(timings.firstByte)}, total ${ms2(timings.total)}`);
1214
+ row("addresses", [...report.addresses.a, ...report.addresses.aaaa].join(", ") || "none found");
1215
+ if (report.tls !== null)
1216
+ row("tls", `${report.tls.protocol} ${report.tls.cipher}`);
1217
+ const cert = report.certificate;
1218
+ if (cert !== null) {
1219
+ row("issuer", cert.issuer);
1220
+ row("expires", `${cert.validTo.slice(0, 10)} (${cert.daysLeft} days left)`);
1221
+ row("names", cert.names.join(", "));
1222
+ }
1223
+ 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(" ")})`}`);
1224
+ for (const [name, text] of Object.entries(report.headers))
1225
+ row(name === "strict-transport-security" ? "hsts" : name, text);
1226
+ if (report.cdn !== null)
1227
+ row("cdn", report.cdn);
1228
+ if (report.httpRedirect !== null)
1229
+ row("http://", report.httpRedirect.toHttps ? `redirects to https (${report.httpRedirect.status})` : `answers ${report.httpRedirect.status}`);
1230
+ for (const warning of report.warnings)
1231
+ console.log(marked("warn", warning, process8.stdout));
1232
+ }
1233
+ 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;
1243
+ }
1244
+ process8.exitCode = await runMain({ name: "probe", version, run: main });
package/package.json CHANGED
@@ -1,6 +1,40 @@
1
1
  {
2
2
  "name": "@kaynooo/cli-probe",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "type": "module",
4
+ "version": "0.1.0",
5
+ "description": "probe: a site's HTTP version, redirect chain, timings, addresses, TLS certificate and notable headers in one call, with warnings.",
6
+ "author": "Kaynooo <contact@kaynooo.fr>",
7
+ "license": "MIT",
8
+ "homepage": "https://git.kaynooo.fr/kaynooo/cli/src/branch/main/packages/probe#readme",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://git.kaynooo.fr/kaynooo/cli.git",
12
+ "directory": "packages/probe"
13
+ },
14
+ "bugs": "https://git.kaynooo.fr/kaynooo/cli/issues",
15
+ "keywords": [
16
+ "cli",
17
+ "http",
18
+ "tls",
19
+ "curl"
20
+ ],
21
+ "bin": {
22
+ "probe": "./dist/probe.js"
23
+ },
24
+ "files": [
25
+ "dist"
26
+ ],
27
+ "engines": {
28
+ "bun": ">=1.4.3"
29
+ },
30
+ "publishConfig": {
31
+ "registry": "https://git.kaynooo.fr/api/packages/kaynooo/npm/"
32
+ },
33
+ "scripts": {
34
+ "build": "$npm_execpath build src/probe.ts --target bun --outdir dist",
35
+ "probe": "$npm_execpath src/probe.ts"
36
+ },
37
+ "devDependencies": {
38
+ "@kaynooo/cli-kit": "0.19.0"
39
+ }
40
+ }