@johnhenry/browsermesh-transport 0.3.2 → 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 CHANGED
@@ -24,6 +24,7 @@ Extracted from the private `clawser` monorepo (previously `packages/browsermesh-
24
24
  |--------|-------------|
25
25
  | transport | `MeshTransport`, `MockMeshTransport`, `MeshTransportNegotiator` |
26
26
  | websocket | `WebSocketTransport`, `WebRTCTransport`, `WebTransportTransport`, `NATTraversal`, `TransportFactory` |
27
+ | wire-data | `encodeWireData`, `isWireNative` |
27
28
  | webrtc | `WebRTCPeerConnection`, `WebRTCMeshManager`, `WebRTCTransportAdapter` |
28
29
  | webtransport | `WebTransportBridge`, `WebTransportAdapterFactory` |
29
30
  | relay | `MeshRelayClient`, `MockRelayServer` |
@@ -46,6 +47,65 @@ npm install @johnhenry/browsermesh-transport @johnhenry/browsermesh-primitives
46
47
  import { MeshTransport, WebSocketTransport, StreamMultiplexer } from '@johnhenry/browsermesh-transport';
47
48
  ```
48
49
 
50
+ ## What `send()` puts on the wire
51
+
52
+ `RTCDataChannel.send()` and `WebSocket.send()` accept only a string or binary
53
+ and quietly turn anything else into the text `"[object Object]"`. Every
54
+ transport here therefore sends strings and binary (`ArrayBuffer`, typed arrays,
55
+ `Blob`) unchanged and any other value as its JSON text (`encodeWireData()`; it
56
+ throws a `TypeError` for `undefined` or a function rather than send the text
57
+ `"undefined"`). The receiving side gets a string; a consumer that wants objects
58
+ parses it (`@johnhenry/browsermesh-apps`' `ctx.onIncomingData()` does). A custom
59
+ `MeshTransport` should follow the same rule.
60
+
61
+ `WebRTCTransport.send(data, { channel })` takes `'control'` (default) or
62
+ `'bulk'` and falls back to control when the bulk channel is not open.
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
+
49
109
  ## License
50
110
 
51
111
  MIT
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/browsermesh-transport",
3
- "version": "0.3.2",
3
+ "version": "0.4.0",
4
4
  "description": "WebSocket, WebRTC, WebTransport, and relay adapters for BrowserMesh",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
package/src/index.mjs CHANGED
@@ -10,3 +10,4 @@ export * from './cross-origin.mjs';
10
10
  export * from './wsh-bridge.mjs';
11
11
  export * from './wisp.mjs';
12
12
  export * from './channel-relay.mjs';
13
+ export * from './wire-data.mjs';
package/src/webrtc.mjs CHANGED
@@ -14,6 +14,7 @@
14
14
 
15
15
  import { MeshTransport } from './transport.mjs'
16
16
  import { silentCatch } from './silent-catch.mjs'
17
+ import { encodeWireData } from './wire-data.mjs'
17
18
 
18
19
  // ---------------------------------------------------------------------------
19
20
  // Feature detection
@@ -102,6 +103,48 @@ export function mergeIceServers(userServers, defaults = DEFAULT_ICE_SERVERS) {
102
103
  return [...defaults, ...valid]
103
104
  }
104
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
+
105
148
  /**
106
149
  * How many remote ICE candidates to hold while waiting for the remote
107
150
  * description. A handful of interfaces gather a handful of candidates each;
@@ -180,6 +223,7 @@ export class WebRTCPeerConnection {
180
223
  */
181
224
  #bulkChannel = null
182
225
  #iceServers
226
+ #iceTransportPolicy
183
227
  #onLog
184
228
  #state = 'new' // new | connecting | connected | failed | closed
185
229
 
@@ -204,18 +248,24 @@ export class WebRTCPeerConnection {
204
248
  * @param {string} opts.localPodId - This pod's identifier
205
249
  * @param {string} opts.remotePodId - Target pod's identifier
206
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'`).
207
256
  * @param {Function} [opts.onLog] - Optional logging callback
208
257
  * @param {number} [opts.disconnectedGraceMs=5000] - How long a peer connection
209
258
  * may sit in the transient `disconnected` state before it is reported
210
259
  * through `onError()`. `failed` is reported immediately and is not
211
260
  * subject to this delay.
212
261
  */
213
- constructor({ localPodId, remotePodId, iceServers, onLog, disconnectedGraceMs = 5000 } = {}) {
262
+ constructor({ localPodId, remotePodId, iceServers, iceTransportPolicy, onLog, disconnectedGraceMs = 5000 } = {}) {
214
263
  if (!localPodId) throw new Error('localPodId is required')
215
264
  if (!remotePodId) throw new Error('remotePodId is required')
216
265
  this.#localPodId = localPodId
217
266
  this.#remotePodId = remotePodId
218
267
  this.#iceServers = iceServers || [...DEFAULT_ICE_SERVERS]
268
+ this.#iceTransportPolicy = resolveIceTransportPolicy(iceTransportPolicy, this.#iceServers)
219
269
  this.#onLog = onLog || null
220
270
  this.#disconnectedGraceMs = disconnectedGraceMs
221
271
  }
@@ -250,6 +300,13 @@ export class WebRTCPeerConnection {
250
300
  return this.#bulkChannel?.readyState === 'open'
251
301
  }
252
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
+
253
310
  // -- Offer / Answer -------------------------------------------------------
254
311
 
255
312
  /**
@@ -261,7 +318,7 @@ export class WebRTCPeerConnection {
261
318
  */
262
319
  async createOffer() {
263
320
  this.#ensureNotClosed()
264
- this.#pc = new RTCPeerConnection({ iceServers: this.#iceServers })
321
+ this.#pc = new RTCPeerConnection(this.#rtcConfig())
265
322
  this.#setupIceHandling()
266
323
  this.#setupConnectionStateHandling()
267
324
 
@@ -347,7 +404,7 @@ export class WebRTCPeerConnection {
347
404
  // unreachable and, with a native stack, keeps threads and sockets alive.
348
405
  this.#releasePeerConnection()
349
406
 
350
- this.#pc = new RTCPeerConnection({ iceServers: this.#iceServers })
407
+ this.#pc = new RTCPeerConnection(this.#rtcConfig())
351
408
  this.#setupIceHandling()
352
409
  this.#setupConnectionStateHandling()
353
410
 
@@ -544,9 +601,9 @@ export class WebRTCPeerConnection {
544
601
  if (dc.readyState !== 'open') {
545
602
  throw new Error('Data channel not open')
546
603
  }
547
- const str = typeof data === 'string' ? data : JSON.stringify(data)
604
+ const str = encodeWireData(data)
548
605
  dc.send(str)
549
- this.#stats.bytesSent += str.length
606
+ this.#stats.bytesSent += str.length ?? str.byteLength ?? str.size ?? 0
550
607
  this.#stats.messagesOut += 1
551
608
  }
552
609
 
@@ -1049,6 +1106,7 @@ export const DEFAULT_CONNECTION_ID = 'default'
1049
1106
  export class WebRTCMeshManager {
1050
1107
  #localPodId
1051
1108
  #iceServers
1109
+ #iceTransportPolicy
1052
1110
  #connections = new Map() // remotePodId -> Map<connectionId, WebRTCPeerConnection>
1053
1111
  #onLog
1054
1112
  #messageCbs = []
@@ -1064,6 +1122,9 @@ export class WebRTCMeshManager {
1064
1122
  * @param {object} opts
1065
1123
  * @param {string} opts.localPodId
1066
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.
1067
1128
  * @param {Function} [opts.onLog]
1068
1129
  * @param {number} [opts.maxReconnectAttempts=5] - Give up auto-reconnecting after this many failures
1069
1130
  * @param {number} [opts.reconnectBaseDelayMs=1000] - Backoff base; doubles each attempt
@@ -1072,12 +1133,13 @@ export class WebRTCMeshManager {
1072
1133
  * before it counts as an error worth reconnecting over.
1073
1134
  */
1074
1135
  constructor({
1075
- localPodId, iceServers, onLog,
1136
+ localPodId, iceServers, iceTransportPolicy, onLog,
1076
1137
  maxReconnectAttempts = 5, reconnectBaseDelayMs = 1000, disconnectedGraceMs = 5000,
1077
1138
  } = {}) {
1078
1139
  if (!localPodId) throw new Error('localPodId is required')
1079
1140
  this.#localPodId = localPodId
1080
1141
  this.#iceServers = iceServers || [...DEFAULT_ICE_SERVERS]
1142
+ this.#iceTransportPolicy = resolveIceTransportPolicy(iceTransportPolicy, this.#iceServers)
1081
1143
  this.#onLog = onLog || null
1082
1144
  this.#maxReconnectAttempts = maxReconnectAttempts
1083
1145
  this.#reconnectBaseDelayMs = reconnectBaseDelayMs
@@ -1146,6 +1208,7 @@ export class WebRTCMeshManager {
1146
1208
  localPodId: this.#localPodId,
1147
1209
  remotePodId,
1148
1210
  iceServers: this.#iceServers,
1211
+ iceTransportPolicy: this.#iceTransportPolicy,
1149
1212
  onLog: this.#onLog,
1150
1213
  disconnectedGraceMs: this.#disconnectedGraceMs,
1151
1214
  })
package/src/websocket.mjs CHANGED
@@ -1,4 +1,10 @@
1
1
  import { silentCatch } from './silent-catch.mjs'
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'
2
8
  /**
3
9
  // STATUS: INTEGRATED — wired into ClawserPod lifecycle, proven via E2E testing
4
10
  * clawser-mesh-websocket.js -- WebSocket, WebRTC & WebTransport Adapters.
@@ -43,6 +49,67 @@ function byteLength(data) {
43
49
  return 0;
44
50
  }
45
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
+
46
113
  /** Valid event names for WebSocketTransport */
47
114
  const WS_EVENTS = Object.freeze(['open', 'message', 'close', 'error', 'reconnect']);
48
115
 
@@ -100,6 +167,18 @@ export class WebSocketTransport {
100
167
  /** @type {number|null} */
101
168
  #heartbeatTimer = null;
102
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
+
103
182
  /** @type {{ open: Function[], message: Function[], close: Function[], error: Function[], reconnect: Function[] }} */
104
183
  #callbacks = { open: [], message: [], close: [], error: [], reconnect: [] };
105
184
 
@@ -114,10 +193,28 @@ export class WebSocketTransport {
114
193
  * @param {number} [opts.maxReconnectAttempts=5] - Max reconnection attempts
115
194
  * @param {number} [opts.reconnectDelayMs=1000] - Base delay between reconnects
116
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.
117
205
  * @param {Function} [opts._WebSocket] - Injectable WebSocket constructor
118
206
  */
119
207
  constructor(opts = {}) {
120
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;
121
218
  this.#url = opts.url;
122
219
  this.#protocols = opts.protocols || [];
123
220
  this.#reconnect = opts.reconnect !== undefined ? opts.reconnect : true;
@@ -166,6 +263,8 @@ export class WebSocketTransport {
166
263
  return new Promise((resolve, reject) => {
167
264
  try {
168
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';
169
268
  } catch (err) {
170
269
  this.#state = 'disconnected';
171
270
  return reject(err);
@@ -201,14 +300,51 @@ export class WebSocketTransport {
201
300
  }
202
301
 
203
302
  /**
204
- * Send data over the WebSocket.
303
+ * Send data over the WebSocket. Strings and binary go out verbatim; any
304
+ * other value (an envelope object) is sent as its JSON text -- a raw
305
+ * `WebSocket.send(object)` would transmit the string `"[object Object]"`.
306
+ * See `wire-data.mjs`.
205
307
  * @param {*} data
206
308
  */
207
309
  send(data) {
208
310
  if (!this.connected) throw new Error('Not connected');
209
- this.#ws.send(data);
311
+ const wire = this.#frameOut(encodeWireData(data));
312
+ this.#dispatch(wire);
210
313
  this.#stats.messagesSent++;
211
- this.#stats.bytesOut += byteLength(data);
314
+ this.#stats.bytesOut += byteLength(wire);
315
+ }
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;
212
348
  }
213
349
 
214
350
  /**
@@ -222,6 +358,7 @@ export class WebSocketTransport {
222
358
  this.#userClosed = true;
223
359
  this.#state = 'closing';
224
360
  this._stopHeartbeat();
361
+ this.#clearJitter();
225
362
 
226
363
  if (this.#ws) {
227
364
  return new Promise((resolve) => {
@@ -277,15 +414,24 @@ export class WebSocketTransport {
277
414
 
278
415
  /** @type {(ev: { data: * }) => void} */
279
416
  #onMessage = (ev) => {
280
- const data = ev.data;
417
+ let data = ev.data;
281
418
  this.#stats.messagesReceived++;
282
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
+ }
283
428
  this._fireEvent('message', data);
284
429
  };
285
430
 
286
431
  /** @type {(ev: { code: number, reason: string }) => void} */
287
432
  #onClose = (ev) => {
288
433
  this._stopHeartbeat();
434
+ this.#clearJitter();
289
435
  if (this.#userClosed) {
290
436
  this.#state = 'closed';
291
437
  this._fireEvent('close', ev);
@@ -360,9 +506,9 @@ export class WebSocketTransport {
360
506
  this._stopHeartbeat();
361
507
  this.#heartbeatTimer = setInterval(() => {
362
508
  if (!this.connected || !this.#ws) return;
363
- const ping = JSON.stringify({ type: 'ping', ts: Date.now() });
509
+ const ping = this.#frameOut(JSON.stringify({ type: 'ping', ts: Date.now() }));
364
510
  try {
365
- this.#ws.send(ping);
511
+ this.#dispatch(ping);
366
512
  this.#stats.lastPingMs = Date.now();
367
513
  } catch (e) { silentCatch('clawser-mesh-websocket', 'ignore-send-errors-during-heartbeat', e) }
368
514
  }, this.#heartbeatIntervalMs);
@@ -466,6 +612,11 @@ export class WebRTCTransport {
466
612
  * @param {string} opts.remotePodId - Remote pod identifier
467
613
  * @param {object} opts.signaler - Signaling channel
468
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.
469
620
  * @param {Function} [opts._RTCPeerConnection] - Injectable constructor
470
621
  */
471
622
  constructor(opts = {}) {
@@ -475,7 +626,12 @@ export class WebRTCTransport {
475
626
  this.#localPodId = opts.localPodId;
476
627
  this.#remotePodId = opts.remotePodId;
477
628
  this.#signaler = opts.signaler;
478
- 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;
479
635
  this.#RTCPeerConnectionCtor = opts._RTCPeerConnection || globalThis.RTCPeerConnection;
480
636
  }
481
637
 
@@ -691,7 +847,10 @@ export class WebRTCTransport {
691
847
  }
692
848
 
693
849
  /**
694
- * Send data over a data channel.
850
+ * Send data over a data channel. Strings and binary go out verbatim; any
851
+ * other value (an envelope object) is sent as its JSON text -- a raw
852
+ * `RTCDataChannel.send(object)` would transmit the string
853
+ * `"[object Object]"`. See `wire-data.mjs`.
695
854
  * @param {*} data
696
855
  * @param {object} [opts]
697
856
  * @param {'control'|'bulk'} [opts.channel='control'] - `'control'` is the
@@ -710,9 +869,10 @@ export class WebRTCTransport {
710
869
  ? this.#bulkChannel
711
870
  : this.#dataChannel;
712
871
  if (!dc) throw new Error('Not connected');
713
- dc.send(data);
872
+ const wire = encodeWireData(data);
873
+ dc.send(wire);
714
874
  this.#stats.messagesSent++;
715
- this.#stats.bytesOut += byteLength(data);
875
+ this.#stats.bytesOut += byteLength(wire);
716
876
  }
717
877
 
718
878
  /**
@@ -943,12 +1103,13 @@ export class WebTransportTransport {
943
1103
  */
944
1104
  async send(data) {
945
1105
  if (!this.connected) throw new Error('Not connected');
946
- const encoded = typeof data === 'string'
947
- ? new TextEncoder().encode(data)
948
- : data;
1106
+ const wire = encodeWireData(data);
1107
+ const encoded = typeof wire === 'string'
1108
+ ? new TextEncoder().encode(wire)
1109
+ : wire;
949
1110
  await this.#writer.write(encoded);
950
1111
  this.#stats.messagesSent++;
951
- this.#stats.bytesOut += byteLength(data);
1112
+ this.#stats.bytesOut += byteLength(wire);
952
1113
  }
953
1114
 
954
1115
  /**
@@ -1140,6 +1301,9 @@ export class TransportFactory {
1140
1301
  /** @type {NATTraversal|null} */
1141
1302
  #natTraversal;
1142
1303
 
1304
+ /** @type {'all'|'relay'|undefined} */
1305
+ #iceTransportPolicy;
1306
+
1143
1307
  /** @type {Function|null} */
1144
1308
  #WebSocketCtor;
1145
1309
 
@@ -1153,6 +1317,10 @@ export class TransportFactory {
1153
1317
  * @param {object} [opts]
1154
1318
  * @param {string[]} [opts.preferredOrder] - Transport preference order
1155
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}.
1156
1324
  * @param {Function} [opts._WebSocket] - Injectable WebSocket constructor
1157
1325
  * @param {Function} [opts._RTCPeerConnection] - Injectable RTCPeerConnection constructor
1158
1326
  * @param {Function} [opts._WebTransport] - Injectable WebTransport constructor
@@ -1160,6 +1328,7 @@ export class TransportFactory {
1160
1328
  constructor(opts = {}) {
1161
1329
  this.#preferredOrder = opts.preferredOrder || ['webrtc', 'wsh-wt', 'wsh-ws'];
1162
1330
  this.#natTraversal = opts.natTraversal || null;
1331
+ this.#iceTransportPolicy = opts.iceTransportPolicy;
1163
1332
  this.#WebSocketCtor = opts._WebSocket !== undefined ? opts._WebSocket : (globalThis.WebSocket || null);
1164
1333
  this.#RTCPeerConnectionCtor = opts._RTCPeerConnection !== undefined ? opts._RTCPeerConnection : (globalThis.RTCPeerConnection || null);
1165
1334
  this.#WebTransportCtor = opts._WebTransport !== undefined ? opts._WebTransport : (globalThis.WebTransport || null);
@@ -1187,6 +1356,7 @@ export class TransportFactory {
1187
1356
  case 'webrtc':
1188
1357
  return new WebRTCTransport({
1189
1358
  ...opts,
1359
+ iceTransportPolicy: opts?.iceTransportPolicy ?? this.#iceTransportPolicy,
1190
1360
  _RTCPeerConnection: this.#RTCPeerConnectionCtor,
1191
1361
  });
1192
1362
  case 'wsh-wt':
@@ -0,0 +1,48 @@
1
+ /**
2
+ * wire-data.mjs -- the one canonical encoding for what a mesh transport
3
+ * hands to a real wire.
4
+ *
5
+ * `RTCDataChannel.send()` and `WebSocket.send()` accept only a string or
6
+ * binary data (`ArrayBuffer`, a typed-array view, a `Blob`). Anything else
7
+ * is coerced with `String(value)`, so a plain object arrives as the
8
+ * literal text `"[object Object]"` -- no error, no warning. PeerNode and
9
+ * every MeshService above it send envelope *objects* (`{ type, ...payload }`),
10
+ * so a transport that forwards its argument untouched silently destroys
11
+ * every message.
12
+ *
13
+ * Rule: strings and binary pass through byte-for-byte; every other value is
14
+ * sent as its JSON text. The receiving side's counterpart (parse a JSON
15
+ * object/array string back into an object) lives with the consumer that
16
+ * wants objects -- see `@johnhenry/browsermesh-apps`'s `ctx.onIncomingData()`.
17
+ */
18
+
19
+ /**
20
+ * Whether `data` is something a data channel / WebSocket accepts verbatim.
21
+ * @param {*} data
22
+ * @returns {boolean}
23
+ */
24
+ export function isWireNative(data) {
25
+ if (typeof data === 'string') return true;
26
+ if (data instanceof ArrayBuffer) return true;
27
+ if (ArrayBuffer.isView(data)) return true;
28
+ if (typeof Blob !== 'undefined' && data instanceof Blob) return true;
29
+ return false;
30
+ }
31
+
32
+ /**
33
+ * Encode a value for `RTCDataChannel.send()` / `WebSocket.send()`.
34
+ *
35
+ * @param {*} data
36
+ * @returns {string|ArrayBuffer|ArrayBufferView|Blob} `data` itself when it is
37
+ * already a string or binary; otherwise its JSON text.
38
+ * @throws {TypeError} When `data` is `undefined` or a function/symbol (no JSON
39
+ * representation) -- failing loudly beats sending the text "undefined".
40
+ */
41
+ export function encodeWireData(data) {
42
+ if (isWireNative(data)) return data;
43
+ const json = JSON.stringify(data);
44
+ if (typeof json !== 'string') {
45
+ throw new TypeError(`Cannot send a ${typeof data} over a transport (no JSON representation)`);
46
+ }
47
+ return json;
48
+ }