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.
- package/dist/bin.js +149 -5
- package/dist/cli.js +180 -8
- package/dist/commands/chaos.js +186 -0
- package/dist/commands/fix.js +177 -0
- package/dist/commands/http.js +2 -0
- package/dist/commands/snapshot.js +81 -0
- package/dist/commands/up.js +2 -0
- package/dist/commands/verify.js +64 -0
- package/dist/commands/watch.js +9 -1
- package/dist/config-template.js +1 -0
- package/dist/config.js +22 -1
- package/dist/curl.js +59 -0
- package/dist/errors.js +3 -0
- package/dist/help.js +279 -0
- package/dist/main.js +4 -2
- package/dist/serve.js +26 -1
- package/dist/shapes.js +216 -0
- package/dist/shortcuts.js +29 -4
- package/dist/signature.js +207 -0
- package/dist/style.js +6 -0
- package/dist/terminal.js +96 -16
- package/dist/traffic.js +247 -0
- package/dist/tui/app.js +748 -0
- package/dist/tui/chrome.js +222 -0
- package/dist/tui/input.js +82 -0
- package/dist/tui/model.js +174 -0
- package/dist/tui/requests.js +271 -0
- package/dist/tui/screen.js +91 -0
- package/dist/tui/state.js +88 -0
- package/dist/tui/tabs.js +239 -0
- package/dist/tui/text.js +182 -0
- package/package.json +1 -1
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.
|
package/dist/help.js
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
import { DOCS_URL } from './output.js';
|
|
2
|
+
const FORCE = { flag: '--force', what: 'Stop the tunnel that holds the data directory and start this one' };
|
|
3
|
+
const NO_AGENT = { flag: '--no-agent', what: 'Do not let a coding agent on this machine read the traffic' };
|
|
4
|
+
const AGENT = { flag: '--agent', what: 'Fail when the socket for coding agents cannot open' };
|
|
5
|
+
const WEBHOOK_SECRET_SIGN = {
|
|
6
|
+
flag: '--webhook-secret <provider>=<VARIABLE>',
|
|
7
|
+
what: 'Sign the webhooks again with the secret in that environment variable',
|
|
8
|
+
};
|
|
9
|
+
export const COMMANDS = {
|
|
10
|
+
http: {
|
|
11
|
+
args: '<port>',
|
|
12
|
+
summary: 'Put Hopwire in front of a local service',
|
|
13
|
+
options: [
|
|
14
|
+
{ flag: '--public', what: 'Give the service a public HTTPS URL (run hopwire login once before)' },
|
|
15
|
+
{ flag: '--subdomain <name>', what: 'With --public: a subdomain your organisation reserved' },
|
|
16
|
+
{ flag: '--share', what: 'Let teammates reach the service and follow the traffic over P2P' },
|
|
17
|
+
{ flag: '--allow <pubkey>', what: 'With --share: only this public key gets in; repeatable' },
|
|
18
|
+
{ flag: '--team', what: 'With --share: only machines of your organisation get in (Team plan)' },
|
|
19
|
+
{ flag: '--relay', what: 'With --share: teammates on strict networks come in through the edge' },
|
|
20
|
+
{ flag: '--log <path>', what: 'Show new entries of a log file next to the requests; repeatable' },
|
|
21
|
+
{
|
|
22
|
+
flag: '--webhook-secret <provider>=<VARIABLE>',
|
|
23
|
+
what: 'Check webhook signatures with the secret in that environment variable',
|
|
24
|
+
},
|
|
25
|
+
{ flag: '--listen <port>', what: 'Port of the entry point (default 4041, 0 picks a free one)' },
|
|
26
|
+
{ flag: '--inspect <port>', what: 'Port of the inspector (default 4040, 0 picks a free one)' },
|
|
27
|
+
{ flag: '--no-inspect', what: 'Run without the inspector' },
|
|
28
|
+
{ flag: '--name <service>', what: 'Service name in the traffic log (default "default")' },
|
|
29
|
+
{ flag: '--plain', what: 'Print lines instead of the full-screen view' },
|
|
30
|
+
{ flag: '--share-logs', what: 'With --share and --log: teammates see the log entries too' },
|
|
31
|
+
{ flag: '--log-request-id', what: 'With --log: send X-Hopwire-Exchange-Id to the service' },
|
|
32
|
+
{ flag: '--allow-agents', what: "With --share: teammates' coding agents may read new traffic" },
|
|
33
|
+
{ flag: '--no-ws-capture', what: 'Record the handshake of a WebSocket but not its messages' },
|
|
34
|
+
NO_AGENT,
|
|
35
|
+
AGENT,
|
|
36
|
+
FORCE,
|
|
37
|
+
],
|
|
38
|
+
examples: [
|
|
39
|
+
['hopwire http 3000', 'Record every request to the service on port 3000'],
|
|
40
|
+
['hopwire http 3000 --public', 'The same, with a public URL for a webhook provider'],
|
|
41
|
+
['hopwire http 3000 --share', 'The same, with keys to send to a teammate'],
|
|
42
|
+
],
|
|
43
|
+
docs: 'getting-started',
|
|
44
|
+
},
|
|
45
|
+
up: {
|
|
46
|
+
args: '',
|
|
47
|
+
summary: 'Start every service of hopwire.yaml',
|
|
48
|
+
options: [
|
|
49
|
+
{ flag: '--config <path>', what: 'The config file (default hopwire.yaml in the working directory)' },
|
|
50
|
+
{ flag: '--plain', what: 'Print lines instead of the full-screen view' },
|
|
51
|
+
NO_AGENT,
|
|
52
|
+
AGENT,
|
|
53
|
+
FORCE,
|
|
54
|
+
],
|
|
55
|
+
examples: [
|
|
56
|
+
['hopwire init', 'Write a hopwire.yaml by answering a few questions'],
|
|
57
|
+
['hopwire up', 'Start what the file says'],
|
|
58
|
+
],
|
|
59
|
+
docs: 'hopwire-yaml',
|
|
60
|
+
},
|
|
61
|
+
init: {
|
|
62
|
+
args: '',
|
|
63
|
+
summary: 'Write a hopwire.yaml by answering questions',
|
|
64
|
+
options: [
|
|
65
|
+
{ flag: '--config <path>', what: 'The file to write (default hopwire.yaml); never replaces one' },
|
|
66
|
+
{ flag: '--yes', what: 'Ask nothing and write what the flags below say' },
|
|
67
|
+
{ flag: '--service <name>=<port|url>', what: 'With --yes: a service and its port; repeatable' },
|
|
68
|
+
{ flag: '--public <name>', what: 'With --yes: give this service a public URL; repeatable' },
|
|
69
|
+
{ flag: '--subdomain <name>=<sub>', what: 'With --yes: the subdomain of a public service' },
|
|
70
|
+
{ flag: '--share', what: 'With --yes: share over P2P' },
|
|
71
|
+
{ flag: '--team', what: 'With --yes: share with your organisation only' },
|
|
72
|
+
{ flag: '--allow-agents', what: "With --yes: teammates' coding agents may read new traffic" },
|
|
73
|
+
],
|
|
74
|
+
examples: [
|
|
75
|
+
['hopwire init', 'Answer a few questions'],
|
|
76
|
+
['hopwire init --yes --service api=3000 --public api', 'The same without questions'],
|
|
77
|
+
],
|
|
78
|
+
docs: 'hopwire-yaml',
|
|
79
|
+
},
|
|
80
|
+
watch: {
|
|
81
|
+
args: '<log-key>',
|
|
82
|
+
summary: "Follow a teammate's traffic and replay it",
|
|
83
|
+
options: [
|
|
84
|
+
{ flag: '--replay-target <url>', what: 'Your own service that replays go to; without it Replay is off' },
|
|
85
|
+
{ flag: '--team', what: 'For a teammate who shares with --team' },
|
|
86
|
+
{ flag: '--relay', what: 'Go through the edge when no direct connection comes about' },
|
|
87
|
+
{ flag: '--log <path>', what: 'Show new entries of a log file of your service; repeatable' },
|
|
88
|
+
{ flag: '--inspect <port>', what: 'Port of the inspector (default 4040, 0 picks a free one)' },
|
|
89
|
+
{ flag: '--plain', what: 'Print lines instead of the full-screen view' },
|
|
90
|
+
{ flag: '--agent', what: 'Let a coding agent here read what your teammate allowed for agents' },
|
|
91
|
+
FORCE,
|
|
92
|
+
],
|
|
93
|
+
examples: [
|
|
94
|
+
['hopwire watch <log-key> --replay-target http://127.0.0.1:3000', 'Watch, and replay to your service'],
|
|
95
|
+
],
|
|
96
|
+
docs: 'private-mode',
|
|
97
|
+
},
|
|
98
|
+
connect: {
|
|
99
|
+
args: '<peer-key>',
|
|
100
|
+
summary: "Reach a teammate's service",
|
|
101
|
+
options: [
|
|
102
|
+
{ flag: '--port <port>', what: "Local port that reaches the teammate's service (0 picks a free one)" },
|
|
103
|
+
{ flag: '--service <name>', what: 'Which service, when the teammate shares more than one' },
|
|
104
|
+
{ flag: '--allow-host <host>', what: 'Also answer requests with this Host header; repeatable' },
|
|
105
|
+
{ flag: '--team', what: 'For a teammate who shares with --team' },
|
|
106
|
+
{ flag: '--relay', what: 'Go through the edge when no direct connection comes about' },
|
|
107
|
+
],
|
|
108
|
+
examples: [['hopwire connect <peer-key> --port 4141', 'Then send requests to http://127.0.0.1:4141']],
|
|
109
|
+
docs: 'private-mode',
|
|
110
|
+
},
|
|
111
|
+
fix: {
|
|
112
|
+
args: '[<exchange-id>]',
|
|
113
|
+
summary: 'Replay a failed request until it passes',
|
|
114
|
+
options: [
|
|
115
|
+
{ flag: '--watch <dir>', what: 'A folder whose changes start a new attempt; repeatable' },
|
|
116
|
+
WEBHOOK_SECRET_SIGN,
|
|
117
|
+
],
|
|
118
|
+
examples: [['hopwire fix', 'The newest failed request of the running tunnel, after every file change']],
|
|
119
|
+
docs: 'cli-reference',
|
|
120
|
+
},
|
|
121
|
+
snapshot: {
|
|
122
|
+
args: '<file>',
|
|
123
|
+
summary: 'Write the recorded requests to a file',
|
|
124
|
+
options: [
|
|
125
|
+
{ flag: '--since <time>', what: 'Only requests of the last 30s, 30m, 2h or 1d (default 30m)' },
|
|
126
|
+
{ flag: '--last <n>', what: 'At most the newest n requests (default 200)' },
|
|
127
|
+
{ flag: '--service <name>', what: 'Only requests of this service' },
|
|
128
|
+
{ flag: '--path <text>', what: 'Only requests whose path contains this text' },
|
|
129
|
+
],
|
|
130
|
+
examples: [['hopwire snapshot hooks.snapshot.json', 'The last 30 minutes of the running tunnel']],
|
|
131
|
+
docs: 'cli-reference',
|
|
132
|
+
},
|
|
133
|
+
verify: {
|
|
134
|
+
args: '<file>',
|
|
135
|
+
summary: 'Send a snapshot to your service and compare answers (CI)',
|
|
136
|
+
options: [
|
|
137
|
+
{ flag: '--target <url>', what: 'Where the requests go: http://127.0.0.1:3000 or a port' },
|
|
138
|
+
WEBHOOK_SECRET_SIGN,
|
|
139
|
+
{ flag: '--strict', what: 'Compare values too, not only the shape of JSON answers' },
|
|
140
|
+
{ flag: '--ignore <field>', what: 'Leave a field out, as a dotted path; repeatable' },
|
|
141
|
+
],
|
|
142
|
+
examples: [['hopwire verify hooks.snapshot.json --target 3000', 'Exits 1 when an answer differs']],
|
|
143
|
+
docs: 'cli-reference',
|
|
144
|
+
},
|
|
145
|
+
chaos: {
|
|
146
|
+
args: '<file>',
|
|
147
|
+
summary: 'Deliver webhooks the way providers really do',
|
|
148
|
+
options: [
|
|
149
|
+
{ flag: '--target <url>', what: 'Where the requests go: http://127.0.0.1:3000 or a port' },
|
|
150
|
+
WEBHOOK_SECRET_SIGN,
|
|
151
|
+
],
|
|
152
|
+
examples: [
|
|
153
|
+
[
|
|
154
|
+
'hopwire chaos hooks.snapshot.json --target 3000',
|
|
155
|
+
'Twice, out of order, with a wrong and an old signature',
|
|
156
|
+
],
|
|
157
|
+
],
|
|
158
|
+
docs: 'cli-reference',
|
|
159
|
+
},
|
|
160
|
+
mcp: {
|
|
161
|
+
args: '',
|
|
162
|
+
summary: 'Let your coding agent read and replay the traffic',
|
|
163
|
+
options: [{ flag: '--read-only', what: 'Leave out the replay tool' }],
|
|
164
|
+
examples: [
|
|
165
|
+
['claude mcp add hopwire -- hopwire mcp', 'Register it with your coding agent; the agent starts it'],
|
|
166
|
+
],
|
|
167
|
+
docs: 'coding-agents',
|
|
168
|
+
},
|
|
169
|
+
login: {
|
|
170
|
+
args: '',
|
|
171
|
+
summary: 'Sign in through the browser, for public mode',
|
|
172
|
+
options: [
|
|
173
|
+
{ flag: '--profile <name>', what: 'Store the login in this profile (one per organisation)' },
|
|
174
|
+
{ flag: '--token', what: 'Paste an API token instead of signing in through the browser' },
|
|
175
|
+
{ flag: '--no-browser', what: 'Print the sign-in page without opening it' },
|
|
176
|
+
{ flag: '--api <url>', what: 'The control plane (default https://hopwire.to)' },
|
|
177
|
+
],
|
|
178
|
+
examples: [['hopwire login', 'Opens the sign-in page and waits for your approval']],
|
|
179
|
+
docs: 'public-mode',
|
|
180
|
+
},
|
|
181
|
+
logout: {
|
|
182
|
+
args: '',
|
|
183
|
+
summary: 'Remove the stored API token from this machine',
|
|
184
|
+
options: [],
|
|
185
|
+
examples: [],
|
|
186
|
+
docs: 'public-mode',
|
|
187
|
+
},
|
|
188
|
+
profiles: {
|
|
189
|
+
args: '',
|
|
190
|
+
summary: 'List the logins on this machine',
|
|
191
|
+
options: [],
|
|
192
|
+
examples: [],
|
|
193
|
+
docs: 'cli-reference',
|
|
194
|
+
},
|
|
195
|
+
use: {
|
|
196
|
+
args: '<profile>',
|
|
197
|
+
summary: 'Make another profile the current one',
|
|
198
|
+
options: [],
|
|
199
|
+
examples: [['hopwire use acme', 'After hopwire login --profile acme']],
|
|
200
|
+
docs: 'cli-reference',
|
|
201
|
+
},
|
|
202
|
+
id: {
|
|
203
|
+
args: '',
|
|
204
|
+
summary: 'Print the public key of this machine',
|
|
205
|
+
options: [],
|
|
206
|
+
examples: [],
|
|
207
|
+
docs: 'private-mode',
|
|
208
|
+
},
|
|
209
|
+
rotate: {
|
|
210
|
+
args: '',
|
|
211
|
+
summary: 'New keys for this machine, for when one went to the wrong person',
|
|
212
|
+
options: [],
|
|
213
|
+
examples: [],
|
|
214
|
+
docs: 'private-mode',
|
|
215
|
+
},
|
|
216
|
+
doctor: {
|
|
217
|
+
args: '',
|
|
218
|
+
summary: 'Print a report about this installation',
|
|
219
|
+
options: [{ flag: '--network', what: 'Also test whether this network allows direct P2P connections' }],
|
|
220
|
+
examples: [],
|
|
221
|
+
docs: 'troubleshooting',
|
|
222
|
+
},
|
|
223
|
+
};
|
|
224
|
+
/** The four groups of the overview; a name in one row shares the line. */
|
|
225
|
+
const GROUPS = [
|
|
226
|
+
{ title: 'Start', rows: [['http'], ['up'], ['init']] },
|
|
227
|
+
{ title: 'With your team', rows: [['watch'], ['connect']] },
|
|
228
|
+
{ title: 'Test and debug', rows: [['fix'], ['snapshot'], ['verify'], ['chaos'], ['mcp']] },
|
|
229
|
+
];
|
|
230
|
+
const ACCOUNT = ['login', 'logout', 'profiles', 'use', 'id', 'rotate', 'doctor'];
|
|
231
|
+
/** hopwire, hopwire --help and hopwire help: every command on one screen. */
|
|
232
|
+
export function overview() {
|
|
233
|
+
const lines = ['Usage: hopwire <command>', ''];
|
|
234
|
+
for (const group of GROUPS) {
|
|
235
|
+
lines.push(group.title);
|
|
236
|
+
for (const [name = ''] of group.rows) {
|
|
237
|
+
const command = COMMANDS[name];
|
|
238
|
+
if (command !== undefined) {
|
|
239
|
+
lines.push(` ${`${name} ${command.args}`.trimEnd().padEnd(19)}${command.summary}`);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
lines.push('');
|
|
243
|
+
}
|
|
244
|
+
lines.push('Account and machine', ` ${ACCOUNT.join(', ')}`, '');
|
|
245
|
+
lines.push('hopwire <command> --help The options of a command, with examples', 'hopwire help --all Everything on one page', `Guides ${DOCS_URL}`);
|
|
246
|
+
return lines.join('\n');
|
|
247
|
+
}
|
|
248
|
+
/** hopwire <command> --help: what it does, examples, its options in a line each. Null for an unknown command. */
|
|
249
|
+
export function commandHelp(name) {
|
|
250
|
+
const command = COMMANDS[name];
|
|
251
|
+
if (command === undefined) {
|
|
252
|
+
return null;
|
|
253
|
+
}
|
|
254
|
+
const lines = [
|
|
255
|
+
`Usage: ${`hopwire ${name} ${command.args}`.trimEnd()}${command.options.length > 0 ? ' [options]' : ''}`,
|
|
256
|
+
];
|
|
257
|
+
lines.push('', command.summary);
|
|
258
|
+
if (command.examples.length > 0) {
|
|
259
|
+
lines.push('', 'Examples');
|
|
260
|
+
for (const [example, what] of command.examples) {
|
|
261
|
+
lines.push(` ${example}`, ` ${what}`);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
if (command.options.length > 0) {
|
|
265
|
+
const width = Math.min(Math.max(...command.options.map((option) => option.flag.length)), 24) + 2;
|
|
266
|
+
lines.push('', 'Options');
|
|
267
|
+
for (const option of command.options) {
|
|
268
|
+
// A flag wider than the column stands on a line of its own
|
|
269
|
+
if (option.flag.length + 2 > width) {
|
|
270
|
+
lines.push(` ${option.flag}`, ` ${' '.repeat(width)}${option.what}`);
|
|
271
|
+
}
|
|
272
|
+
else {
|
|
273
|
+
lines.push(` ${option.flag.padEnd(width)}${option.what}`);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
lines.push('', 'Every command also takes --data-dir <path> and --profile <name>.', 'All details: hopwire help --all', `Guide: ${DOCS_URL}/${command.docs}`);
|
|
278
|
+
return lines.join('\n');
|
|
279
|
+
}
|
package/dist/main.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { HopwireError, UsageError, unexpectedFailure } from './errors.js';
|
|
1
|
+
import { ChecksFailed, HopwireError, UsageError, unexpectedFailure } from './errors.js';
|
|
2
2
|
import { DOCS_URL } from './output.js';
|
|
3
3
|
import { superviseProcess } from './supervisor.js';
|
|
4
4
|
/** The line after a wrong command line. */
|
|
@@ -44,7 +44,9 @@ export async function main(proc) {
|
|
|
44
44
|
proc.exit(2);
|
|
45
45
|
return;
|
|
46
46
|
}
|
|
47
|
-
fail(error instanceof HopwireError ? error.message : unexpectedFailure(error), proc.failure !== undefined && error instanceof HopwireError
|
|
47
|
+
fail(error instanceof HopwireError ? error.message : unexpectedFailure(error), proc.failure !== undefined && error instanceof HopwireError && !(error instanceof ChecksFailed)
|
|
48
|
+
? TROUBLESHOOTING_HINT
|
|
49
|
+
: null);
|
|
48
50
|
proc.exit(1);
|
|
49
51
|
}
|
|
50
52
|
}
|
package/dist/serve.js
CHANGED
|
@@ -9,6 +9,7 @@ import { createInterceptor } from './interceptor.js';
|
|
|
9
9
|
import { openOwnLog } from './data-dir-holder.js';
|
|
10
10
|
import { InFlightExchanges, followLogFile } from './log-follow.js';
|
|
11
11
|
import { createProxyServer } from './proxy-server.js';
|
|
12
|
+
import { ShapeBook } from './shapes.js';
|
|
12
13
|
import { Supervisor } from './supervisor.js';
|
|
13
14
|
/**
|
|
14
15
|
* What `hopwire http` (one service) and `hopwire up` (the services of hopwire.yaml) have in common: one traffic log,
|
|
@@ -46,6 +47,30 @@ export async function startServing(options) {
|
|
|
46
47
|
supervisor.add('store', () => local.close());
|
|
47
48
|
}
|
|
48
49
|
const shareLogs = options.share && options.shareLogs === true;
|
|
50
|
+
// Payload drift: the shapes of earlier webhooks, kept in the data directory; saved a moment after a change
|
|
51
|
+
const shapes = await ShapeBook.open(options.dataDir);
|
|
52
|
+
let saving = null;
|
|
53
|
+
const saveShapes = () => {
|
|
54
|
+
saving = null;
|
|
55
|
+
void shapes.save().catch(() => { });
|
|
56
|
+
};
|
|
57
|
+
supervisor.add('servers', async () => {
|
|
58
|
+
if (saving !== null) {
|
|
59
|
+
clearTimeout(saving);
|
|
60
|
+
await shapes.save().catch(() => { });
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
const onExchange = (exchange) => {
|
|
64
|
+
options.onExchange(exchange);
|
|
65
|
+
const drift = shapes.observe(exchange);
|
|
66
|
+
if (drift !== null) {
|
|
67
|
+
options.onDrift?.(drift);
|
|
68
|
+
}
|
|
69
|
+
if (exchange.source !== 'replay' && saving === null) {
|
|
70
|
+
saving = setTimeout(saveShapes, 2000);
|
|
71
|
+
saving.unref();
|
|
72
|
+
}
|
|
73
|
+
};
|
|
49
74
|
const interceptors = new Map();
|
|
50
75
|
const inFlight = new Map();
|
|
51
76
|
const services = [];
|
|
@@ -63,7 +88,7 @@ export async function startServing(options) {
|
|
|
63
88
|
logRequestId: options.logRequestId === true && tracked !== undefined,
|
|
64
89
|
allowAgents: options.share && options.allowAgents === true,
|
|
65
90
|
captureWebSocketMessages: options.captureWebSocketMessages ?? true,
|
|
66
|
-
onExchange
|
|
91
|
+
onExchange,
|
|
67
92
|
onLogError: () => {
|
|
68
93
|
if (!storeClosing) {
|
|
69
94
|
options.onLogError(service.name);
|
package/dist/shapes.js
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { printable } from './output.js';
|
|
4
|
+
import { recogniseWebhook } from './webhook.js';
|
|
5
|
+
/**
|
|
6
|
+
* Payload drift: the shape of the JSON bodies of each provider's events, as this machine saw them, and a line when a
|
|
7
|
+
* new body of the same event differs: a field never seen, a field that was always there and is missing, a field whose
|
|
8
|
+
* type changed. Only paths and types are kept, never values, in shapes.json of the data directory.
|
|
9
|
+
*/
|
|
10
|
+
/** How deep into a body paths are followed, and how many of one body are kept. */
|
|
11
|
+
const MAX_DEPTH = 6;
|
|
12
|
+
const MAX_PATHS = 500;
|
|
13
|
+
/** Samples needed before something counts as new, and before a missing field counts as missing. */
|
|
14
|
+
const NEW_AFTER = 3;
|
|
15
|
+
const MISSING_AFTER = 5;
|
|
16
|
+
/** Bodies larger than this are not read for their shape. */
|
|
17
|
+
const PARSE_LIMIT_BYTES = 1024 * 1024;
|
|
18
|
+
/** Events kept in the file; the ones seen least recently go first. */
|
|
19
|
+
const MAX_EVENTS = 500;
|
|
20
|
+
/** The paths of a JSON value with their types: `data.object.id` -> string; array items share `items[]`. */
|
|
21
|
+
export function shapeOf(value) {
|
|
22
|
+
const paths = new Map();
|
|
23
|
+
const walk = (node, at, depth) => {
|
|
24
|
+
if (paths.size >= MAX_PATHS) {
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
const type = typeOf(node);
|
|
28
|
+
if (at !== '') {
|
|
29
|
+
paths.set(at, type);
|
|
30
|
+
}
|
|
31
|
+
if (depth >= MAX_DEPTH) {
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
if (type === 'object') {
|
|
35
|
+
for (const [key, child] of Object.entries(node)) {
|
|
36
|
+
walk(child, at === '' ? key : `${at}.${key}`, depth + 1);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
else if (type === 'array') {
|
|
40
|
+
for (const item of node) {
|
|
41
|
+
walk(item, `${at}[]`, depth + 1);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
walk(value, '', 0);
|
|
46
|
+
return paths;
|
|
47
|
+
}
|
|
48
|
+
function typeOf(value) {
|
|
49
|
+
if (value === null) {
|
|
50
|
+
return 'null';
|
|
51
|
+
}
|
|
52
|
+
if (Array.isArray(value)) {
|
|
53
|
+
return 'array';
|
|
54
|
+
}
|
|
55
|
+
const type = typeof value;
|
|
56
|
+
return type === 'object' || type === 'string' || type === 'number' || type === 'boolean' ? type : 'null';
|
|
57
|
+
}
|
|
58
|
+
/** The book of shapes of one data directory. */
|
|
59
|
+
export class ShapeBook {
|
|
60
|
+
file;
|
|
61
|
+
events;
|
|
62
|
+
constructor(file, events) {
|
|
63
|
+
this.file = file;
|
|
64
|
+
this.events = events;
|
|
65
|
+
}
|
|
66
|
+
/** Opens shapes.json of the data directory; a missing or unreadable file starts an empty book. */
|
|
67
|
+
static async open(dataDir) {
|
|
68
|
+
const file = path.join(dataDir, 'shapes.json');
|
|
69
|
+
const events = new Map();
|
|
70
|
+
try {
|
|
71
|
+
const parsed = JSON.parse(await readFile(file, 'utf8'));
|
|
72
|
+
if (typeof parsed === 'object' && parsed !== null && 'events' in parsed) {
|
|
73
|
+
const stored = parsed.events;
|
|
74
|
+
if (typeof stored === 'object' && stored !== null) {
|
|
75
|
+
for (const [key, shape] of Object.entries(stored)) {
|
|
76
|
+
if (isEventShape(shape)) {
|
|
77
|
+
events.set(key, shape);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
// No book yet, or one that cannot be read: start again
|
|
85
|
+
}
|
|
86
|
+
return new ShapeBook(file, events);
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Takes in one exchange: a drift when the body of a known event differs from what was seen before, else null. The
|
|
90
|
+
* body is learned either way.
|
|
91
|
+
*/
|
|
92
|
+
observe(exchange) {
|
|
93
|
+
if (exchange.source === 'replay') {
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
const webhook = recogniseWebhook(exchange);
|
|
97
|
+
if (webhook === null || webhook.event === null) {
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
const body = jsonBody(exchange);
|
|
101
|
+
if (body === null) {
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
const now = exchange.timestamp;
|
|
105
|
+
const shape = shapeOf(body);
|
|
106
|
+
const key = `${webhook.provider} ${webhook.event}`;
|
|
107
|
+
const known = this.events.get(key);
|
|
108
|
+
const drift = known === undefined ? null : compare(webhook.provider, webhook.event, known, shape);
|
|
109
|
+
const entry = known ?? { samples: 0, firstSeen: now, lastSeen: now, paths: {} };
|
|
110
|
+
entry.samples += 1;
|
|
111
|
+
entry.lastSeen = now;
|
|
112
|
+
for (const [at, type] of shape) {
|
|
113
|
+
const seen = entry.paths[at] ?? { count: 0, types: [] };
|
|
114
|
+
seen.count += 1;
|
|
115
|
+
if (!seen.types.includes(type)) {
|
|
116
|
+
seen.types.push(type);
|
|
117
|
+
}
|
|
118
|
+
entry.paths[at] = seen;
|
|
119
|
+
}
|
|
120
|
+
this.events.delete(key);
|
|
121
|
+
this.events.set(key, entry);
|
|
122
|
+
while (this.events.size > MAX_EVENTS) {
|
|
123
|
+
const oldest = this.events.keys().next().value;
|
|
124
|
+
if (oldest === undefined) {
|
|
125
|
+
break;
|
|
126
|
+
}
|
|
127
|
+
this.events.delete(oldest);
|
|
128
|
+
}
|
|
129
|
+
return drift;
|
|
130
|
+
}
|
|
131
|
+
/** Writes the book: to a temporary file first, so a crash never leaves half of it. */
|
|
132
|
+
async save() {
|
|
133
|
+
await mkdir(path.dirname(this.file), { recursive: true });
|
|
134
|
+
const temporary = `${this.file}.${process.pid}.tmp`;
|
|
135
|
+
await writeFile(temporary, JSON.stringify({ version: 1, events: Object.fromEntries(this.events) }), {
|
|
136
|
+
mode: 0o600,
|
|
137
|
+
});
|
|
138
|
+
await rename(temporary, this.file);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
function compare(provider, event, known, shape) {
|
|
142
|
+
const added = [];
|
|
143
|
+
const missing = [];
|
|
144
|
+
const retyped = [];
|
|
145
|
+
if (known.samples >= NEW_AFTER) {
|
|
146
|
+
for (const [at, type] of shape) {
|
|
147
|
+
const seen = known.paths[at];
|
|
148
|
+
if (seen === undefined) {
|
|
149
|
+
// Under a new object or array only its top is named
|
|
150
|
+
if (!added.some((parent) => at.startsWith(`${parent}.`) || at.startsWith(`${parent}[]`))) {
|
|
151
|
+
added.push(at);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
else if (!seen.types.includes(type) && !(type === 'null' || seen.types.includes('null'))) {
|
|
155
|
+
retyped.push({ path: at, was: [...seen.types], now: type });
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
if (known.samples >= MISSING_AFTER) {
|
|
160
|
+
for (const [at, seen] of Object.entries(known.paths)) {
|
|
161
|
+
if (seen.count === known.samples && !shape.has(at)) {
|
|
162
|
+
if (!missing.some((parent) => at.startsWith(`${parent}.`) || at.startsWith(`${parent}[]`))) {
|
|
163
|
+
missing.push(at);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
if (added.length === 0 && missing.length === 0 && retyped.length === 0) {
|
|
169
|
+
return null;
|
|
170
|
+
}
|
|
171
|
+
return { provider, event, added, missing, retyped, samples: known.samples, since: known.firstSeen };
|
|
172
|
+
}
|
|
173
|
+
function jsonBody(exchange) {
|
|
174
|
+
const { request } = exchange;
|
|
175
|
+
if (request.bodyTruncated ||
|
|
176
|
+
request.bodyBase64.length === 0 ||
|
|
177
|
+
(request.bodyBase64.length / 4) * 3 > PARSE_LIMIT_BYTES) {
|
|
178
|
+
return null;
|
|
179
|
+
}
|
|
180
|
+
try {
|
|
181
|
+
const value = JSON.parse(Buffer.from(request.bodyBase64, 'base64').toString('utf8'));
|
|
182
|
+
return typeof value === 'object' && value !== null ? value : null;
|
|
183
|
+
}
|
|
184
|
+
catch {
|
|
185
|
+
return null;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
function isEventShape(value) {
|
|
189
|
+
if (typeof value !== 'object' || value === null) {
|
|
190
|
+
return false;
|
|
191
|
+
}
|
|
192
|
+
const shape = value;
|
|
193
|
+
return (typeof shape.samples === 'number' &&
|
|
194
|
+
typeof shape.firstSeen === 'number' &&
|
|
195
|
+
typeof shape.lastSeen === 'number' &&
|
|
196
|
+
typeof shape.paths === 'object' &&
|
|
197
|
+
shape.paths !== null);
|
|
198
|
+
}
|
|
199
|
+
/** Longest list of paths a drift line names; the rest are counted. */
|
|
200
|
+
const LISTED = 4;
|
|
201
|
+
/** The line of a drift, as hopwire prints it. */
|
|
202
|
+
export function formatDrift(drift) {
|
|
203
|
+
const list = (paths) => paths.length <= LISTED
|
|
204
|
+
? paths.join(', ')
|
|
205
|
+
: `${paths.slice(0, LISTED).join(', ')} and ${paths.length - LISTED} more`;
|
|
206
|
+
const parts = [
|
|
207
|
+
...(drift.added.length > 0 ? [`new ${list(drift.added)}`] : []),
|
|
208
|
+
...(drift.missing.length > 0 ? [`missing ${list(drift.missing)}`] : []),
|
|
209
|
+
...drift.retyped
|
|
210
|
+
.slice(0, LISTED)
|
|
211
|
+
.map((entry) => `${entry.path} is now ${entry.now} (was ${entry.was.join(' or ')})`),
|
|
212
|
+
];
|
|
213
|
+
const day = new Date(drift.since).toISOString().slice(0, 10);
|
|
214
|
+
// Provider, event and paths come from a request: nothing in them may reach the terminal as an escape sequence
|
|
215
|
+
return `Drift ${printable(`${drift.provider} ${drift.event}: ${parts.join('; ')}`)} (against ${drift.samples} earlier ${drift.samples === 1 ? 'request' : 'requests'} since ${day})`;
|
|
216
|
+
}
|