hopwire 0.1.6 → 0.1.7
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/cli.js +5 -0
- package/dist/commands/http.js +1 -0
- package/dist/commands/up.js +1 -0
- package/dist/config.js +20 -2
- package/dist/edge-bridge.js +8 -2
- package/dist/inspector/assets/index-CUURvDyL.js +2 -0
- package/dist/inspector/assets/index-XotF7D1X.css +2 -0
- package/dist/inspector/index.html +2 -2
- package/dist/inspector-api.js +145 -20
- package/dist/interceptor.js +17 -3
- package/dist/log.js +154 -18
- package/dist/mcp/tools.js +139 -7
- package/dist/mcp/ws-messages.js +72 -0
- package/dist/proxy-server.js +22 -1
- package/dist/serve.js +1 -0
- package/dist/websocket.js +9 -5
- package/dist/ws-capture.js +129 -0
- package/dist/ws-replay.js +97 -0
- package/node_modules/@hopwire/protocol/dist/index.d.ts +1 -0
- package/node_modules/@hopwire/protocol/dist/index.js +1 -0
- package/node_modules/@hopwire/protocol/dist/inspector.d.ts +33 -1
- package/node_modules/@hopwire/protocol/dist/inspector.js +32 -1
- package/node_modules/@hopwire/protocol/dist/websocket.d.ts +2 -2
- package/node_modules/@hopwire/protocol/dist/websocket.js +2 -2
- package/node_modules/@hopwire/protocol/dist/ws-messages.d.ts +69 -0
- package/node_modules/@hopwire/protocol/dist/ws-messages.js +104 -0
- package/package.json +1 -1
- package/dist/inspector/assets/index-BvwyMIFs.css +0 -2
- package/dist/inspector/assets/index-Ctrz3UJp.js +0 -2
package/dist/mcp/tools.js
CHANGED
|
@@ -5,6 +5,7 @@ import { printable } from '../output.js';
|
|
|
5
5
|
import { contentEncoding, decodedBytes, encode, showBody, shownText } from './body.js';
|
|
6
6
|
import { START_HINT, ToolError } from './client.js';
|
|
7
7
|
import { summarizeError } from './error-summary.js';
|
|
8
|
+
import { messageMatches, showClose, showWsMessage } from './ws-messages.js';
|
|
8
9
|
/**
|
|
9
10
|
* The tools of `hopwire mcp` (spec phase 10). Everything they return is captured traffic of third parties, so every
|
|
10
11
|
* result carries NOTE and every description repeats it; values a model reads are escaped and redacted, and a replay
|
|
@@ -22,6 +23,12 @@ export function resetReplayGuard() {
|
|
|
22
23
|
const DEFAULT_BODY_CHARS = 8000;
|
|
23
24
|
const MAX_BODY_CHARS = 100_000;
|
|
24
25
|
const DEFAULT_RESPONSE_BODY_CHARS = 4000;
|
|
26
|
+
/** Recorded messages of a WebSocket hopwire_get_exchange shows at most, and the characters of each */
|
|
27
|
+
const HANDSHAKE_MESSAGES = 10;
|
|
28
|
+
const DEFAULT_MESSAGE_CHARS = 2000;
|
|
29
|
+
const MAX_MESSAGE_CHARS = 100_000;
|
|
30
|
+
const DEFAULT_MESSAGES = 20;
|
|
31
|
+
const MAX_MESSAGES = 100;
|
|
25
32
|
const DEFAULT_WAIT_SECONDS = 60;
|
|
26
33
|
const MAX_WAIT_SECONDS = 300;
|
|
27
34
|
// ---- input schemas ----
|
|
@@ -260,10 +267,15 @@ function errorSummaryOf(part) {
|
|
|
260
267
|
const shown = shownText(part);
|
|
261
268
|
return shown === null ? null : summarizeError(shown.text, shown.contentType);
|
|
262
269
|
}
|
|
263
|
-
/**
|
|
264
|
-
|
|
270
|
+
/**
|
|
271
|
+
* Why an exchange cannot be replayed as it is, or null. For a WebSocket handshake its recorded messages decide: a
|
|
272
|
+
* client message that was captured only in part cannot be sent again.
|
|
273
|
+
*/
|
|
274
|
+
function notReplayable(exchange, messages = []) {
|
|
265
275
|
if (isWebSocketHandshake(exchange)) {
|
|
266
|
-
return
|
|
276
|
+
return messages.some((message) => message.direction === 'in' && message.truncated)
|
|
277
|
+
? 'A client message of this WebSocket was cut at the 64 KiB capture limit, so its messages cannot be sent again as recorded.'
|
|
278
|
+
: null;
|
|
267
279
|
}
|
|
268
280
|
if (exchange.request.bodyTruncated) {
|
|
269
281
|
return 'The request body was cut at the 2 MB capture limit; a replay needs edit.body or edit.bodyBase64 with the whole body.';
|
|
@@ -278,6 +290,7 @@ function apiFailure(answer) {
|
|
|
278
290
|
const message = typeof body.message === 'string' ? body.message : `The tunnel answered ${answer.status}.`;
|
|
279
291
|
const hints = {
|
|
280
292
|
body_truncated: 'Pass edit.body or edit.bodyBase64 with the whole body.',
|
|
293
|
+
message_truncated: 'A client message was cut at the 64 KiB capture limit; such a WebSocket can only be replayed with Edit & Replay in the inspector.',
|
|
281
294
|
no_replay_target: START_HINT,
|
|
282
295
|
unknown_exchange: 'List the exchanges again with hopwire_list_exchanges; the id may be of another data directory.',
|
|
283
296
|
};
|
|
@@ -293,6 +306,27 @@ async function getJson(context, route) {
|
|
|
293
306
|
async function record(context, id) {
|
|
294
307
|
return getJson(context, `/api/exchanges/${encodeURIComponent(id)}`);
|
|
295
308
|
}
|
|
309
|
+
/** Every recorded message of the WebSocket of a handshake, and its close once it closed. */
|
|
310
|
+
async function wsSession(context, found) {
|
|
311
|
+
const messages = [];
|
|
312
|
+
let close;
|
|
313
|
+
let after = null;
|
|
314
|
+
for (;;) {
|
|
315
|
+
const query = new URLSearchParams({ origin: found.origin });
|
|
316
|
+
if (after !== null) {
|
|
317
|
+
query.set('after', String(after));
|
|
318
|
+
}
|
|
319
|
+
const page = await getJson(context, `/api/ws-messages/${encodeURIComponent(found.exchange.id)}?${query.toString()}`);
|
|
320
|
+
for (const block of page.blocks) {
|
|
321
|
+
messages.push(...block.messages);
|
|
322
|
+
close = block.close ?? close;
|
|
323
|
+
after = block.seq;
|
|
324
|
+
}
|
|
325
|
+
if (!page.more || page.blocks.length === 0) {
|
|
326
|
+
return { messages, close };
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
}
|
|
296
330
|
// ---- the tools ----
|
|
297
331
|
const statusTool = {
|
|
298
332
|
name: 'hopwire_status',
|
|
@@ -378,11 +412,30 @@ const getTool = {
|
|
|
378
412
|
const max = optionalInteger(args, 'maxBodyChars', 1, MAX_BODY_CHARS) ?? DEFAULT_BODY_CHARS;
|
|
379
413
|
const offset = optionalInteger(args, 'bodyOffset', 0, Number.MAX_SAFE_INTEGER) ?? 0;
|
|
380
414
|
const found = await record(context, id);
|
|
381
|
-
|
|
415
|
+
if (!isWebSocketHandshake(found.exchange)) {
|
|
416
|
+
const reason = notReplayable(found.exchange);
|
|
417
|
+
return {
|
|
418
|
+
exchange: showHead(summarize(found)),
|
|
419
|
+
...(part === 'response' ? {} : { request: shownPart(found.exchange.request, offset, max) }),
|
|
420
|
+
...(part === 'request' ? {} : { response: shownResponse(found.exchange, offset, max) }),
|
|
421
|
+
replayable: reason === null,
|
|
422
|
+
notReplayableReason: reason,
|
|
423
|
+
};
|
|
424
|
+
}
|
|
425
|
+
const { messages, close } = await wsSession(context, found);
|
|
426
|
+
const reason = notReplayable(found.exchange, messages);
|
|
382
427
|
return {
|
|
383
428
|
exchange: showHead(summarize(found)),
|
|
384
429
|
...(part === 'response' ? {} : { request: shownPart(found.exchange.request, offset, max) }),
|
|
385
430
|
...(part === 'request' ? {} : { response: shownResponse(found.exchange, offset, max) }),
|
|
431
|
+
websocket: {
|
|
432
|
+
recordedMessages: messages.length,
|
|
433
|
+
firstMessages: messages
|
|
434
|
+
.slice(0, HANDSHAKE_MESSAGES)
|
|
435
|
+
.map((message, position) => showWsMessage(message, position, Math.min(max, DEFAULT_MESSAGE_CHARS))),
|
|
436
|
+
close: showClose(close),
|
|
437
|
+
more: messages.length > HANDSHAKE_MESSAGES ? 'Read the rest with hopwire_get_ws_messages.' : null,
|
|
438
|
+
},
|
|
386
439
|
replayable: reason === null,
|
|
387
440
|
notReplayableReason: reason,
|
|
388
441
|
};
|
|
@@ -455,6 +508,59 @@ const waitTool = {
|
|
|
455
508
|
}
|
|
456
509
|
},
|
|
457
510
|
};
|
|
511
|
+
const wsMessagesTool = {
|
|
512
|
+
name: 'hopwire_get_ws_messages',
|
|
513
|
+
title: 'Show the messages of a WebSocket',
|
|
514
|
+
description: `The recorded messages of one WebSocket, by the id of its handshake (an exchange with status 101 and websocket: true): both directions (in: client to service, out: service to client) in order, with the time since the 101, paged by offset; filter by direction and by a substring of the text. Each message is captured up to 64 KiB (truncatedAtCapture) and a WebSocket up to 2 MB or 10,000 messages (close.omittedMessages counts the rest). A text message that is JSON or form data is shown with fields such as password or token redacted; other text is shown as it was sent and is NOT redacted, and a binary message is only its size and sha256. close says how the WebSocket ended (code, reason, by client, service or hopwire), null while it is open. ${NOTE}`,
|
|
515
|
+
inputSchema: schema({
|
|
516
|
+
id: { type: 'string', description: 'Id of the handshake' },
|
|
517
|
+
direction: { type: 'string', enum: ['in', 'out', 'both'], default: 'both' },
|
|
518
|
+
contains: {
|
|
519
|
+
type: 'string',
|
|
520
|
+
description: 'Only text messages whose shown text contains this, ignoring case',
|
|
521
|
+
},
|
|
522
|
+
offset: { type: 'integer', minimum: 0, default: 0, description: 'nextOffset of an earlier answer' },
|
|
523
|
+
limit: { type: 'integer', minimum: 1, maximum: MAX_MESSAGES, default: DEFAULT_MESSAGES },
|
|
524
|
+
maxChars: {
|
|
525
|
+
type: 'integer',
|
|
526
|
+
minimum: 1,
|
|
527
|
+
maximum: MAX_MESSAGE_CHARS,
|
|
528
|
+
default: DEFAULT_MESSAGE_CHARS,
|
|
529
|
+
description: 'Characters of each message at most',
|
|
530
|
+
},
|
|
531
|
+
}, ['id']),
|
|
532
|
+
annotations: { readOnlyHint: true, openWorldHint: false },
|
|
533
|
+
async call(args, context) {
|
|
534
|
+
allowOnly(args, ['id', 'direction', 'contains', 'offset', 'limit', 'maxChars']);
|
|
535
|
+
const id = requiredId(args);
|
|
536
|
+
const direction = args.direction ?? 'both';
|
|
537
|
+
if (direction !== 'in' && direction !== 'out' && direction !== 'both') {
|
|
538
|
+
throw invalid('direction must be in, out or both');
|
|
539
|
+
}
|
|
540
|
+
const contains = optionalString(args, 'contains');
|
|
541
|
+
const offset = optionalInteger(args, 'offset', 0, Number.MAX_SAFE_INTEGER) ?? 0;
|
|
542
|
+
const limit = optionalInteger(args, 'limit', 1, MAX_MESSAGES) ?? DEFAULT_MESSAGES;
|
|
543
|
+
const maxChars = optionalInteger(args, 'maxChars', 1, MAX_MESSAGE_CHARS) ?? DEFAULT_MESSAGE_CHARS;
|
|
544
|
+
const found = await record(context, id);
|
|
545
|
+
if (!isWebSocketHandshake(found.exchange)) {
|
|
546
|
+
throw new ToolError('not_websocket', 'This exchange is not the handshake of a WebSocket.', 'Use hopwire_get_exchange for an HTTP exchange.');
|
|
547
|
+
}
|
|
548
|
+
const { messages, close } = await wsSession(context, found);
|
|
549
|
+
const matching = messages
|
|
550
|
+
.map((message, position) => ({ message, position }))
|
|
551
|
+
.filter(({ message }) => (direction === 'both' || message.direction === direction) &&
|
|
552
|
+
(contains === undefined || messageMatches(message, contains)));
|
|
553
|
+
const page = matching.slice(offset, offset + limit);
|
|
554
|
+
return {
|
|
555
|
+
exchange: showHead(summarize(found)),
|
|
556
|
+
recordedMessages: messages.length,
|
|
557
|
+
matching: matching.length,
|
|
558
|
+
messages: page.map(({ message, position }) => showWsMessage(message, position, maxChars)),
|
|
559
|
+
nextOffset: offset + page.length < matching.length ? offset + page.length : null,
|
|
560
|
+
close: showClose(close),
|
|
561
|
+
};
|
|
562
|
+
},
|
|
563
|
+
};
|
|
458
564
|
function invalidEdit(message, hint) {
|
|
459
565
|
return new ToolError('invalid_edit', message, hint);
|
|
460
566
|
}
|
|
@@ -650,7 +756,7 @@ export function applyEdit(stored, edit) {
|
|
|
650
756
|
const replayTool = {
|
|
651
757
|
name: 'hopwire_replay',
|
|
652
758
|
title: 'Replay a captured request',
|
|
653
|
-
description: `Sends a captured request again to the tunnel's local service (and nowhere else) and returns the new response; the replay is logged with source replay. Without edit the stored request is sent byte for byte, credentials and signatures included, and the result says sentAsCaptured: true; with edit it is false. edit changes it: method, path, setHeaders, removeHeaders, and one of body (text), bodyBase64 or jsonSet (RFC 6901 pointers patched into the stored JSON body). Redacted placeholders are refused: leave a field out to keep its stored value. Side effects on the local service are real (database writes, mails). Signed webhooks (Stripe's timestamp tolerance, GitHub's HMAC) may reject an old or edited replay; use the handler's test signing mode. One replay at a time, at most ${REPLAYS_PER_MINUTE} a minute. ${NOTE}`,
|
|
759
|
+
description: `Sends a captured request again to the tunnel's local service (and nowhere else) and returns the new response; the replay is logged with source replay. A WebSocket handshake (status 101) is replayed as a new WebSocket that sends the recorded client messages with their recorded gaps (each at most 5 s), stays open 5 s for the answers and closes with 1000; the result is the new handshake, and its messages follow: read them with hopwire_get_ws_messages on its id. For a WebSocket edit takes only path, setHeaders and removeHeaders. Without edit the stored request is sent byte for byte, credentials and signatures included, and the result says sentAsCaptured: true; with edit it is false. edit changes it: method, path, setHeaders, removeHeaders, and one of body (text), bodyBase64 or jsonSet (RFC 6901 pointers patched into the stored JSON body). Redacted placeholders are refused: leave a field out to keep its stored value. Side effects on the local service are real (database writes, mails). Signed webhooks (Stripe's timestamp tolerance, GitHub's HMAC) may reject an old or edited replay; use the handler's test signing mode. One replay at a time, at most ${REPLAYS_PER_MINUTE} a minute. ${NOTE}`,
|
|
654
760
|
inputSchema: schema({
|
|
655
761
|
id: { type: 'string' },
|
|
656
762
|
responseBodyChars: {
|
|
@@ -698,7 +804,22 @@ const replayTool = {
|
|
|
698
804
|
replayGuard.busy = true;
|
|
699
805
|
try {
|
|
700
806
|
const original = await record(context, id);
|
|
701
|
-
const
|
|
807
|
+
const websocket = isWebSocketHandshake(original.exchange);
|
|
808
|
+
if (websocket &&
|
|
809
|
+
edit !== null &&
|
|
810
|
+
(edit.method !== undefined ||
|
|
811
|
+
edit.body !== undefined ||
|
|
812
|
+
edit.bodyBase64 !== undefined ||
|
|
813
|
+
edit.jsonSet !== undefined)) {
|
|
814
|
+
throw invalidEdit('A WebSocket is replayed with its recorded messages: edit takes only path and headers.');
|
|
815
|
+
}
|
|
816
|
+
const edited = edit === null ? {} : applyEdit(original.exchange.request, edit);
|
|
817
|
+
const overrides = websocket
|
|
818
|
+
? {
|
|
819
|
+
...(edited.path === undefined ? {} : { path: edited.path }),
|
|
820
|
+
...(edited.headers === undefined ? {} : { headers: edited.headers }),
|
|
821
|
+
}
|
|
822
|
+
: edited;
|
|
702
823
|
replayGuard.recent.push(now());
|
|
703
824
|
const answer = await context.client.request('POST',
|
|
704
825
|
// The block that was just read and edited, not whichever block a second lookup of the id finds
|
|
@@ -712,6 +833,17 @@ const replayTool = {
|
|
|
712
833
|
origin: 'own',
|
|
713
834
|
exchange,
|
|
714
835
|
}));
|
|
836
|
+
if (websocket) {
|
|
837
|
+
return {
|
|
838
|
+
original: { id: original.exchange.id, status: original.exchange.response.status },
|
|
839
|
+
sentAsCaptured: edit === null,
|
|
840
|
+
replay: show(summarize(stored)),
|
|
841
|
+
response: { status: exchange.response.status, headers: shownHeaders(exchange.response.headers) },
|
|
842
|
+
messages: exchange.response.status === 101
|
|
843
|
+
? 'The recorded client messages are being sent now; read them and the answers with hopwire_get_ws_messages on the replay id.'
|
|
844
|
+
: null,
|
|
845
|
+
};
|
|
846
|
+
}
|
|
715
847
|
const body = showBody(exchange.response, 0, chars);
|
|
716
848
|
return {
|
|
717
849
|
original: { id: original.exchange.id, status: original.exchange.response.status },
|
|
@@ -730,7 +862,7 @@ const replayTool = {
|
|
|
730
862
|
}
|
|
731
863
|
},
|
|
732
864
|
};
|
|
733
|
-
export const TOOLS = [statusTool, listTool, getTool, waitTool, replayTool];
|
|
865
|
+
export const TOOLS = [statusTool, listTool, getTool, waitTool, wsMessagesTool, replayTool];
|
|
734
866
|
/** The tools offered: --read-only leaves out the one that changes state. */
|
|
735
867
|
export function offeredTools(readOnly) {
|
|
736
868
|
return TOOLS.filter((tool) => !readOnly || tool.name !== 'hopwire_replay');
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { redactJson, redactJsonText, redactUrlEncoded } from '../agent/redact.js';
|
|
3
|
+
import { printable } from '../output.js';
|
|
4
|
+
import { safeText } from './body.js';
|
|
5
|
+
const FORM = /^[^\s=&]+=[^\s&]*(?:&[^\s=&]+=[^\s&]*)*$/;
|
|
6
|
+
/** The text a model may read of one text message, redacted where it can be, or null for one that is no UTF-8. */
|
|
7
|
+
export function messageText(message) {
|
|
8
|
+
if (message.binary) {
|
|
9
|
+
return null;
|
|
10
|
+
}
|
|
11
|
+
let text;
|
|
12
|
+
try {
|
|
13
|
+
text = new TextDecoder('utf-8', { fatal: !message.truncated }).decode(Buffer.from(message.dataBase64, 'base64'));
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
18
|
+
try {
|
|
19
|
+
return { text: JSON.stringify(redactJson(JSON.parse(text))), display: 'json-redacted' };
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
// Not JSON
|
|
23
|
+
}
|
|
24
|
+
if (FORM.test(text)) {
|
|
25
|
+
return { text: redactUrlEncoded(text), display: 'form-redacted' };
|
|
26
|
+
}
|
|
27
|
+
if (/^\s*[[{]/.test(text)) {
|
|
28
|
+
// JSON cut at the capture limit: what looks like a sensitive field is still redacted
|
|
29
|
+
return { text: redactJsonText(text), display: 'as-captured' };
|
|
30
|
+
}
|
|
31
|
+
return { text, display: 'as-captured' };
|
|
32
|
+
}
|
|
33
|
+
export function showWsMessage(message, position, maxChars) {
|
|
34
|
+
const head = {
|
|
35
|
+
position,
|
|
36
|
+
atMs: message.atMs,
|
|
37
|
+
direction: message.direction,
|
|
38
|
+
length: message.length,
|
|
39
|
+
truncatedAtCapture: message.truncated,
|
|
40
|
+
};
|
|
41
|
+
const shown = messageText(message);
|
|
42
|
+
if (shown === null) {
|
|
43
|
+
const raw = Buffer.from(message.dataBase64, 'base64');
|
|
44
|
+
return { ...head, kind: 'binary', sha256: createHash('sha256').update(raw).digest('hex') };
|
|
45
|
+
}
|
|
46
|
+
const text = safeText(shown.text);
|
|
47
|
+
return {
|
|
48
|
+
...head,
|
|
49
|
+
kind: 'text',
|
|
50
|
+
display: shown.display,
|
|
51
|
+
text: text.slice(0, maxChars),
|
|
52
|
+
totalChars: text.length,
|
|
53
|
+
more: text.length > maxChars,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
/** Whether a message matches a substring filter: only text, and only as shown (redacted), never binary. */
|
|
57
|
+
export function messageMatches(message, contains) {
|
|
58
|
+
const shown = messageText(message);
|
|
59
|
+
return shown !== null && shown.text.toLowerCase().includes(contains.toLowerCase());
|
|
60
|
+
}
|
|
61
|
+
export function showClose(close) {
|
|
62
|
+
if (close === undefined) {
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
return {
|
|
66
|
+
code: close.code,
|
|
67
|
+
reason: printable(close.reason),
|
|
68
|
+
by: close.by,
|
|
69
|
+
omittedMessages: close.omittedMessages,
|
|
70
|
+
omittedBytes: close.omittedBytes,
|
|
71
|
+
};
|
|
72
|
+
}
|
package/dist/proxy-server.js
CHANGED
|
@@ -68,6 +68,8 @@ export function createProxyServer(interceptor, source) {
|
|
|
68
68
|
class ProxyServer extends http.Server {
|
|
69
69
|
/** Both ends of every WebSocket that passes through: the client's and the one to the local service */
|
|
70
70
|
tunneled = new Set();
|
|
71
|
+
/** The recorder of every socket to the local service that passes through */
|
|
72
|
+
captures = new Map();
|
|
71
73
|
/** The connections of upgrade requests that are not a WebSocket yet: the local service has not answered */
|
|
72
74
|
upgrading = new Set();
|
|
73
75
|
/**
|
|
@@ -79,6 +81,11 @@ class ProxyServer extends http.Server {
|
|
|
79
81
|
for (const socket of this.upgrading) {
|
|
80
82
|
socket.destroy();
|
|
81
83
|
}
|
|
84
|
+
// Said before any socket closes: a client that answers the close quickly must not be taken for the one
|
|
85
|
+
// that ended the WebSocket
|
|
86
|
+
for (const capture of this.captures.values()) {
|
|
87
|
+
capture.closingBy('hopwire');
|
|
88
|
+
}
|
|
82
89
|
for (const socket of this.tunneled) {
|
|
83
90
|
if (socket.readyState === WebSocket.OPEN) {
|
|
84
91
|
socket.close(WS_CLOSE.goingAway, 'Hopwire stopped');
|
|
@@ -201,7 +208,21 @@ async function tunnelWebSocket(server, accepter, answers, interceptor, source, r
|
|
|
201
208
|
server.tunneled.add(end);
|
|
202
209
|
end.once('close', () => server.tunneled.delete(end));
|
|
203
210
|
}
|
|
204
|
-
|
|
211
|
+
const { capture } = outcome;
|
|
212
|
+
server.captures.set(upstream, capture);
|
|
213
|
+
upstream.once('close', () => server.captures.delete(upstream));
|
|
214
|
+
joinWebSockets(client, upstream, {
|
|
215
|
+
message(from, data, isBinary) {
|
|
216
|
+
if (from === client) {
|
|
217
|
+
capture.inbound(data, isBinary);
|
|
218
|
+
}
|
|
219
|
+
},
|
|
220
|
+
closed(from) {
|
|
221
|
+
if (from === client) {
|
|
222
|
+
capture.closingBy('client');
|
|
223
|
+
}
|
|
224
|
+
},
|
|
225
|
+
});
|
|
205
226
|
// Paused by the interceptor until somebody listens
|
|
206
227
|
upstream.resume();
|
|
207
228
|
}
|
package/dist/serve.js
CHANGED
|
@@ -46,6 +46,7 @@ export async function startServing(options) {
|
|
|
46
46
|
serviceName: service.name,
|
|
47
47
|
log,
|
|
48
48
|
allowAgents: options.share && options.allowAgents === true,
|
|
49
|
+
captureWebSocketMessages: options.captureWebSocketMessages ?? true,
|
|
49
50
|
onExchange: options.onExchange,
|
|
50
51
|
onLogError: () => {
|
|
51
52
|
if (!storeClosing) {
|
package/dist/websocket.js
CHANGED
|
@@ -41,9 +41,9 @@ export function closeLike(socket, code, reason) {
|
|
|
41
41
|
* and a close on one closes the other with the same code and reason. A side that sends faster than the other takes
|
|
42
42
|
* is held back (its socket is not read while more than a window waits to be written), so nothing piles up here.
|
|
43
43
|
*/
|
|
44
|
-
export function joinWebSockets(a, b) {
|
|
45
|
-
carry(a, b);
|
|
46
|
-
carry(b, a);
|
|
44
|
+
export function joinWebSockets(a, b, tap = {}) {
|
|
45
|
+
carry(a, b, tap);
|
|
46
|
+
carry(b, a, tap);
|
|
47
47
|
}
|
|
48
48
|
/**
|
|
49
49
|
* The close code a socket ended itself with when what it received broke the protocol: a message above the limit
|
|
@@ -79,11 +79,12 @@ export function onceClosed(socket, onClose) {
|
|
|
79
79
|
}
|
|
80
80
|
});
|
|
81
81
|
}
|
|
82
|
-
function carry(from, to) {
|
|
82
|
+
function carry(from, to, tap) {
|
|
83
83
|
from.on('message', (data, isBinary) => {
|
|
84
84
|
if (to.readyState !== WebSocket.OPEN) {
|
|
85
85
|
return;
|
|
86
86
|
}
|
|
87
|
+
tap.message?.(from, data, isBinary);
|
|
87
88
|
to.send(data, { binary: isBinary }, () => {
|
|
88
89
|
if (from.isPaused && to.bufferedAmount <= LOW_WATER_BYTES) {
|
|
89
90
|
from.resume();
|
|
@@ -93,7 +94,10 @@ function carry(from, to) {
|
|
|
93
94
|
from.pause();
|
|
94
95
|
}
|
|
95
96
|
});
|
|
96
|
-
onceClosed(from, (code, reason) =>
|
|
97
|
+
onceClosed(from, (code, reason) => {
|
|
98
|
+
tap.closed?.(from);
|
|
99
|
+
closeLike(to, code, reason);
|
|
100
|
+
});
|
|
97
101
|
// A sender that was held back for this socket must still learn that the connection is over
|
|
98
102
|
to.once('close', () => from.resume());
|
|
99
103
|
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { WS_BATCH_INTERVAL_MS, WS_BATCH_MAX_BYTES, WS_BATCH_MAX_MESSAGES, WS_MESSAGES_KIND, WS_MESSAGE_CAPTURE_LIMIT_BYTES, WS_SESSION_CAPTURE_LIMIT_BYTES, WS_SESSION_CAPTURE_LIMIT_MESSAGES, closeReason, } from '@hopwire/protocol';
|
|
2
|
+
import { onceClosed } from './websocket.js';
|
|
3
|
+
/** A WebSocket whose messages are not recorded (--no-ws-capture, capture.websocket false). */
|
|
4
|
+
export const NO_WS_CAPTURE = {
|
|
5
|
+
inbound() { },
|
|
6
|
+
closingBy() { },
|
|
7
|
+
finished: Promise.resolve(),
|
|
8
|
+
};
|
|
9
|
+
export const WS_CAPTURE_LIMITS = {
|
|
10
|
+
messageBytes: WS_MESSAGE_CAPTURE_LIMIT_BYTES,
|
|
11
|
+
sessionBytes: WS_SESSION_CAPTURE_LIMIT_BYTES,
|
|
12
|
+
sessionMessages: WS_SESSION_CAPTURE_LIMIT_MESSAGES,
|
|
13
|
+
batchIntervalMs: WS_BATCH_INTERVAL_MS,
|
|
14
|
+
batchBytes: WS_BATCH_MAX_BYTES,
|
|
15
|
+
batchMessages: WS_BATCH_MAX_MESSAGES,
|
|
16
|
+
};
|
|
17
|
+
export function captureWebSocket(options) {
|
|
18
|
+
const { socket, exchangeId } = options;
|
|
19
|
+
const limits = options.limits ?? WS_CAPTURE_LIMITS;
|
|
20
|
+
const startedAt = performance.now();
|
|
21
|
+
let waiting = [];
|
|
22
|
+
let waitingBytes = 0;
|
|
23
|
+
let seq = 0;
|
|
24
|
+
let capturedBytes = 0;
|
|
25
|
+
let capturedMessages = 0;
|
|
26
|
+
let omittedMessages = 0;
|
|
27
|
+
let omittedBytes = 0;
|
|
28
|
+
let closedBy = null;
|
|
29
|
+
let timer = null;
|
|
30
|
+
let ended = false;
|
|
31
|
+
// Batches are written one after the other and only once the 101 exchange is in the log
|
|
32
|
+
let logged = false;
|
|
33
|
+
let writing = options.handshake.then((exchange) => {
|
|
34
|
+
logged = exchange !== null;
|
|
35
|
+
}, () => { });
|
|
36
|
+
const write = (close) => {
|
|
37
|
+
if (timer !== null) {
|
|
38
|
+
clearTimeout(timer);
|
|
39
|
+
timer = null;
|
|
40
|
+
}
|
|
41
|
+
const block = {
|
|
42
|
+
kind: WS_MESSAGES_KIND,
|
|
43
|
+
exchangeId,
|
|
44
|
+
seq,
|
|
45
|
+
messages: waiting,
|
|
46
|
+
...(close === undefined ? {} : { close }),
|
|
47
|
+
};
|
|
48
|
+
seq += 1;
|
|
49
|
+
waiting = [];
|
|
50
|
+
waitingBytes = 0;
|
|
51
|
+
writing = writing.then(async () => {
|
|
52
|
+
if (!logged) {
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
try {
|
|
56
|
+
await options.append(block);
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
options.onLogError?.(error);
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
};
|
|
63
|
+
const record = (direction, data, binary) => {
|
|
64
|
+
if (ended) {
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
const captured = Math.min(data.byteLength, limits.messageBytes);
|
|
68
|
+
if (capturedMessages >= limits.sessionMessages || capturedBytes + captured > limits.sessionBytes) {
|
|
69
|
+
// Past a limit of the session: still carried in full, only counted
|
|
70
|
+
omittedMessages += 1;
|
|
71
|
+
omittedBytes += data.byteLength;
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
capturedMessages += 1;
|
|
75
|
+
capturedBytes += captured;
|
|
76
|
+
waiting.push({
|
|
77
|
+
atMs: Math.round(performance.now() - startedAt),
|
|
78
|
+
direction,
|
|
79
|
+
binary,
|
|
80
|
+
dataBase64: data.subarray(0, captured).toString('base64'),
|
|
81
|
+
length: data.byteLength,
|
|
82
|
+
truncated: captured < data.byteLength,
|
|
83
|
+
});
|
|
84
|
+
waitingBytes += captured;
|
|
85
|
+
if (waiting.length >= limits.batchMessages || waitingBytes >= limits.batchBytes) {
|
|
86
|
+
write();
|
|
87
|
+
}
|
|
88
|
+
else if (timer === null) {
|
|
89
|
+
timer = setTimeout(() => {
|
|
90
|
+
timer = null;
|
|
91
|
+
if (waiting.length > 0) {
|
|
92
|
+
write();
|
|
93
|
+
}
|
|
94
|
+
}, limits.batchIntervalMs);
|
|
95
|
+
timer.unref();
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
socket.on('message', (data, isBinary) => record('out', toBuffer(data), isBinary));
|
|
99
|
+
let finish = () => { };
|
|
100
|
+
const finished = new Promise((resolve) => {
|
|
101
|
+
finish = resolve;
|
|
102
|
+
});
|
|
103
|
+
onceClosed(socket, (code, reason) => {
|
|
104
|
+
ended = true;
|
|
105
|
+
write({
|
|
106
|
+
code,
|
|
107
|
+
reason: closeReason(reason),
|
|
108
|
+
by: closedBy ?? 'service',
|
|
109
|
+
omittedMessages,
|
|
110
|
+
omittedBytes,
|
|
111
|
+
});
|
|
112
|
+
void writing.then(finish);
|
|
113
|
+
});
|
|
114
|
+
return {
|
|
115
|
+
inbound(data, binary) {
|
|
116
|
+
record('in', data, binary);
|
|
117
|
+
},
|
|
118
|
+
closingBy(by) {
|
|
119
|
+
closedBy ??= by;
|
|
120
|
+
},
|
|
121
|
+
finished,
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
function toBuffer(data) {
|
|
125
|
+
if (Buffer.isBuffer(data)) {
|
|
126
|
+
return data;
|
|
127
|
+
}
|
|
128
|
+
return Array.isArray(data) ? Buffer.concat(data) : Buffer.from(data);
|
|
129
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { setTimeout as sleep } from 'node:timers/promises';
|
|
2
|
+
import { WebSocket } from 'ws';
|
|
3
|
+
import { WS_CLOSE, WS_REPLAY_GAP_CAP_MS, WS_REPLAY_LINGER_MS, } from '@hopwire/protocol';
|
|
4
|
+
const TIMINGS = { gapCapMs: WS_REPLAY_GAP_CAP_MS, lingerMs: WS_REPLAY_LINGER_MS };
|
|
5
|
+
/** The recorded client messages of a WebSocket as a replay sends them. */
|
|
6
|
+
export function recordedInMessages(messages) {
|
|
7
|
+
return messages
|
|
8
|
+
.filter((message) => message.direction === 'in')
|
|
9
|
+
.map(({ binary, dataBase64, atMs }) => ({ binary, dataBase64, atMs }));
|
|
10
|
+
}
|
|
11
|
+
/** The replays of WebSockets that are still running, so a tunnel that stops can end them. */
|
|
12
|
+
export class WsReplays {
|
|
13
|
+
timings;
|
|
14
|
+
running = new Map();
|
|
15
|
+
stopped = false;
|
|
16
|
+
constructor(timings = TIMINGS) {
|
|
17
|
+
this.timings = timings;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Opens the WebSocket and resolves with its handshake as soon as it is in the log: the 101 exchange, or the
|
|
21
|
+
* exchange of the answer when the service refused the upgrade or cannot be reached (a 502). Null when the
|
|
22
|
+
* exchange could not be written to the log. The messages follow on their own.
|
|
23
|
+
*/
|
|
24
|
+
async start(request) {
|
|
25
|
+
const outcome = await request.interceptor.upgrade({
|
|
26
|
+
path: request.path,
|
|
27
|
+
headers: request.headers,
|
|
28
|
+
source: 'replay',
|
|
29
|
+
replayOf: request.replayOf,
|
|
30
|
+
});
|
|
31
|
+
if (!outcome.accepted) {
|
|
32
|
+
// Read to its end, which is what puts the answer into the log
|
|
33
|
+
for await (const chunk of outcome.response.body) {
|
|
34
|
+
void chunk;
|
|
35
|
+
}
|
|
36
|
+
return outcome.response.completed;
|
|
37
|
+
}
|
|
38
|
+
const { socket, capture } = outcome;
|
|
39
|
+
if (this.stopped) {
|
|
40
|
+
capture.closingBy('hopwire');
|
|
41
|
+
socket.close(WS_CLOSE.goingAway, 'Hopwire stopped');
|
|
42
|
+
return outcome.completed;
|
|
43
|
+
}
|
|
44
|
+
this.running.set(socket, capture);
|
|
45
|
+
socket.once('close', () => this.running.delete(socket));
|
|
46
|
+
// The service's answers are recorded by the capture; nobody else reads them
|
|
47
|
+
socket.resume();
|
|
48
|
+
void this.script(socket, capture, request.messages, request.timing);
|
|
49
|
+
return outcome.completed;
|
|
50
|
+
}
|
|
51
|
+
/** Ends every replay that still runs, with 1001. */
|
|
52
|
+
stop() {
|
|
53
|
+
this.stopped = true;
|
|
54
|
+
for (const [socket, capture] of this.running) {
|
|
55
|
+
capture.closingBy('hopwire');
|
|
56
|
+
if (socket.readyState === WebSocket.OPEN) {
|
|
57
|
+
socket.close(WS_CLOSE.goingAway, 'Hopwire stopped');
|
|
58
|
+
}
|
|
59
|
+
else {
|
|
60
|
+
socket.terminate();
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
this.running.clear();
|
|
64
|
+
}
|
|
65
|
+
async script(socket, capture, messages, timing) {
|
|
66
|
+
const closed = new Promise((resolve) => socket.once('close', () => resolve()));
|
|
67
|
+
const open = () => socket.readyState === WebSocket.OPEN;
|
|
68
|
+
/** Waits, and says whether the socket is still open afterwards */
|
|
69
|
+
const pause = async (ms) => {
|
|
70
|
+
if (ms > 0) {
|
|
71
|
+
const controller = new AbortController();
|
|
72
|
+
await Promise.race([closed, sleep(ms, undefined, { signal: controller.signal }).catch(() => { })]);
|
|
73
|
+
controller.abort();
|
|
74
|
+
}
|
|
75
|
+
return open();
|
|
76
|
+
};
|
|
77
|
+
let previousAt = 0;
|
|
78
|
+
for (const message of messages) {
|
|
79
|
+
let gap = 0;
|
|
80
|
+
if (timing === 'recorded' && message.atMs !== undefined) {
|
|
81
|
+
gap = Math.min(this.timings.gapCapMs, Math.max(0, message.atMs - previousAt));
|
|
82
|
+
previousAt = message.atMs;
|
|
83
|
+
}
|
|
84
|
+
if (!(await pause(gap))) {
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
const data = Buffer.from(message.dataBase64, 'base64');
|
|
88
|
+
capture.inbound(data, message.binary);
|
|
89
|
+
socket.send(data, { binary: message.binary });
|
|
90
|
+
}
|
|
91
|
+
if (!(await pause(this.timings.lingerMs))) {
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
capture.closingBy('client');
|
|
95
|
+
socket.close(WS_CLOSE.normal);
|
|
96
|
+
}
|
|
97
|
+
}
|