@johnhenry/browsermesh-transport 0.3.3 → 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/README.md +45 -0
- package/package.json +1 -1
- package/src/webrtc.mjs +66 -4
- package/src/websocket.mjs +166 -6
package/README.md
CHANGED
|
@@ -61,6 +61,51 @@ parses it (`@johnhenry/browsermesh-apps`' `ctx.onIncomingData()` does). A custom
|
|
|
61
61
|
`WebRTCTransport.send(data, { channel })` takes `'control'` (default) or
|
|
62
62
|
`'bulk'` and falls back to control when the bulk channel is not open.
|
|
63
63
|
|
|
64
|
+
## TURN-only pods: `iceTransportPolicy`
|
|
65
|
+
|
|
66
|
+
By default a pod that has configured a TURN server still gathers host and
|
|
67
|
+
server-reflexive candidates, so its public IP reaches every peer it negotiates
|
|
68
|
+
with. To avoid that, pass `iceTransportPolicy: 'relay'`; the browser then
|
|
69
|
+
gathers only relayed (TURN) candidates:
|
|
70
|
+
|
|
71
|
+
```js
|
|
72
|
+
const mesh = new WebRTCMeshManager({
|
|
73
|
+
localPodId,
|
|
74
|
+
iceServers: [{ urls: 'turns:turn.example.com:443', username, credential }],
|
|
75
|
+
iceTransportPolicy: 'relay',
|
|
76
|
+
});
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
It is accepted by `WebRTCPeerConnection`, `WebRTCMeshManager`, `WebRTCTransport`
|
|
80
|
+
(also as `config.iceTransportPolicy`) and `TransportFactory` (a default for the
|
|
81
|
+
`'webrtc'` transports it creates), and forwarded verbatim to
|
|
82
|
+
`RTCPeerConnection`. `'relay'` with no `turn:`/`turns:` entry in `iceServers`
|
|
83
|
+
throws at construction, because relay-only gathering without a TURN server
|
|
84
|
+
yields zero candidates and the connection would just hang. Leaving the option
|
|
85
|
+
out keeps the browser default (`'all'`).
|
|
86
|
+
|
|
87
|
+
## Size-bucket padding and send jitter (opt-in)
|
|
88
|
+
|
|
89
|
+
A relay that only sees ciphertext still learns exact payload sizes, which for
|
|
90
|
+
short agent messages distinguishes message types. Padding rounds each message
|
|
91
|
+
up to a bucket size (`padTo()`/`unpad()` in `@johnhenry/browsermesh-primitives`;
|
|
92
|
+
default buckets 256 / 1024 / 4096 / 16384 bytes, larger payloads round up to a
|
|
93
|
+
multiple of 16384). It is off by default. Hiding sizes from a relay requires
|
|
94
|
+
padding *inside* the end-to-end seal:
|
|
95
|
+
|
|
96
|
+
- **Group-key envelopes** (`@johnhenry/browsermesh-core`):
|
|
97
|
+
`groupKeys.encrypt(bytes, { padding: true })` and
|
|
98
|
+
`groupKeys.decrypt(ct, iv, epoch, { padding: true })`.
|
|
99
|
+
- **`WebSocketTransport`** (what talks to a relay): `new WebSocketTransport({ url,
|
|
100
|
+
padding: true })` sends every frame as a binary frame padded to a bucket
|
|
101
|
+
(text and binary round-trip; both ends must enable it) and `jitterMs: 50`
|
|
102
|
+
adds a random 0..50 ms delay to each send, order preserved. A transport-level
|
|
103
|
+
frame is visible to whoever terminates the WebSocket, so on its own this
|
|
104
|
+
hides sizes from network observers, not from the relay; combine it with
|
|
105
|
+
padding inside the seal for relay-blind payloads.
|
|
106
|
+
|
|
107
|
+
Constant-rate cover traffic is deliberately not provided.
|
|
108
|
+
|
|
64
109
|
## License
|
|
65
110
|
|
|
66
111
|
MIT
|
package/package.json
CHANGED
package/src/webrtc.mjs
CHANGED
|
@@ -103,6 +103,48 @@ export function mergeIceServers(userServers, defaults = DEFAULT_ICE_SERVERS) {
|
|
|
103
103
|
return [...defaults, ...valid]
|
|
104
104
|
}
|
|
105
105
|
|
|
106
|
+
/**
|
|
107
|
+
* True when `iceServers` contains at least one `turn:` / `turns:` URL.
|
|
108
|
+
*
|
|
109
|
+
* @param {RTCIceServer[]} [iceServers]
|
|
110
|
+
* @returns {boolean}
|
|
111
|
+
*/
|
|
112
|
+
export function hasTurnServer(iceServers) {
|
|
113
|
+
return (Array.isArray(iceServers) ? iceServers : []).some((server) => {
|
|
114
|
+
const urls = server && server.urls
|
|
115
|
+
const list = Array.isArray(urls) ? urls : [urls]
|
|
116
|
+
return list.some((u) => typeof u === 'string' && /^turns?:/i.test(u))
|
|
117
|
+
})
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Validate an `iceTransportPolicy` against the ICE servers it will run with.
|
|
122
|
+
*
|
|
123
|
+
* `'relay'` makes the browser gather only relayed (TURN) candidates, so the
|
|
124
|
+
* pod's host and server-reflexive addresses are never disclosed to peers or
|
|
125
|
+
* to the STUN host. With no TURN server it would silently gather zero
|
|
126
|
+
* candidates and never connect, so that combination is rejected up front.
|
|
127
|
+
*
|
|
128
|
+
* @param {'all'|'relay'|undefined|null} policy
|
|
129
|
+
* @param {RTCIceServer[]} iceServers
|
|
130
|
+
* @returns {'all'|'relay'|undefined} The policy to forward, or undefined to leave the browser default
|
|
131
|
+
* @throws {TypeError} For a value other than 'all' or 'relay'
|
|
132
|
+
* @throws {Error} For 'relay' with no `turn:`/`turns:` server
|
|
133
|
+
*/
|
|
134
|
+
export function resolveIceTransportPolicy(policy, iceServers) {
|
|
135
|
+
if (policy === undefined || policy === null) return undefined
|
|
136
|
+
if (policy !== 'all' && policy !== 'relay') {
|
|
137
|
+
throw new TypeError(`iceTransportPolicy must be 'all' or 'relay', got ${JSON.stringify(policy)}`)
|
|
138
|
+
}
|
|
139
|
+
if (policy === 'relay' && !hasTurnServer(iceServers)) {
|
|
140
|
+
throw new Error(
|
|
141
|
+
"iceTransportPolicy 'relay' requires at least one turn:/turns: entry in iceServers " +
|
|
142
|
+
'(relay-only gathering with no TURN server yields no candidates)'
|
|
143
|
+
)
|
|
144
|
+
}
|
|
145
|
+
return policy
|
|
146
|
+
}
|
|
147
|
+
|
|
106
148
|
/**
|
|
107
149
|
* How many remote ICE candidates to hold while waiting for the remote
|
|
108
150
|
* description. A handful of interfaces gather a handful of candidates each;
|
|
@@ -181,6 +223,7 @@ export class WebRTCPeerConnection {
|
|
|
181
223
|
*/
|
|
182
224
|
#bulkChannel = null
|
|
183
225
|
#iceServers
|
|
226
|
+
#iceTransportPolicy
|
|
184
227
|
#onLog
|
|
185
228
|
#state = 'new' // new | connecting | connected | failed | closed
|
|
186
229
|
|
|
@@ -205,18 +248,24 @@ export class WebRTCPeerConnection {
|
|
|
205
248
|
* @param {string} opts.localPodId - This pod's identifier
|
|
206
249
|
* @param {string} opts.remotePodId - Target pod's identifier
|
|
207
250
|
* @param {RTCIceServer[]} [opts.iceServers]
|
|
251
|
+
* @param {'all'|'relay'} [opts.iceTransportPolicy] - Forwarded verbatim to
|
|
252
|
+
* `RTCPeerConnection`. `'relay'` gathers TURN candidates only, so host and
|
|
253
|
+
* server-reflexive addresses are never disclosed; it requires a
|
|
254
|
+
* `turn:`/`turns:` entry in `iceServers` and throws otherwise. Omitted by
|
|
255
|
+
* default (browser default, `'all'`).
|
|
208
256
|
* @param {Function} [opts.onLog] - Optional logging callback
|
|
209
257
|
* @param {number} [opts.disconnectedGraceMs=5000] - How long a peer connection
|
|
210
258
|
* may sit in the transient `disconnected` state before it is reported
|
|
211
259
|
* through `onError()`. `failed` is reported immediately and is not
|
|
212
260
|
* subject to this delay.
|
|
213
261
|
*/
|
|
214
|
-
constructor({ localPodId, remotePodId, iceServers, onLog, disconnectedGraceMs = 5000 } = {}) {
|
|
262
|
+
constructor({ localPodId, remotePodId, iceServers, iceTransportPolicy, onLog, disconnectedGraceMs = 5000 } = {}) {
|
|
215
263
|
if (!localPodId) throw new Error('localPodId is required')
|
|
216
264
|
if (!remotePodId) throw new Error('remotePodId is required')
|
|
217
265
|
this.#localPodId = localPodId
|
|
218
266
|
this.#remotePodId = remotePodId
|
|
219
267
|
this.#iceServers = iceServers || [...DEFAULT_ICE_SERVERS]
|
|
268
|
+
this.#iceTransportPolicy = resolveIceTransportPolicy(iceTransportPolicy, this.#iceServers)
|
|
220
269
|
this.#onLog = onLog || null
|
|
221
270
|
this.#disconnectedGraceMs = disconnectedGraceMs
|
|
222
271
|
}
|
|
@@ -251,6 +300,13 @@ export class WebRTCPeerConnection {
|
|
|
251
300
|
return this.#bulkChannel?.readyState === 'open'
|
|
252
301
|
}
|
|
253
302
|
|
|
303
|
+
/** The RTCConfiguration handed to every RTCPeerConnection this class creates. */
|
|
304
|
+
#rtcConfig() {
|
|
305
|
+
const config = { iceServers: this.#iceServers }
|
|
306
|
+
if (this.#iceTransportPolicy) config.iceTransportPolicy = this.#iceTransportPolicy
|
|
307
|
+
return config
|
|
308
|
+
}
|
|
309
|
+
|
|
254
310
|
// -- Offer / Answer -------------------------------------------------------
|
|
255
311
|
|
|
256
312
|
/**
|
|
@@ -262,7 +318,7 @@ export class WebRTCPeerConnection {
|
|
|
262
318
|
*/
|
|
263
319
|
async createOffer() {
|
|
264
320
|
this.#ensureNotClosed()
|
|
265
|
-
this.#pc = new RTCPeerConnection(
|
|
321
|
+
this.#pc = new RTCPeerConnection(this.#rtcConfig())
|
|
266
322
|
this.#setupIceHandling()
|
|
267
323
|
this.#setupConnectionStateHandling()
|
|
268
324
|
|
|
@@ -348,7 +404,7 @@ export class WebRTCPeerConnection {
|
|
|
348
404
|
// unreachable and, with a native stack, keeps threads and sockets alive.
|
|
349
405
|
this.#releasePeerConnection()
|
|
350
406
|
|
|
351
|
-
this.#pc = new RTCPeerConnection(
|
|
407
|
+
this.#pc = new RTCPeerConnection(this.#rtcConfig())
|
|
352
408
|
this.#setupIceHandling()
|
|
353
409
|
this.#setupConnectionStateHandling()
|
|
354
410
|
|
|
@@ -1050,6 +1106,7 @@ export const DEFAULT_CONNECTION_ID = 'default'
|
|
|
1050
1106
|
export class WebRTCMeshManager {
|
|
1051
1107
|
#localPodId
|
|
1052
1108
|
#iceServers
|
|
1109
|
+
#iceTransportPolicy
|
|
1053
1110
|
#connections = new Map() // remotePodId -> Map<connectionId, WebRTCPeerConnection>
|
|
1054
1111
|
#onLog
|
|
1055
1112
|
#messageCbs = []
|
|
@@ -1065,6 +1122,9 @@ export class WebRTCMeshManager {
|
|
|
1065
1122
|
* @param {object} opts
|
|
1066
1123
|
* @param {string} opts.localPodId
|
|
1067
1124
|
* @param {RTCIceServer[]} [opts.iceServers]
|
|
1125
|
+
* @param {'all'|'relay'} [opts.iceTransportPolicy] - Passed to every connection.
|
|
1126
|
+
* `'relay'` (TURN-only) never gathers host/srflx candidates; it requires a
|
|
1127
|
+
* `turn:`/`turns:` entry in `iceServers` and throws here otherwise.
|
|
1068
1128
|
* @param {Function} [opts.onLog]
|
|
1069
1129
|
* @param {number} [opts.maxReconnectAttempts=5] - Give up auto-reconnecting after this many failures
|
|
1070
1130
|
* @param {number} [opts.reconnectBaseDelayMs=1000] - Backoff base; doubles each attempt
|
|
@@ -1073,12 +1133,13 @@ export class WebRTCMeshManager {
|
|
|
1073
1133
|
* before it counts as an error worth reconnecting over.
|
|
1074
1134
|
*/
|
|
1075
1135
|
constructor({
|
|
1076
|
-
localPodId, iceServers, onLog,
|
|
1136
|
+
localPodId, iceServers, iceTransportPolicy, onLog,
|
|
1077
1137
|
maxReconnectAttempts = 5, reconnectBaseDelayMs = 1000, disconnectedGraceMs = 5000,
|
|
1078
1138
|
} = {}) {
|
|
1079
1139
|
if (!localPodId) throw new Error('localPodId is required')
|
|
1080
1140
|
this.#localPodId = localPodId
|
|
1081
1141
|
this.#iceServers = iceServers || [...DEFAULT_ICE_SERVERS]
|
|
1142
|
+
this.#iceTransportPolicy = resolveIceTransportPolicy(iceTransportPolicy, this.#iceServers)
|
|
1082
1143
|
this.#onLog = onLog || null
|
|
1083
1144
|
this.#maxReconnectAttempts = maxReconnectAttempts
|
|
1084
1145
|
this.#reconnectBaseDelayMs = reconnectBaseDelayMs
|
|
@@ -1147,6 +1208,7 @@ export class WebRTCMeshManager {
|
|
|
1147
1208
|
localPodId: this.#localPodId,
|
|
1148
1209
|
remotePodId,
|
|
1149
1210
|
iceServers: this.#iceServers,
|
|
1211
|
+
iceTransportPolicy: this.#iceTransportPolicy,
|
|
1150
1212
|
onLog: this.#onLog,
|
|
1151
1213
|
disconnectedGraceMs: this.#disconnectedGraceMs,
|
|
1152
1214
|
})
|
package/src/websocket.mjs
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
import { silentCatch } from './silent-catch.mjs'
|
|
2
2
|
import { encodeWireData } from './wire-data.mjs'
|
|
3
|
+
import { resolveIceTransportPolicy } from './webrtc.mjs'
|
|
4
|
+
// Namespace import, not `import { padTo, unpad }`: padding needs primitives >= 0.3.0,
|
|
5
|
+
// but this package's peer range still admits 0.2.x, and a missing named export
|
|
6
|
+
// would fail to link (breaking the whole transport package) instead of only `padding`.
|
|
7
|
+
import * as primitives from '@johnhenry/browsermesh-primitives'
|
|
3
8
|
/**
|
|
4
9
|
// STATUS: INTEGRATED — wired into ClawserPod lifecycle, proven via E2E testing
|
|
5
10
|
* clawser-mesh-websocket.js -- WebSocket, WebRTC & WebTransport Adapters.
|
|
@@ -44,6 +49,67 @@ function byteLength(data) {
|
|
|
44
49
|
return 0;
|
|
45
50
|
}
|
|
46
51
|
|
|
52
|
+
/** The padding functions, or a clear error when primitives predates 0.3.0. */
|
|
53
|
+
function paddingFns() {
|
|
54
|
+
if (typeof primitives.padTo !== 'function' || typeof primitives.unpad !== 'function') {
|
|
55
|
+
throw new Error('padding requires @johnhenry/browsermesh-primitives >= 0.3.0');
|
|
56
|
+
}
|
|
57
|
+
return primitives;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** First byte of a padded frame: the payload is raw bytes. */
|
|
61
|
+
const PAD_FRAME_BINARY = 0;
|
|
62
|
+
/** First byte of a padded frame: the payload is UTF-8 text. */
|
|
63
|
+
const PAD_FRAME_TEXT = 1;
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Wrap an outgoing wire value in a size-bucketed frame:
|
|
67
|
+
* `[kind byte][payload]`, padded with `padTo()`. Always binary on the wire.
|
|
68
|
+
* @param {string|ArrayBuffer|ArrayBufferView} wire - Output of encodeWireData()
|
|
69
|
+
* @param {{ buckets?: number[] }} padding
|
|
70
|
+
* @returns {Uint8Array}
|
|
71
|
+
*/
|
|
72
|
+
function padFrame(wire, padding) {
|
|
73
|
+
let kind;
|
|
74
|
+
let payload;
|
|
75
|
+
if (typeof wire === 'string') {
|
|
76
|
+
kind = PAD_FRAME_TEXT;
|
|
77
|
+
payload = new TextEncoder().encode(wire);
|
|
78
|
+
} else if (wire instanceof ArrayBuffer) {
|
|
79
|
+
kind = PAD_FRAME_BINARY;
|
|
80
|
+
payload = new Uint8Array(wire);
|
|
81
|
+
} else if (ArrayBuffer.isView(wire)) {
|
|
82
|
+
kind = PAD_FRAME_BINARY;
|
|
83
|
+
payload = new Uint8Array(wire.buffer, wire.byteOffset, wire.byteLength);
|
|
84
|
+
} else {
|
|
85
|
+
throw new TypeError('padding cannot be applied to a Blob; send a string, ArrayBuffer or typed array');
|
|
86
|
+
}
|
|
87
|
+
const framed = new Uint8Array(payload.length + 1);
|
|
88
|
+
framed[0] = kind;
|
|
89
|
+
framed.set(payload, 1);
|
|
90
|
+
return paddingFns().padTo(framed, padding);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Inverse of {@link padFrame}. Returns a string for text frames and a
|
|
95
|
+
* `Uint8Array` for binary ones.
|
|
96
|
+
* @param {*} data - A received ArrayBuffer / typed array
|
|
97
|
+
* @returns {string|Uint8Array}
|
|
98
|
+
* @throws {Error} When `data` is not a padded frame
|
|
99
|
+
*/
|
|
100
|
+
function unpadFrame(data) {
|
|
101
|
+
let bytes;
|
|
102
|
+
if (data instanceof ArrayBuffer) bytes = new Uint8Array(data);
|
|
103
|
+
else if (ArrayBuffer.isView(data)) bytes = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
|
104
|
+
else throw new Error('padding is enabled but a non-binary frame arrived (is the peer padding too?)');
|
|
105
|
+
const framed = paddingFns().unpad(bytes);
|
|
106
|
+
if (framed.length < 1) throw new Error('padded frame is empty');
|
|
107
|
+
const body = framed.subarray(1);
|
|
108
|
+
if (framed[0] === PAD_FRAME_TEXT) return new TextDecoder().decode(body);
|
|
109
|
+
if (framed[0] === PAD_FRAME_BINARY) return body.slice();
|
|
110
|
+
throw new Error(`unknown padded frame kind ${framed[0]}`);
|
|
111
|
+
}
|
|
112
|
+
|
|
47
113
|
/** Valid event names for WebSocketTransport */
|
|
48
114
|
const WS_EVENTS = Object.freeze(['open', 'message', 'close', 'error', 'reconnect']);
|
|
49
115
|
|
|
@@ -101,6 +167,18 @@ export class WebSocketTransport {
|
|
|
101
167
|
/** @type {number|null} */
|
|
102
168
|
#heartbeatTimer = null;
|
|
103
169
|
|
|
170
|
+
/** @type {false|{ buckets?: number[] }} Size-bucket padding for outgoing/incoming frames */
|
|
171
|
+
#padding;
|
|
172
|
+
|
|
173
|
+
/** @type {number} Max random delay (ms) added before each send; 0 = off */
|
|
174
|
+
#jitterMs;
|
|
175
|
+
|
|
176
|
+
/** @type {Set<*>} Outstanding jitter timers, cleared on close */
|
|
177
|
+
#jitterTimers = new Set();
|
|
178
|
+
|
|
179
|
+
/** @type {number} Earliest time the next jittered send may fire (keeps order) */
|
|
180
|
+
#nextSendAt = 0;
|
|
181
|
+
|
|
104
182
|
/** @type {{ open: Function[], message: Function[], close: Function[], error: Function[], reconnect: Function[] }} */
|
|
105
183
|
#callbacks = { open: [], message: [], close: [], error: [], reconnect: [] };
|
|
106
184
|
|
|
@@ -115,10 +193,28 @@ export class WebSocketTransport {
|
|
|
115
193
|
* @param {number} [opts.maxReconnectAttempts=5] - Max reconnection attempts
|
|
116
194
|
* @param {number} [opts.reconnectDelayMs=1000] - Base delay between reconnects
|
|
117
195
|
* @param {number} [opts.heartbeatIntervalMs=30000] - Heartbeat interval
|
|
196
|
+
* @param {boolean|{ buckets?: number[] }} [opts.padding=false] - Opt in to
|
|
197
|
+
* size-bucket padding: every frame goes out as a binary frame padded to a
|
|
198
|
+
* bucket size (`true` = 256/1024/4096/16384), and incoming frames are
|
|
199
|
+
* unpadded. BOTH ends must enable it. It hides message sizes from network
|
|
200
|
+
* observers; it does not hide them from a relay that reads the frame,
|
|
201
|
+
* so for relay-blind payloads pad inside the end-to-end seal instead
|
|
202
|
+
* (e.g. `GroupKeyManager.encrypt(data, { padding: true })`).
|
|
203
|
+
* @param {number} [opts.jitterMs=0] - Delay each send by a random 0..jitterMs
|
|
204
|
+
* milliseconds (order preserved) for coarse timing decorrelation.
|
|
118
205
|
* @param {Function} [opts._WebSocket] - Injectable WebSocket constructor
|
|
119
206
|
*/
|
|
120
207
|
constructor(opts = {}) {
|
|
121
208
|
if (!opts.url) throw new Error('url is required');
|
|
209
|
+
if (opts.jitterMs !== undefined && !(Number.isFinite(opts.jitterMs) && opts.jitterMs >= 0)) {
|
|
210
|
+
throw new TypeError('jitterMs must be a non-negative number');
|
|
211
|
+
}
|
|
212
|
+
if (opts.padding && opts.padding !== true && typeof opts.padding !== 'object') {
|
|
213
|
+
throw new TypeError('padding must be a boolean or { buckets }');
|
|
214
|
+
}
|
|
215
|
+
this.#padding = opts.padding ? (opts.padding === true ? {} : { buckets: opts.padding.buckets }) : false;
|
|
216
|
+
if (this.#padding) paddingFns();
|
|
217
|
+
this.#jitterMs = opts.jitterMs ?? 0;
|
|
122
218
|
this.#url = opts.url;
|
|
123
219
|
this.#protocols = opts.protocols || [];
|
|
124
220
|
this.#reconnect = opts.reconnect !== undefined ? opts.reconnect : true;
|
|
@@ -167,6 +263,8 @@ export class WebSocketTransport {
|
|
|
167
263
|
return new Promise((resolve, reject) => {
|
|
168
264
|
try {
|
|
169
265
|
this.#ws = new this.#WebSocketCtor(this.#url, this.#protocols.length ? this.#protocols : undefined);
|
|
266
|
+
// Padded frames are binary; ask for ArrayBuffer so they arrive synchronously (not as Blobs).
|
|
267
|
+
if (this.#padding) this.#ws.binaryType = 'arraybuffer';
|
|
170
268
|
} catch (err) {
|
|
171
269
|
this.#state = 'disconnected';
|
|
172
270
|
return reject(err);
|
|
@@ -210,12 +308,45 @@ export class WebSocketTransport {
|
|
|
210
308
|
*/
|
|
211
309
|
send(data) {
|
|
212
310
|
if (!this.connected) throw new Error('Not connected');
|
|
213
|
-
const wire = encodeWireData(data);
|
|
214
|
-
this.#
|
|
311
|
+
const wire = this.#frameOut(encodeWireData(data));
|
|
312
|
+
this.#dispatch(wire);
|
|
215
313
|
this.#stats.messagesSent++;
|
|
216
314
|
this.#stats.bytesOut += byteLength(wire);
|
|
217
315
|
}
|
|
218
316
|
|
|
317
|
+
/** Apply size-bucket padding when enabled. */
|
|
318
|
+
#frameOut(wire) {
|
|
319
|
+
return this.#padding ? padFrame(wire, this.#padding) : wire;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* Hand a frame to the socket, after a random delay when `jitterMs` is set.
|
|
324
|
+
* Delayed sends keep their order: a send never fires before an earlier one.
|
|
325
|
+
*/
|
|
326
|
+
#dispatch(wire) {
|
|
327
|
+
const ws = this.#ws;
|
|
328
|
+
if (!(this.#jitterMs > 0)) {
|
|
329
|
+
ws.send(wire);
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
const now = Date.now();
|
|
333
|
+
const at = Math.max(now + Math.random() * this.#jitterMs, this.#nextSendAt);
|
|
334
|
+
this.#nextSendAt = at;
|
|
335
|
+
const timer = setTimeout(() => {
|
|
336
|
+
this.#jitterTimers.delete(timer);
|
|
337
|
+
if (this.#ws !== ws || !this.connected) return;
|
|
338
|
+
try { ws.send(wire); } catch (e) { this._fireEvent('error', e); }
|
|
339
|
+
}, Math.max(0, at - now));
|
|
340
|
+
this.#jitterTimers.add(timer);
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** Cancel sends still waiting out their jitter delay. */
|
|
344
|
+
#clearJitter() {
|
|
345
|
+
for (const t of this.#jitterTimers) clearTimeout(t);
|
|
346
|
+
this.#jitterTimers.clear();
|
|
347
|
+
this.#nextSendAt = 0;
|
|
348
|
+
}
|
|
349
|
+
|
|
219
350
|
/**
|
|
220
351
|
* Close the WebSocket connection gracefully.
|
|
221
352
|
* @param {number} [code]
|
|
@@ -227,6 +358,7 @@ export class WebSocketTransport {
|
|
|
227
358
|
this.#userClosed = true;
|
|
228
359
|
this.#state = 'closing';
|
|
229
360
|
this._stopHeartbeat();
|
|
361
|
+
this.#clearJitter();
|
|
230
362
|
|
|
231
363
|
if (this.#ws) {
|
|
232
364
|
return new Promise((resolve) => {
|
|
@@ -282,15 +414,24 @@ export class WebSocketTransport {
|
|
|
282
414
|
|
|
283
415
|
/** @type {(ev: { data: * }) => void} */
|
|
284
416
|
#onMessage = (ev) => {
|
|
285
|
-
|
|
417
|
+
let data = ev.data;
|
|
286
418
|
this.#stats.messagesReceived++;
|
|
287
419
|
this.#stats.bytesIn += byteLength(data);
|
|
420
|
+
if (this.#padding) {
|
|
421
|
+
try {
|
|
422
|
+
data = unpadFrame(data);
|
|
423
|
+
} catch (err) {
|
|
424
|
+
this._fireEvent('error', err);
|
|
425
|
+
return;
|
|
426
|
+
}
|
|
427
|
+
}
|
|
288
428
|
this._fireEvent('message', data);
|
|
289
429
|
};
|
|
290
430
|
|
|
291
431
|
/** @type {(ev: { code: number, reason: string }) => void} */
|
|
292
432
|
#onClose = (ev) => {
|
|
293
433
|
this._stopHeartbeat();
|
|
434
|
+
this.#clearJitter();
|
|
294
435
|
if (this.#userClosed) {
|
|
295
436
|
this.#state = 'closed';
|
|
296
437
|
this._fireEvent('close', ev);
|
|
@@ -365,9 +506,9 @@ export class WebSocketTransport {
|
|
|
365
506
|
this._stopHeartbeat();
|
|
366
507
|
this.#heartbeatTimer = setInterval(() => {
|
|
367
508
|
if (!this.connected || !this.#ws) return;
|
|
368
|
-
const ping = JSON.stringify({ type: 'ping', ts: Date.now() });
|
|
509
|
+
const ping = this.#frameOut(JSON.stringify({ type: 'ping', ts: Date.now() }));
|
|
369
510
|
try {
|
|
370
|
-
this.#
|
|
511
|
+
this.#dispatch(ping);
|
|
371
512
|
this.#stats.lastPingMs = Date.now();
|
|
372
513
|
} catch (e) { silentCatch('clawser-mesh-websocket', 'ignore-send-errors-during-heartbeat', e) }
|
|
373
514
|
}, this.#heartbeatIntervalMs);
|
|
@@ -471,6 +612,11 @@ export class WebRTCTransport {
|
|
|
471
612
|
* @param {string} opts.remotePodId - Remote pod identifier
|
|
472
613
|
* @param {object} opts.signaler - Signaling channel
|
|
473
614
|
* @param {object} [opts.config] - RTCConfiguration
|
|
615
|
+
* @param {'all'|'relay'} [opts.iceTransportPolicy] - Shorthand for
|
|
616
|
+
* `config.iceTransportPolicy` (this option wins if both are given).
|
|
617
|
+
* `'relay'` gathers TURN candidates only, so host and server-reflexive
|
|
618
|
+
* addresses are never disclosed; it requires a `turn:`/`turns:` entry in
|
|
619
|
+
* `config.iceServers` and throws otherwise.
|
|
474
620
|
* @param {Function} [opts._RTCPeerConnection] - Injectable constructor
|
|
475
621
|
*/
|
|
476
622
|
constructor(opts = {}) {
|
|
@@ -480,7 +626,12 @@ export class WebRTCTransport {
|
|
|
480
626
|
this.#localPodId = opts.localPodId;
|
|
481
627
|
this.#remotePodId = opts.remotePodId;
|
|
482
628
|
this.#signaler = opts.signaler;
|
|
483
|
-
this.#config = opts.config || {};
|
|
629
|
+
this.#config = { ...(opts.config || {}) };
|
|
630
|
+
const policy = resolveIceTransportPolicy(
|
|
631
|
+
opts.iceTransportPolicy ?? this.#config.iceTransportPolicy,
|
|
632
|
+
this.#config.iceServers,
|
|
633
|
+
);
|
|
634
|
+
if (policy) this.#config.iceTransportPolicy = policy;
|
|
484
635
|
this.#RTCPeerConnectionCtor = opts._RTCPeerConnection || globalThis.RTCPeerConnection;
|
|
485
636
|
}
|
|
486
637
|
|
|
@@ -1150,6 +1301,9 @@ export class TransportFactory {
|
|
|
1150
1301
|
/** @type {NATTraversal|null} */
|
|
1151
1302
|
#natTraversal;
|
|
1152
1303
|
|
|
1304
|
+
/** @type {'all'|'relay'|undefined} */
|
|
1305
|
+
#iceTransportPolicy;
|
|
1306
|
+
|
|
1153
1307
|
/** @type {Function|null} */
|
|
1154
1308
|
#WebSocketCtor;
|
|
1155
1309
|
|
|
@@ -1163,6 +1317,10 @@ export class TransportFactory {
|
|
|
1163
1317
|
* @param {object} [opts]
|
|
1164
1318
|
* @param {string[]} [opts.preferredOrder] - Transport preference order
|
|
1165
1319
|
* @param {NATTraversal} [opts.natTraversal] - NAT traversal helper
|
|
1320
|
+
* @param {'all'|'relay'} [opts.iceTransportPolicy] - Default `iceTransportPolicy`
|
|
1321
|
+
* for every `'webrtc'` transport this factory creates (a per-call
|
|
1322
|
+
* `opts.iceTransportPolicy` overrides it). `'relay'` = TURN-only, see
|
|
1323
|
+
* {@link WebRTCTransport}.
|
|
1166
1324
|
* @param {Function} [opts._WebSocket] - Injectable WebSocket constructor
|
|
1167
1325
|
* @param {Function} [opts._RTCPeerConnection] - Injectable RTCPeerConnection constructor
|
|
1168
1326
|
* @param {Function} [opts._WebTransport] - Injectable WebTransport constructor
|
|
@@ -1170,6 +1328,7 @@ export class TransportFactory {
|
|
|
1170
1328
|
constructor(opts = {}) {
|
|
1171
1329
|
this.#preferredOrder = opts.preferredOrder || ['webrtc', 'wsh-wt', 'wsh-ws'];
|
|
1172
1330
|
this.#natTraversal = opts.natTraversal || null;
|
|
1331
|
+
this.#iceTransportPolicy = opts.iceTransportPolicy;
|
|
1173
1332
|
this.#WebSocketCtor = opts._WebSocket !== undefined ? opts._WebSocket : (globalThis.WebSocket || null);
|
|
1174
1333
|
this.#RTCPeerConnectionCtor = opts._RTCPeerConnection !== undefined ? opts._RTCPeerConnection : (globalThis.RTCPeerConnection || null);
|
|
1175
1334
|
this.#WebTransportCtor = opts._WebTransport !== undefined ? opts._WebTransport : (globalThis.WebTransport || null);
|
|
@@ -1197,6 +1356,7 @@ export class TransportFactory {
|
|
|
1197
1356
|
case 'webrtc':
|
|
1198
1357
|
return new WebRTCTransport({
|
|
1199
1358
|
...opts,
|
|
1359
|
+
iceTransportPolicy: opts?.iceTransportPolicy ?? this.#iceTransportPolicy,
|
|
1200
1360
|
_RTCPeerConnection: this.#RTCPeerConnectionCtor,
|
|
1201
1361
|
});
|
|
1202
1362
|
case 'wsh-wt':
|