@johnhenry/browsermesh-transport 0.5.1 → 0.6.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/README.md +181 -2
- package/package.json +13 -4
- package/src/channel-relay.mjs +2 -2
- package/src/cross-origin.mjs +3 -3
- package/src/gateway.mjs +3 -3
- package/src/identity-binding.mjs +181 -0
- package/src/index.mjs +8 -0
- package/src/relay.mjs +2 -2
- package/src/silent-catch.mjs +38 -9
- package/src/streams.mjs +3 -3
- package/src/transport.mjs +48 -6
- package/src/webrtc.mjs +236 -25
- package/src/websocket.mjs +23 -16
- package/src/webtransport.mjs +5 -5
- package/src/wisp-client.mjs +5 -5
- package/src/wisp.mjs +4 -4
- package/src/wsh-bridge.mjs +9 -14
- package/src/wsh-frames.mjs +180 -0
- package/src/wsh-in-process.mjs +82 -0
- package/src/wsh-links.mjs +1005 -0
- package/src/wsh-pod-transport.mjs +159 -0
package/src/websocket.mjs
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { silentCatch } from './silent-catch.mjs'
|
|
2
2
|
import { encodeWireData } from './wire-data.mjs'
|
|
3
3
|
import { resolveIceTransportPolicy } from './webrtc.mjs'
|
|
4
|
+
import { WshLink } from './wsh-links.mjs'
|
|
4
5
|
import { padTo, unpad } from '@johnhenry/browsermesh-primitives';
|
|
5
6
|
/**
|
|
6
|
-
// STATUS: INTEGRATED — wired into
|
|
7
|
-
*
|
|
7
|
+
// STATUS: INTEGRATED — wired into the `Pod` lifecycle (@johnhenry/browsermesh-pod), proven via E2E testing
|
|
8
|
+
* websocket.mjs -- WebSocket, WebRTC & WebTransport Adapters.
|
|
8
9
|
*
|
|
9
10
|
* Concrete transport implementations for the BrowserMesh transport
|
|
10
11
|
* abstraction layer. Each adapter wraps a browser API (WebSocket,
|
|
@@ -15,7 +16,7 @@ import { padTo, unpad } from '@johnhenry/browsermesh-primitives';
|
|
|
15
16
|
* negotiates the best available transport for a given peer pair.
|
|
16
17
|
*
|
|
17
18
|
* Run tests:
|
|
18
|
-
* node --import ./
|
|
19
|
+
* cd packages/browsermesh-transport && node --import ./test/_setup-globals.mjs --test test/websocket.test.mjs
|
|
19
20
|
*/
|
|
20
21
|
|
|
21
22
|
// ---------------------------------------------------------------------------
|
|
@@ -457,7 +458,7 @@ export class WebSocketTransport {
|
|
|
457
458
|
*/
|
|
458
459
|
_fireEvent(event, data) {
|
|
459
460
|
for (const cb of this.#callbacks[event] || []) {
|
|
460
|
-
try { cb(data); } catch (e) { silentCatch('
|
|
461
|
+
try { cb(data); } catch (e) { silentCatch('websocket', 'swallow-listener-errors', e) }
|
|
461
462
|
}
|
|
462
463
|
}
|
|
463
464
|
|
|
@@ -508,7 +509,7 @@ export class WebSocketTransport {
|
|
|
508
509
|
try {
|
|
509
510
|
this.#dispatch(ping);
|
|
510
511
|
this.#stats.lastPingMs = Date.now();
|
|
511
|
-
} catch (e) { silentCatch('
|
|
512
|
+
} catch (e) { silentCatch('websocket', 'ignore-send-errors-during-heartbeat', e) }
|
|
512
513
|
}, this.#heartbeatIntervalMs);
|
|
513
514
|
}
|
|
514
515
|
|
|
@@ -546,8 +547,8 @@ const BULK_CHANNEL_LABEL = 'mesh-bulk';
|
|
|
546
547
|
|
|
547
548
|
/**
|
|
548
549
|
* `ordered: false`, still fully reliable (no `maxRetransmits`/
|
|
549
|
-
* `maxPacketLifeTime`). Justified by
|
|
550
|
-
* (
|
|
550
|
+
* `maxPacketLifeTime`). Justified by the host application's chunk reassembly
|
|
551
|
+
* (its mesh file-transfer module), which addresses each chunk by content hash
|
|
551
552
|
* plus offset and dedupes into a `Set` -- no order dependency -- so an
|
|
552
553
|
* out-of-order chunk on this channel reassembles identically to an in-order
|
|
553
554
|
* one, and unordered delivery also avoids head-of-line blocking *within*
|
|
@@ -689,7 +690,7 @@ export class WebRTCTransport {
|
|
|
689
690
|
const offs = this.#signalerOffs;
|
|
690
691
|
this.#signalerOffs = [];
|
|
691
692
|
for (const off of offs) {
|
|
692
|
-
try { off(); } catch (e) { silentCatch('
|
|
693
|
+
try { off(); } catch (e) { silentCatch('websocket', 'signaler-unsubscribe', e) }
|
|
693
694
|
}
|
|
694
695
|
}
|
|
695
696
|
|
|
@@ -739,7 +740,7 @@ export class WebRTCTransport {
|
|
|
739
740
|
// addIceCandidate docblock records this being fixed there; this path
|
|
740
741
|
// still had it.
|
|
741
742
|
Promise.resolve(this.#pc.addIceCandidate(data.candidate)).catch((e) => {
|
|
742
|
-
silentCatch('
|
|
743
|
+
silentCatch('websocket', 'ignore-rejected-ice-candidate', e);
|
|
743
744
|
});
|
|
744
745
|
}
|
|
745
746
|
}));
|
|
@@ -842,7 +843,7 @@ export class WebRTCTransport {
|
|
|
842
843
|
// See connect()'s identical handler: the promise must not be
|
|
843
844
|
// dropped, for the same reason.
|
|
844
845
|
Promise.resolve(this.#pc.addIceCandidate(data.candidate)).catch((e) => {
|
|
845
|
-
silentCatch('
|
|
846
|
+
silentCatch('websocket', 'ignore-rejected-ice-candidate', e);
|
|
846
847
|
});
|
|
847
848
|
}
|
|
848
849
|
}));
|
|
@@ -934,10 +935,10 @@ export class WebRTCTransport {
|
|
|
934
935
|
async close() {
|
|
935
936
|
this.#state = 'closing';
|
|
936
937
|
if (this.#dataChannel) {
|
|
937
|
-
try { this.#dataChannel.close(); } catch (e) { silentCatch('
|
|
938
|
+
try { this.#dataChannel.close(); } catch (e) { silentCatch('websocket', 'this', e) }
|
|
938
939
|
}
|
|
939
940
|
if (this.#bulkChannel) {
|
|
940
|
-
try { this.#bulkChannel.close(); } catch (e) { silentCatch('
|
|
941
|
+
try { this.#bulkChannel.close(); } catch (e) { silentCatch('websocket', 'this', e) }
|
|
941
942
|
}
|
|
942
943
|
if (this.#pc) {
|
|
943
944
|
this.#pc.close();
|
|
@@ -1037,7 +1038,7 @@ export class WebRTCTransport {
|
|
|
1037
1038
|
*/
|
|
1038
1039
|
_fireEvent(event, data) {
|
|
1039
1040
|
for (const cb of this.#callbacks[event] || []) {
|
|
1040
|
-
try { cb(data); } catch (e) { silentCatch('
|
|
1041
|
+
try { cb(data); } catch (e) { silentCatch('websocket', 'swallow-listener-errors', e) }
|
|
1041
1042
|
}
|
|
1042
1043
|
}
|
|
1043
1044
|
}
|
|
@@ -1173,10 +1174,10 @@ export class WebTransportTransport {
|
|
|
1173
1174
|
if (this.#state === 'closed' || this.#state === 'disconnected') return;
|
|
1174
1175
|
this.#state = 'closing';
|
|
1175
1176
|
if (this.#writer) {
|
|
1176
|
-
try { await this.#writer.close(); } catch (e) { silentCatch('
|
|
1177
|
+
try { await this.#writer.close(); } catch (e) { silentCatch('websocket', 'this', e) }
|
|
1177
1178
|
}
|
|
1178
1179
|
if (this.#transport) {
|
|
1179
|
-
try { this.#transport.close(); } catch (e) { silentCatch('
|
|
1180
|
+
try { this.#transport.close(); } catch (e) { silentCatch('websocket', 'this', e) }
|
|
1180
1181
|
}
|
|
1181
1182
|
this.#state = 'closed';
|
|
1182
1183
|
this._fireEvent('close');
|
|
@@ -1234,7 +1235,7 @@ export class WebTransportTransport {
|
|
|
1234
1235
|
*/
|
|
1235
1236
|
_fireEvent(event, data) {
|
|
1236
1237
|
for (const cb of this.#callbacks[event] || []) {
|
|
1237
|
-
try { cb(data); } catch (e) { silentCatch('
|
|
1238
|
+
try { cb(data); } catch (e) { silentCatch('websocket', 'swallow-listener-errors', e) }
|
|
1238
1239
|
}
|
|
1239
1240
|
}
|
|
1240
1241
|
}
|
|
@@ -1417,6 +1418,12 @@ export class TransportFactory {
|
|
|
1417
1418
|
...opts,
|
|
1418
1419
|
_WebTransport: this.#WebTransportCtor,
|
|
1419
1420
|
});
|
|
1421
|
+
case 'wsh': {
|
|
1422
|
+
// The sealed wsh peer link: `{ links: WshPeerLinks, peerPodId }`. Not
|
|
1423
|
+
// part of getSupportedTypes()/negotiate(): it is only ever asked for.
|
|
1424
|
+
if (!opts?.links || !opts?.peerPodId) throw new Error("create('wsh') needs { links, peerPodId }");
|
|
1425
|
+
return new WshLink(opts.links, opts.peerPodId);
|
|
1426
|
+
}
|
|
1420
1427
|
default:
|
|
1421
1428
|
throw new Error(`Unknown transport type: ${type}`);
|
|
1422
1429
|
}
|
package/src/webtransport.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
// STATUS: INTEGRATED — wired into
|
|
3
|
-
*
|
|
2
|
+
// STATUS: INTEGRATED — wired into the `Pod` lifecycle (@johnhenry/browsermesh-pod), proven via E2E testing
|
|
3
|
+
* webtransport.mjs -- WebTransport transport bridge.
|
|
4
4
|
*
|
|
5
5
|
* Extends MeshTransport with WebTransport API support. Provides
|
|
6
6
|
* datagram and bidirectional stream communication. Falls back gracefully
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
* No browser-only imports at module level.
|
|
10
10
|
*
|
|
11
11
|
* Run tests:
|
|
12
|
-
* node --import ./
|
|
12
|
+
* cd packages/browsermesh-transport && node --import ./test/_setup-globals.mjs --test test/webtransport.test.mjs
|
|
13
13
|
*/
|
|
14
14
|
|
|
15
15
|
import { MeshTransport } from './transport.mjs'
|
|
@@ -127,11 +127,11 @@ export class WebTransportBridge extends MeshTransport {
|
|
|
127
127
|
this._setState('closing')
|
|
128
128
|
this.#streams.clear()
|
|
129
129
|
if (this.#writer) {
|
|
130
|
-
try { this.#writer.close() } catch (e) { silentCatch('
|
|
130
|
+
try { this.#writer.close() } catch (e) { silentCatch('webtransport', 'this', e) }
|
|
131
131
|
this.#writer = null
|
|
132
132
|
}
|
|
133
133
|
if (this.#transport) {
|
|
134
|
-
try { this.#transport.close() } catch (e) { silentCatch('
|
|
134
|
+
try { this.#transport.close() } catch (e) { silentCatch('webtransport', 'this', e) }
|
|
135
135
|
this.#transport = null
|
|
136
136
|
}
|
|
137
137
|
this._setState('closed')
|
package/src/wisp-client.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { silentCatch } from './silent-catch.mjs'
|
|
2
2
|
/**
|
|
3
|
-
*
|
|
3
|
+
* wisp-client.mjs -- WISP (WebSocket Internet Subprotocol) Transport.
|
|
4
4
|
*
|
|
5
5
|
* Multiplexes TCP streams over a single WebSocket connection to a WISP
|
|
6
6
|
* relay server. Each stream gets a unique 32-bit stream ID. Messages
|
|
@@ -17,10 +17,10 @@ import { silentCatch } from './silent-catch.mjs'
|
|
|
17
17
|
* 0x05 INFO — relay→client: server info (WISP v2 extension)
|
|
18
18
|
*
|
|
19
19
|
* Can be used standalone for tunneling or as the backing transport for
|
|
20
|
-
*
|
|
20
|
+
* wisp.mjs (WSH adapter).
|
|
21
21
|
*
|
|
22
22
|
* Run tests:
|
|
23
|
-
* node --import ./
|
|
23
|
+
* cd packages/browsermesh-transport && node --import ./test/_setup-globals.mjs --test test/wisp-client.test.mjs
|
|
24
24
|
*/
|
|
25
25
|
|
|
26
26
|
// ---------------------------------------------------------------------------
|
|
@@ -313,7 +313,7 @@ export class WispStream {
|
|
|
313
313
|
*/
|
|
314
314
|
_fireEvent(event, data) {
|
|
315
315
|
for (const cb of this.#callbacks[event] || []) {
|
|
316
|
-
try { cb(data) } catch (e) { silentCatch('
|
|
316
|
+
try { cb(data) } catch (e) { silentCatch('wisp-client', 'swallow-listener-errors', e) }
|
|
317
317
|
}
|
|
318
318
|
}
|
|
319
319
|
|
|
@@ -741,7 +741,7 @@ export class WispClient {
|
|
|
741
741
|
*/
|
|
742
742
|
_fireEvent(event, data) {
|
|
743
743
|
for (const cb of this.#callbacks[event] || []) {
|
|
744
|
-
try { cb(data) } catch (e) { silentCatch('
|
|
744
|
+
try { cb(data) } catch (e) { silentCatch('wisp-client', 'swallow-listener-errors', e) }
|
|
745
745
|
}
|
|
746
746
|
}
|
|
747
747
|
}
|
package/src/wisp.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* wisp.mjs -- WISP Transport Adapter for WSH.
|
|
3
3
|
*
|
|
4
4
|
* Adapts a WispClient as a mesh transport that can carry WSH protocol
|
|
5
5
|
* messages through a WISP relay tunnel. WSH commands are serialized
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
* opened for data transfer, RPC, or mesh relay connections.
|
|
8
8
|
*
|
|
9
9
|
* Implements the same interface as WebSocketTransport from
|
|
10
|
-
*
|
|
10
|
+
* websocket.mjs so it can be used interchangeably.
|
|
11
11
|
*
|
|
12
12
|
* Standalone uses beyond WSH:
|
|
13
13
|
* - Exposing RPC mode over a tunneled port
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
* - Future v86 guest networking
|
|
16
16
|
*
|
|
17
17
|
* Run tests:
|
|
18
|
-
* node --import ./
|
|
18
|
+
* cd packages/browsermesh-transport && node --import ./test/_setup-globals.mjs --test test/wisp.test.mjs
|
|
19
19
|
*/
|
|
20
20
|
|
|
21
21
|
import { WispClient, WispStream, WISP_DATA } from './wisp-client.mjs'
|
|
@@ -342,7 +342,7 @@ export class WispTransport {
|
|
|
342
342
|
*/
|
|
343
343
|
_fireEvent(event, data) {
|
|
344
344
|
for (const cb of this.#callbacks[event] || []) {
|
|
345
|
-
try { cb(data) } catch (e) { silentCatch('
|
|
345
|
+
try { cb(data) } catch (e) { silentCatch('wisp', 'swallow-listener-errors', e) }
|
|
346
346
|
}
|
|
347
347
|
}
|
|
348
348
|
}
|
package/src/wsh-bridge.mjs
CHANGED
|
@@ -9,21 +9,18 @@
|
|
|
9
9
|
*
|
|
10
10
|
* This bridge converts between the two formats and syncs keys.
|
|
11
11
|
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
* is no
|
|
15
|
-
*
|
|
16
|
-
*
|
|
12
|
+
* The wsh peer-link transport (`wsh-links.mjs`) does not construct this
|
|
13
|
+
* class: a link authenticates with the pod's own key (a `PodIdentity`), so
|
|
14
|
+
* there is no key store to sync. The two format conversions here ARE that
|
|
15
|
+
* transport's (`podIdToFingerprint` / `fingerprintToPodId`, one source of
|
|
16
|
+
* truth), and the class stays for consumers that maintain both a
|
|
17
|
+
* WshKeyStore and a MeshIdentityManager and need to keep them in sync.
|
|
17
18
|
*
|
|
18
19
|
* Run tests: `npm test` in this package (runs `test/wsh-bridge.test.mjs`
|
|
19
20
|
* along with the rest of the suite).
|
|
20
21
|
*/
|
|
21
22
|
|
|
22
|
-
import {
|
|
23
|
-
derivePodId,
|
|
24
|
-
encodeBase64url,
|
|
25
|
-
decodeBase64url,
|
|
26
|
-
} from '@johnhenry/browsermesh-primitives';
|
|
23
|
+
import { podIdToFingerprint, fingerprintToPodId } from './wsh-links.mjs';
|
|
27
24
|
|
|
28
25
|
// ---------------------------------------------------------------------------
|
|
29
26
|
// Hex <-> Base64url conversion helpers
|
|
@@ -90,8 +87,7 @@ export class MeshWshBridge {
|
|
|
90
87
|
* @returns {string} Base64url-encoded pod ID
|
|
91
88
|
*/
|
|
92
89
|
fingerprint2podId(hex) {
|
|
93
|
-
|
|
94
|
-
return encodeBase64url(bytes);
|
|
90
|
+
return fingerprintToPodId(hex);
|
|
95
91
|
}
|
|
96
92
|
|
|
97
93
|
/**
|
|
@@ -100,8 +96,7 @@ export class MeshWshBridge {
|
|
|
100
96
|
* @returns {string} Hex-encoded fingerprint
|
|
101
97
|
*/
|
|
102
98
|
podId2fingerprint(b64url) {
|
|
103
|
-
|
|
104
|
-
return bytesToHex(bytes);
|
|
99
|
+
return podIdToFingerprint(b64url);
|
|
105
100
|
}
|
|
106
101
|
|
|
107
102
|
/**
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* wsh-frames.mjs -- message boundaries for a mesh link carried on a wsh
|
|
3
|
+
* named endpoint.
|
|
4
|
+
*
|
|
5
|
+
* A wsh endpoint is a duplex byte stream with credit based flow control and
|
|
6
|
+
* no message boundaries. A mesh frame on it is
|
|
7
|
+
*
|
|
8
|
+
* u32 big-endian length | u8 kind | payload
|
|
9
|
+
*
|
|
10
|
+
* where `length` counts the kind byte and the payload. Kind 0 is binary and
|
|
11
|
+
* kind 1 is UTF-8 text. Strings and binary go out unchanged and any other
|
|
12
|
+
* value as its JSON text, the rule every adapter in this package follows
|
|
13
|
+
* (`encodeWireData`).
|
|
14
|
+
*
|
|
15
|
+
* The limit is checked on the HEADER, before any payload is buffered, so a
|
|
16
|
+
* peer cannot make a reader allocate by announcing a large frame.
|
|
17
|
+
*
|
|
18
|
+
* Pure and browser-safe: no imports beyond a sibling helper.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { encodeWireData } from './wire-data.mjs';
|
|
22
|
+
|
|
23
|
+
export const FRAME_KIND_BINARY = 0;
|
|
24
|
+
export const FRAME_KIND_TEXT = 1;
|
|
25
|
+
|
|
26
|
+
/** Default largest frame (kind byte included): 1 MiB. */
|
|
27
|
+
export const DEFAULT_MAX_FRAME_BYTES = 1024 * 1024;
|
|
28
|
+
|
|
29
|
+
/** Hard ceiling for `maxFrameBytes`: the length field is a u32. */
|
|
30
|
+
const MAX_POSSIBLE = 0xffffffff;
|
|
31
|
+
|
|
32
|
+
export class WshFrameError extends Error {
|
|
33
|
+
/**
|
|
34
|
+
* @param {'WSH_FRAME_TOO_LARGE'|'WSH_BAD_FRAME'} code
|
|
35
|
+
* @param {string} message
|
|
36
|
+
*/
|
|
37
|
+
constructor(code, message) {
|
|
38
|
+
super(message);
|
|
39
|
+
this.name = 'WshFrameError';
|
|
40
|
+
this.code = code;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const textEncoder = new TextEncoder();
|
|
45
|
+
const textDecoder = new TextDecoder('utf-8', { fatal: true });
|
|
46
|
+
|
|
47
|
+
/** @param {unknown} v */
|
|
48
|
+
function checkLimit(v) {
|
|
49
|
+
if (!Number.isSafeInteger(v) || v < 2 || v > MAX_POSSIBLE) {
|
|
50
|
+
throw new TypeError('maxFrameBytes must be an integer between 2 and 4294967295');
|
|
51
|
+
}
|
|
52
|
+
return v;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Frame one outgoing value.
|
|
57
|
+
*
|
|
58
|
+
* @param {*} data - string, ArrayBuffer, typed array, or anything JSON can carry
|
|
59
|
+
* @param {{ maxFrameBytes?: number }} [opts]
|
|
60
|
+
* @returns {Uint8Array}
|
|
61
|
+
* @throws {WshFrameError} `WSH_FRAME_TOO_LARGE` when the frame would exceed the limit
|
|
62
|
+
* @throws {TypeError} for values that have no wire form (`undefined`, functions)
|
|
63
|
+
*/
|
|
64
|
+
export function encodeFrame(data, { maxFrameBytes = DEFAULT_MAX_FRAME_BYTES } = {}) {
|
|
65
|
+
checkLimit(maxFrameBytes);
|
|
66
|
+
const wire = encodeWireData(data);
|
|
67
|
+
let kind;
|
|
68
|
+
let payload;
|
|
69
|
+
if (typeof wire === 'string') {
|
|
70
|
+
kind = FRAME_KIND_TEXT;
|
|
71
|
+
payload = textEncoder.encode(wire);
|
|
72
|
+
} else if (wire instanceof ArrayBuffer) {
|
|
73
|
+
kind = FRAME_KIND_BINARY;
|
|
74
|
+
payload = new Uint8Array(wire);
|
|
75
|
+
} else if (ArrayBuffer.isView(wire)) {
|
|
76
|
+
kind = FRAME_KIND_BINARY;
|
|
77
|
+
payload = new Uint8Array(wire.buffer, wire.byteOffset, wire.byteLength);
|
|
78
|
+
} else {
|
|
79
|
+
throw new TypeError('a wsh link carries strings, binary and JSON values, not Blobs');
|
|
80
|
+
}
|
|
81
|
+
const length = payload.length + 1;
|
|
82
|
+
if (length > maxFrameBytes) {
|
|
83
|
+
throw new WshFrameError('WSH_FRAME_TOO_LARGE', `frame of ${length} bytes exceeds the limit of ${maxFrameBytes}`);
|
|
84
|
+
}
|
|
85
|
+
const out = new Uint8Array(4 + length);
|
|
86
|
+
new DataView(out.buffer).setUint32(0, length);
|
|
87
|
+
out[4] = kind;
|
|
88
|
+
out.set(payload, 5);
|
|
89
|
+
return out;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Incremental reader: feed it the chunks of the endpoint's readable side, get
|
|
94
|
+
* whole frames back. After it throws it is dead (a link that framed badly is
|
|
95
|
+
* closed by the caller; it must not resynchronise).
|
|
96
|
+
*/
|
|
97
|
+
export class FrameDecoder {
|
|
98
|
+
#max;
|
|
99
|
+
#chunks = [];
|
|
100
|
+
#buffered = 0;
|
|
101
|
+
#want = -1; // length of the frame being assembled, -1 while the header is incomplete
|
|
102
|
+
#dead = false;
|
|
103
|
+
|
|
104
|
+
/** @param {{ maxFrameBytes?: number }} [opts] */
|
|
105
|
+
constructor({ maxFrameBytes = DEFAULT_MAX_FRAME_BYTES } = {}) {
|
|
106
|
+
this.#max = checkLimit(maxFrameBytes);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Bytes held for a frame that is not complete yet. */
|
|
110
|
+
get bufferedBytes() { return this.#buffered; }
|
|
111
|
+
|
|
112
|
+
#fail(code, message) {
|
|
113
|
+
this.#dead = true;
|
|
114
|
+
this.#chunks = [];
|
|
115
|
+
this.#buffered = 0;
|
|
116
|
+
throw new WshFrameError(code, message);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
#take(n) {
|
|
120
|
+
const out = new Uint8Array(n);
|
|
121
|
+
let o = 0;
|
|
122
|
+
while (o < n) {
|
|
123
|
+
const head = this.#chunks[0];
|
|
124
|
+
const need = n - o;
|
|
125
|
+
if (head.length <= need) {
|
|
126
|
+
out.set(head, o);
|
|
127
|
+
o += head.length;
|
|
128
|
+
this.#chunks.shift();
|
|
129
|
+
} else {
|
|
130
|
+
out.set(head.subarray(0, need), o);
|
|
131
|
+
this.#chunks[0] = head.subarray(need);
|
|
132
|
+
o += need;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
this.#buffered -= n;
|
|
136
|
+
return out;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* @param {Uint8Array} chunk
|
|
141
|
+
* @returns {Array<string|Uint8Array>} the frames completed by this chunk, in order
|
|
142
|
+
*/
|
|
143
|
+
push(chunk) {
|
|
144
|
+
if (this.#dead) throw new WshFrameError('WSH_BAD_FRAME', 'the stream is not usable after a framing error');
|
|
145
|
+
if (chunk.length) {
|
|
146
|
+
this.#chunks.push(chunk);
|
|
147
|
+
this.#buffered += chunk.length;
|
|
148
|
+
}
|
|
149
|
+
const frames = [];
|
|
150
|
+
for (;;) {
|
|
151
|
+
if (this.#want < 0) {
|
|
152
|
+
if (this.#buffered < 4) break;
|
|
153
|
+
const len = new DataView(this.#take(4).buffer).getUint32(0);
|
|
154
|
+
if (len > this.#max) this.#fail('WSH_FRAME_TOO_LARGE', `peer announced a frame of ${len} bytes; the limit is ${this.#max}`);
|
|
155
|
+
if (len < 1) this.#fail('WSH_BAD_FRAME', 'empty frame (no kind byte)');
|
|
156
|
+
this.#want = len;
|
|
157
|
+
}
|
|
158
|
+
if (this.#buffered < this.#want) break;
|
|
159
|
+
const body = this.#take(this.#want);
|
|
160
|
+
this.#want = -1;
|
|
161
|
+
const kind = body[0];
|
|
162
|
+
const payload = body.subarray(1);
|
|
163
|
+
if (kind === FRAME_KIND_TEXT) {
|
|
164
|
+
try { frames.push(textDecoder.decode(payload)); } catch { this.#fail('WSH_BAD_FRAME', 'text frame is not valid UTF-8'); }
|
|
165
|
+
} else if (kind === FRAME_KIND_BINARY) {
|
|
166
|
+
frames.push(payload.slice());
|
|
167
|
+
} else {
|
|
168
|
+
this.#fail('WSH_BAD_FRAME', `unknown frame kind ${kind}`);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
return frames;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** The stream ended: it must not end inside a frame. */
|
|
175
|
+
end() {
|
|
176
|
+
if (this.#want >= 0 || this.#buffered > 0) {
|
|
177
|
+
this.#fail('WSH_BAD_FRAME', 'the stream ended inside a frame');
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* wsh-in-process.mjs -- a wsh pipe relay that lives in this process, for tests
|
|
3
|
+
* and examples: no network, no ports.
|
|
4
|
+
*
|
|
5
|
+
* `createInProcessPipeRelay()` returns a `WebSocket` constructor that dials the
|
|
6
|
+
* relay (`new env.WebSocket(pipeUrl)`), so a `WshPeerLinks` takes it as
|
|
7
|
+
* `{ WebSocket: env.WebSocket }` and two pods link in one process through the
|
|
8
|
+
* real pipe relay, the real wsh handshake and the real sealed session.
|
|
9
|
+
*
|
|
10
|
+
* The relay can also misbehave on request, which is how the tests show what a
|
|
11
|
+
* hostile relay cannot do. Every byte it copies is recorded in `env.recorded`
|
|
12
|
+
* (`{ to: 'host'|'operator', id, bytes }`, `to` being the role it was written
|
|
13
|
+
* to), `env.tap` may change, drop, repeat or add to what it writes, and
|
|
14
|
+
* `env.dropAll()` ends every pipe at once.
|
|
15
|
+
*
|
|
16
|
+
* Needs `@johnhenry/wsh` (imported on the call).
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* @param {object} [opts]
|
|
21
|
+
* @param {(info: { to: 'host'|'operator', id: string, bytes: Uint8Array }) => (Uint8Array | Uint8Array[] | null | undefined)} [opts.tap]
|
|
22
|
+
* Called for every message the relay writes. Return `undefined` to pass it through, `null` to drop it, or one or more
|
|
23
|
+
* `Uint8Array`s to write instead.
|
|
24
|
+
* @param {object} [opts.relayOptions] - Options for `createPipeRelay()`.
|
|
25
|
+
*/
|
|
26
|
+
export async function createInProcessPipeRelay({ tap = null, relayOptions } = {}) {
|
|
27
|
+
let pipeRelay;
|
|
28
|
+
let memory;
|
|
29
|
+
try {
|
|
30
|
+
pipeRelay = await import('@johnhenry/wsh/pipe-relay');
|
|
31
|
+
memory = await import('@johnhenry/wsh/memory');
|
|
32
|
+
} catch (cause) {
|
|
33
|
+
throw new Error('createInProcessPipeRelay needs @johnhenry/wsh (npm install @johnhenry/wsh)', { cause });
|
|
34
|
+
}
|
|
35
|
+
const relay = pipeRelay.createPipeRelay(relayOptions);
|
|
36
|
+
const sockets = new Set();
|
|
37
|
+
const env = {
|
|
38
|
+
relay,
|
|
39
|
+
recorded: [],
|
|
40
|
+
tap,
|
|
41
|
+
stats: () => relay.stats(),
|
|
42
|
+
/** End every pipe, as a relay restart would. */
|
|
43
|
+
dropAll() {
|
|
44
|
+
for (const s of [...sockets]) { try { s.close(1012, 'relay restarted'); } catch { /* already closed */ } }
|
|
45
|
+
},
|
|
46
|
+
async close() {
|
|
47
|
+
env.dropAll();
|
|
48
|
+
await relay.close();
|
|
49
|
+
},
|
|
50
|
+
WebSocket: null,
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
const toBytes = (data) => (data instanceof ArrayBuffer
|
|
54
|
+
? new Uint8Array(data)
|
|
55
|
+
: new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
|
|
56
|
+
|
|
57
|
+
env.WebSocket = class InProcessWebSocket {
|
|
58
|
+
constructor(url) {
|
|
59
|
+
const u = new URL(url);
|
|
60
|
+
const id = u.pathname.split('/').pop();
|
|
61
|
+
const role = u.searchParams.get('role') === 'host' ? 'host' : 'operator';
|
|
62
|
+
const [client, server] = memory.createSocketPair();
|
|
63
|
+
const send = server.send.bind(server);
|
|
64
|
+
server.send = (data) => {
|
|
65
|
+
const bytes = toBytes(data);
|
|
66
|
+
env.recorded.push({ to: role, id, bytes: bytes.slice() });
|
|
67
|
+
let out = [bytes];
|
|
68
|
+
if (env.tap) {
|
|
69
|
+
const r = env.tap({ to: role, id, bytes });
|
|
70
|
+
if (r === null) out = [];
|
|
71
|
+
else if (r !== undefined) out = Array.isArray(r) ? r : [r];
|
|
72
|
+
}
|
|
73
|
+
for (const b of out) send(b);
|
|
74
|
+
};
|
|
75
|
+
sockets.add(server);
|
|
76
|
+
server.addEventListener('close', () => sockets.delete(server));
|
|
77
|
+
void relay.accept(server, { id, role }).catch(() => {});
|
|
78
|
+
return client;
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
return env;
|
|
82
|
+
}
|