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 +142 -6
- package/dist/cli.js +164 -14
- package/dist/commands/chaos.js +186 -0
- package/dist/commands/fix.js +177 -0
- package/dist/commands/http.js +5 -2
- package/dist/commands/snapshot.js +81 -0
- package/dist/commands/up.js +5 -2
- package/dist/commands/verify.js +64 -0
- package/dist/commands/watch.js +12 -4
- 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/inspector/assets/{index-CIOfyIbK.js → index-CdyIIKdA.js} +1 -1
- package/dist/inspector/index.html +1 -1
- package/dist/live.js +226 -0
- package/dist/main.js +17 -4
- package/dist/output.js +19 -0
- package/dist/p2p.js +59 -1
- package/dist/serve.js +27 -1
- package/dist/shapes.js +216 -0
- package/dist/shortcuts.js +242 -0
- package/dist/signature.js +207 -0
- package/dist/style.js +6 -0
- package/dist/terminal.js +671 -0
- package/dist/traffic.js +247 -0
- package/dist/version.js +12 -0
- package/dist/webhook.js +91 -0
- package/package.json +1 -1
|
@@ -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
|
+
}
|
package/dist/commands/http.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { formatDrift } from '../shapes.js';
|
|
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';
|
|
4
5
|
/**
|
|
@@ -35,6 +36,8 @@ export async function startHttpTunnel(options) {
|
|
|
35
36
|
onTeamEvent: (event, organisation) => options.print(formatTeamEvent(event, organisation)),
|
|
36
37
|
relay: options.relay,
|
|
37
38
|
onRelayEvent: (event) => options.print(formatRelayEvent(event)),
|
|
39
|
+
onPeerEvent: (event) => options.print(formatPeerEvent(event)),
|
|
40
|
+
onDrift: (drift) => options.print(formatDrift(drift)),
|
|
38
41
|
bootstrap: options.bootstrap,
|
|
39
42
|
inspectorFiles: options.inspectorFiles,
|
|
40
43
|
agent: options.agent,
|
|
@@ -42,7 +45,7 @@ export async function startHttpTunnel(options) {
|
|
|
42
45
|
signal: options.signal,
|
|
43
46
|
listenOption: '--listen <port>',
|
|
44
47
|
inspectOption: '--inspect <port> or run with --no-inspect',
|
|
45
|
-
onExchange: (exchange) => options.print(
|
|
48
|
+
onExchange: (exchange) => exchangeSink(options.print, options.exchange)(exchange),
|
|
46
49
|
onLogError: () => options.print('Could not write to the traffic log; the request was still forwarded'),
|
|
47
50
|
onBridgeEvent: (_service, event) => options.print(formatBridgeEvent(event)),
|
|
48
51
|
});
|
|
@@ -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
|
+
}
|
package/dist/commands/up.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
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';
|
|
4
5
|
import { HopwireError } from '../errors.js';
|
|
5
|
-
import { MODE_LOCAL, MODE_P2P, MODE_P2P_TEAM, relayLine, MODE_PUBLIC, MODE_PUBLIC_P2P, MODE_PUBLIC_P2P_TEAM, AGENTS_ALLOWED_LINE, agentLine, agentOffLine,
|
|
6
|
+
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, formatLogNotice, logLines, formatRelayEvent, formatTeamEvent, formatUsage, shareNotice, tunnelGuide, mainPublicUrl, publicUrlText, } from '../output.js';
|
|
6
7
|
import { startServing } from '../serve.js';
|
|
7
8
|
import { formatBridgeEvent } from './http.js';
|
|
8
9
|
/**
|
|
@@ -53,6 +54,8 @@ export async function startUp(options) {
|
|
|
53
54
|
onTeamEvent: (event, organisation) => options.print(formatTeamEvent(event, organisation)),
|
|
54
55
|
relay: options.relay,
|
|
55
56
|
onRelayEvent: (event) => options.print(formatRelayEvent(event)),
|
|
57
|
+
onPeerEvent: (event) => options.print(formatPeerEvent(event)),
|
|
58
|
+
onDrift: (drift) => options.print(formatDrift(drift)),
|
|
56
59
|
bootstrap: options.bootstrap,
|
|
57
60
|
inspectorFiles: options.inspectorFiles,
|
|
58
61
|
agent: options.agent,
|
|
@@ -63,7 +66,7 @@ export async function startUp(options) {
|
|
|
63
66
|
signal: options.signal,
|
|
64
67
|
listenOption: 'a free port',
|
|
65
68
|
inspectOption: 'inspector.port in hopwire.yaml',
|
|
66
|
-
onExchange: (exchange) => options.print(
|
|
69
|
+
onExchange: (exchange) => exchangeSink(options.print, options.exchange)(exchange, label(exchange.serviceName)),
|
|
67
70
|
onLogError: (name) => options.print(`${label(name)}Could not write to the traffic log; the request was still forwarded`),
|
|
68
71
|
onBridgeEvent: (name, event) => options.print(several ? `${formatBridgeEvent(event)} (service ${name})` : formatBridgeEvent(event)),
|
|
69
72
|
});
|
|
@@ -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
|
+
}
|
package/dist/commands/watch.js
CHANGED
|
@@ -7,7 +7,7 @@ import { startInspectorServer } from '../inspector-server.js';
|
|
|
7
7
|
import { createInterceptor } from '../interceptor.js';
|
|
8
8
|
import { InFlightExchanges, followLogFile } from '../log-follow.js';
|
|
9
9
|
import { REMOTE_LOG_BUDGET_BYTES } from '../log.js';
|
|
10
|
-
import { MODE_P2P, MODE_P2P_RELAYED, MODE_P2P_TEAM,
|
|
10
|
+
import { MODE_P2P, MODE_P2P_RELAYED, MODE_P2P_TEAM, exchangeSink, formatLogNotice, logLines, printable, relayedLine, shortKey, watchAgentLine, watchGuide, } from '../output.js';
|
|
11
11
|
import { INSPECTOR_FILES } from '../serve.js';
|
|
12
12
|
import { Supervisor, unlessAborted } from '../supervisor.js';
|
|
13
13
|
/**
|
|
@@ -114,7 +114,7 @@ export async function startWatch(options) {
|
|
|
114
114
|
serviceName,
|
|
115
115
|
log: own,
|
|
116
116
|
inFlight,
|
|
117
|
-
onExchange: (exchange) => options.print(
|
|
117
|
+
onExchange: (exchange) => exchangeSink(options.print, options.exchange)(exchange),
|
|
118
118
|
onLogError: () => options.print('Could not write to the traffic log; the replay was still sent'),
|
|
119
119
|
});
|
|
120
120
|
interceptors.set(serviceName, interceptor);
|
|
@@ -162,7 +162,7 @@ export async function startWatch(options) {
|
|
|
162
162
|
}
|
|
163
163
|
// Stopped at the last step: nothing is reported as running
|
|
164
164
|
proceed();
|
|
165
|
-
const stopPrinting = remote.subscribe((_index, exchange) => options.print(
|
|
165
|
+
const stopPrinting = remote.subscribe((_index, exchange) => exchangeSink(options.print, options.exchange)(exchange));
|
|
166
166
|
supervisor.add('servers', async () => stopPrinting());
|
|
167
167
|
void remote.exhausted.then(() => options.print(`Watching stopped: this run has downloaded ${REMOTE_LOG_BUDGET_BYTES / (1024 * 1024)} MB of the log; new exchanges are no longer fetched until hopwire watch is started again`));
|
|
168
168
|
options.print(joined.relayed ? MODE_P2P_RELAYED : organisation === null ? MODE_P2P : MODE_P2P_TEAM);
|
|
@@ -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 {
|
|
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(() => { });
|
package/dist/config-template.js
CHANGED
|
@@ -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) {
|
package/dist/curl.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/** Headers curl sets itself, or that describe the connection the request came in on rather than the request. */
|
|
2
|
+
const LEFT_OUT = new Set([
|
|
3
|
+
'host',
|
|
4
|
+
'content-length',
|
|
5
|
+
'connection',
|
|
6
|
+
'keep-alive',
|
|
7
|
+
'transfer-encoding',
|
|
8
|
+
'te',
|
|
9
|
+
'upgrade',
|
|
10
|
+
'proxy-connection',
|
|
11
|
+
'x-forwarded-for',
|
|
12
|
+
'x-forwarded-host',
|
|
13
|
+
'x-forwarded-proto',
|
|
14
|
+
'x-real-ip',
|
|
15
|
+
'accept-encoding',
|
|
16
|
+
]);
|
|
17
|
+
/** Headers whose values are credentials: the line about the copy names them, so nobody pastes one by accident. */
|
|
18
|
+
const CREDENTIALS = new Set(['authorization', 'proxy-authorization', 'cookie', 'x-api-key', 'api-key']);
|
|
19
|
+
/**
|
|
20
|
+
* A request as a curl command to `base` (an entry point or replay target on this machine), ready to paste into a
|
|
21
|
+
* shell: every value single-quoted, so nothing in it is expanded. A body that is not text, or was cut by the capture,
|
|
22
|
+
* is left out and said so.
|
|
23
|
+
*/
|
|
24
|
+
export function curlCommand(exchange, base) {
|
|
25
|
+
const { request } = exchange;
|
|
26
|
+
const parts = ['curl', '-X', quote(request.method), quote(`${base.replace(/\/$/, '')}${request.path}`)];
|
|
27
|
+
const credentials = [];
|
|
28
|
+
for (const [name, value] of request.headers) {
|
|
29
|
+
const lower = name.toLowerCase();
|
|
30
|
+
if (LEFT_OUT.has(lower)) {
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
if (CREDENTIALS.has(lower)) {
|
|
34
|
+
credentials.push(name);
|
|
35
|
+
}
|
|
36
|
+
parts.push('-H', quote(`${name}: ${value}`));
|
|
37
|
+
}
|
|
38
|
+
let bodyLeftOut = null;
|
|
39
|
+
const body = Buffer.from(request.bodyBase64, 'base64');
|
|
40
|
+
if (body.byteLength > 0) {
|
|
41
|
+
const text = body.toString('utf8');
|
|
42
|
+
if (request.bodyTruncated) {
|
|
43
|
+
bodyLeftOut = 'the body was longer than the capture limit';
|
|
44
|
+
}
|
|
45
|
+
else if (text.includes('\ufffd') ||
|
|
46
|
+
// eslint-disable-next-line no-control-regex -- control characters mark a body that is not text
|
|
47
|
+
/[\u0000-\u0008\u000e-\u001f\u007f]/.test(text)) {
|
|
48
|
+
bodyLeftOut = 'the body is binary';
|
|
49
|
+
}
|
|
50
|
+
else {
|
|
51
|
+
parts.push('--data-binary', quote(text));
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return { command: parts.join(' '), credentials, bodyLeftOut };
|
|
55
|
+
}
|
|
56
|
+
/** A shell word in single quotes; a single quote inside closes, escapes and reopens. */
|
|
57
|
+
function quote(value) {
|
|
58
|
+
return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
59
|
+
}
|
package/dist/errors.js
CHANGED
|
@@ -4,6 +4,9 @@ export class HopwireError extends Error {
|
|
|
4
4
|
/** A wrong command line; the CLI exits with code 2. */
|
|
5
5
|
export class UsageError extends HopwireError {
|
|
6
6
|
}
|
|
7
|
+
/** Checks that ran and found what they look for (hopwire verify, chaos): exit code 1, no troubleshooting hint. */
|
|
8
|
+
export class ChecksFailed extends HopwireError {
|
|
9
|
+
}
|
|
7
10
|
/**
|
|
8
11
|
* A failure that may pass by itself: a server that cannot be reached, answers with a server error or limits the
|
|
9
12
|
* rate. Whoever can wait tries again later; whoever cannot reports the sentence like any other HopwireError.
|