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.
package/dist/bin.js CHANGED
@@ -1,26 +1,162 @@
1
1
  #!/usr/bin/env node
2
2
  import { openBrowser } from './browser.js';
3
3
  import { main } from './main.js';
4
+ import { formatExchange } from './output.js';
4
5
  import { promptHidden, promptLine } from './prompt.js';
5
- import { decorate, wantsColor } from './style.js';
6
+ import { copyToClipboard, replayThroughInspector, shortcutTarget, startShortcuts } from './shortcuts.js';
7
+ import { wantsColor } from './style.js';
8
+ import { LiveFeed } from './live.js';
9
+ import { STARTING, Spinner, TerminalScreen, hopFrames, terminalLook } from './terminal.js';
10
+ import { readVersion } from './version.js';
11
+ const argv = process.argv.slice(2);
12
+ const look = terminalLook(process.env);
6
13
  const color = wantsColor(process.stdout, process.env);
14
+ const colorErrors = wantsColor(process.stderr, process.env);
15
+ // A command that runs a tunnel, not its help: only these get the spinner and the keys
16
+ const command = argv[0] ?? '';
17
+ const tunnel = command in STARTING && !argv.some((arg) => arg === '--help' || arg === '-h' || arg === '--version');
18
+ const keys = tunnel && process.stdin.isTTY === true && command !== 'connect';
19
+ // hopwire --version on a terminal shows the mark beside the version; a script reading it gets the bare version
20
+ const versionOnly = argv.length === 1 && argv[0] === '--version';
21
+ const screen = color || colorErrors
22
+ ? new TerminalScreen({
23
+ look,
24
+ width: () => process.stdout.columns ?? 100,
25
+ version: readVersion(),
26
+ shortcuts: keys,
27
+ })
28
+ : null;
29
+ // Cleared before anything else is written: a prompt, a line, a failure
30
+ const spinner = tunnel && colorErrors && screen !== null ? new Spinner(process.stderr, look, `${STARTING[command] ?? ''}...`) : null;
31
+ spinner?.start();
32
+ const quiet = () => spinner?.stop();
33
+ // A tunnel's feed on a colour terminal: rows scroll above a status line that stays put
34
+ const live = tunnel && color && screen !== null
35
+ ? new LiveFeed(screen, process.stdout, () => process.stdout.columns ?? 100)
36
+ : null;
37
+ process.once('exit', () => live?.stop());
38
+ const out = (text) => {
39
+ quiet();
40
+ if (live === null) {
41
+ process.stdout.write(`${text}\n`);
42
+ }
43
+ else {
44
+ live.write(text);
45
+ }
46
+ };
47
+ /**
48
+ * The rabbit hops into its place once, about a third of a second, before the mark is drawn: on --version and after a
49
+ * login. Not on CI, and never where there is no colour. The wait blocks the process on purpose: nothing else runs yet.
50
+ */
51
+ const hop = () => {
52
+ if (!color || process.env.CI !== undefined) {
53
+ return;
54
+ }
55
+ const pause = new Int32Array(new SharedArrayBuffer(4));
56
+ const height = 6;
57
+ for (const frame of hopFrames(look)) {
58
+ process.stdout.write(`${frame}\n`);
59
+ Atomics.wait(pause, 0, 0, 60);
60
+ // Back to the first line of the frame, and away with it
61
+ process.stdout.write(`\u001b[${height}A\r\u001b[J`);
62
+ }
63
+ };
64
+ // Without the live feed (no colour), the newest exchange is still noted for the r key
65
+ let last = null;
66
+ let markShown = false;
7
67
  await main({
8
- argv: process.argv.slice(2),
68
+ argv,
9
69
  env: process.env,
10
- print: (line) => process.stdout.write(`${color ? decorate(line) : line}\n`),
11
- error: (line) => process.stderr.write(`${line}\n`),
70
+ print: (line) => {
71
+ if (color && screen !== null && (versionOnly || line.startsWith('Logged in '))) {
72
+ hop();
73
+ }
74
+ out(color && screen !== null ? (versionOnly ? screen.markBlock() : screen.render(line)) : line);
75
+ },
76
+ error: (line) => {
77
+ quiet();
78
+ const write = () => process.stderr.write(`${line}\n`);
79
+ if (live === null) {
80
+ write();
81
+ }
82
+ else {
83
+ live.around(write);
84
+ }
85
+ },
12
86
  on: (signal, listener) => process.on(signal, listener),
13
87
  exit: (code) => process.exit(code),
14
88
  // Opened only when a command reads it
15
89
  input: () => process.stdin,
16
90
  // Only a terminal can be asked without showing the answer
17
91
  promptSecret: process.stdin.isTTY
18
- ? (question, stop) => promptHidden(question, process.stdin, process.stderr, stop)
92
+ ? (question, stop) => {
93
+ quiet();
94
+ return promptHidden(question, process.stdin, process.stderr, stop);
95
+ }
19
96
  : undefined,
20
97
  // hopwire init asks its questions on standard error, so standard output keeps the lines of the result
21
98
  promptLine: process.stdin.isTTY
22
- ? (question, stop) => promptLine(question, process.stdin, process.stderr, stop)
99
+ ? (question, stop) => {
100
+ quiet();
101
+ // hopwire init: the mark above its first question
102
+ if (colorErrors && screen !== null && !markShown) {
103
+ markShown = true;
104
+ process.stderr.write(`${screen.markBlock()}\n\n`);
105
+ }
106
+ return promptLine(question, process.stdin, process.stderr, stop);
107
+ }
23
108
  : undefined,
24
109
  // hopwire login opens its sign-in page; the URL is printed too
25
110
  openBrowser: (url) => openBrowser(url),
111
+ // A row of columns on a colour terminal; the plain line otherwise, still noted for the r key
112
+ exchange: color || keys
113
+ ? (exchange, label = '') => {
114
+ quiet();
115
+ if (exchange.source !== 'replay') {
116
+ last = exchange;
117
+ }
118
+ if (live !== null) {
119
+ live.exchange(exchange, label);
120
+ }
121
+ else {
122
+ out(color && screen !== null ? screen.row(exchange, label) : `${label}${formatExchange(exchange)}`);
123
+ }
124
+ }
125
+ : undefined,
126
+ started: (running) => {
127
+ quiet();
128
+ const target = shortcutTarget(running);
129
+ // The signing secrets named on the command line or in hopwire.yaml: webhook rows show their signature
130
+ if (screen !== null &&
131
+ (running.kind === 'http' || running.kind === 'up') &&
132
+ running.webhookSecrets !== undefined) {
133
+ screen.checkSignatures(running.webhookSecrets);
134
+ }
135
+ if (target !== null) {
136
+ live?.start();
137
+ }
138
+ if (!keys || target === null) {
139
+ return;
140
+ }
141
+ const say = (text, problem = false) => out(color && screen !== null ? screen.say(text, problem) : text);
142
+ startShortcuts(process.stdin, {
143
+ target,
144
+ lastExchange: () => (live === null ? last : live.target()),
145
+ move: live === null ? undefined : (step) => live.move(step),
146
+ unpick: live === null ? undefined : () => live.unpick(),
147
+ details: live === null ? undefined : () => live.details(target.inspectorUrl !== null),
148
+ say,
149
+ openBrowser: (url) => openBrowser(url),
150
+ copy: (text) => copyToClipboard(text, (escape) => process.stdout.write(escape)),
151
+ replay: replayThroughInspector,
152
+ // The same way out as Ctrl+C in a terminal that is not in raw mode: the supervisor's shutdown
153
+ interrupt: () => process.kill(process.pid, 'SIGINT'),
154
+ });
155
+ },
156
+ failure: colorErrors && screen !== null
157
+ ? (message, hint) => {
158
+ quiet();
159
+ process.stderr.write(`${screen.failure(message, hint)}\n`);
160
+ }
161
+ : undefined,
26
162
  });
package/dist/cli.js CHANGED
@@ -1,5 +1,4 @@
1
1
  import { randomBytes } from 'node:crypto';
2
- import { readFileSync } from 'node:fs';
3
2
  import os from 'node:os';
4
3
  import path from 'node:path';
5
4
  import { parseArgs } from 'node:util';
@@ -14,11 +13,18 @@ import { startMcp } from './commands/mcp.js';
14
13
  import { rotate } from './commands/rotate.js';
15
14
  import { startUp } from './commands/up.js';
16
15
  import { startWatch } from './commands/watch.js';
16
+ import { chaos } from './commands/chaos.js';
17
+ import { startFix } from './commands/fix.js';
18
+ import { snapshot } from './commands/snapshot.js';
19
+ import { verify } from './commands/verify.js';
20
+ import { parseTarget } from './traffic.js';
17
21
  import { ConfigError, isServiceName, loadConfig } from './config.js';
18
22
  import { HopwireError, TemporaryError, UsageError, errorCode } from './errors.js';
19
23
  import { loadOrCreateIdentity } from './identity.js';
20
24
  import { defaultLogName, isFollowablePath } from './log-follow.js';
21
25
  import { DOCS_URL, printable } from './output.js';
26
+ import { SIGNED_PROVIDERS, isSignedProvider, isVariableName, } from './signature.js';
27
+ import { readVersion } from './version.js';
22
28
  import { createUpdateNotice } from './update-notice.js';
23
29
  import { parseControlPlaneUrl, parseEdgeUrl, parseLocalTarget } from './urls.js';
24
30
  export { UsageError };
@@ -60,6 +66,13 @@ Commands:
60
66
  hopwire.yaml) to read or to paste into a bug report. It is sent nowhere
61
67
  hopwire mcp An MCP server for a coding agent on this machine (stdio): it reads and replays
62
68
  the traffic of a tunnel running on the same data directory
69
+ hopwire snapshot <file> Write the requests a running tunnel recorded to a file, for verify and chaos
70
+ hopwire verify <file> Send the requests of a snapshot to your service and compare every answer with
71
+ the recorded one; exits 1 when one differs (for CI)
72
+ hopwire chaos <file> Deliver the webhooks of a snapshot the way providers do: twice, out of order,
73
+ with a wrong and with an old signature; says whether your handler held
74
+ hopwire fix [<exchange-id>] Replay a failed request through the running tunnel after every file change until
75
+ it passes (default: the newest that failed)
63
76
 
64
77
  Options for http:
65
78
  --listen <port> Loopback port of the entry point (default ${LOCAL_ENTRY_DEFAULT_PORT}, 0 picks a free one)
@@ -107,6 +120,10 @@ Options for http:
107
120
  other people's data. Neither the edge nor the control plane ever sees them
108
121
  --log-request-id With --log: every request forwarded to the service carries X-Hopwire-Exchange-Id; a
109
122
  service that writes it into its log gets exact links when requests overlap
123
+ --webhook-secret <provider>=<VARIABLE>
124
+ Checks the signatures of a provider's webhooks with the signing secret in that
125
+ environment variable and shows the result next to each request; repeatable. Providers:
126
+ ${SIGNED_PROVIDERS.join(', ')}
110
127
 
111
128
  Options for init:
112
129
  --config <path> The file to write (default ${HOPWIRE_YAML_FILE} in the working directory). An existing file
@@ -177,6 +194,26 @@ Options for watch:
177
194
  show next to them. They stay on this machine
178
195
  --force As for http: stop the tunnel that holds the data directory first
179
196
 
197
+ Options for snapshot:
198
+ --since <time> Only requests of the last 30s, 30m, 2h or 1d (default 30m)
199
+ --last <n> At most the newest n requests (default 200)
200
+ --service <name> Only requests of this service
201
+ --path <text> Only requests whose path contains this text
202
+
203
+ Options for verify and chaos:
204
+ --target <url> Where the requests go: an http origin such as http://127.0.0.1:3000 or a port
205
+ --webhook-secret <provider>=<VARIABLE>
206
+ Sign the webhooks of that provider again with the secret in that environment variable,
207
+ since recorded signatures are too old for every provider; repeatable
208
+ --strict verify only: compare values too, not only the shape of JSON answers
209
+ --ignore <field> verify only: leave a field out, as a dotted path such as data.created; repeatable
210
+
211
+ Options for fix:
212
+ --watch <dir> A folder whose changes start a new attempt (default the working directory);
213
+ repeatable
214
+ --webhook-secret <provider>=<VARIABLE>
215
+ Sign the webhook again for every attempt, as for verify
216
+
180
217
  Global options:
181
218
  --data-dir <path> Where identity, traffic log and the API token are stored (default $HOPWIRE_HOME or
182
219
  ~/.hopwire)
@@ -213,6 +250,7 @@ const COMMAND_OPTIONS = {
213
250
  'log',
214
251
  'share-logs',
215
252
  'log-request-id',
253
+ 'webhook-secret',
216
254
  'public',
217
255
  'subdomain',
218
256
  'agent',
@@ -229,6 +267,10 @@ const COMMAND_OPTIONS = {
229
267
  profiles: [],
230
268
  use: [],
231
269
  mcp: ['read-only'],
270
+ snapshot: ['since', 'last', 'service', 'path'],
271
+ verify: ['target', 'webhook-secret', 'strict', 'ignore'],
272
+ chaos: ['target', 'webhook-secret'],
273
+ fix: ['watch', 'webhook-secret'],
232
274
  doctor: ['network'],
233
275
  };
234
276
  /** Parses the arguments and starts the command. Resolves with what keeps running, or null when the command is done. */
@@ -268,6 +310,75 @@ export async function run(argv, io) {
268
310
  const profile = resolveProfile(values.profile, io.env);
269
311
  // The login a command uses: the profile it names, else the current one of the data directory
270
312
  const store = { dataDir, profile };
313
+ if (command === 'snapshot') {
314
+ noMoreArguments(rest, 1, 'hopwire snapshot <file>');
315
+ const file = rest[0] ?? '';
316
+ if (file === '') {
317
+ throw new UsageError('hopwire snapshot needs the file to write, for example hooks.snapshot.json');
318
+ }
319
+ const last = values.last === undefined ? 200 : Number(values.last);
320
+ if (!Number.isInteger(last) || last < 1 || last > 5000) {
321
+ throw new UsageError('--last must be a number of requests between 1 and 5000');
322
+ }
323
+ if (values.service !== undefined && !isServiceName(values.service)) {
324
+ throw new UsageError('--service must be the name of a service');
325
+ }
326
+ if (values.path === '') {
327
+ throw new UsageError('--path needs the text to look for in the path');
328
+ }
329
+ await snapshot({
330
+ dataDir,
331
+ file: path.resolve(io.cwd ?? process.cwd(), file),
332
+ shown: file,
333
+ sinceMs: parseDuration(values.since ?? '30m'),
334
+ last,
335
+ service: values.service,
336
+ pathContains: values.path,
337
+ print: io.print,
338
+ signal: io.signal,
339
+ });
340
+ return null;
341
+ }
342
+ if (command === 'verify' || command === 'chaos') {
343
+ noMoreArguments(rest, 1, `hopwire ${command} <file>`);
344
+ const file = rest[0] ?? '';
345
+ if (file === '') {
346
+ throw new UsageError(`hopwire ${command} needs a snapshot file, written with hopwire snapshot <file>`);
347
+ }
348
+ const target = values.target === undefined ? null : parseTarget(values.target);
349
+ if (target === null) {
350
+ throw new UsageError(`hopwire ${command} needs --target <url>: an http origin without a path, such as http://127.0.0.1:3000, or a port`);
351
+ }
352
+ const secrets = parseWebhookSecrets(values['webhook-secret'], io.env);
353
+ const where = path.resolve(io.cwd ?? process.cwd(), file);
354
+ if (command === 'verify') {
355
+ await verify({
356
+ file: where,
357
+ shown: file,
358
+ target,
359
+ secrets,
360
+ strict: values.strict ?? false,
361
+ ignore: values.ignore ?? [],
362
+ print: io.print,
363
+ });
364
+ }
365
+ else {
366
+ await chaos({ file: where, shown: file, target, secrets, print: io.print });
367
+ }
368
+ return null;
369
+ }
370
+ if (command === 'fix') {
371
+ noMoreArguments(rest, 1, 'hopwire fix [<exchange-id>]');
372
+ const cwd = io.cwd ?? process.cwd();
373
+ return startFix({
374
+ dataDir,
375
+ id: rest[0] ?? null,
376
+ watch: (values.watch ?? ['.']).map((folder) => path.resolve(cwd, folder)),
377
+ secrets: parseWebhookSecrets(values['webhook-secret'], io.env),
378
+ print: io.print,
379
+ signal: io.signal,
380
+ });
381
+ }
271
382
  if (command === 'id') {
272
383
  noMoreArguments(rest, 0, 'hopwire id');
273
384
  io.print((await loadOrCreateIdentity(dataDir)).publicKey.toString('hex'));
@@ -392,6 +503,7 @@ export async function run(argv, io) {
392
503
  relay: values.relay ? await relayAccess('--relay', store) : undefined,
393
504
  dataDir,
394
505
  print: io.print,
506
+ exchange: io.exchange,
395
507
  bootstrap: parseBootstrap(io.env.HOPWIRE_DHT_BOOTSTRAP),
396
508
  agent: values.agent ?? false,
397
509
  signal: io.signal,
@@ -406,6 +518,11 @@ export async function run(argv, io) {
406
518
  const cwd = io.cwd ?? process.cwd();
407
519
  const { file, shown } = configFile(cwd, values.config);
408
520
  const config = await loadConfig(file, values.config !== undefined, shown);
521
+ // Read before anything starts: a variable that is not set stops the start, like any other mistake in the file
522
+ const webhookSecrets = new Map(config.services.map((service) => [
523
+ service.name,
524
+ service.webhooks.map(({ provider, variable }) => webhookSecret(provider, variable, io.env, `services.${service.name}.webhooks.${provider}`)),
525
+ ]));
409
526
  const update = createUpdateNotice(readVersion());
410
527
  const running = await startUp({
411
528
  force: values.force ?? false,
@@ -413,6 +530,7 @@ export async function run(argv, io) {
413
530
  configFile: file,
414
531
  dataDir,
415
532
  print: io.print,
533
+ exchange: io.exchange,
416
534
  // Token and account are only read when a service is public: private mode never looks at them
417
535
  ...(config.services.some((service) => service.public)
418
536
  ? update.watch(await publicAccess(shown, config, io.env, store))
@@ -427,7 +545,7 @@ export async function run(argv, io) {
427
545
  });
428
546
  // After the lines of the start, so the mode stays the first line of every tunnel
429
547
  update.print(io.print);
430
- return running;
548
+ return Object.assign(running, { webhookSecrets });
431
549
  }
432
550
  noMoreArguments(rest, 1, 'hopwire http <port>');
433
551
  if (values.inspect !== undefined && values['no-inspect']) {
@@ -471,6 +589,7 @@ export async function run(argv, io) {
471
589
  // The rule of a service name in hopwire.yaml: a teammate asks for a service by this name
472
590
  throw new UsageError('--name must be a service name of 1 to 255 bytes without control characters');
473
591
  }
592
+ const webhookSecrets = new Map([[values.name ?? 'default', parseWebhookSecrets(values['webhook-secret'], io.env)]]);
474
593
  const update = createUpdateNotice(readVersion());
475
594
  const running = await startHttpTunnel({
476
595
  force: values.force ?? false,
@@ -482,6 +601,7 @@ export async function run(argv, io) {
482
601
  dataDir,
483
602
  serviceName: values.name ?? 'default',
484
603
  print: io.print,
604
+ exchange: io.exchange,
485
605
  share: values.share ?? false,
486
606
  allowAgents: values['allow-agents'] ?? false,
487
607
  allow,
@@ -501,7 +621,40 @@ export async function run(argv, io) {
501
621
  });
502
622
  // After the lines of the start, so the mode stays the first line of every tunnel
503
623
  update.print(io.print);
504
- return running;
624
+ return Object.assign(running, { webhookSecrets });
625
+ }
626
+ /** 30s, 30m, 2h, 1d as milliseconds. */
627
+ function parseDuration(value) {
628
+ const match = /^(\d{1,6})(s|m|h|d)$/.exec(value);
629
+ if (match === null) {
630
+ throw new UsageError('--since must be a time such as 30s, 30m, 2h or 1d');
631
+ }
632
+ const unit = { s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 }[match[2]];
633
+ return Number(match[1]) * unit;
634
+ }
635
+ /** --webhook-secret <provider>=<VARIABLE>, repeatable: each provider once. */
636
+ function parseWebhookSecrets(values, env) {
637
+ const named = [];
638
+ for (const value of values ?? []) {
639
+ const [provider = '', variable = ''] = value.split('=', 2);
640
+ if (!isSignedProvider(provider) || !isVariableName(variable) || !value.includes('=')) {
641
+ throw new UsageError(`--webhook-secret must be <provider>=<VARIABLE>, the name of an environment variable that holds the signing secret (never the secret itself); providers: ${SIGNED_PROVIDERS.join(', ')}`);
642
+ }
643
+ if (named.some((entry) => entry.provider === provider)) {
644
+ throw new UsageError(`--webhook-secret names ${provider} twice`);
645
+ }
646
+ named.push({ provider, variable });
647
+ }
648
+ // Read once the command line is known to be right
649
+ return named.map(({ provider, variable }) => webhookSecret(provider, variable, env, '--webhook-secret'));
650
+ }
651
+ /** The secret in an environment variable; one that is not set stops the start. The secret is never in the sentence. */
652
+ function webhookSecret(provider, variable, env, named) {
653
+ const secret = env[variable] ?? '';
654
+ if (secret === '') {
655
+ throw new HopwireError(`${named} names the environment variable ${variable}, which is not set or empty; set it to the signing secret of your ${provider} webhook endpoint.`);
656
+ }
657
+ return { provider, secret, variable };
505
658
  }
506
659
  /**
507
660
  * The files of --log, resolved against the working directory and named after themselves. Two files with the same name
@@ -689,6 +842,14 @@ function parse(argv) {
689
842
  log: { type: 'string', multiple: true },
690
843
  'share-logs': { type: 'boolean' },
691
844
  'log-request-id': { type: 'boolean' },
845
+ 'webhook-secret': { type: 'string', multiple: true },
846
+ since: { type: 'string' },
847
+ last: { type: 'string' },
848
+ path: { type: 'string' },
849
+ target: { type: 'string' },
850
+ strict: { type: 'boolean' },
851
+ ignore: { type: 'string', multiple: true },
852
+ watch: { type: 'string', multiple: true },
692
853
  'read-only': { type: 'boolean' },
693
854
  api: { type: 'string' },
694
855
  token: { type: 'boolean' },
@@ -983,17 +1144,6 @@ function parseBootstrap(value) {
983
1144
  return { host: match[1], port };
984
1145
  });
985
1146
  }
986
- /** The version of the package this file ships in; package.json lies next to `src` and `dist` alike. */
987
- function readVersion() {
988
- const manifest = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
989
- if (typeof manifest === 'object' &&
990
- manifest !== null &&
991
- 'version' in manifest &&
992
- typeof manifest.version === 'string') {
993
- return manifest.version;
994
- }
995
- throw new Error('package.json carries no version');
996
- }
997
1147
  function parsePort(value, label, min) {
998
1148
  const port = Number(value);
999
1149
  if (value === undefined || value === '' || !Number.isInteger(port) || port < min || port > 65535) {
@@ -0,0 +1,186 @@
1
+ import { ChecksFailed, HopwireError } from '../errors.js';
2
+ import { printable } from '../output.js';
3
+ import { isSignedProvider, signedBy } from '../signature.js';
4
+ import { readSnapshot, send } from '../traffic.js';
5
+ import { recogniseWebhook } from '../webhook.js';
6
+ import { requestLabel, secretFor } from './verify.js';
7
+ /** How far in the past a stale signature is made: twice the five minutes providers allow by default. */
8
+ const STALE_SECONDS = 10 * 60;
9
+ /** Providers whose signatures carry a time, so a stale one can be made. */
10
+ const TIMESTAMPED = new Set(['stripe', 'slack', 'svix', 'paddle']);
11
+ /** An id as providers write them: a lowercase prefix, an underscore, letters and digits with a digit or capital. */
12
+ const ID = /^[a-z]{1,16}_(?=[A-Za-z0-9]*[0-9A-Z])[A-Za-z0-9]+$/;
13
+ /** Headers that carry the id of a delivery, which handlers and libraries use to drop duplicates. */
14
+ const DELIVERY_HEADERS = new Set([
15
+ 'x-github-delivery',
16
+ 'x-shopify-webhook-id',
17
+ 'x-shopify-event-id',
18
+ 'svix-id',
19
+ 'webhook-id',
20
+ ]);
21
+ /**
22
+ * A copy of a webhook whose ids are new: every string in the JSON body that looks like a provider id gets `tag`
23
+ * appended, the same way in every webhook, so related events still name each other; delivery id headers too. The
24
+ * signature is made again when it is sent.
25
+ */
26
+ export function freshCopy(exchange, tag) {
27
+ const { request } = exchange;
28
+ let bodyBase64 = request.bodyBase64;
29
+ try {
30
+ const parsed = JSON.parse(Buffer.from(request.bodyBase64, 'base64').toString('utf8'));
31
+ const rewrite = (value) => {
32
+ if (typeof value === 'string') {
33
+ return ID.test(value) ? `${value}${tag}` : value;
34
+ }
35
+ if (Array.isArray(value)) {
36
+ return value.map(rewrite);
37
+ }
38
+ if (typeof value === 'object' && value !== null) {
39
+ return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, rewrite(child)]));
40
+ }
41
+ return value;
42
+ };
43
+ bodyBase64 = Buffer.from(JSON.stringify(rewrite(parsed))).toString('base64');
44
+ }
45
+ catch {
46
+ // Not JSON: sent as it is
47
+ }
48
+ const headers = request.headers.map(([name, value]) => DELIVERY_HEADERS.has(name.toLowerCase()) ? [name, `${value}-${tag}`] : [name, value]);
49
+ return { ...exchange, request: { ...request, headers, bodyBase64 } };
50
+ }
51
+ const ok = (answer) => answer !== null && answer.status >= 200 && answer.status < 300;
52
+ const refused = (answer) => answer !== null && answer.status >= 400 && answer.status < 500;
53
+ /**
54
+ * `hopwire chaos <file> --target <url>`: delivers the webhooks of a snapshot the way providers really do (twice, out
55
+ * of order, with a wrong or an old signature) and says per case whether the handler held. Exits 1 when a case failed.
56
+ */
57
+ export async function chaos(options) {
58
+ const snapshot = await readSnapshot(options.file);
59
+ // Only webhooks the handler took when they were recorded: one that failed then says nothing now
60
+ const recorded = snapshot.exchanges.filter((exchange) => recogniseWebhook(exchange) !== null && exchange.response.status >= 200 && exchange.response.status < 300);
61
+ if (recorded.length === 0) {
62
+ throw new HopwireError(`${printable(options.shown ?? options.file)} holds no webhook that was answered 2xx when it was recorded; chaos only sends those again.`);
63
+ }
64
+ // A fresh copy is a new body, so a signed webhook needs its secret to be signed again
65
+ const unsignable = recorded.filter((exchange) => {
66
+ const provider = recogniseWebhook(exchange)?.provider ?? '';
67
+ const signed = isSignedProvider(provider) && signedBy(exchange.request.headers, provider);
68
+ return signed && secretFor(exchange, options.secrets) === undefined;
69
+ });
70
+ const missing = [...new Set(unsignable.map((exchange) => recogniseWebhook(exchange)?.provider ?? ''))];
71
+ if (missing.length > 0) {
72
+ options.print(`skip ${unsignable.length} signed ${unsignable.length === 1 ? 'webhook' : 'webhooks'} of ${missing.join(' and ')}: name the signing secret with --webhook-secret ${missing[0] ?? ''}=<VARIABLE> to send them`);
73
+ }
74
+ const webhooks = recorded.filter((exchange) => !unsignable.includes(exchange));
75
+ if (webhooks.length === 0) {
76
+ throw new HopwireError('No webhook is left to send without a signing secret; name it with --webhook-secret.');
77
+ }
78
+ const now = options.nowSeconds ?? (() => Math.floor(Date.now() / 1000));
79
+ // Every round sends a copy with ids of its own, so the handler sees new events and not the ones it already took
80
+ let round = 0;
81
+ const freshRound = () => {
82
+ round += 1;
83
+ const tag = `hw${round}${Math.random().toString(36).slice(2, 7)}`;
84
+ return new Map(webhooks.map((exchange) => [exchange, freshCopy(exchange, tag)]));
85
+ };
86
+ const deliver = async (exchange, sign = {}) => {
87
+ try {
88
+ const answer = await send(exchange, options.target, {
89
+ secret: secretFor(exchange, options.secrets),
90
+ signAt: sign.at ?? now(),
91
+ wrongKey: sign.wrongKey,
92
+ });
93
+ return { exchange, answer, problem: null };
94
+ }
95
+ catch (error) {
96
+ if (error instanceof HopwireError && error.message.startsWith('nothing answers')) {
97
+ throw new HopwireError(error.message.replace(/^n/, 'N'));
98
+ }
99
+ return { exchange, answer: null, problem: error instanceof Error ? error.message : 'failed' };
100
+ }
101
+ };
102
+ const shown = (outcome) => `${requestLabel(outcome.exchange)} ${outcome.answer === null ? `failed: ${outcome.problem ?? ''}` : `answered ${outcome.answer.status}`}`;
103
+ options.print(`Chaos ${webhooks.length} ${webhooks.length === 1 ? 'webhook' : 'webhooks'} of ${printable(options.shown ?? options.file)} to ${options.target.origin}, in four rounds; your handler runs for every delivery`);
104
+ const failures = [];
105
+ const report = (name, broken, passed, why) => {
106
+ if (broken.length === 0) {
107
+ options.print(`pass ${name}: ${passed}`);
108
+ return;
109
+ }
110
+ failures.push(name);
111
+ options.print(`FAIL ${name}: ${why}`);
112
+ for (const outcome of broken.slice(0, 5)) {
113
+ options.print(` ${shown(outcome)}`);
114
+ }
115
+ if (broken.length > 5) {
116
+ options.print(` and ${broken.length - 5} more`);
117
+ }
118
+ };
119
+ // 1. Every webhook twice in a row, as a provider retries one whose answer it did not get
120
+ const twice = [];
121
+ const copies1 = freshRound();
122
+ for (const exchange of webhooks) {
123
+ const copy = copies1.get(exchange) ?? exchange;
124
+ const first = await deliver(copy);
125
+ const second = await deliver(copy);
126
+ if (!ok(first.answer)) {
127
+ twice.push(first);
128
+ }
129
+ else if (!ok(second.answer)) {
130
+ twice.push(second);
131
+ }
132
+ }
133
+ report('duplicate delivery', twice, 'both deliveries of every webhook were answered 2xx', 'a webhook delivered twice was not answered 2xx the second time; the provider retries it again and again');
134
+ // 2. All of them in reverse order
135
+ const reversed = [];
136
+ const copies2 = freshRound();
137
+ for (const exchange of [...webhooks].reverse()) {
138
+ const outcome = await deliver(copies2.get(exchange) ?? exchange);
139
+ if (!ok(outcome.answer)) {
140
+ reversed.push(outcome);
141
+ }
142
+ }
143
+ report('out of order', webhooks.length < 2 ? [] : reversed, webhooks.length < 2
144
+ ? 'one webhook only, nothing to reorder'
145
+ : 'every webhook was answered 2xx in reverse order', 'a webhook that arrived before the one it follows was not answered 2xx');
146
+ // 3. and 4. Signatures: only for providers whose secret was given
147
+ const signed = webhooks.filter((exchange) => {
148
+ const secret = secretFor(exchange, options.secrets);
149
+ return secret !== undefined && signedBy(exchange.request.headers, secret.provider);
150
+ });
151
+ if (signed.length === 0) {
152
+ options.print('skip wrong signature and stale signature: name the signing secret with --webhook-secret <provider>=<VARIABLE> to try them');
153
+ }
154
+ else {
155
+ const wrong = [];
156
+ const copies3 = freshRound();
157
+ for (const exchange of signed) {
158
+ const outcome = await deliver(copies3.get(exchange) ?? exchange, { wrongKey: true });
159
+ if (!refused(outcome.answer)) {
160
+ wrong.push(outcome);
161
+ }
162
+ }
163
+ report('wrong signature', wrong, 'every webhook with a signature made with another key was refused with 4xx', 'a webhook with a wrong signature was not refused with 4xx; anyone who knows the URL can send events');
164
+ const timed = signed.filter((exchange) => TIMESTAMPED.has(recogniseWebhook(exchange)?.provider ?? ''));
165
+ if (timed.length === 0) {
166
+ options.print('skip stale signature: the signatures of these providers carry no time');
167
+ }
168
+ else {
169
+ const stale = [];
170
+ const copies4 = freshRound();
171
+ for (const exchange of timed) {
172
+ const outcome = await deliver(copies4.get(exchange) ?? exchange, { at: now() - STALE_SECONDS });
173
+ if (!refused(outcome.answer)) {
174
+ stale.push(outcome);
175
+ }
176
+ }
177
+ report('stale signature', stale, 'every webhook signed 10 minutes ago was refused with 4xx', 'a webhook signed 10 minutes ago was not refused; a recorded webhook can be sent again later (replay attack)');
178
+ }
179
+ }
180
+ options.print('');
181
+ options.print(' Every round sent copies with new ids (evt_1Qf... became evt_1Qf...hw1...), so a handler that looks them up at the provider fails on them.');
182
+ options.print(' Answers are what chaos can see: check that a duplicate did not charge, mail or ship twice in your own data.');
183
+ if (failures.length > 0) {
184
+ throw new ChecksFailed(`${failures.length} of the chaos rounds failed: ${failures.join(', ')}.`);
185
+ }
186
+ }