hopwire 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +6 -0
- package/dist/cli.js +160 -2
- package/dist/commands/chaos.js +186 -0
- package/dist/commands/fix.js +177 -0
- package/dist/commands/http.js +2 -0
- package/dist/commands/snapshot.js +81 -0
- package/dist/commands/up.js +2 -0
- package/dist/commands/verify.js +64 -0
- package/dist/commands/watch.js +9 -1
- package/dist/config-template.js +1 -0
- package/dist/config.js +22 -1
- package/dist/curl.js +59 -0
- package/dist/errors.js +3 -0
- package/dist/main.js +4 -2
- package/dist/serve.js +26 -1
- package/dist/shapes.js +216 -0
- package/dist/shortcuts.js +29 -4
- package/dist/signature.js +207 -0
- package/dist/style.js +6 -0
- package/dist/terminal.js +60 -8
- package/dist/traffic.js +247 -0
- package/package.json +1 -1
|
@@ -0,0 +1,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,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
|
+
}
|
package/dist/commands/watch.js
CHANGED
|
@@ -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.
|
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
|
+
}
|
package/dist/shortcuts.js
CHANGED
|
@@ -1,19 +1,21 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
|
-
import {
|
|
2
|
+
import { curlCommand } from './curl.js';
|
|
3
|
+
import { mainPublicUrl, printable } from './output.js';
|
|
3
4
|
/** The keys act on tunnels that show exchanges: http, up and watch. Connect and mcp keep the terminal as it is. */
|
|
4
5
|
export function shortcutTarget(running) {
|
|
5
6
|
switch (running.kind) {
|
|
6
7
|
case 'http':
|
|
7
|
-
return { inspectorUrl: running.inspectorUrl, publicUrl: running.publicUrl };
|
|
8
|
+
return { inspectorUrl: running.inspectorUrl, publicUrl: running.publicUrl, entry: () => running.url };
|
|
8
9
|
case 'up': {
|
|
9
10
|
const published = running.services.find((service) => service.publicUrl !== null);
|
|
10
11
|
return {
|
|
11
12
|
inspectorUrl: running.inspectorUrl,
|
|
12
13
|
publicUrl: published === undefined ? null : mainPublicUrl(published.publicUrl, published.customDomains),
|
|
14
|
+
entry: (name) => running.services.find((service) => service.name === name)?.url ?? null,
|
|
13
15
|
};
|
|
14
16
|
}
|
|
15
17
|
case 'watch':
|
|
16
|
-
return { inspectorUrl: running.inspectorUrl, publicUrl: null };
|
|
18
|
+
return { inspectorUrl: running.inspectorUrl, publicUrl: null, entry: () => running.replayTarget };
|
|
17
19
|
default:
|
|
18
20
|
return null;
|
|
19
21
|
}
|
|
@@ -37,7 +39,7 @@ export function keysOf(chunk) {
|
|
|
37
39
|
return keys;
|
|
38
40
|
}
|
|
39
41
|
/** What ? lists. */
|
|
40
|
-
export const KEYS_HELP = '\u2191\u2193 pick a request, enter shows it, i opens it in the inspector, r replays it, o inspector, c copy the public URL, q quit';
|
|
42
|
+
export const KEYS_HELP = '\u2191\u2193 pick a request, enter shows it, i opens it in the inspector, r replays it, y copies it as curl, o inspector, c copy the public URL, q quit';
|
|
41
43
|
/**
|
|
42
44
|
* Reads single keys while a tunnel runs: o opens the inspector, c copies the public URL, r replays the newest
|
|
43
45
|
* request, q and Ctrl+C stop. The terminal is put in raw mode for it, so Ctrl+C reaches here as a key and is turned
|
|
@@ -67,6 +69,29 @@ export function startShortcuts(input, actions) {
|
|
|
67
69
|
say('No request has come in yet.', true);
|
|
68
70
|
}
|
|
69
71
|
break;
|
|
72
|
+
case 'y': {
|
|
73
|
+
const picked = actions.lastExchange();
|
|
74
|
+
const base = picked === null ? null : target.entry(picked.serviceName);
|
|
75
|
+
if (picked === null) {
|
|
76
|
+
say('No request has come in yet.', true);
|
|
77
|
+
}
|
|
78
|
+
else if (base === null) {
|
|
79
|
+
say('There is nowhere on this machine to send it: start with --replay-target.', true);
|
|
80
|
+
}
|
|
81
|
+
else {
|
|
82
|
+
const copy = curlCommand(picked, base);
|
|
83
|
+
void actions.copy(copy.command).then((how) => {
|
|
84
|
+
const notes = [
|
|
85
|
+
...(copy.credentials.length > 0
|
|
86
|
+
? [`it carries ${copy.credentials.join(', ')}; mind where you paste it`]
|
|
87
|
+
: []),
|
|
88
|
+
...(copy.bodyLeftOut === null ? [] : [`no body: ${copy.bodyLeftOut}`]),
|
|
89
|
+
];
|
|
90
|
+
say(`${how === 'copied' ? 'Copied' : 'Sent to the clipboard of the terminal:'} curl for ${printable(picked.request.method)} ${printable(picked.request.path)} to ${base}${notes.length > 0 ? ` (${notes.join('; ')})` : ''}`);
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
break;
|
|
94
|
+
}
|
|
70
95
|
case 'i': {
|
|
71
96
|
const picked = actions.lastExchange();
|
|
72
97
|
if (target.inspectorUrl === null) {
|