hopwire 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.
- package/dist/bin.js +6 -0
- package/dist/cli.js +160 -2
- package/dist/commands/chaos.js +186 -0
- package/dist/commands/fix.js +177 -0
- package/dist/commands/http.js +2 -0
- package/dist/commands/snapshot.js +81 -0
- package/dist/commands/up.js +2 -0
- package/dist/commands/verify.js +64 -0
- package/dist/commands/watch.js +9 -1
- package/dist/config-template.js +1 -0
- package/dist/config.js +22 -1
- package/dist/curl.js +59 -0
- package/dist/errors.js +3 -0
- package/dist/main.js +4 -2
- package/dist/serve.js +26 -1
- package/dist/shapes.js +216 -0
- package/dist/shortcuts.js +29 -4
- package/dist/signature.js +207 -0
- package/dist/style.js +6 -0
- package/dist/terminal.js +60 -8
- package/dist/traffic.js +247 -0
- package/package.json +1 -1
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import { createHmac, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
/**
|
|
3
|
+
* Checks the signature a webhook provider put on a request, with the signing secret the user named in an environment
|
|
4
|
+
* variable. It runs on this machine over what was captured; the secret never leaves the process, is never printed and
|
|
5
|
+
* never written to the traffic log. The result is shown next to the request; nothing is refused because of it.
|
|
6
|
+
*/
|
|
7
|
+
/** The providers whose signatures can be checked from the request alone. */
|
|
8
|
+
export const SIGNED_PROVIDERS = ['stripe', 'github', 'gitlab', 'shopify', 'slack', 'svix', 'paddle', 'linear'];
|
|
9
|
+
export function isSignedProvider(name) {
|
|
10
|
+
return SIGNED_PROVIDERS.includes(name);
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Stripe, Slack and Svix refuse a signature whose timestamp is older than five minutes by default; a replay keeps the
|
|
14
|
+
* original timestamp, so its signature is valid and still refused by those libraries. Said next to the result.
|
|
15
|
+
*/
|
|
16
|
+
export const TOLERANCE_MS = 5 * 60_000;
|
|
17
|
+
/** The check of one request against the secrets of its service; null when none of them is for this request. */
|
|
18
|
+
export function checkSignature(exchange, secrets, now = Date.now()) {
|
|
19
|
+
const headers = new Map(exchange.request.headers.map(([name, value]) => [name.toLowerCase(), value]));
|
|
20
|
+
for (const entry of secrets) {
|
|
21
|
+
const verify = VERIFIERS[entry.provider];
|
|
22
|
+
const signed = verify.signs(headers);
|
|
23
|
+
if (!signed) {
|
|
24
|
+
continue;
|
|
25
|
+
}
|
|
26
|
+
const { provider, variable } = entry;
|
|
27
|
+
if (exchange.request.bodyTruncated) {
|
|
28
|
+
return {
|
|
29
|
+
result: 'unchecked',
|
|
30
|
+
provider,
|
|
31
|
+
variable,
|
|
32
|
+
reason: 'the body was longer than the capture limit, so the signature cannot be checked',
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
const body = Buffer.from(exchange.request.bodyBase64, 'base64');
|
|
36
|
+
const outcome = verify.check(headers, body, entry.secret);
|
|
37
|
+
if (typeof outcome === 'string') {
|
|
38
|
+
return { result: 'invalid', provider, variable, reason: outcome };
|
|
39
|
+
}
|
|
40
|
+
return {
|
|
41
|
+
result: 'valid',
|
|
42
|
+
provider,
|
|
43
|
+
variable,
|
|
44
|
+
ageMs: outcome.timestamp === null ? null : now - outcome.timestamp,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
const MISMATCH = 'does not match the secret; check that it is the signing secret of this endpoint and that the body reaches the handler unchanged';
|
|
50
|
+
const VERIFIERS = {
|
|
51
|
+
// Stripe-Signature: t=<seconds>,v1=<hex>[,v1=...]; HMAC-SHA256 over "<t>.<body>"
|
|
52
|
+
stripe: {
|
|
53
|
+
signs: (h) => h.has('stripe-signature'),
|
|
54
|
+
check: (h, body, secret) => {
|
|
55
|
+
const parts = (h.get('stripe-signature') ?? '').split(',').map((part) => part.split('=', 2));
|
|
56
|
+
const t = parts.find(([key]) => key === 't')?.[1];
|
|
57
|
+
const signatures = parts.filter(([key]) => key === 'v1').map(([, value]) => value ?? '');
|
|
58
|
+
if (t === undefined || !/^\d+$/.test(t) || signatures.length === 0) {
|
|
59
|
+
return 'the Stripe-Signature header has no t= and v1= parts';
|
|
60
|
+
}
|
|
61
|
+
const expected = hmac(secret, Buffer.concat([Buffer.from(`${t}.`), body]), 'hex');
|
|
62
|
+
return signatures.some((value) => same(value, expected)) ? { timestamp: Number(t) * 1000 } : MISMATCH;
|
|
63
|
+
},
|
|
64
|
+
},
|
|
65
|
+
// X-Hub-Signature-256: sha256=<hex>; HMAC-SHA256 over the body
|
|
66
|
+
github: {
|
|
67
|
+
signs: (h) => h.has('x-hub-signature-256'),
|
|
68
|
+
check: (h, body, secret) => {
|
|
69
|
+
const value = h.get('x-hub-signature-256') ?? '';
|
|
70
|
+
if (!value.startsWith('sha256=')) {
|
|
71
|
+
return 'the X-Hub-Signature-256 header does not start with sha256=';
|
|
72
|
+
}
|
|
73
|
+
return same(value.slice(7), hmac(secret, body, 'hex')) ? { timestamp: null } : MISMATCH;
|
|
74
|
+
},
|
|
75
|
+
},
|
|
76
|
+
// X-Gitlab-Token: the secret token itself
|
|
77
|
+
gitlab: {
|
|
78
|
+
signs: (h) => h.has('x-gitlab-token'),
|
|
79
|
+
check: (h, _body, secret) => same(h.get('x-gitlab-token') ?? '', secret)
|
|
80
|
+
? { timestamp: null }
|
|
81
|
+
: 'the X-Gitlab-Token header is not the secret token of this webhook',
|
|
82
|
+
},
|
|
83
|
+
// X-Shopify-Hmac-Sha256: base64 HMAC-SHA256 over the body
|
|
84
|
+
shopify: {
|
|
85
|
+
signs: (h) => h.has('x-shopify-hmac-sha256'),
|
|
86
|
+
check: (h, body, secret) => same(h.get('x-shopify-hmac-sha256') ?? '', hmac(secret, body, 'base64')) ? { timestamp: null } : MISMATCH,
|
|
87
|
+
},
|
|
88
|
+
// X-Slack-Signature: v0=<hex>; HMAC-SHA256 over "v0:<X-Slack-Request-Timestamp>:<body>"
|
|
89
|
+
slack: {
|
|
90
|
+
signs: (h) => h.has('x-slack-signature'),
|
|
91
|
+
check: (h, body, secret) => {
|
|
92
|
+
const ts = h.get('x-slack-request-timestamp') ?? '';
|
|
93
|
+
const value = h.get('x-slack-signature') ?? '';
|
|
94
|
+
if (!/^\d+$/.test(ts) || !value.startsWith('v0=')) {
|
|
95
|
+
return 'X-Slack-Request-Timestamp or the v0= of X-Slack-Signature is missing';
|
|
96
|
+
}
|
|
97
|
+
const expected = hmac(secret, Buffer.concat([Buffer.from(`v0:${ts}:`), body]), 'hex');
|
|
98
|
+
return same(value.slice(3), expected) ? { timestamp: Number(ts) * 1000 } : MISMATCH;
|
|
99
|
+
},
|
|
100
|
+
},
|
|
101
|
+
// svix-id, svix-timestamp, svix-signature: "v1,<base64> ..."; the secret is whsec_<base64 key>
|
|
102
|
+
svix: {
|
|
103
|
+
signs: (h) => h.has('svix-signature') || h.has('webhook-signature'),
|
|
104
|
+
check: (h, body, secret) => {
|
|
105
|
+
const id = h.get('svix-id') ?? h.get('webhook-id') ?? '';
|
|
106
|
+
const ts = h.get('svix-timestamp') ?? h.get('webhook-timestamp') ?? '';
|
|
107
|
+
const value = h.get('svix-signature') ?? h.get('webhook-signature') ?? '';
|
|
108
|
+
if (id === '' || !/^\d+$/.test(ts)) {
|
|
109
|
+
return 'the id or timestamp header of the signature is missing';
|
|
110
|
+
}
|
|
111
|
+
const key = Buffer.from(secret.startsWith('whsec_') ? secret.slice(6) : secret, 'base64');
|
|
112
|
+
const expected = createHmac('sha256', key)
|
|
113
|
+
.update(Buffer.concat([Buffer.from(`${id}.${ts}.`), body]))
|
|
114
|
+
.digest('base64');
|
|
115
|
+
const signatures = value.split(' ').map((entry) => entry.split(',', 2));
|
|
116
|
+
return signatures.some(([version, signature]) => version === 'v1' && same(signature ?? '', expected))
|
|
117
|
+
? { timestamp: Number(ts) * 1000 }
|
|
118
|
+
: MISMATCH;
|
|
119
|
+
},
|
|
120
|
+
},
|
|
121
|
+
// Paddle-Signature: ts=<seconds>;h1=<hex>; HMAC-SHA256 over "<ts>:<body>"
|
|
122
|
+
paddle: {
|
|
123
|
+
signs: (h) => h.has('paddle-signature'),
|
|
124
|
+
check: (h, body, secret) => {
|
|
125
|
+
const parts = new Map((h.get('paddle-signature') ?? '').split(';').map((part) => part.split('=', 2)));
|
|
126
|
+
const ts = parts.get('ts') ?? '';
|
|
127
|
+
const h1 = parts.get('h1') ?? '';
|
|
128
|
+
if (!/^\d+$/.test(ts) || h1 === '') {
|
|
129
|
+
return 'the Paddle-Signature header has no ts= and h1= parts';
|
|
130
|
+
}
|
|
131
|
+
const expected = hmac(secret, Buffer.concat([Buffer.from(`${ts}:`), body]), 'hex');
|
|
132
|
+
return same(h1, expected) ? { timestamp: Number(ts) * 1000 } : MISMATCH;
|
|
133
|
+
},
|
|
134
|
+
},
|
|
135
|
+
// Linear-Signature: hex HMAC-SHA256 over the body
|
|
136
|
+
linear: {
|
|
137
|
+
signs: (h) => h.has('linear-signature'),
|
|
138
|
+
check: (h, body, secret) => same(h.get('linear-signature') ?? '', hmac(secret, body, 'hex')) ? { timestamp: null } : MISMATCH,
|
|
139
|
+
},
|
|
140
|
+
};
|
|
141
|
+
function hmac(secret, data, encoding) {
|
|
142
|
+
return createHmac('sha256', secret).update(data).digest(encoding);
|
|
143
|
+
}
|
|
144
|
+
/** Compares in constant time; texts of different length are different. */
|
|
145
|
+
function same(a, b) {
|
|
146
|
+
const left = Buffer.from(a);
|
|
147
|
+
const right = Buffer.from(b);
|
|
148
|
+
return left.byteLength === right.byteLength && timingSafeEqual(left, right);
|
|
149
|
+
}
|
|
150
|
+
/** An environment variable name as hopwire.yaml and --webhook-secret take it. */
|
|
151
|
+
export function isVariableName(name) {
|
|
152
|
+
return /^[A-Za-z_][A-Za-z0-9_]{0,127}$/.test(name);
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* The headers of a request signed again for `provider` at `timestampSeconds` (hopwire verify and chaos): the recorded
|
|
156
|
+
* signature headers are replaced, the rest kept. With `wrongKey` the signature is made with another key, for a handler
|
|
157
|
+
* that must refuse it. Without a timestamp in the provider's scheme (GitHub, GitLab, Shopify, Linear) only the
|
|
158
|
+
* signature changes.
|
|
159
|
+
*/
|
|
160
|
+
export function signHeaders(headers, body, secret, timestampSeconds, wrongKey = false) {
|
|
161
|
+
const key = wrongKey ? `${secret.secret}-not-the-signing-secret` : secret.secret;
|
|
162
|
+
const t = String(timestampSeconds);
|
|
163
|
+
const set = new Map();
|
|
164
|
+
switch (secret.provider) {
|
|
165
|
+
case 'stripe':
|
|
166
|
+
set.set('stripe-signature', `t=${t},v1=${hmac(key, Buffer.concat([Buffer.from(`${t}.`), body]), 'hex')}`);
|
|
167
|
+
break;
|
|
168
|
+
case 'github':
|
|
169
|
+
set.set('x-hub-signature-256', `sha256=${hmac(key, body, 'hex')}`);
|
|
170
|
+
break;
|
|
171
|
+
case 'gitlab':
|
|
172
|
+
set.set('x-gitlab-token', key);
|
|
173
|
+
break;
|
|
174
|
+
case 'shopify':
|
|
175
|
+
set.set('x-shopify-hmac-sha256', hmac(key, body, 'base64'));
|
|
176
|
+
break;
|
|
177
|
+
case 'slack':
|
|
178
|
+
set.set('x-slack-request-timestamp', t);
|
|
179
|
+
set.set('x-slack-signature', `v0=${hmac(key, Buffer.concat([Buffer.from(`v0:${t}:`), body]), 'hex')}`);
|
|
180
|
+
break;
|
|
181
|
+
case 'svix': {
|
|
182
|
+
const lower = new Map(headers.map(([name, value]) => [name.toLowerCase(), value]));
|
|
183
|
+
const prefix = lower.has('webhook-id') && !lower.has('svix-id') ? 'webhook' : 'svix';
|
|
184
|
+
const id = lower.get(`${prefix}-id`) ?? 'msg_hopwire';
|
|
185
|
+
const raw = Buffer.from(key.startsWith('whsec_') ? key.slice(6) : key, 'base64');
|
|
186
|
+
const signature = createHmac('sha256', wrongKey ? Buffer.concat([raw, Buffer.from('x')]) : raw)
|
|
187
|
+
.update(Buffer.concat([Buffer.from(`${id}.${t}.`), body]))
|
|
188
|
+
.digest('base64');
|
|
189
|
+
set.set(`${prefix}-id`, id);
|
|
190
|
+
set.set(`${prefix}-timestamp`, t);
|
|
191
|
+
set.set(`${prefix}-signature`, `v1,${signature}`);
|
|
192
|
+
break;
|
|
193
|
+
}
|
|
194
|
+
case 'paddle':
|
|
195
|
+
set.set('paddle-signature', `ts=${t};h1=${hmac(key, Buffer.concat([Buffer.from(`${t}:`), body]), 'hex')}`);
|
|
196
|
+
break;
|
|
197
|
+
case 'linear':
|
|
198
|
+
set.set('linear-signature', hmac(key, body, 'hex'));
|
|
199
|
+
break;
|
|
200
|
+
}
|
|
201
|
+
const kept = headers.filter(([name]) => !set.has(name.toLowerCase()));
|
|
202
|
+
return [...kept, ...set.entries()];
|
|
203
|
+
}
|
|
204
|
+
/** Whether a request carries a signature of `provider`: only those are signed again. */
|
|
205
|
+
export function signedBy(headers, provider) {
|
|
206
|
+
return VERIFIERS[provider].signs(new Map(headers.map(([name, value]) => [name.toLowerCase(), value])));
|
|
207
|
+
}
|
package/dist/style.js
CHANGED
|
@@ -21,6 +21,12 @@ export function decorate(line) {
|
|
|
21
21
|
if (line === 'Next steps') {
|
|
22
22
|
return paint(line, BOLD);
|
|
23
23
|
}
|
|
24
|
+
// A check of verify or chaos: its verdict first
|
|
25
|
+
const verdict = /^(pass|FAIL|skip)( {2}.*)$/.exec(line);
|
|
26
|
+
if (verdict !== null) {
|
|
27
|
+
const [, word = '', rest = ''] = verdict;
|
|
28
|
+
return `${paint(word, word === 'pass' ? `${BOLD};${GREEN}` : word === 'FAIL' ? `${BOLD};${RED}` : DIM)}${rest}`;
|
|
29
|
+
}
|
|
24
30
|
if (line.startsWith('Requests appear below') || line === 'Press Ctrl+C to stop.') {
|
|
25
31
|
return paint(line, DIM);
|
|
26
32
|
}
|
package/dist/terminal.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { printable } from './output.js';
|
|
2
2
|
import { decorate } from './style.js';
|
|
3
|
+
import { TOLERANCE_MS, checkSignature } from './signature.js';
|
|
3
4
|
import { recogniseWebhook } from './webhook.js';
|
|
4
5
|
/** The dark theme of docs/design_system.md: brand tokens and status colours as text. */
|
|
5
6
|
const DARK = {
|
|
@@ -62,7 +63,7 @@ const URL_PATTERN = /https?:\/\/[^\s"'<>()]*[^\s"'<>().,;:]/g;
|
|
|
62
63
|
/** Width of a label and its padding: every line of facts starts with one. */
|
|
63
64
|
const LABEL_WIDTH = 13;
|
|
64
65
|
/** Labels that warn. */
|
|
65
|
-
const WARNING_LABELS = new Set(['Notice', 'Limit']);
|
|
66
|
+
const WARNING_LABELS = new Set(['Notice', 'Limit', 'Drift']);
|
|
66
67
|
/** The line every tunnel prints after its facts, in the words of output.ts. */
|
|
67
68
|
const WAITING_LINE = 'Requests appear below as they arrive: method, path, status, duration. Press Ctrl+C to stop.';
|
|
68
69
|
/**
|
|
@@ -125,10 +126,19 @@ export function wrap(text, width) {
|
|
|
125
126
|
export class TerminalScreen {
|
|
126
127
|
options;
|
|
127
128
|
headerShown = false;
|
|
129
|
+
/** Checks the signature of a webhook row; set once the tunnel runs and its secrets are known */
|
|
130
|
+
verify = () => null;
|
|
128
131
|
seen = new Set();
|
|
129
132
|
constructor(options) {
|
|
130
133
|
this.options = options;
|
|
131
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
|
+
}
|
|
132
142
|
get look() {
|
|
133
143
|
return this.options.look;
|
|
134
144
|
}
|
|
@@ -239,15 +249,15 @@ export class TerminalScreen {
|
|
|
239
249
|
}
|
|
240
250
|
const keys = [];
|
|
241
251
|
if (this.seen.has('Inspector')) {
|
|
242
|
-
keys.push(['o', '
|
|
252
|
+
keys.push(['o', 'inspector']);
|
|
243
253
|
}
|
|
244
254
|
if (this.seen.has('Public URL')) {
|
|
245
|
-
keys.push(['c', 'copy
|
|
255
|
+
keys.push(['c', 'copy URL']);
|
|
246
256
|
}
|
|
247
257
|
if (this.seen.has('Inspector')) {
|
|
248
258
|
keys.push(['r', 'replay']);
|
|
249
259
|
}
|
|
250
|
-
keys.push(['\u2191\u2193', 'pick
|
|
260
|
+
keys.push(['\u2191\u2193', 'pick'], ['enter', 'details'], ['y', 'curl'], ['?', 'keys'], ['q', 'quit']);
|
|
251
261
|
return keys
|
|
252
262
|
.map(([key, what]) => `${paint(look, key, null, true)} ${paint(look, what, look.palette.muted)}`)
|
|
253
263
|
.join(paint(look, ' · ', look.palette.muted));
|
|
@@ -275,11 +285,17 @@ export class TerminalScreen {
|
|
|
275
285
|
// The webhook after the path, dimmed; the path gives way first, down to a third of the column
|
|
276
286
|
const webhook = recogniseWebhook(exchange);
|
|
277
287
|
const named = webhook === null ? '' : printable(`${webhook.provider}${webhook.event === null ? '' : ` ${webhook.event}`}`);
|
|
278
|
-
|
|
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);
|
|
279
293
|
const cutPath = truncate(path, room);
|
|
280
|
-
const cutName = named === '' ? '' : truncate(named, Math.max(pathWidth - cutPath.length - 2, 0));
|
|
281
|
-
const
|
|
282
|
-
const
|
|
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}`;
|
|
283
299
|
const slow = response.durationMs >= 1000;
|
|
284
300
|
return (`${label}${time}${paint(look, method, null, true)} ${shown} ` +
|
|
285
301
|
`${paint(look, status, statusTone(palette, response.status))}` +
|
|
@@ -345,6 +361,13 @@ export class TerminalScreen {
|
|
|
345
361
|
SOURCE_WORDS[exchange.source] ?? exchange.source,
|
|
346
362
|
];
|
|
347
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
|
+
}
|
|
348
371
|
lines.push(`${bar} ${paint(look, 'Request', null, true)}`);
|
|
349
372
|
lines.push(...this.part(request.headers, request.bodyBase64, request.bodyTruncated).map((line) => `${bar} ${line}`));
|
|
350
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)}`);
|
|
@@ -492,6 +515,35 @@ export function bodyLines(body, truncated) {
|
|
|
492
515
|
}
|
|
493
516
|
return text.split(/\r?\n/);
|
|
494
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
|
+
}
|
|
495
547
|
/** The time of day as HH:MM:SS on this machine's clock. */
|
|
496
548
|
function clock(timestamp) {
|
|
497
549
|
const date = new Date(timestamp);
|
package/dist/traffic.js
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
import { readFile, writeFile } from 'node:fs/promises';
|
|
2
|
+
import http from 'node:http';
|
|
3
|
+
import { isCapturedExchange } from '@hopwire/protocol';
|
|
4
|
+
import { HopwireError, errorCode } from './errors.js';
|
|
5
|
+
import { printable } from './output.js';
|
|
6
|
+
import { signHeaders, signedBy } from './signature.js';
|
|
7
|
+
export async function writeSnapshot(file, exchanges, now = Date.now()) {
|
|
8
|
+
const snapshot = { hopwire: 'snapshot', version: 1, createdAt: now, exchanges };
|
|
9
|
+
// Owner-only: the file holds headers and bodies as captured. Never over an existing file
|
|
10
|
+
try {
|
|
11
|
+
await writeFile(file, `${JSON.stringify(snapshot, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
|
|
12
|
+
}
|
|
13
|
+
catch (error) {
|
|
14
|
+
if (errorCode(error) === 'EEXIST') {
|
|
15
|
+
throw new HopwireError(`${printable(file)} exists already; name a new file, or remove that one first.`);
|
|
16
|
+
}
|
|
17
|
+
throw error;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/** Reads a snapshot file; one that is not exactly a snapshot is refused with one sentence. */
|
|
21
|
+
export async function readSnapshot(file) {
|
|
22
|
+
let text;
|
|
23
|
+
try {
|
|
24
|
+
text = await readFile(file, 'utf8');
|
|
25
|
+
}
|
|
26
|
+
catch (error) {
|
|
27
|
+
throw new HopwireError(errorCode(error) === 'ENOENT'
|
|
28
|
+
? `${printable(file)} does not exist; write one with hopwire snapshot <file>.`
|
|
29
|
+
: `${printable(file)} cannot be read (${errorCode(error) ?? 'unknown error'}).`);
|
|
30
|
+
}
|
|
31
|
+
let parsed;
|
|
32
|
+
try {
|
|
33
|
+
parsed = JSON.parse(text);
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
throw new HopwireError(`${printable(file)} is not a snapshot of hopwire: it is not JSON.`);
|
|
37
|
+
}
|
|
38
|
+
if (typeof parsed !== 'object' ||
|
|
39
|
+
parsed === null ||
|
|
40
|
+
parsed.hopwire !== 'snapshot' ||
|
|
41
|
+
parsed.version !== 1 ||
|
|
42
|
+
!Array.isArray(parsed.exchanges)) {
|
|
43
|
+
throw new HopwireError(`${printable(file)} is not a snapshot of hopwire (version 1).`);
|
|
44
|
+
}
|
|
45
|
+
const exchanges = parsed.exchanges;
|
|
46
|
+
const bad = exchanges.findIndex((entry) => !isCapturedExchange(entry));
|
|
47
|
+
if (bad !== -1) {
|
|
48
|
+
throw new HopwireError(`${printable(file)}: exchange ${bad + 1} is not a request hopwire recorded.`);
|
|
49
|
+
}
|
|
50
|
+
return parsed;
|
|
51
|
+
}
|
|
52
|
+
/** Headers that describe the connection the request came in on; the new request has its own. */
|
|
53
|
+
const CONNECTION_HEADERS = new Set([
|
|
54
|
+
'connection',
|
|
55
|
+
'keep-alive',
|
|
56
|
+
'transfer-encoding',
|
|
57
|
+
'te',
|
|
58
|
+
'upgrade',
|
|
59
|
+
'proxy-connection',
|
|
60
|
+
'content-length',
|
|
61
|
+
]);
|
|
62
|
+
/** Largest answer read; the rest is cut. */
|
|
63
|
+
const ANSWER_LIMIT_BYTES = 8 * 1024 * 1024;
|
|
64
|
+
/** A request that sees no answer within this time counts as failed. */
|
|
65
|
+
const SEND_TIMEOUT_MS = 30_000;
|
|
66
|
+
/**
|
|
67
|
+
* Sends the request of an exchange to `target` (an http origin), with its method, path, headers and body; Host stays
|
|
68
|
+
* as recorded, as the tunnel forwards it. A secret for its provider signs it again at `signAt` (seconds).
|
|
69
|
+
*/
|
|
70
|
+
export function send(exchange, target, options = {}) {
|
|
71
|
+
const { request } = exchange;
|
|
72
|
+
const body = Buffer.from(request.bodyBase64, 'base64');
|
|
73
|
+
let headers = request.headers.filter(([name]) => !CONNECTION_HEADERS.has(name.toLowerCase()));
|
|
74
|
+
if (options.secret !== undefined && signedBy(request.headers, options.secret.provider)) {
|
|
75
|
+
headers = signHeaders(headers, body, options.secret, options.signAt ?? Math.floor(Date.now() / 1000), options.wrongKey);
|
|
76
|
+
}
|
|
77
|
+
if (body.byteLength > 0 || !['GET', 'HEAD', 'DELETE', 'OPTIONS'].includes(request.method)) {
|
|
78
|
+
headers.push(['content-length', String(body.byteLength)]);
|
|
79
|
+
}
|
|
80
|
+
const started = performance.now();
|
|
81
|
+
return new Promise((resolve, reject) => {
|
|
82
|
+
const req = http.request({
|
|
83
|
+
host: target.hostname.replace(/^\[|\]$/g, ''),
|
|
84
|
+
port: target.port === '' ? 80 : Number(target.port),
|
|
85
|
+
method: request.method,
|
|
86
|
+
path: request.path,
|
|
87
|
+
headers: headers.flat(),
|
|
88
|
+
timeout: SEND_TIMEOUT_MS,
|
|
89
|
+
}, (res) => {
|
|
90
|
+
const chunks = [];
|
|
91
|
+
let size = 0;
|
|
92
|
+
res.on('data', (chunk) => {
|
|
93
|
+
size += chunk.byteLength;
|
|
94
|
+
if (size <= ANSWER_LIMIT_BYTES) {
|
|
95
|
+
chunks.push(chunk);
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
res.on('end', () => {
|
|
99
|
+
const raw = res.rawHeaders;
|
|
100
|
+
const answerHeaders = [];
|
|
101
|
+
for (let index = 0; index + 1 < raw.length; index += 2) {
|
|
102
|
+
answerHeaders.push([raw[index] ?? '', raw[index + 1] ?? '']);
|
|
103
|
+
}
|
|
104
|
+
resolve({
|
|
105
|
+
status: res.statusCode ?? 0,
|
|
106
|
+
headers: answerHeaders,
|
|
107
|
+
body: Buffer.concat(chunks),
|
|
108
|
+
durationMs: Math.round(performance.now() - started),
|
|
109
|
+
});
|
|
110
|
+
});
|
|
111
|
+
res.on('error', reject);
|
|
112
|
+
});
|
|
113
|
+
req.on('timeout', () => req.destroy(new HopwireError(`no answer within ${SEND_TIMEOUT_MS / 1000} s`)));
|
|
114
|
+
req.on('error', (error) => {
|
|
115
|
+
const code = errorCode(error);
|
|
116
|
+
reject(new HopwireError(code === 'ECONNREFUSED'
|
|
117
|
+
? `nothing answers on ${target.origin}; is the service running?`
|
|
118
|
+
: error instanceof HopwireError
|
|
119
|
+
? error.message
|
|
120
|
+
: `the request failed (${code ?? 'unknown error'})`));
|
|
121
|
+
});
|
|
122
|
+
req.end(body);
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* What differs between the recorded response and a new one; empty when they match. The status must be the same; a JSON
|
|
127
|
+
* body must have the same keys and types (and values with `strict`); another body is compared only with `strict`.
|
|
128
|
+
*/
|
|
129
|
+
export function compareAnswer(recorded, answer, options) {
|
|
130
|
+
const differences = [];
|
|
131
|
+
if (recorded.status !== answer.status) {
|
|
132
|
+
differences.push(`status ${answer.status}, recorded ${recorded.status}`);
|
|
133
|
+
}
|
|
134
|
+
if (recorded.bodyTruncated) {
|
|
135
|
+
return differences;
|
|
136
|
+
}
|
|
137
|
+
const before = Buffer.from(recorded.bodyBase64, 'base64');
|
|
138
|
+
const was = parseJson(before);
|
|
139
|
+
const now = parseJson(answer.body);
|
|
140
|
+
if (was !== undefined && now !== undefined) {
|
|
141
|
+
differences.push(...compareJson(was, now, '', options));
|
|
142
|
+
}
|
|
143
|
+
else if (was !== undefined || now !== undefined) {
|
|
144
|
+
differences.push(was === undefined ? 'body is JSON now, was not' : 'body is no longer JSON');
|
|
145
|
+
}
|
|
146
|
+
else if (options.strict && !before.equals(answer.body)) {
|
|
147
|
+
differences.push('body differs');
|
|
148
|
+
}
|
|
149
|
+
return differences.slice(0, 8);
|
|
150
|
+
}
|
|
151
|
+
function parseJson(body) {
|
|
152
|
+
if (body.byteLength === 0) {
|
|
153
|
+
return undefined;
|
|
154
|
+
}
|
|
155
|
+
try {
|
|
156
|
+
return JSON.parse(body.toString('utf8'));
|
|
157
|
+
}
|
|
158
|
+
catch {
|
|
159
|
+
return undefined;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
function kind(value) {
|
|
163
|
+
return value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value;
|
|
164
|
+
}
|
|
165
|
+
function compareJson(was, now, at, options) {
|
|
166
|
+
if (at !== '' && options.ignore.includes(at)) {
|
|
167
|
+
return [];
|
|
168
|
+
}
|
|
169
|
+
const name = at === '' ? 'body' : at;
|
|
170
|
+
if (kind(was) !== kind(now)) {
|
|
171
|
+
return [`${printable(name)} is ${kind(now)}, was ${kind(was)}`];
|
|
172
|
+
}
|
|
173
|
+
if (Array.isArray(was) && Array.isArray(now)) {
|
|
174
|
+
const out = [];
|
|
175
|
+
if (options.strict && was.length !== now.length) {
|
|
176
|
+
out.push(`${printable(name)} has ${now.length} items, had ${was.length}`);
|
|
177
|
+
}
|
|
178
|
+
// Items are compared by their shape: against the first recorded one
|
|
179
|
+
const sample = was[0];
|
|
180
|
+
if (sample !== undefined) {
|
|
181
|
+
for (const item of now.slice(0, 20)) {
|
|
182
|
+
out.push(...compareJson(sample, item, `${at}[]`, { ...options, strict: false }));
|
|
183
|
+
if (out.length > 0) {
|
|
184
|
+
break;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
if (options.strict) {
|
|
189
|
+
for (const [index, item] of was.entries()) {
|
|
190
|
+
if (index < now.length) {
|
|
191
|
+
out.push(...compareJson(item, now[index], `${at}[]`, options));
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
return [...new Set(out)];
|
|
196
|
+
}
|
|
197
|
+
if (kind(was) === 'object') {
|
|
198
|
+
const before = was;
|
|
199
|
+
const after = now;
|
|
200
|
+
const out = [];
|
|
201
|
+
for (const key of Object.keys(before)) {
|
|
202
|
+
const child = at === '' ? key : `${at}.${key}`;
|
|
203
|
+
if (options.ignore.includes(child)) {
|
|
204
|
+
continue;
|
|
205
|
+
}
|
|
206
|
+
if (!(key in after)) {
|
|
207
|
+
out.push(`${printable(child)} is missing`);
|
|
208
|
+
}
|
|
209
|
+
else {
|
|
210
|
+
out.push(...compareJson(before[key], after[key], child, options));
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
for (const key of Object.keys(after)) {
|
|
214
|
+
const child = at === '' ? key : `${at}.${key}`;
|
|
215
|
+
if (!(key in before) && !options.ignore.includes(child)) {
|
|
216
|
+
out.push(`${printable(child)} is new`);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
return out;
|
|
220
|
+
}
|
|
221
|
+
if (options.strict && was !== now) {
|
|
222
|
+
return [
|
|
223
|
+
`${printable(name)} is ${printable(JSON.stringify(now).slice(0, 40))}, was ${printable(JSON.stringify(was).slice(0, 40))}`,
|
|
224
|
+
];
|
|
225
|
+
}
|
|
226
|
+
return [];
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* `http://127.0.0.1:3000`, `http://app:3000` (a service in CI) or a bare port: where verify, chaos and fix send to.
|
|
230
|
+
* An http origin without a path; the requests carry what was captured, so it is the user's own service.
|
|
231
|
+
*/
|
|
232
|
+
export function parseTarget(value) {
|
|
233
|
+
const text = /^\d+$/.test(value) ? `http://127.0.0.1:${value}` : value;
|
|
234
|
+
let url;
|
|
235
|
+
try {
|
|
236
|
+
url = new URL(text);
|
|
237
|
+
}
|
|
238
|
+
catch {
|
|
239
|
+
return null;
|
|
240
|
+
}
|
|
241
|
+
return url.protocol === 'http:' &&
|
|
242
|
+
(url.pathname === '/' || url.pathname === '') &&
|
|
243
|
+
url.search === '' &&
|
|
244
|
+
url.username === ''
|
|
245
|
+
? new URL(url.origin)
|
|
246
|
+
: null;
|
|
247
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "hopwire",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"mcpName": "to.hopwire/hopwire",
|
|
5
5
|
"description": "Record, share and replay the HTTP traffic of your local services: private P2P sharing with teammates, and public HTTPS URLs.",
|
|
6
6
|
"license": "Apache-2.0",
|