@johnhenry/browsermesh-transport 0.5.0 → 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 +35 -18
- 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
|
// ---------------------------------------------------------------------------
|
|
@@ -165,6 +166,9 @@ export class WebSocketTransport {
|
|
|
165
166
|
/** @type {Set<*>} Outstanding jitter timers, cleared on close */
|
|
166
167
|
#jitterTimers = new Set();
|
|
167
168
|
|
|
169
|
+
/** FIFO delivery is independent of timer scheduling and clock rounding. */
|
|
170
|
+
#jitterQueue = [];
|
|
171
|
+
|
|
168
172
|
/** @type {number} Earliest time the next jittered send may fire (keeps order) */
|
|
169
173
|
#nextSendAt = 0;
|
|
170
174
|
|
|
@@ -320,10 +324,16 @@ export class WebSocketTransport {
|
|
|
320
324
|
const now = Date.now();
|
|
321
325
|
const at = Math.max(now + Math.random() * this.#jitterMs, this.#nextSendAt);
|
|
322
326
|
this.#nextSendAt = at;
|
|
327
|
+
const entry = { wire, ws, ready: false };
|
|
328
|
+
this.#jitterQueue.push(entry);
|
|
323
329
|
const timer = setTimeout(() => {
|
|
324
330
|
this.#jitterTimers.delete(timer);
|
|
325
|
-
|
|
326
|
-
|
|
331
|
+
entry.ready = true;
|
|
332
|
+
while (this.#jitterQueue[0]?.ready) {
|
|
333
|
+
const next = this.#jitterQueue.shift();
|
|
334
|
+
if (this.#ws !== next.ws || !this.connected) continue;
|
|
335
|
+
try { next.ws.send(next.wire); } catch (e) { this._fireEvent('error', e); }
|
|
336
|
+
}
|
|
327
337
|
}, Math.max(0, at - now));
|
|
328
338
|
this.#jitterTimers.add(timer);
|
|
329
339
|
}
|
|
@@ -332,6 +342,7 @@ export class WebSocketTransport {
|
|
|
332
342
|
#clearJitter() {
|
|
333
343
|
for (const t of this.#jitterTimers) clearTimeout(t);
|
|
334
344
|
this.#jitterTimers.clear();
|
|
345
|
+
this.#jitterQueue.length = 0;
|
|
335
346
|
this.#nextSendAt = 0;
|
|
336
347
|
}
|
|
337
348
|
|
|
@@ -447,7 +458,7 @@ export class WebSocketTransport {
|
|
|
447
458
|
*/
|
|
448
459
|
_fireEvent(event, data) {
|
|
449
460
|
for (const cb of this.#callbacks[event] || []) {
|
|
450
|
-
try { cb(data); } catch (e) { silentCatch('
|
|
461
|
+
try { cb(data); } catch (e) { silentCatch('websocket', 'swallow-listener-errors', e) }
|
|
451
462
|
}
|
|
452
463
|
}
|
|
453
464
|
|
|
@@ -498,7 +509,7 @@ export class WebSocketTransport {
|
|
|
498
509
|
try {
|
|
499
510
|
this.#dispatch(ping);
|
|
500
511
|
this.#stats.lastPingMs = Date.now();
|
|
501
|
-
} catch (e) { silentCatch('
|
|
512
|
+
} catch (e) { silentCatch('websocket', 'ignore-send-errors-during-heartbeat', e) }
|
|
502
513
|
}, this.#heartbeatIntervalMs);
|
|
503
514
|
}
|
|
504
515
|
|
|
@@ -536,8 +547,8 @@ const BULK_CHANNEL_LABEL = 'mesh-bulk';
|
|
|
536
547
|
|
|
537
548
|
/**
|
|
538
549
|
* `ordered: false`, still fully reliable (no `maxRetransmits`/
|
|
539
|
-
* `maxPacketLifeTime`). Justified by
|
|
540
|
-
* (
|
|
550
|
+
* `maxPacketLifeTime`). Justified by the host application's chunk reassembly
|
|
551
|
+
* (its mesh file-transfer module), which addresses each chunk by content hash
|
|
541
552
|
* plus offset and dedupes into a `Set` -- no order dependency -- so an
|
|
542
553
|
* out-of-order chunk on this channel reassembles identically to an in-order
|
|
543
554
|
* one, and unordered delivery also avoids head-of-line blocking *within*
|
|
@@ -679,7 +690,7 @@ export class WebRTCTransport {
|
|
|
679
690
|
const offs = this.#signalerOffs;
|
|
680
691
|
this.#signalerOffs = [];
|
|
681
692
|
for (const off of offs) {
|
|
682
|
-
try { off(); } catch (e) { silentCatch('
|
|
693
|
+
try { off(); } catch (e) { silentCatch('websocket', 'signaler-unsubscribe', e) }
|
|
683
694
|
}
|
|
684
695
|
}
|
|
685
696
|
|
|
@@ -729,7 +740,7 @@ export class WebRTCTransport {
|
|
|
729
740
|
// addIceCandidate docblock records this being fixed there; this path
|
|
730
741
|
// still had it.
|
|
731
742
|
Promise.resolve(this.#pc.addIceCandidate(data.candidate)).catch((e) => {
|
|
732
|
-
silentCatch('
|
|
743
|
+
silentCatch('websocket', 'ignore-rejected-ice-candidate', e);
|
|
733
744
|
});
|
|
734
745
|
}
|
|
735
746
|
}));
|
|
@@ -832,7 +843,7 @@ export class WebRTCTransport {
|
|
|
832
843
|
// See connect()'s identical handler: the promise must not be
|
|
833
844
|
// dropped, for the same reason.
|
|
834
845
|
Promise.resolve(this.#pc.addIceCandidate(data.candidate)).catch((e) => {
|
|
835
|
-
silentCatch('
|
|
846
|
+
silentCatch('websocket', 'ignore-rejected-ice-candidate', e);
|
|
836
847
|
});
|
|
837
848
|
}
|
|
838
849
|
}));
|
|
@@ -924,10 +935,10 @@ export class WebRTCTransport {
|
|
|
924
935
|
async close() {
|
|
925
936
|
this.#state = 'closing';
|
|
926
937
|
if (this.#dataChannel) {
|
|
927
|
-
try { this.#dataChannel.close(); } catch (e) { silentCatch('
|
|
938
|
+
try { this.#dataChannel.close(); } catch (e) { silentCatch('websocket', 'this', e) }
|
|
928
939
|
}
|
|
929
940
|
if (this.#bulkChannel) {
|
|
930
|
-
try { this.#bulkChannel.close(); } catch (e) { silentCatch('
|
|
941
|
+
try { this.#bulkChannel.close(); } catch (e) { silentCatch('websocket', 'this', e) }
|
|
931
942
|
}
|
|
932
943
|
if (this.#pc) {
|
|
933
944
|
this.#pc.close();
|
|
@@ -1027,7 +1038,7 @@ export class WebRTCTransport {
|
|
|
1027
1038
|
*/
|
|
1028
1039
|
_fireEvent(event, data) {
|
|
1029
1040
|
for (const cb of this.#callbacks[event] || []) {
|
|
1030
|
-
try { cb(data); } catch (e) { silentCatch('
|
|
1041
|
+
try { cb(data); } catch (e) { silentCatch('websocket', 'swallow-listener-errors', e) }
|
|
1031
1042
|
}
|
|
1032
1043
|
}
|
|
1033
1044
|
}
|
|
@@ -1163,10 +1174,10 @@ export class WebTransportTransport {
|
|
|
1163
1174
|
if (this.#state === 'closed' || this.#state === 'disconnected') return;
|
|
1164
1175
|
this.#state = 'closing';
|
|
1165
1176
|
if (this.#writer) {
|
|
1166
|
-
try { await this.#writer.close(); } catch (e) { silentCatch('
|
|
1177
|
+
try { await this.#writer.close(); } catch (e) { silentCatch('websocket', 'this', e) }
|
|
1167
1178
|
}
|
|
1168
1179
|
if (this.#transport) {
|
|
1169
|
-
try { this.#transport.close(); } catch (e) { silentCatch('
|
|
1180
|
+
try { this.#transport.close(); } catch (e) { silentCatch('websocket', 'this', e) }
|
|
1170
1181
|
}
|
|
1171
1182
|
this.#state = 'closed';
|
|
1172
1183
|
this._fireEvent('close');
|
|
@@ -1224,7 +1235,7 @@ export class WebTransportTransport {
|
|
|
1224
1235
|
*/
|
|
1225
1236
|
_fireEvent(event, data) {
|
|
1226
1237
|
for (const cb of this.#callbacks[event] || []) {
|
|
1227
|
-
try { cb(data); } catch (e) { silentCatch('
|
|
1238
|
+
try { cb(data); } catch (e) { silentCatch('websocket', 'swallow-listener-errors', e) }
|
|
1228
1239
|
}
|
|
1229
1240
|
}
|
|
1230
1241
|
}
|
|
@@ -1407,6 +1418,12 @@ export class TransportFactory {
|
|
|
1407
1418
|
...opts,
|
|
1408
1419
|
_WebTransport: this.#WebTransportCtor,
|
|
1409
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
|
+
}
|
|
1410
1427
|
default:
|
|
1411
1428
|
throw new Error(`Unknown transport type: ${type}`);
|
|
1412
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
|
+
}
|