@johnhenry/browsermesh-transport 0.3.3 → 0.4.1

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
@@ -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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/browsermesh-transport",
3
- "version": "0.3.3",
3
+ "version": "0.4.1",
4
4
  "description": "WebSocket, WebRTC, WebTransport, and relay adapters for BrowserMesh",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
@@ -19,7 +19,7 @@
19
19
  "directory": "packages/browsermesh-transport"
20
20
  },
21
21
  "peerDependencies": {
22
- "@johnhenry/browsermesh-primitives": ">=0.2.0 <1.0.0"
22
+ "@johnhenry/browsermesh-primitives": ">=0.3.0 <1.0.0"
23
23
  },
24
24
  "devDependencies": {
25
25
  "node-datachannel": "^0.33.4"
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({ iceServers: this.#iceServers })
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({ iceServers: this.#iceServers })
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,7 @@
1
1
  import { silentCatch } from './silent-catch.mjs'
2
2
  import { encodeWireData } from './wire-data.mjs'
3
+ import { resolveIceTransportPolicy } from './webrtc.mjs'
4
+ import { padTo, unpad } from '@johnhenry/browsermesh-primitives';
3
5
  /**
4
6
  // STATUS: INTEGRATED — wired into ClawserPod lifecycle, proven via E2E testing
5
7
  * clawser-mesh-websocket.js -- WebSocket, WebRTC & WebTransport Adapters.
@@ -44,6 +46,59 @@ function byteLength(data) {
44
46
  return 0;
45
47
  }
46
48
 
49
+ /** First byte of a padded frame: the payload is raw bytes. */
50
+ const PAD_FRAME_BINARY = 0;
51
+ /** First byte of a padded frame: the payload is UTF-8 text. */
52
+ const PAD_FRAME_TEXT = 1;
53
+
54
+ /**
55
+ * Wrap an outgoing wire value in a size-bucketed frame:
56
+ * `[kind byte][payload]`, padded with `padTo()`. Always binary on the wire.
57
+ * @param {string|ArrayBuffer|ArrayBufferView} wire - Output of encodeWireData()
58
+ * @param {{ buckets?: number[] }} padding
59
+ * @returns {Uint8Array}
60
+ */
61
+ function padFrame(wire, padding) {
62
+ let kind;
63
+ let payload;
64
+ if (typeof wire === 'string') {
65
+ kind = PAD_FRAME_TEXT;
66
+ payload = new TextEncoder().encode(wire);
67
+ } else if (wire instanceof ArrayBuffer) {
68
+ kind = PAD_FRAME_BINARY;
69
+ payload = new Uint8Array(wire);
70
+ } else if (ArrayBuffer.isView(wire)) {
71
+ kind = PAD_FRAME_BINARY;
72
+ payload = new Uint8Array(wire.buffer, wire.byteOffset, wire.byteLength);
73
+ } else {
74
+ throw new TypeError('padding cannot be applied to a Blob; send a string, ArrayBuffer or typed array');
75
+ }
76
+ const framed = new Uint8Array(payload.length + 1);
77
+ framed[0] = kind;
78
+ framed.set(payload, 1);
79
+ return padTo(framed, padding);
80
+ }
81
+
82
+ /**
83
+ * Inverse of {@link padFrame}. Returns a string for text frames and a
84
+ * `Uint8Array` for binary ones.
85
+ * @param {*} data - A received ArrayBuffer / typed array
86
+ * @returns {string|Uint8Array}
87
+ * @throws {Error} When `data` is not a padded frame
88
+ */
89
+ function unpadFrame(data) {
90
+ let bytes;
91
+ if (data instanceof ArrayBuffer) bytes = new Uint8Array(data);
92
+ else if (ArrayBuffer.isView(data)) bytes = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
93
+ else throw new Error('padding is enabled but a non-binary frame arrived (is the peer padding too?)');
94
+ const framed = unpad(bytes);
95
+ if (framed.length < 1) throw new Error('padded frame is empty');
96
+ const body = framed.subarray(1);
97
+ if (framed[0] === PAD_FRAME_TEXT) return new TextDecoder().decode(body);
98
+ if (framed[0] === PAD_FRAME_BINARY) return body.slice();
99
+ throw new Error(`unknown padded frame kind ${framed[0]}`);
100
+ }
101
+
47
102
  /** Valid event names for WebSocketTransport */
48
103
  const WS_EVENTS = Object.freeze(['open', 'message', 'close', 'error', 'reconnect']);
49
104
 
@@ -101,6 +156,18 @@ export class WebSocketTransport {
101
156
  /** @type {number|null} */
102
157
  #heartbeatTimer = null;
103
158
 
159
+ /** @type {false|{ buckets?: number[] }} Size-bucket padding for outgoing/incoming frames */
160
+ #padding;
161
+
162
+ /** @type {number} Max random delay (ms) added before each send; 0 = off */
163
+ #jitterMs;
164
+
165
+ /** @type {Set<*>} Outstanding jitter timers, cleared on close */
166
+ #jitterTimers = new Set();
167
+
168
+ /** @type {number} Earliest time the next jittered send may fire (keeps order) */
169
+ #nextSendAt = 0;
170
+
104
171
  /** @type {{ open: Function[], message: Function[], close: Function[], error: Function[], reconnect: Function[] }} */
105
172
  #callbacks = { open: [], message: [], close: [], error: [], reconnect: [] };
106
173
 
@@ -115,10 +182,27 @@ export class WebSocketTransport {
115
182
  * @param {number} [opts.maxReconnectAttempts=5] - Max reconnection attempts
116
183
  * @param {number} [opts.reconnectDelayMs=1000] - Base delay between reconnects
117
184
  * @param {number} [opts.heartbeatIntervalMs=30000] - Heartbeat interval
185
+ * @param {boolean|{ buckets?: number[] }} [opts.padding=false] - Opt in to
186
+ * size-bucket padding: every frame goes out as a binary frame padded to a
187
+ * bucket size (`true` = 256/1024/4096/16384), and incoming frames are
188
+ * unpadded. BOTH ends must enable it. It hides message sizes from network
189
+ * observers; it does not hide them from a relay that reads the frame,
190
+ * so for relay-blind payloads pad inside the end-to-end seal instead
191
+ * (e.g. `GroupKeyManager.encrypt(data, { padding: true })`).
192
+ * @param {number} [opts.jitterMs=0] - Delay each send by a random 0..jitterMs
193
+ * milliseconds (order preserved) for coarse timing decorrelation.
118
194
  * @param {Function} [opts._WebSocket] - Injectable WebSocket constructor
119
195
  */
120
196
  constructor(opts = {}) {
121
197
  if (!opts.url) throw new Error('url is required');
198
+ if (opts.jitterMs !== undefined && !(Number.isFinite(opts.jitterMs) && opts.jitterMs >= 0)) {
199
+ throw new TypeError('jitterMs must be a non-negative number');
200
+ }
201
+ if (opts.padding && opts.padding !== true && typeof opts.padding !== 'object') {
202
+ throw new TypeError('padding must be a boolean or { buckets }');
203
+ }
204
+ this.#padding = opts.padding ? (opts.padding === true ? {} : { buckets: opts.padding.buckets }) : false;
205
+ this.#jitterMs = opts.jitterMs ?? 0;
122
206
  this.#url = opts.url;
123
207
  this.#protocols = opts.protocols || [];
124
208
  this.#reconnect = opts.reconnect !== undefined ? opts.reconnect : true;
@@ -167,6 +251,8 @@ export class WebSocketTransport {
167
251
  return new Promise((resolve, reject) => {
168
252
  try {
169
253
  this.#ws = new this.#WebSocketCtor(this.#url, this.#protocols.length ? this.#protocols : undefined);
254
+ // Padded frames are binary; ask for ArrayBuffer so they arrive synchronously (not as Blobs).
255
+ if (this.#padding) this.#ws.binaryType = 'arraybuffer';
170
256
  } catch (err) {
171
257
  this.#state = 'disconnected';
172
258
  return reject(err);
@@ -210,12 +296,45 @@ export class WebSocketTransport {
210
296
  */
211
297
  send(data) {
212
298
  if (!this.connected) throw new Error('Not connected');
213
- const wire = encodeWireData(data);
214
- this.#ws.send(wire);
299
+ const wire = this.#frameOut(encodeWireData(data));
300
+ this.#dispatch(wire);
215
301
  this.#stats.messagesSent++;
216
302
  this.#stats.bytesOut += byteLength(wire);
217
303
  }
218
304
 
305
+ /** Apply size-bucket padding when enabled. */
306
+ #frameOut(wire) {
307
+ return this.#padding ? padFrame(wire, this.#padding) : wire;
308
+ }
309
+
310
+ /**
311
+ * Hand a frame to the socket, after a random delay when `jitterMs` is set.
312
+ * Delayed sends keep their order: a send never fires before an earlier one.
313
+ */
314
+ #dispatch(wire) {
315
+ const ws = this.#ws;
316
+ if (!(this.#jitterMs > 0)) {
317
+ ws.send(wire);
318
+ return;
319
+ }
320
+ const now = Date.now();
321
+ const at = Math.max(now + Math.random() * this.#jitterMs, this.#nextSendAt);
322
+ this.#nextSendAt = at;
323
+ const timer = setTimeout(() => {
324
+ this.#jitterTimers.delete(timer);
325
+ if (this.#ws !== ws || !this.connected) return;
326
+ try { ws.send(wire); } catch (e) { this._fireEvent('error', e); }
327
+ }, Math.max(0, at - now));
328
+ this.#jitterTimers.add(timer);
329
+ }
330
+
331
+ /** Cancel sends still waiting out their jitter delay. */
332
+ #clearJitter() {
333
+ for (const t of this.#jitterTimers) clearTimeout(t);
334
+ this.#jitterTimers.clear();
335
+ this.#nextSendAt = 0;
336
+ }
337
+
219
338
  /**
220
339
  * Close the WebSocket connection gracefully.
221
340
  * @param {number} [code]
@@ -227,6 +346,7 @@ export class WebSocketTransport {
227
346
  this.#userClosed = true;
228
347
  this.#state = 'closing';
229
348
  this._stopHeartbeat();
349
+ this.#clearJitter();
230
350
 
231
351
  if (this.#ws) {
232
352
  return new Promise((resolve) => {
@@ -282,15 +402,24 @@ export class WebSocketTransport {
282
402
 
283
403
  /** @type {(ev: { data: * }) => void} */
284
404
  #onMessage = (ev) => {
285
- const data = ev.data;
405
+ let data = ev.data;
286
406
  this.#stats.messagesReceived++;
287
407
  this.#stats.bytesIn += byteLength(data);
408
+ if (this.#padding) {
409
+ try {
410
+ data = unpadFrame(data);
411
+ } catch (err) {
412
+ this._fireEvent('error', err);
413
+ return;
414
+ }
415
+ }
288
416
  this._fireEvent('message', data);
289
417
  };
290
418
 
291
419
  /** @type {(ev: { code: number, reason: string }) => void} */
292
420
  #onClose = (ev) => {
293
421
  this._stopHeartbeat();
422
+ this.#clearJitter();
294
423
  if (this.#userClosed) {
295
424
  this.#state = 'closed';
296
425
  this._fireEvent('close', ev);
@@ -365,9 +494,9 @@ export class WebSocketTransport {
365
494
  this._stopHeartbeat();
366
495
  this.#heartbeatTimer = setInterval(() => {
367
496
  if (!this.connected || !this.#ws) return;
368
- const ping = JSON.stringify({ type: 'ping', ts: Date.now() });
497
+ const ping = this.#frameOut(JSON.stringify({ type: 'ping', ts: Date.now() }));
369
498
  try {
370
- this.#ws.send(ping);
499
+ this.#dispatch(ping);
371
500
  this.#stats.lastPingMs = Date.now();
372
501
  } catch (e) { silentCatch('clawser-mesh-websocket', 'ignore-send-errors-during-heartbeat', e) }
373
502
  }, this.#heartbeatIntervalMs);
@@ -462,6 +591,15 @@ export class WebRTCTransport {
462
591
  /** @type {{ open: Function[], message: Function[], close: Function[], error: Function[], 'ice-candidate': Function[] }} */
463
592
  #callbacks = { open: [], message: [], close: [], error: [], 'ice-candidate': [] };
464
593
 
594
+ /**
595
+ * Unsubscribe functions for the listeners this transport put on the shared
596
+ * signaler (when the signaler returns them), so a finished or closed
597
+ * transport stops receiving -- and acting on -- every later answer and ICE
598
+ * candidate on that signaler.
599
+ * @type {Function[]}
600
+ */
601
+ #signalerOffs = [];
602
+
465
603
  /** @type {{ messagesSent: number, messagesReceived: number, bytesIn: number, bytesOut: number, iceState: string }} */
466
604
  #stats = { messagesSent: 0, messagesReceived: 0, bytesIn: 0, bytesOut: 0, iceState: 'new' };
467
605
 
@@ -471,6 +609,11 @@ export class WebRTCTransport {
471
609
  * @param {string} opts.remotePodId - Remote pod identifier
472
610
  * @param {object} opts.signaler - Signaling channel
473
611
  * @param {object} [opts.config] - RTCConfiguration
612
+ * @param {'all'|'relay'} [opts.iceTransportPolicy] - Shorthand for
613
+ * `config.iceTransportPolicy` (this option wins if both are given).
614
+ * `'relay'` gathers TURN candidates only, so host and server-reflexive
615
+ * addresses are never disclosed; it requires a `turn:`/`turns:` entry in
616
+ * `config.iceServers` and throws otherwise.
474
617
  * @param {Function} [opts._RTCPeerConnection] - Injectable constructor
475
618
  */
476
619
  constructor(opts = {}) {
@@ -480,7 +623,12 @@ export class WebRTCTransport {
480
623
  this.#localPodId = opts.localPodId;
481
624
  this.#remotePodId = opts.remotePodId;
482
625
  this.#signaler = opts.signaler;
483
- this.#config = opts.config || {};
626
+ this.#config = { ...(opts.config || {}) };
627
+ const policy = resolveIceTransportPolicy(
628
+ opts.iceTransportPolicy ?? this.#config.iceTransportPolicy,
629
+ this.#config.iceServers,
630
+ );
631
+ if (policy) this.#config.iceTransportPolicy = policy;
484
632
  this.#RTCPeerConnectionCtor = opts._RTCPeerConnection || globalThis.RTCPeerConnection;
485
633
  }
486
634
 
@@ -501,6 +649,40 @@ export class WebRTCTransport {
501
649
  /** Remote pod identifier. */
502
650
  get remotePodId() { return this.#remotePodId; }
503
651
 
652
+
653
+ /**
654
+ * True when a signaling message came from this transport's own remote peer.
655
+ *
656
+ * A signaler is shared: one SignalingClient serves every negotiation a pod
657
+ * has in flight, and it hands EVERY answer and ICE candidate to EVERY
658
+ * listener along with the sender's podId. A transport that ignores that
659
+ * second argument applies a third peer's answer to its own
660
+ * RTCPeerConnection (and the right answer, arriving later, then fails with
661
+ * "wrong state: stable") -- with three pods, one link comes up one-way and
662
+ * a pod can end with no sessions. A signaler that does not say who a
663
+ * message is from (a bare two-party channel) is trusted as before.
664
+ *
665
+ * @param {string|undefined|null} fromPodId
666
+ * @returns {boolean}
667
+ */
668
+ #isFromRemote(fromPodId) {
669
+ return fromPodId === undefined || fromPodId === null || fromPodId === this.#remotePodId;
670
+ }
671
+
672
+ /** Remember a signaler subscription's unsubscribe function, if it returned one. */
673
+ #track(off) {
674
+ if (typeof off === 'function') this.#signalerOffs.push(off);
675
+ }
676
+
677
+ /** Stop listening on the shared signaler. Idempotent. */
678
+ #detachSignaler() {
679
+ const offs = this.#signalerOffs;
680
+ this.#signalerOffs = [];
681
+ for (const off of offs) {
682
+ try { off(); } catch (e) { silentCatch('clawser-mesh-websocket', 'signaler-unsubscribe', e) }
683
+ }
684
+ }
685
+
504
686
  // -- Public API ------------------------------------------------------------
505
687
 
506
688
  /**
@@ -530,13 +712,15 @@ export class WebRTCTransport {
530
712
  if (this.#pc.connectionState === 'failed' || this.#pc.connectionState === 'closed') {
531
713
  if (this.#state !== 'closed' && this.#state !== 'closing') {
532
714
  this.#state = 'closed';
715
+ this.#detachSignaler();
533
716
  this._fireEvent('close');
534
717
  }
535
718
  }
536
719
  });
537
720
 
538
721
  // Set up signaler listeners for remote ICE candidates
539
- this.#signaler.onIceCandidate((data) => {
722
+ this.#track(this.#signaler.onIceCandidate((data, fromPodId) => {
723
+ if (!this.#isFromRemote(fromPodId)) return;
540
724
  if (this.#pc) {
541
725
  // The promise must not be dropped. addIceCandidate rejects on a
542
726
  // malformed candidate and on one that arrives before the remote
@@ -548,7 +732,7 @@ export class WebRTCTransport {
548
732
  silentCatch('clawser-mesh-websocket', 'ignore-rejected-ice-candidate', e);
549
733
  });
550
734
  }
551
- });
735
+ }));
552
736
 
553
737
  // Create data channels and offer. A second createDataChannel() call on
554
738
  // the same RTCPeerConnection is a second SCTP stream, not a second
@@ -571,7 +755,13 @@ export class WebRTCTransport {
571
755
  reject(new Error('WebRTC answer timeout'));
572
756
  }, 30000);
573
757
 
574
- this.#signaler.onAnswer(async (data) => {
758
+ // eslint-disable-next-line prefer-const
759
+ let offAnswer;
760
+ offAnswer = this.#signaler.onAnswer(async (data, fromPodId) => {
761
+ // Not ours: another negotiation's answer on the shared signaler.
762
+ if (!this.#isFromRemote(fromPodId)) return;
763
+ // An offer gets one answer; a repeat must not re-apply to a stable pc.
764
+ if (typeof offAnswer === 'function') offAnswer();
575
765
  clearTimeout(timeout);
576
766
  try {
577
767
  await this.#pc.setRemoteDescription(data.answer);
@@ -595,6 +785,7 @@ export class WebRTCTransport {
595
785
  this.#dataChannel.addEventListener('open', onDCOpen);
596
786
  }
597
787
  });
788
+ this.#track(offAnswer);
598
789
  });
599
790
  }
600
791
 
@@ -629,12 +820,14 @@ export class WebRTCTransport {
629
820
  if (this.#pc.connectionState === 'failed' || this.#pc.connectionState === 'closed') {
630
821
  if (this.#state !== 'closed' && this.#state !== 'closing') {
631
822
  this.#state = 'closed';
823
+ this.#detachSignaler();
632
824
  this._fireEvent('close');
633
825
  }
634
826
  }
635
827
  });
636
828
 
637
- this.#signaler.onIceCandidate((data) => {
829
+ this.#track(this.#signaler.onIceCandidate((data, fromPodId) => {
830
+ if (!this.#isFromRemote(fromPodId)) return;
638
831
  if (this.#pc) {
639
832
  // See connect()'s identical handler: the promise must not be
640
833
  // dropped, for the same reason.
@@ -642,7 +835,7 @@ export class WebRTCTransport {
642
835
  silentCatch('clawser-mesh-websocket', 'ignore-rejected-ice-candidate', e);
643
836
  });
644
837
  }
645
- });
838
+ }));
646
839
  }
647
840
  this.#state = 'connecting';
648
841
 
@@ -740,6 +933,7 @@ export class WebRTCTransport {
740
933
  this.#pc.close();
741
934
  }
742
935
  this.#state = 'closed';
936
+ this.#detachSignaler();
743
937
  this._fireEvent('close');
744
938
  }
745
939
 
@@ -1150,6 +1344,9 @@ export class TransportFactory {
1150
1344
  /** @type {NATTraversal|null} */
1151
1345
  #natTraversal;
1152
1346
 
1347
+ /** @type {'all'|'relay'|undefined} */
1348
+ #iceTransportPolicy;
1349
+
1153
1350
  /** @type {Function|null} */
1154
1351
  #WebSocketCtor;
1155
1352
 
@@ -1163,6 +1360,10 @@ export class TransportFactory {
1163
1360
  * @param {object} [opts]
1164
1361
  * @param {string[]} [opts.preferredOrder] - Transport preference order
1165
1362
  * @param {NATTraversal} [opts.natTraversal] - NAT traversal helper
1363
+ * @param {'all'|'relay'} [opts.iceTransportPolicy] - Default `iceTransportPolicy`
1364
+ * for every `'webrtc'` transport this factory creates (a per-call
1365
+ * `opts.iceTransportPolicy` overrides it). `'relay'` = TURN-only, see
1366
+ * {@link WebRTCTransport}.
1166
1367
  * @param {Function} [opts._WebSocket] - Injectable WebSocket constructor
1167
1368
  * @param {Function} [opts._RTCPeerConnection] - Injectable RTCPeerConnection constructor
1168
1369
  * @param {Function} [opts._WebTransport] - Injectable WebTransport constructor
@@ -1170,6 +1371,7 @@ export class TransportFactory {
1170
1371
  constructor(opts = {}) {
1171
1372
  this.#preferredOrder = opts.preferredOrder || ['webrtc', 'wsh-wt', 'wsh-ws'];
1172
1373
  this.#natTraversal = opts.natTraversal || null;
1374
+ this.#iceTransportPolicy = opts.iceTransportPolicy;
1173
1375
  this.#WebSocketCtor = opts._WebSocket !== undefined ? opts._WebSocket : (globalThis.WebSocket || null);
1174
1376
  this.#RTCPeerConnectionCtor = opts._RTCPeerConnection !== undefined ? opts._RTCPeerConnection : (globalThis.RTCPeerConnection || null);
1175
1377
  this.#WebTransportCtor = opts._WebTransport !== undefined ? opts._WebTransport : (globalThis.WebTransport || null);
@@ -1197,6 +1399,7 @@ export class TransportFactory {
1197
1399
  case 'webrtc':
1198
1400
  return new WebRTCTransport({
1199
1401
  ...opts,
1402
+ iceTransportPolicy: opts?.iceTransportPolicy ?? this.#iceTransportPolicy,
1200
1403
  _RTCPeerConnection: this.#RTCPeerConnectionCtor,
1201
1404
  });
1202
1405
  case 'wsh-wt':