hopwire 0.2.1 → 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.
@@ -0,0 +1,671 @@
1
+ import { printable } from './output.js';
2
+ import { decorate } from './style.js';
3
+ import { TOLERANCE_MS, checkSignature } from './signature.js';
4
+ import { recogniseWebhook } from './webhook.js';
5
+ /** The dark theme of docs/design_system.md: brand tokens and status colours as text. */
6
+ const DARK = {
7
+ green: { rgb: [0x00, 0xff, 0x66], basic: '32' },
8
+ cyan: { rgb: [0x00, 0xf0, 0xff], basic: '36' },
9
+ blue: { rgb: [0x0a, 0x5c, 0xff], basic: '34' },
10
+ muted: { rgb: [0x94, 0xa3, 0xb8], basic: '2' },
11
+ mark: { rgb: [0x00, 0xff, 0x66], basic: '32' },
12
+ ok: { rgb: [0x6e, 0xe7, 0xb7], basic: '32' },
13
+ info: { rgb: [0x7d, 0xd3, 0xfc], basic: '36' },
14
+ warn: { rgb: [0xfc, 0xd3, 0x4d], basic: '33' },
15
+ err: { rgb: [0xfc, 0xa5, 0xa5], basic: '31' },
16
+ };
17
+ /** The light theme: green and cyan as text take their darker text tokens. */
18
+ const LIGHT = {
19
+ green: { rgb: [0x00, 0x7a, 0x33], basic: '32' },
20
+ cyan: { rgb: [0x00, 0x6e, 0x7a], basic: '36' },
21
+ blue: { rgb: [0x0a, 0x5c, 0xff], basic: '34' },
22
+ muted: { rgb: [0x47, 0x55, 0x69], basic: '2' },
23
+ mark: null,
24
+ ok: { rgb: [0x06, 0x5f, 0x46], basic: '32' },
25
+ info: { rgb: [0x07, 0x59, 0x85], basic: '36' },
26
+ warn: { rgb: [0x92, 0x40, 0x0e], basic: '33' },
27
+ err: { rgb: [0x99, 0x1b, 0x1b], basic: '31' },
28
+ };
29
+ /**
30
+ * The look of the terminal from its environment. A light background is only known when the terminal says so in
31
+ * COLORFGBG (its last field the background colour: 7 or 15 is light); dark is the default, as in the brand.
32
+ */
33
+ export function terminalLook(env) {
34
+ const background = Number((env.COLORFGBG ?? '').split(';').pop() ?? '');
35
+ return {
36
+ truecolor: /^(truecolor|24bit)$/i.test(env.COLORTERM ?? ''),
37
+ palette: background === 7 || background === 15 ? LIGHT : DARK,
38
+ // The Linux console prints the escape as text
39
+ links: env.TERM !== 'linux',
40
+ };
41
+ }
42
+ const RESET = '\u001b[0m';
43
+ /** Text in a colour, optionally bold. */
44
+ function paint(look, text, tone, bold = false) {
45
+ if (text === '') {
46
+ return '';
47
+ }
48
+ const codes = [
49
+ ...(bold ? ['1'] : []),
50
+ ...(tone === null ? [] : [look.truecolor ? `38;2;${tone.rgb.join(';')}` : tone.basic]),
51
+ ];
52
+ return codes.length === 0 ? text : `\u001b[${codes.join(';')}m${text}${RESET}`;
53
+ }
54
+ /** A URL in a text as a hyperlink to itself; the text stays as it is. */
55
+ function linkify(look, text) {
56
+ if (!look.links) {
57
+ return text;
58
+ }
59
+ return text.replace(URL_PATTERN, (url) => `\u001b]8;;${url}\u001b\\${url}\u001b]8;;\u001b\\`);
60
+ }
61
+ /** A URL up to the first space or bracket, without a full stop or comma that ends the sentence. */
62
+ const URL_PATTERN = /https?:\/\/[^\s"'<>()]*[^\s"'<>().,;:]/g;
63
+ /** Width of a label and its padding: every line of facts starts with one. */
64
+ const LABEL_WIDTH = 13;
65
+ /** Labels that warn. */
66
+ const WARNING_LABELS = new Set(['Notice', 'Limit', 'Drift']);
67
+ /** The line every tunnel prints after its facts, in the words of output.ts. */
68
+ const WAITING_LINE = 'Requests appear below as they arrive: method, path, status, duration. Press Ctrl+C to stop.';
69
+ /**
70
+ * The rabbit of docs/brand/logo/hopwire-mark-green.svg: its paths sampled and traced in Braille dots (2 by 4 dots per
71
+ * cell), 6 rows high. Smaller it no longer reads as the rabbit. A single dotted line, never filled, as the brand asks.
72
+ */
73
+ export const MARK = [
74
+ ' ⢻⡙⠲⣄',
75
+ ' ⠓⢦⣈⠧⣄⣀',
76
+ ' ⡖⢲⠴⠚⠉⠉⠑⠲⠞ ⠈⢳',
77
+ ' ⠉⡏ ⡄ ⣠⠖⠒⠋',
78
+ '⢀⡖⠚⣁⣀⡼⠁⠒⠒⠒⠲⢬⣙⠲⡄',
79
+ '⣞⡼⠉⠁ ⠈⠙⠁',
80
+ ];
81
+ /** The hop: how far the rabbit still is from its place (columns cut on the left) and whether it is in the air. */
82
+ const HOP = [
83
+ [12, false],
84
+ [9, true],
85
+ [6, true],
86
+ [3, true],
87
+ [1, false],
88
+ ];
89
+ /**
90
+ * The frames of the rabbit hopping into its place, each as many lines as the mark: it comes in from the left, the
91
+ * middle frames one row up (in the air). The last frame is the mark itself, drawn by markBlock.
92
+ */
93
+ export function hopFrames(look) {
94
+ const tone = look.palette.mark;
95
+ return HOP.map(([cut, air]) => {
96
+ const rows = MARK.map((row) => row.slice(cut));
97
+ const lifted = air ? [...rows.slice(1), ''] : rows;
98
+ return lifted.map((row) => paint(look, row, tone)).join('\n');
99
+ });
100
+ }
101
+ /** A line for the dot of a mode or a source. */
102
+ const DOT = '●';
103
+ /** The words of a text in lines of at most `width` characters; a longer word gets a line of its own. */
104
+ export function wrap(text, width) {
105
+ const lines = [];
106
+ let current = '';
107
+ for (const word of text.split(' ')) {
108
+ if (current === '') {
109
+ current = word;
110
+ }
111
+ else if (current.length + 1 + word.length <= width) {
112
+ current += ` ${word}`;
113
+ }
114
+ else {
115
+ lines.push(current);
116
+ current = word;
117
+ }
118
+ }
119
+ lines.push(current);
120
+ return lines;
121
+ }
122
+ /**
123
+ * Renders the lines of a command for a terminal. It holds a little state: whether the header was shown and which
124
+ * facts were printed, so the hint under them names only the keys that do something.
125
+ */
126
+ export class TerminalScreen {
127
+ options;
128
+ headerShown = false;
129
+ /** Checks the signature of a webhook row; set once the tunnel runs and its secrets are known */
130
+ verify = () => null;
131
+ seen = new Set();
132
+ constructor(options) {
133
+ this.options = options;
134
+ }
135
+ /** The secrets of the running tunnel by service: the rows of their webhooks show the signature from now on. */
136
+ checkSignatures(secrets) {
137
+ this.verify = (exchange) => {
138
+ const ofService = secrets.get(exchange.serviceName);
139
+ return ofService === undefined || ofService.length === 0 ? null : checkSignature(exchange, ofService);
140
+ };
141
+ }
142
+ get look() {
143
+ return this.options.look;
144
+ }
145
+ get width() {
146
+ // Narrower than this a table is no help; a line then simply wraps in the terminal
147
+ return Math.max(this.options.width(), 60);
148
+ }
149
+ /** One line of a command as it is shown: possibly several lines of the terminal, joined by newlines. */
150
+ render(line) {
151
+ const { look } = this;
152
+ const { palette } = look;
153
+ if (line === WAITING_LINE) {
154
+ return [paint(look, 'Requests appear below as they arrive.', palette.muted), this.keyHint()].join('\n');
155
+ }
156
+ if (line === 'Press Ctrl+C to stop.') {
157
+ return paint(look, line, palette.muted);
158
+ }
159
+ if (line === 'Next steps') {
160
+ return paint(look, line, null, true);
161
+ }
162
+ const label = /^[A-Z][A-Za-z]*(?: [A-Za-z]+)? +(?=\S)/.exec(line)?.[0];
163
+ if (label !== undefined && label.length === LABEL_WIDTH) {
164
+ const name = label.trimEnd();
165
+ this.seen.add(name);
166
+ // A tunnel gets the one-line header, a login that just went through the mark
167
+ const header = this.headerShown
168
+ ? ''
169
+ : name === 'Mode'
170
+ ? this.header()
171
+ : name === 'Logged in'
172
+ ? `${this.markBlock()}\n\n`
173
+ : '';
174
+ return header + this.fact(name, line.slice(LABEL_WIDTH));
175
+ }
176
+ // What the user copies: a command or a URL on a line of its own; never wrapped, so it copies in one piece
177
+ if (/^ {6}\S/.test(line)) {
178
+ return paint(look, linkify(look, line), palette.cyan);
179
+ }
180
+ // The sentences of the next steps keep their indent on every line
181
+ const indent = /^( {2,4})\S/.exec(line)?.[1];
182
+ if (indent !== undefined) {
183
+ return wrap(line.slice(indent.length), this.width - indent.length)
184
+ .map((part) => `${indent}${linkify(look, part)}`)
185
+ .join('\n');
186
+ }
187
+ return decorate(line);
188
+ }
189
+ /** The header above the first line of a tunnel: the live dot, the name and the version. */
190
+ header() {
191
+ this.headerShown = true;
192
+ const { look } = this;
193
+ return `${paint(look, DOT, look.palette.green)} ${paint(look, 'hopwire', null, true)} ${paint(look, this.options.version, look.palette.muted)}\n\n`;
194
+ }
195
+ /**
196
+ * The mark with the name and the version beside it, for the moments a person meets the CLI rather than the
197
+ * traffic: hopwire --version, hopwire init and a login that went through. Tunnels keep the one-line header.
198
+ */
199
+ markBlock() {
200
+ this.headerShown = true;
201
+ const { look } = this;
202
+ const width = Math.max(...MARK.map((row) => row.length));
203
+ const beside = {
204
+ 2: `${paint(look, 'hopwire', null, true)} ${paint(look, this.options.version, look.palette.muted)}`,
205
+ 3: paint(look, 'HTTP and webhook gateway', look.palette.muted),
206
+ };
207
+ return MARK.map((row, index) => {
208
+ const text = beside[index];
209
+ return text === undefined
210
+ ? paint(look, row, look.palette.mark)
211
+ : `${paint(look, row.padEnd(width), look.palette.mark)} ${text}`;
212
+ }).join('\n');
213
+ }
214
+ /** A line of facts: the label in bold, the value wrapped under itself. */
215
+ fact(name, value) {
216
+ const { look } = this;
217
+ const { palette } = look;
218
+ const labelText = paint(look, name.padEnd(LABEL_WIDTH), WARNING_LABELS.has(name) ? palette.warn : null, true);
219
+ const dots = name === 'Mode' ? this.modeDots(value) : '';
220
+ // Each dot is one column, and a space follows them
221
+ const dotWidth = dots === '' ? 0 : dots.split(DOT).length;
222
+ const parts = wrap(value, this.width - LABEL_WIDTH - dotWidth);
223
+ const accent = name === 'Public URL' || name === 'Inspector' ? palette.cyan : null;
224
+ return parts
225
+ .map((part, index) => {
226
+ const start = index === 0 ? `${labelText}${dots === '' ? '' : `${dots} `}` : ' '.repeat(LABEL_WIDTH + dotWidth);
227
+ return `${start}${paint(look, linkify(look, part), accent)}`;
228
+ })
229
+ .join('\n');
230
+ }
231
+ /** The dots of a mode: cyan for private P2P, blue for the public URL through the edge. */
232
+ modeDots(value) {
233
+ const { look } = this;
234
+ const cyan = paint(look, DOT, look.palette.cyan);
235
+ const blue = paint(look, DOT, look.palette.blue);
236
+ if (value.startsWith('public and private')) {
237
+ return `${blue}${cyan}`;
238
+ }
239
+ if (value.startsWith('public')) {
240
+ return blue;
241
+ }
242
+ return value.startsWith('private') ? cyan : '';
243
+ }
244
+ /** The keys of a running tunnel, or how to stop it when no keys are read. */
245
+ keyHint() {
246
+ const { look } = this;
247
+ if (!this.options.shortcuts) {
248
+ return paint(look, 'Press Ctrl+C to stop.', look.palette.muted);
249
+ }
250
+ const keys = [];
251
+ if (this.seen.has('Inspector')) {
252
+ keys.push(['o', 'inspector']);
253
+ }
254
+ if (this.seen.has('Public URL')) {
255
+ keys.push(['c', 'copy URL']);
256
+ }
257
+ if (this.seen.has('Inspector')) {
258
+ keys.push(['r', 'replay']);
259
+ }
260
+ keys.push(['\u2191\u2193', 'pick'], ['enter', 'details'], ['y', 'curl'], ['?', 'keys'], ['q', 'quit']);
261
+ return keys
262
+ .map(([key, what]) => `${paint(look, key, null, true)} ${paint(look, what, look.palette.muted)}`)
263
+ .join(paint(look, ' · ', look.palette.muted));
264
+ }
265
+ /**
266
+ * One exchange as a row: time, method, path, status, duration, size and where it came from. The path is cut to
267
+ * the width of the terminal so the columns stay in line; method and path of a teammate's log are written by
268
+ * another machine and pass through printable().
269
+ */
270
+ row(exchange, label = '') {
271
+ const { look } = this;
272
+ const { palette } = look;
273
+ const { request, response } = exchange;
274
+ const wide = this.width >= 90;
275
+ const time = wide ? `${paint(look, clock(exchange.timestamp), palette.muted)} ` : '';
276
+ const method = printable(request.method).padEnd(7);
277
+ const status = String(response.status);
278
+ const duration = formatDuration(response.durationMs).padStart(7);
279
+ const size = wide ? formatSize(responseSize(exchange)).padStart(9) : '';
280
+ // label, time, method + space, path, two spaces, status, duration, size, two spaces, tag
281
+ // The tag column has one width whatever the tag, so the paths of all rows end in the same column
282
+ const fixed = label.length + (wide ? 10 : 0) + 8 + 2 + 3 + 7 + (wide ? 9 : 0) + 2 + TAG_WIDTH;
283
+ const pathWidth = Math.max(this.width - fixed - 1, 12);
284
+ const path = printable(request.path);
285
+ // The webhook after the path, dimmed; the path gives way first, down to a third of the column
286
+ const webhook = recogniseWebhook(exchange);
287
+ const named = webhook === null ? '' : printable(`${webhook.provider}${webhook.event === null ? '' : ` ${webhook.event}`}`);
288
+ // The signature after the name: valid, valid but older than the providers' tolerance, wrong, not checkable
289
+ const check = webhook === null ? null : this.verify(exchange);
290
+ const mark = check === null ? null : signatureMark(check, palette);
291
+ const markWidth = mark === null ? 0 : 2;
292
+ const room = named === '' ? pathWidth : Math.max(Math.floor(pathWidth / 3), pathWidth - named.length - 2 - markWidth);
293
+ const cutPath = truncate(path, room);
294
+ const cutName = named === '' ? '' : truncate(named, Math.max(pathWidth - cutPath.length - 2 - markWidth, 0));
295
+ const used = cutPath.length + (cutName === '' ? 0 : cutName.length + 2 + markWidth);
296
+ const pad = ' '.repeat(Math.max(pathWidth - used, 0));
297
+ const signed = mark === null || cutName === '' ? '' : ` ${paint(look, mark.symbol, mark.tone, true)}`;
298
+ const shown = `${cutPath}${cutName === '' ? '' : ` ${paint(look, cutName, palette.muted)}${signed}`}${pad}`;
299
+ const slow = response.durationMs >= 1000;
300
+ return (`${label}${time}${paint(look, method, null, true)} ${shown} ` +
301
+ `${paint(look, status, statusTone(palette, response.status))}` +
302
+ `${paint(look, duration, slow ? palette.warn : palette.muted)}` +
303
+ `${paint(look, size, palette.muted)} ${sourceTag(exchange, look)}`);
304
+ }
305
+ /** A start that failed: a cross and the sentence, the hint dimmed under it. */
306
+ failure(message, hint) {
307
+ const { look } = this;
308
+ const lines = message.split('\n').flatMap((line) => wrap(line, this.width - 2));
309
+ const shown = lines.map((line, index) => index === 0 ? `${paint(look, '✖', look.palette.err, true)} ${paint(look, line, null, true)}` : ` ${line}`);
310
+ if (hint !== null) {
311
+ shown.push(` ${paint(look, linkify(look, hint), look.palette.muted)}`);
312
+ }
313
+ return shown.join('\n');
314
+ }
315
+ /** A line about something a key did, set apart from the rows of exchanges. */
316
+ say(text, problem = false) {
317
+ const { look } = this;
318
+ return `${paint(look, '›', problem ? look.palette.err : look.palette.green, true)} ${paint(look, linkify(look, text), problem ? null : look.palette.muted)}`;
319
+ }
320
+ /**
321
+ * The line under a replay whose original is still known: what changed between the two. It starts under the path,
322
+ * so it reads as part of the row above.
323
+ */
324
+ replayNote(original, replay) {
325
+ const { look } = this;
326
+ const { palette } = look;
327
+ const was = original.response;
328
+ const now = replay.response;
329
+ const status = was.status === now.status
330
+ ? `same status ${paint(look, String(now.status), statusTone(palette, now.status))}`
331
+ : `${paint(look, String(was.status), statusTone(palette, was.status))} → ${paint(look, String(now.status), statusTone(palette, now.status))}`;
332
+ const body = was.bodyTruncated || now.bodyTruncated
333
+ ? 'body cut by the capture, not compared'
334
+ : was.bodyBase64 === now.bodyBase64
335
+ ? 'same body'
336
+ : 'body changed';
337
+ const time = `${formatDuration(was.durationMs)} → ${formatDuration(now.durationMs)}`;
338
+ const indent = ' '.repeat(this.width >= 90 ? 18 : 8);
339
+ const muted = (text) => paint(look, text, palette.muted);
340
+ return `${indent}${muted('↳ replay of the request at')} ${muted(clock(original.timestamp))}${muted(':')} ${status}${muted(`, ${body}, ${time}`)}`;
341
+ }
342
+ /**
343
+ * An exchange unfolded under the feed: request and response with their headers and bodies. Long bodies stop after
344
+ * a few lines with a pointer to the inspector, and the values of headers that carry credentials are shortened,
345
+ * since the terminal's scrollback outlives the run. Everything passes printable(): a teammate's log is written by
346
+ * another machine.
347
+ */
348
+ details(exchange, inspector) {
349
+ const { look } = this;
350
+ const { palette } = look;
351
+ const { request, response } = exchange;
352
+ const bar = paint(look, '│', palette.muted);
353
+ const lines = [];
354
+ const webhook = recogniseWebhook(exchange);
355
+ const title = [
356
+ `${paint(look, printable(request.method), null, true)} ${printable(request.path)}`,
357
+ ...(webhook === null
358
+ ? []
359
+ : [printable(`${webhook.provider}${webhook.event === null ? '' : ` ${webhook.event}`}`)]),
360
+ clock(exchange.timestamp),
361
+ SOURCE_WORDS[exchange.source] ?? exchange.source,
362
+ ];
363
+ lines.push(`${paint(look, '┌', palette.muted)} ${title.join(paint(look, ' · ', palette.muted))}`);
364
+ const check = webhook === null ? null : this.verify(exchange);
365
+ if (check !== null) {
366
+ const mark = signatureMark(check, palette);
367
+ for (const [index, part] of wrap(signatureSentence(check), this.width - 6).entries()) {
368
+ lines.push(`${bar} ${index === 0 ? paint(look, mark.symbol, mark.tone, true) : ' '} ${part}`);
369
+ }
370
+ }
371
+ lines.push(`${bar} ${paint(look, 'Request', null, true)}`);
372
+ lines.push(...this.part(request.headers, request.bodyBase64, request.bodyTruncated).map((line) => `${bar} ${line}`));
373
+ lines.push(`${bar} ${paint(look, 'Response', null, true)} ${paint(look, String(response.status), statusTone(palette, response.status))} ${paint(look, `· ${formatDuration(response.durationMs)}`, palette.muted)}`);
374
+ lines.push(...this.part(response.headers, response.bodyBase64, response.bodyTruncated).map((line) => `${bar} ${line}`));
375
+ lines.push(`${paint(look, '└', palette.muted)} ${paint(look, inspector ? 'i opens this request in the inspector' : 'the full request is in the traffic log', palette.muted)}`);
376
+ return lines.join('\n');
377
+ }
378
+ /** Headers and body of one side of an exchange, as lines. */
379
+ part(headers, bodyBase64, truncated) {
380
+ const { look } = this;
381
+ const width = this.width - 6;
382
+ const lines = [];
383
+ for (const [name, value] of headers.slice(0, DETAIL_HEADERS)) {
384
+ const shown = CREDENTIAL_HEADERS.has(name.toLowerCase()) ? hidden(value) : value;
385
+ const label = `${printable(name)}:`;
386
+ const room = Math.max(width - label.length - 1, 8);
387
+ lines.push(`${paint(look, label, look.palette.muted)} ${truncate(printable(shown), room)}`);
388
+ }
389
+ if (headers.length > DETAIL_HEADERS) {
390
+ lines.push(paint(look, `+ ${headers.length - DETAIL_HEADERS} more headers`, look.palette.muted));
391
+ }
392
+ const body = Buffer.from(bodyBase64, 'base64');
393
+ if (body.byteLength === 0) {
394
+ lines.push(paint(look, 'no body', look.palette.muted));
395
+ return lines;
396
+ }
397
+ const shown = bodyLines(body, truncated);
398
+ const kept = shown.slice(0, DETAIL_BODY_LINES).map((line) => truncate(printable(line), width));
399
+ lines.push('', ...kept);
400
+ if (shown.length > DETAIL_BODY_LINES) {
401
+ lines.push(paint(look, `… ${shown.length - DETAIL_BODY_LINES} more lines`, look.palette.muted));
402
+ }
403
+ if (truncated) {
404
+ lines.push(paint(look, 'the body was longer than the capture limit; only its start was recorded', look.palette.warn));
405
+ }
406
+ return lines;
407
+ }
408
+ /**
409
+ * The status line under the feed: whether the tunnel is live, what came in, how fast, and the connection. Parts are
410
+ * dropped from the end when the terminal is narrow, so the line never wraps (it is redrawn in place).
411
+ */
412
+ statusLine(stats, columns) {
413
+ const { look } = this;
414
+ const { palette } = look;
415
+ const muted = (text) => paint(look, text, palette.muted);
416
+ const parts = [];
417
+ const part = (text, width) => {
418
+ parts.push({ text, width });
419
+ };
420
+ const pulse = stats.pulse ? paint(look, DOT, palette.green) : paint(look, DOT, palette.muted);
421
+ part(`${pulse} ${stats.requests === 1 ? '1 request' : `${stats.requests} requests`}`, String(stats.requests).length + 11);
422
+ if (stats.clientErrors > 0 || stats.serverErrors > 0) {
423
+ const text = [
424
+ ...(stats.clientErrors > 0 ? [paint(look, `${stats.clientErrors} × 4xx`, palette.warn)] : []),
425
+ ...(stats.serverErrors > 0 ? [paint(look, `${stats.serverErrors} × 5xx`, palette.err)] : []),
426
+ ].join(' ');
427
+ part(text, `${stats.clientErrors} x 4xx ${stats.serverErrors} x 5xx`.length);
428
+ }
429
+ // What the arrows picked comes early: it is what the user is looking at
430
+ if (stats.selected !== null) {
431
+ const sel = stats.selected;
432
+ const label = truncate(printable(`${sel.request.method} ${sel.request.path}`), 28);
433
+ part(`${muted('▸')} ${label} ${paint(look, String(sel.response.status), statusTone(palette, sel.response.status))} ${muted('enter details · esc')}`, label.length + 26);
434
+ }
435
+ if (stats.median !== null && stats.slowest !== null) {
436
+ const text = `${muted('median')} ${formatDuration(stats.median)} ${muted('slowest')} ${formatDuration(stats.slowest)}`;
437
+ part(text, 17 + formatDuration(stats.median).length + formatDuration(stats.slowest).length);
438
+ }
439
+ if (stats.requests > 0) {
440
+ part(paint(look, sparkline(stats.perBucket), palette.green), stats.perBucket.length);
441
+ }
442
+ if (stats.edge !== null) {
443
+ const tone = stats.edge ? palette.blue : palette.err;
444
+ part(`${paint(look, DOT, tone)} ${stats.edge ? 'edge' : muted('edge offline')}`, stats.edge ? 6 : 14);
445
+ }
446
+ if (stats.teammates !== null) {
447
+ const words = stats.teammates === 1 ? '1 teammate' : `${stats.teammates} teammates`;
448
+ part(`${paint(look, DOT, palette.cyan)} ${words}`, words.length + 2);
449
+ }
450
+ if (stats.selected === null && stats.requests > 0) {
451
+ part(muted('↑↓ select'), 8);
452
+ }
453
+ const separator = muted(' │ ');
454
+ let used = 0;
455
+ const kept = [];
456
+ for (const entry of parts) {
457
+ const next = used + (kept.length === 0 ? 0 : 5) + entry.width;
458
+ if (next > columns - 1) {
459
+ break;
460
+ }
461
+ kept.push(entry.text);
462
+ used = next;
463
+ }
464
+ return kept.join(separator);
465
+ }
466
+ }
467
+ const SPARKS = ['▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];
468
+ /** Counts as a sparkline, scaled to the largest; an empty bucket is the lowest bar. */
469
+ export function sparkline(counts) {
470
+ const top = Math.max(...counts, 1);
471
+ return counts
472
+ .map((count) => SPARKS[count === 0 ? 0 : Math.min(SPARKS.length - 1, Math.ceil((count / top) * (SPARKS.length - 1)))] ??
473
+ '')
474
+ .join('');
475
+ }
476
+ const SOURCE_WORDS = {
477
+ local: 'local',
478
+ p2p_peer: 'from a teammate',
479
+ public_edge: 'through the edge',
480
+ replay: 'replay',
481
+ };
482
+ /** Headers of the details block, and lines of each body, before the rest is left to the inspector. */
483
+ const DETAIL_HEADERS = 14;
484
+ const DETAIL_BODY_LINES = 24;
485
+ /** Headers whose values are credentials: shown shortened in the details block. */
486
+ const CREDENTIAL_HEADERS = new Set([
487
+ 'authorization',
488
+ 'proxy-authorization',
489
+ 'cookie',
490
+ 'set-cookie',
491
+ 'x-api-key',
492
+ 'api-key',
493
+ ]);
494
+ /** The first characters of a secret, enough to tell two apart. */
495
+ function hidden(value) {
496
+ return value.length <= 8 ? '••••' : `${value.slice(0, 6)}… (${value.length} characters)`;
497
+ }
498
+ /**
499
+ * A body as lines to read: JSON indented, text as it is, anything else as its size. A JSON body cut by the capture
500
+ * cannot be parsed and is shown as text.
501
+ */
502
+ export function bodyLines(body, truncated) {
503
+ const text = body.toString('utf8');
504
+ // Not text: invalid UTF-8 shows as replacement characters, and binary has NUL bytes
505
+ if (text.includes('�') || text.includes('\u0000')) {
506
+ return [`binary, ${formatSize({ bytes: body.byteLength, more: truncated })}`];
507
+ }
508
+ if (!truncated && /^\s*[[{]/.test(text)) {
509
+ try {
510
+ return JSON.stringify(JSON.parse(text), null, 2).split('\n');
511
+ }
512
+ catch {
513
+ // Not JSON after all: shown as text
514
+ }
515
+ }
516
+ return text.split(/\r?\n/);
517
+ }
518
+ /** The mark of a signature check in a row and in the details. */
519
+ function signatureMark(check, palette) {
520
+ switch (check.result) {
521
+ case 'valid':
522
+ return check.ageMs !== null && check.ageMs > TOLERANCE_MS
523
+ ? { symbol: '\u2713', tone: palette.warn }
524
+ : { symbol: '\u2713', tone: palette.ok };
525
+ case 'invalid':
526
+ return { symbol: '\u2717', tone: palette.err };
527
+ case 'unchecked':
528
+ return { symbol: '?', tone: palette.muted };
529
+ }
530
+ }
531
+ /** What a signature check found, in one sentence that names the variable, never the secret. */
532
+ export function signatureSentence(check) {
533
+ const where = `${check.provider} signature, checked with ${check.variable}`;
534
+ switch (check.result) {
535
+ case 'valid': {
536
+ const minutes = check.ageMs === null ? 0 : Math.floor(check.ageMs / 60_000);
537
+ return check.ageMs !== null && check.ageMs > TOLERANCE_MS
538
+ ? `Valid ${where}, but signed ${minutes} minutes ago: libraries that allow 5 minutes refuse it, as those of Stripe, Slack and Svix do by default (a replay keeps the original signature)`
539
+ : `Valid ${where}`;
540
+ }
541
+ case 'invalid':
542
+ return `Wrong ${where}: ${check.reason}`;
543
+ case 'unchecked':
544
+ return `Not checked (${where}): ${check.reason}`;
545
+ }
546
+ }
547
+ /** The time of day as HH:MM:SS on this machine's clock. */
548
+ function clock(timestamp) {
549
+ const date = new Date(timestamp);
550
+ return [date.getHours(), date.getMinutes(), date.getSeconds()]
551
+ .map((part) => String(part).padStart(2, '0'))
552
+ .join(':');
553
+ }
554
+ /** 12 ms, 1.4 s */
555
+ export function formatDuration(ms) {
556
+ return ms < 1000 ? `${ms} ms` : `${(ms / 1000).toFixed(1)} s`;
557
+ }
558
+ /** The size of a response body in binary units: 512 B, 1.2 KiB, 3.4 MiB; a trailing + when only part was captured. */
559
+ export function formatSize(size) {
560
+ if (size === null) {
561
+ return '';
562
+ }
563
+ const { bytes, more } = size;
564
+ const shown = bytes < 1024
565
+ ? `${bytes} B`
566
+ : bytes < 1024 * 1024
567
+ ? `${(bytes / 1024).toFixed(1)} KiB`
568
+ : `${(bytes / (1024 * 1024)).toFixed(1)} MiB`;
569
+ return more ? `${shown}+` : shown;
570
+ }
571
+ /**
572
+ * The size of the response body: Content-Length when the service sent one, otherwise what was captured (with "more"
573
+ * when the capture was cut). Null for the handshake of a WebSocket, which has no body.
574
+ */
575
+ export function responseSize(exchange) {
576
+ const { response } = exchange;
577
+ if (response.status === 101) {
578
+ return null;
579
+ }
580
+ const declared = response.headers.find(([name]) => name.toLowerCase() === 'content-length')?.[1];
581
+ if (declared !== undefined && /^\d+$/.test(declared)) {
582
+ return { bytes: Number(declared), more: false };
583
+ }
584
+ const base64 = response.bodyBase64;
585
+ const padding = base64.endsWith('==') ? 2 : base64.endsWith('=') ? 1 : 0;
586
+ return { bytes: (base64.length / 4) * 3 - padding, more: response.bodyTruncated };
587
+ }
588
+ /** The tag at the end of a row: where the exchange came in, and ws for the handshake of a WebSocket. */
589
+ function sourceTag(exchange, look) {
590
+ const { palette } = look;
591
+ const ws = paint(look, exchange.response.status === 101 ? ' ws' : '', palette.info);
592
+ switch (exchange.source) {
593
+ case 'public_edge':
594
+ return `${paint(look, DOT, palette.blue)} public${ws}`;
595
+ case 'p2p_peer':
596
+ return `${paint(look, DOT, palette.cyan)} p2p${ws}`;
597
+ case 'replay':
598
+ return `${paint(look, 'replay', palette.warn)}${ws}`;
599
+ default:
600
+ return `${paint(look, 'local', palette.muted)}${ws}`;
601
+ }
602
+ }
603
+ function statusTone(palette, status) {
604
+ if (status >= 500) {
605
+ return palette.err;
606
+ }
607
+ if (status >= 400) {
608
+ return palette.warn;
609
+ }
610
+ if (status >= 300 || status < 200) {
611
+ return palette.info;
612
+ }
613
+ return palette.ok;
614
+ }
615
+ /** Width of the widest common tag, "● public" or "replay ws"; a wider one (public ws) overhangs by two. */
616
+ const TAG_WIDTH = 9;
617
+ /** A text cut to `width` characters with an ellipsis at the end. */
618
+ function truncate(text, width) {
619
+ return text.length <= width ? text : `${text.slice(0, Math.max(width - 1, 0))}…`;
620
+ }
621
+ const FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
622
+ /**
623
+ * A spinner on one line of standard error while a tunnel starts. It is cleared before anything else is written, so
624
+ * the lines of the command stand where they would stand without it.
625
+ */
626
+ export class Spinner {
627
+ output;
628
+ look;
629
+ text;
630
+ intervalMs;
631
+ timer = null;
632
+ frame = 0;
633
+ constructor(output, look, text, intervalMs = 80) {
634
+ this.output = output;
635
+ this.look = look;
636
+ this.text = text;
637
+ this.intervalMs = intervalMs;
638
+ }
639
+ start() {
640
+ if (this.timer !== null) {
641
+ return;
642
+ }
643
+ // The cursor is hidden while it spins and shown again on stop, also when the process exits on its own
644
+ this.output.write('\u001b[?25l');
645
+ process.once('exit', this.stop);
646
+ this.draw();
647
+ this.timer = setInterval(() => this.draw(), this.intervalMs);
648
+ this.timer.unref();
649
+ }
650
+ stop = () => {
651
+ if (this.timer === null) {
652
+ return;
653
+ }
654
+ clearInterval(this.timer);
655
+ this.timer = null;
656
+ process.off('exit', this.stop);
657
+ this.output.write('\r\u001b[2K\u001b[?25h');
658
+ };
659
+ draw() {
660
+ const frame = FRAMES[this.frame % FRAMES.length] ?? '';
661
+ this.frame += 1;
662
+ this.output.write(`\r\u001b[2K${paint(this.look, frame, this.look.palette.green)} ${paint(this.look, this.text, this.look.palette.muted)}`);
663
+ }
664
+ }
665
+ /** What the spinner says while each command that runs a tunnel starts. */
666
+ export const STARTING = {
667
+ http: 'Starting the tunnel',
668
+ up: 'Starting the services of hopwire.yaml',
669
+ watch: "Looking for your teammate's log",
670
+ connect: 'Connecting to your teammate',
671
+ };