hopwire 0.3.0 → 0.5.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,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
+ }
@@ -0,0 +1,177 @@
1
+ import { watch } from 'node:fs';
2
+ import { HopwireError } from '../errors.js';
3
+ import { createAgentClient } from '../mcp/client.js';
4
+ import { printable } from '../output.js';
5
+ import { asHopwireError, getJson } from './snapshot.js';
6
+ import { isSignedProvider, signHeaders, signedBy } from '../signature.js';
7
+ import { recogniseWebhook } from '../webhook.js';
8
+ import { requestLabel, secretFor } from './verify.js';
9
+ /** Paths whose changes are not the user's code: they change by themselves, or on every request. */
10
+ const IGNORED = /(^|[\\/])(\.git|node_modules|vendor|storage|var|tmp|\.hopwire|\.next|\.nuxt|coverage)([\\/]|$)|\.(log|lock|sqlite|db)$/;
11
+ /** A service that is restarting after a change answers 502 for a moment: tried again this often. */
12
+ const RESTART_TRIES = 5;
13
+ const RESTART_WAIT_MS = 1000;
14
+ /**
15
+ * `hopwire fix [<id>]`: takes a request that failed, says how to hand it to a coding agent, and replays it through
16
+ * the running tunnel after every change to the project's files until it passes.
17
+ */
18
+ export async function startFix(options) {
19
+ const client = options.client ?? createAgentClient(options.dataDir);
20
+ let record;
21
+ try {
22
+ record =
23
+ options.id === null
24
+ ? await newestFailure(client, options.signal)
25
+ : await byId(client, options.id, options.signal);
26
+ }
27
+ catch (error) {
28
+ throw asHopwireError(error);
29
+ }
30
+ const original = record.exchange;
31
+ const first = original.response.status;
32
+ options.print(`Fix ${requestLabel(original)} answered ${first} at ${new Date(original.timestamp).toLocaleTimeString()}`);
33
+ options.print(`Exchange ${printable(original.id)}`);
34
+ options.print(`Watching ${options.watch.map((folder) => printable(folder)).join(', ')}`);
35
+ options.print('');
36
+ options.print('Next steps');
37
+ options.print(' Fix it yourself, or give your coding agent (with the hopwire MCP server) this task:');
38
+ options.print(` Fix the handler of the request with hopwire exchange id ${printable(original.id)}: read it with hopwire_get_exchange and its log lines with hopwire_get_logs, change the code, and check with hopwire_replay until it answers 2xx.`);
39
+ options.print(' Every time a file changes, the request is sent again through the tunnel; this ends when it passes.');
40
+ options.print('');
41
+ let resolveFinished = () => { };
42
+ const finished = new Promise((resolve) => {
43
+ resolveFinished = resolve;
44
+ });
45
+ let attempts = 0;
46
+ let running = false;
47
+ let again = false;
48
+ let done = false;
49
+ let timer = null;
50
+ const attempt = async () => {
51
+ if (done) {
52
+ return;
53
+ }
54
+ if (running) {
55
+ again = true;
56
+ return;
57
+ }
58
+ running = true;
59
+ attempts += 1;
60
+ try {
61
+ let replayed = null;
62
+ for (let tries = 0; tries < RESTART_TRIES && !done; tries += 1) {
63
+ replayed = await replay(client, record, options.secrets ?? [], options.signal);
64
+ // A service still restarting: wait for it instead of counting an attempt that never reached it
65
+ if (replayed.response.status !== 502 || first === 502) {
66
+ break;
67
+ }
68
+ await new Promise((resolve) => setTimeout(resolve, RESTART_WAIT_MS));
69
+ }
70
+ if (replayed === null) {
71
+ return;
72
+ }
73
+ const { status, durationMs } = replayed.response;
74
+ if (status >= 200 && status < 400) {
75
+ done = true;
76
+ options.print(`Fixed after ${attempts} ${attempts === 1 ? 'attempt' : 'attempts'}: ${first} → ${status} (${durationMs}ms)`);
77
+ resolveFinished();
78
+ }
79
+ else {
80
+ options.print(`Attempt ${attempts}: ${status} in ${durationMs}ms; still failing, waiting for the next change`);
81
+ const provider = recogniseWebhook(original)?.provider;
82
+ if (attempts === 1 &&
83
+ status >= 400 &&
84
+ status < 500 &&
85
+ provider !== undefined &&
86
+ isSignedProvider(provider) &&
87
+ secretFor(original, options.secrets ?? []) === undefined) {
88
+ options.print(`Notice The replay carries the recorded ${provider} signature, which a handler that checks it refuses as too old; start again with --webhook-secret ${provider}=<VARIABLE>.`);
89
+ }
90
+ }
91
+ }
92
+ catch (error) {
93
+ const problem = asHopwireError(error);
94
+ options.print(`Attempt ${attempts}: ${problem instanceof Error ? problem.message : 'failed'}`);
95
+ }
96
+ finally {
97
+ running = false;
98
+ if (again && !done) {
99
+ again = false;
100
+ void attempt();
101
+ }
102
+ }
103
+ };
104
+ const changed = (file) => {
105
+ if (done || IGNORED.test(file)) {
106
+ return;
107
+ }
108
+ if (timer !== null) {
109
+ clearTimeout(timer);
110
+ }
111
+ timer = setTimeout(() => {
112
+ timer = null;
113
+ void attempt();
114
+ }, options.settleMs ?? 1000);
115
+ };
116
+ const watchFolder = options.watchFolder ??
117
+ ((folder, onChange) => watch(folder, { recursive: true }, (_event, name) => onChange(name ?? '')));
118
+ const watchers = options.watch.map((folder) => {
119
+ try {
120
+ return watchFolder(folder, changed);
121
+ }
122
+ catch {
123
+ throw new HopwireError(`${printable(folder)} cannot be watched; name an existing folder with --watch.`);
124
+ }
125
+ });
126
+ // The first attempt at once: it may pass already
127
+ void attempt();
128
+ return {
129
+ kind: 'fix',
130
+ finished,
131
+ close: async () => {
132
+ done = true;
133
+ if (timer !== null) {
134
+ clearTimeout(timer);
135
+ }
136
+ for (const watcher of watchers) {
137
+ watcher.close();
138
+ }
139
+ },
140
+ };
141
+ }
142
+ async function byId(client, id, signal) {
143
+ return getJson(client, `/api/exchanges/${encodeURIComponent(id)}`, signal);
144
+ }
145
+ /** The newest exchange of this machine's log that ended in 4xx or 5xx, replays and WebSockets left out. */
146
+ async function newestFailure(client, signal) {
147
+ const candidates = [];
148
+ for (const status of ['5xx', '4xx']) {
149
+ const page = await getJson(client, `/api/summaries?${new URLSearchParams({ status, limit: '20' }).toString()}`, signal);
150
+ const found = page.items.find((item) => item.source !== 'replay' && !item.websocket);
151
+ if (found !== undefined) {
152
+ candidates.push(found);
153
+ }
154
+ }
155
+ const newest = candidates.sort((a, b) => b.timestamp - a.timestamp)[0];
156
+ if (newest === undefined) {
157
+ throw new HopwireError('No request failed in this tunnel yet; name one with hopwire fix <exchange-id>.');
158
+ }
159
+ return byId(client, newest.id, signal);
160
+ }
161
+ async function replay(client, record, secrets, signal) {
162
+ const { request } = record.exchange;
163
+ const secret = secretFor(record.exchange, secrets);
164
+ const overrides = secret !== undefined && signedBy(request.headers, secret.provider)
165
+ ? {
166
+ headers: signHeaders(request.headers, Buffer.from(request.bodyBase64, 'base64'), secret, Math.floor(Date.now() / 1000)),
167
+ }
168
+ : {};
169
+ const answer = await client.request('POST', `/api/replay/${encodeURIComponent(record.exchange.id)}?origin=${record.origin}&index=${record.index}`, overrides, signal);
170
+ if (answer.status !== 200) {
171
+ const message = typeof answer.body === 'object' && answer.body !== null && 'message' in answer.body
172
+ ? String(answer.body.message)
173
+ : `the tunnel answered ${answer.status}`;
174
+ throw new HopwireError(printable(message));
175
+ }
176
+ return answer.body;
177
+ }
@@ -1,3 +1,4 @@
1
+ import { formatDrift } from '../shapes.js';
1
2
  import { MODE_LOCAL, MODE_P2P, MODE_P2P_TEAM, relayLine, MODE_PUBLIC, MODE_PUBLIC_P2P, MODE_PUBLIC_P2P_TEAM, AGENTS_ALLOWED_LINE, agentLine, agentOffLine, exchangeSink, formatPeerEvent, formatLimitReached, formatLogNotice, logLines, formatMeteredUsage, formatRelayEvent, formatTeamEvent, formatUsage, shareNotice, tunnelGuide, mainPublicUrl, publicUrlText, } from '../output.js';
2
3
  import { startServing } from '../serve.js';
3
4
  export { INSPECTOR_FILES } from '../serve.js';
@@ -36,6 +37,7 @@ export async function startHttpTunnel(options) {
36
37
  relay: options.relay,
37
38
  onRelayEvent: (event) => options.print(formatRelayEvent(event)),
38
39
  onPeerEvent: (event) => options.print(formatPeerEvent(event)),
40
+ onDrift: (drift) => options.print(formatDrift(drift)),
39
41
  bootstrap: options.bootstrap,
40
42
  inspectorFiles: options.inspectorFiles,
41
43
  agent: options.agent,
@@ -0,0 +1,81 @@
1
+ import { HopwireError } from '../errors.js';
2
+ import { START_HINT, ToolError, createAgentClient } from '../mcp/client.js';
3
+ import { printable } from '../output.js';
4
+ import { writeSnapshot } from '../traffic.js';
5
+ /** One page of summaries the API gives at most */
6
+ const PAGE = 50;
7
+ /**
8
+ * `hopwire snapshot <file>`: the requests the running tunnel recorded, oldest first, written to a file that
9
+ * `hopwire verify` and `hopwire chaos` send again. Replays and WebSocket handshakes are left out. Read through the
10
+ * agent socket, like hopwire mcp.
11
+ */
12
+ export async function snapshot(options) {
13
+ const client = options.client ?? createAgentClient(options.dataDir);
14
+ const now = (options.now ?? Date.now)();
15
+ const since = now - options.sinceMs;
16
+ const chosen = [];
17
+ let before = null;
18
+ try {
19
+ while (chosen.length < options.last) {
20
+ const query = new URLSearchParams({ limit: String(PAGE), since: String(since) });
21
+ if (options.service !== undefined) {
22
+ query.set('service', options.service);
23
+ }
24
+ if (options.pathContains !== undefined) {
25
+ query.set('pathContains', options.pathContains);
26
+ }
27
+ if (before !== null) {
28
+ query.set('before', String(before));
29
+ }
30
+ const page = await getJson(client, `/api/summaries?${query.toString()}`, options.signal);
31
+ for (const item of page.items) {
32
+ if (item.source !== 'replay' && !item.websocket && item.timestamp >= since) {
33
+ chosen.push(item);
34
+ }
35
+ }
36
+ if (page.nextBefore === null || page.items.length === 0) {
37
+ break;
38
+ }
39
+ // Older than the window: nothing further down can be in it
40
+ if ((page.items.at(-1)?.timestamp ?? 0) < since) {
41
+ break;
42
+ }
43
+ before = page.nextBefore;
44
+ }
45
+ const exchanges = [];
46
+ for (const item of chosen.slice(0, options.last).reverse()) {
47
+ const record = await getJson(client, `/api/exchanges/${encodeURIComponent(item.id)}`, options.signal);
48
+ exchanges.push(record.exchange);
49
+ }
50
+ if (exchanges.length === 0) {
51
+ throw new HopwireError('No request in that window: send some through the tunnel first, or widen it with --since or --last.');
52
+ }
53
+ await writeSnapshot(options.file, exchanges, now);
54
+ options.print(`Snapshot ${exchanges.length} ${exchanges.length === 1 ? 'request' : 'requests'} written to ${printable(options.shown ?? options.file)}`);
55
+ options.print('Notice The file holds headers and bodies as captured, credentials and customer data included; read it before you commit or share it.');
56
+ options.print('');
57
+ options.print('Next steps');
58
+ options.print(` Run "hopwire verify ${printable(options.shown ?? options.file)} --target http://127.0.0.1:<port>" after a change,`);
59
+ options.print(' or in CI, to see whether your service still answers these requests the same way.');
60
+ }
61
+ catch (error) {
62
+ throw asHopwireError(error);
63
+ }
64
+ }
65
+ /** A failure of the agent client as the sentence and hint of the CLI. */
66
+ export function asHopwireError(error) {
67
+ if (error instanceof ToolError) {
68
+ return new HopwireError(`${error.message} ${error.hint ?? START_HINT}`);
69
+ }
70
+ return error;
71
+ }
72
+ export async function getJson(client, route, signal) {
73
+ const answer = await client.request('GET', route, undefined, signal);
74
+ if (answer.status !== 200) {
75
+ const message = typeof answer.body === 'object' && answer.body !== null && 'message' in answer.body
76
+ ? String(answer.body.message)
77
+ : `the tunnel answered ${answer.status}`;
78
+ throw new HopwireError(printable(message));
79
+ }
80
+ return answer.body;
81
+ }
@@ -1,3 +1,4 @@
1
+ import { formatDrift } from '../shapes.js';
1
2
  import { randomBytes } from 'node:crypto';
2
3
  import path from 'node:path';
3
4
  import { LOCAL_ENTRY_DEFAULT_PORT, RANDOM_SUBDOMAIN_BYTES, randomSubdomain } from '@hopwire/protocol';
@@ -54,6 +55,7 @@ export async function startUp(options) {
54
55
  relay: options.relay,
55
56
  onRelayEvent: (event) => options.print(formatRelayEvent(event)),
56
57
  onPeerEvent: (event) => options.print(formatPeerEvent(event)),
58
+ onDrift: (drift) => options.print(formatDrift(drift)),
57
59
  bootstrap: options.bootstrap,
58
60
  inspectorFiles: options.inspectorFiles,
59
61
  agent: options.agent,
@@ -0,0 +1,64 @@
1
+ import { ChecksFailed, HopwireError } from '../errors.js';
2
+ import { printable } from '../output.js';
3
+ import { isSignedProvider } from '../signature.js';
4
+ import { compareAnswer, readSnapshot, send } from '../traffic.js';
5
+ import { recogniseWebhook } from '../webhook.js';
6
+ /** The method and path of a request as a line shows it. */
7
+ export function requestLabel(exchange) {
8
+ const webhook = recogniseWebhook(exchange);
9
+ const named = webhook === null ? '' : ` (${webhook.provider}${webhook.event === null ? '' : ` ${webhook.event}`})`;
10
+ return printable(`${exchange.request.method} ${exchange.request.path}${named}`);
11
+ }
12
+ /** The secret that signs a request again: the one of the provider that sent it. */
13
+ export function secretFor(exchange, secrets) {
14
+ const provider = recogniseWebhook(exchange)?.provider;
15
+ return secrets.find((entry) => entry.provider === provider);
16
+ }
17
+ /**
18
+ * `hopwire verify <file> --target <url>`: sends the requests of a snapshot in order and compares each answer with the
19
+ * recorded one. Exits 1 when one differs, so it runs in CI.
20
+ */
21
+ export async function verify(options) {
22
+ const snapshot = await readSnapshot(options.file);
23
+ const exchanges = snapshot.exchanges;
24
+ options.print(`Verify ${exchanges.length} ${exchanges.length === 1 ? 'request' : 'requests'} of ${printable(options.shown ?? options.file)} against ${options.target.origin}`);
25
+ let failed = 0;
26
+ for (const exchange of exchanges) {
27
+ let answer;
28
+ try {
29
+ answer = await send(exchange, options.target, { secret: secretFor(exchange, options.secrets) });
30
+ }
31
+ catch (error) {
32
+ if (error instanceof HopwireError && error.message.startsWith('nothing answers')) {
33
+ // Every other request would fail the same way
34
+ throw new HopwireError(`${error.message.replace(/^n/, 'N')}`);
35
+ }
36
+ failed += 1;
37
+ options.print(`FAIL ${requestLabel(exchange)} ${error instanceof Error ? error.message : 'failed'}`);
38
+ continue;
39
+ }
40
+ const differences = compareAnswer(exchange.response, answer, { strict: options.strict, ignore: options.ignore });
41
+ if (differences.length === 0) {
42
+ options.print(`pass ${requestLabel(exchange)} ${answer.status} ${answer.durationMs}ms`);
43
+ }
44
+ else {
45
+ failed += 1;
46
+ options.print(`FAIL ${requestLabel(exchange)} ${differences.join('; ')}`);
47
+ }
48
+ }
49
+ const passed = exchanges.length - failed;
50
+ // Webhooks sent with their recorded signatures: too old for any handler that checks them
51
+ const unsigned = new Set(exchanges
52
+ .map((exchange) => recogniseWebhook(exchange)?.provider)
53
+ .filter((provider) => provider !== undefined &&
54
+ isSignedProvider(provider) &&
55
+ !options.secrets.some((entry) => entry.provider === provider)));
56
+ if (failed > 0 && unsigned.size > 0) {
57
+ options.print('');
58
+ options.print(` The ${[...unsigned].join(' and ')} webhooks went out with their recorded signatures, which a handler that checks them refuses as too old. Sign them again with --webhook-secret ${[...unsigned][0] ?? 'stripe'}=<VARIABLE>.`);
59
+ }
60
+ if (failed > 0) {
61
+ throw new ChecksFailed(`${failed} of ${exchanges.length} ${exchanges.length === 1 ? 'request does' : 'requests do'} not answer as recorded.`);
62
+ }
63
+ options.print(`Verified all ${passed} ${passed === 1 ? 'request answers' : 'requests answer'} as recorded`);
64
+ }
@@ -190,7 +190,15 @@ export async function startWatch(options) {
190
190
  for (const line of stopped) {
191
191
  options.print(line);
192
192
  }
193
- return { kind: 'watch', inspectorUrl: inspector.url, agentSocket, logKey, peerKey, close };
193
+ return {
194
+ kind: 'watch',
195
+ inspectorUrl: inspector.url,
196
+ agentSocket,
197
+ logKey,
198
+ peerKey,
199
+ replayTarget: options.replayTarget?.origin ?? null,
200
+ close,
201
+ };
194
202
  }
195
203
  catch (error) {
196
204
  await close().catch(() => { });
@@ -55,6 +55,7 @@ export function renderConfig(answers) {
55
55
  else {
56
56
  lines.push(`${INDENT}${INDENT}# logs:`, `${INDENT}${INDENT}# - storage/logs/laravel.log`);
57
57
  }
58
+ lines.push(`${INDENT}${INDENT}# Signing secrets of its webhooks, by the name of the environment variable that holds each (never the`, `${INDENT}${INDENT}# secret itself): the terminal marks every webhook's signature as valid or wrong.`, `${INDENT}${INDENT}# webhooks:`, `${INDENT}${INDENT}# stripe: STRIPE_WEBHOOK_SECRET`);
58
59
  if (!service.public) {
59
60
  return;
60
61
  }
package/dist/config.js CHANGED
@@ -5,6 +5,7 @@ import { INSPECTOR_DEFAULT_PORT, HOPWIRE_YAML_FILE, HOPWIRE_YAML_VERSION, isBasi
5
5
  import { HopwireError } from './errors.js';
6
6
  import { defaultLogName } from './log-follow.js';
7
7
  import { printable } from './output.js';
8
+ import { SIGNED_PROVIDERS, isVariableName } from './signature.js';
8
9
  import { parseControlPlaneUrl, parseEdgeUrl, parseLocalTarget } from './urls.js';
9
10
  /** A hopwire.yaml that cannot be used. `path` is the offending field, null when the file as a whole is at fault. */
10
11
  export class ConfigError extends HopwireError {
@@ -26,7 +27,7 @@ class Problem {
26
27
  }
27
28
  }
28
29
  const ROOT_KEYS = ['version', 'inspector', 'agent', 'capture', 'edge', 'controlPlane', 'p2p', 'services'];
29
- const SERVICE_KEYS = ['local', 'public', 'subdomain', 'auth', 'logs'];
30
+ const SERVICE_KEYS = ['local', 'public', 'subdomain', 'auth', 'logs', 'webhooks'];
30
31
  const LOCAL_RULE = 'must be an http URL on this machine without a path, for example http://127.0.0.1:3000; Hopwire only forwards to loopback addresses.';
31
32
  const SUBDOMAIN_RULE = 'must be 3 to 63 lowercase letters, digits or hyphens, must not start or end with a hyphen, must not start with t- and must not be a reserved name such as www or api.';
32
33
  /**
@@ -310,8 +311,28 @@ function validateService(name, value) {
310
311
  subdomain,
311
312
  basicAuth,
312
313
  logs: validateLogs(service.logs, [...path, 'logs']),
314
+ webhooks: validateWebhooks(service.webhooks, [...path, 'webhooks']),
313
315
  };
314
316
  }
317
+ /** services.<name>.webhooks: provider to the name of the environment variable with its signing secret. */
318
+ function validateWebhooks(value, at) {
319
+ if (value === undefined) {
320
+ return [];
321
+ }
322
+ const webhooks = mapping(value, at, SIGNED_PROVIDERS, 'webhooks');
323
+ const entries = [];
324
+ for (const provider of SIGNED_PROVIDERS) {
325
+ const variable = webhooks[provider];
326
+ if (variable === undefined) {
327
+ continue;
328
+ }
329
+ if (typeof variable !== 'string' || !isVariableName(variable)) {
330
+ throw new Problem([...at, provider], 'must be the name of an environment variable that holds the signing secret, such as STRIPE_WEBHOOK_SECRET; the secret itself does not belong in this file.');
331
+ }
332
+ entries.push({ provider, variable });
333
+ }
334
+ return entries;
335
+ }
315
336
  const LOG_PATH_RULE = 'must be the path of a log file, relative to the folder of this file or absolute, with a * at most in the file name.';
316
337
  /** services.<name>.logs: a list of paths, or of mappings with path and name. */
317
338
  function validateLogs(value, at) {