@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/src/transport.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- // STATUS: INTEGRATED — wired into ClawserPod lifecycle, proven via E2E testing
3
- * clawser-mesh-transport.js -- Transport Abstraction Layer.
2
+ // STATUS: INTEGRATED — wired into the `Pod` lifecycle (@johnhenry/browsermesh-pod), proven via E2E testing
3
+ * transport.mjs -- Transport Abstraction Layer.
4
4
  *
5
5
  * Unified interface for mesh connections across transport types.
6
6
  * Actual transport creation is pluggable via adapter factories passed
@@ -8,15 +8,22 @@
8
8
  * without real WebRTC/WebSocket/WebTransport connections.
9
9
  *
10
10
  * Run tests:
11
- * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-transport.test.mjs
11
+ * cd packages/browsermesh-transport && node --import ./test/_setup-globals.mjs --test test/transport.test.mjs
12
12
  */
13
13
 
14
14
  // ---------------------------------------------------------------------------
15
15
  // Constants
16
16
  // ---------------------------------------------------------------------------
17
17
 
18
- /** @type {readonly string[]} */
19
- const TRANSPORT_TYPES = Object.freeze(['webrtc', 'wsh-wt', 'wsh-ws']);
18
+ /**
19
+ * `'wsh'` is the sealed, key-authenticated peer link over the wsh protocol
20
+ * (`wsh-links.mjs`). It is a type but is NOT in any default preference order:
21
+ * nothing uses it unless a caller lists it or requires it. (`'wsh-wt'` and
22
+ * `'wsh-ws'` are plain WebTransport and WebSocket and do not speak wsh; the
23
+ * names are historical.)
24
+ * @type {readonly string[]}
25
+ */
26
+ const TRANSPORT_TYPES = Object.freeze(['webrtc', 'wsh-wt', 'wsh-ws', 'wsh']);
20
27
 
21
28
  /** @type {readonly string[]} */
22
29
  const TRANSPORT_STATES = Object.freeze([
@@ -283,14 +290,25 @@ export class MeshTransportNegotiator {
283
290
  /** @type {string[]} */
284
291
  #preferenceOrder = ['webrtc', 'wsh-wt', 'wsh-ws'];
285
292
 
293
+ /** @type {string|null} */
294
+ #require = null;
295
+
286
296
  /**
287
297
  * @param {object} [opts]
288
298
  * @param {string[]} [opts.preferenceOrder] - Override default preference
299
+ * @param {string} [opts.require] - A transport type that must be used:
300
+ * only its adapter is tried, and its failure is the failure (there is
301
+ * no fallback to any other type). Use `require: 'wsh'` to never fall
302
+ * back from the sealed wsh link to an unsealed transport.
289
303
  */
290
304
  constructor(opts = {}) {
291
305
  if (opts.preferenceOrder) {
292
306
  this.#preferenceOrder = [...opts.preferenceOrder];
293
307
  }
308
+ if (opts.require !== undefined && opts.require !== null) {
309
+ if (!TRANSPORT_TYPES.includes(opts.require)) throw new Error(`Unknown transport type: ${opts.require}`);
310
+ this.#require = opts.require;
311
+ }
294
312
  }
295
313
 
296
314
  /**
@@ -316,9 +334,22 @@ export class MeshTransportNegotiator {
316
334
  *
317
335
  * @param {object} endpoints - Map of type -> endpoint string
318
336
  * @param {object} [auth] - Auth credentials to pass to adapters
337
+ * @param {object} [opts]
338
+ * @param {string} [opts.require] - As the constructor option, for this call.
339
+ * When a type is required, only that adapter is tried and its own error
340
+ * is thrown unchanged.
319
341
  * @returns {Promise<MeshTransport>}
320
342
  */
321
- async negotiate(endpoints, auth) {
343
+ async negotiate(endpoints, auth, opts = {}) {
344
+ const required = opts?.require ?? this.#require;
345
+ if (required) {
346
+ if (!TRANSPORT_TYPES.includes(required)) throw new Error(`Unknown transport type: ${required}`);
347
+ const factory = this.#adapters.get(required);
348
+ if (!factory) throw new Error(`Transport "${required}" is required but no adapter is registered for it`);
349
+ const endpoint = endpoints?.[required];
350
+ if (!endpoint) throw new Error(`Transport "${required}" is required but no "${required}" endpoint was given`);
351
+ return factory(endpoint, auth);
352
+ }
322
353
  const errors = [];
323
354
  for (const type of this.#preferenceOrder) {
324
355
  const factory = this.#adapters.get(type);
@@ -335,6 +366,17 @@ export class MeshTransportNegotiator {
335
366
  throw new Error(`All transports failed: ${JSON.stringify(errors)}`);
336
367
  }
337
368
 
369
+ /**
370
+ * The transport type this negotiator was told to require, or `null`.
371
+ * `PeerNode.connectToPeer()` reads it: with a required transport a failed
372
+ * negotiation is a failed connect, never a session on something else.
373
+ *
374
+ * @returns {string|null}
375
+ */
376
+ get required() {
377
+ return this.#require;
378
+ }
379
+
338
380
  /**
339
381
  * List transport types that have a registered adapter.
340
382
  *
package/src/webrtc.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- // STATUS: INTEGRATED — wired into ClawserPod lifecycle, proven via E2E testing
3
- * clawser-mesh-webrtc.js -- WebRTC mesh transport.
2
+ // STATUS: INTEGRATED — wired into the `Pod` lifecycle (@johnhenry/browsermesh-pod), proven via E2E testing
3
+ * webrtc.mjs -- WebRTC mesh transport.
4
4
  *
5
5
  * Provides WebRTC DataChannel-based P2P connections for the BrowserMesh.
6
6
  * Includes signaling helpers, connection management, and a transport
@@ -9,12 +9,18 @@
9
9
  * No browser-only imports at module level.
10
10
  *
11
11
  * Run tests:
12
- * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-webrtc.test.mjs
12
+ * cd packages/browsermesh-transport && node --import ./test/_setup-globals.mjs --test test/webrtc.test.mjs
13
13
  */
14
14
 
15
15
  import { MeshTransport } from './transport.mjs'
16
16
  import { silentCatch } from './silent-catch.mjs'
17
17
  import { encodeWireData } from './wire-data.mjs'
18
+ import {
19
+ BINDING_FRAME_TYPE, extractDtlsFingerprints, createBindingProof, verifyBindingProof,
20
+ } from './identity-binding.mjs'
21
+
22
+ /** Default time to wait for the peer's identity proof once the control channel is open. */
23
+ const DEFAULT_BINDING_TIMEOUT_MS = 10_000
18
24
 
19
25
  // ---------------------------------------------------------------------------
20
26
  // Feature detection
@@ -81,6 +87,21 @@ export const PUBLIC_STUN_SERVERS = Object.freeze([
81
87
  { urls: 'stun:stun.l.google.com:19302' },
82
88
  ])
83
89
 
90
+ let _noIceServersNoted = false
91
+
92
+ /**
93
+ * Reset the once-per-process "no ICE servers" note. For tests.
94
+ * @returns {void}
95
+ */
96
+ export function resetNoIceServersNote() { _noIceServersNoted = false }
97
+
98
+ const NO_ICE_SERVERS_NOTE =
99
+ 'WebRTC connection failed and no ICE servers are configured, so only host ' +
100
+ 'candidates were tried (fine on one LAN, usually not across NATs). Pass ' +
101
+ '`iceServers` with your own STUN/TURN server; PUBLIC_STUN_SERVERS is an ' +
102
+ 'opt-in public one, at the cost of telling its operator your public address. ' +
103
+ 'This note is shown once.'
104
+
84
105
  /**
85
106
  * Merge user-configured ICE servers (typically TURN, for NAT traversal
86
107
  * when direct/STUN connectivity fails) with the defaults. Silently
@@ -179,8 +200,8 @@ const BULK_CHANNEL_LABEL = 'mesh-bulk'
179
200
  * still fully *reliable* (SCTP retransmits until every chunk arrives; there
180
201
  * is no `maxRetransmits`/`maxPacketLifeTime` bound here), just not ordered.
181
202
  *
182
- * Justified by the consumer, not assumed: clawser's chunk reassembly
183
- * (`web/clawser-mesh-files.js`) addresses each chunk by content hash (`cid`)
203
+ * Justified by the consumer, not assumed: the host application's chunk reassembly
204
+ * (its mesh file-transfer module) addresses each chunk by content hash (`cid`)
184
205
  * plus offset and dedupes into a `Set` keyed by that hash -- there is no
185
206
  * array-index/push-order dependency, so a chunk that overtakes an earlier
186
207
  * one on the wire reassembles identically to one that didn't. Callers
@@ -260,10 +281,32 @@ export class WebRTCPeerConnection {
260
281
  #disconnectedGraceMs
261
282
  #disconnectedTimer = null
262
283
 
284
+ // -- Identity binding (see identity-binding.mjs); all inert unless `identity` is given
285
+ #identity = null
286
+ #bindingRequired = false
287
+ #bindingTimeoutMs = DEFAULT_BINDING_TIMEOUT_MS
288
+ #bindingTimer = null
289
+ #role = null // 'offerer' | 'answerer'
290
+ #offerSdp = null
291
+ #answerSdp = null
292
+ #bound = false
293
+ #bindingFailure = null
294
+ #droppedUnbound = 0
295
+
263
296
  /**
264
297
  * @param {object} opts
265
298
  * @param {string} opts.localPodId - This pod's identifier
266
299
  * @param {string} opts.remotePodId - Target pod's identifier
300
+ * @param {{ podId: string, sign: Function, rawPublicKey: Function }} [opts.identity] - This pod's
301
+ * identity (a `PodIdentity`). When given, each side proves possession of its pod key over the
302
+ * DTLS fingerprints of BOTH session descriptions, on the control channel, and the peer's proof
303
+ * must verify against `remotePodId`. Nothing is on by default. See `identity-binding.mjs`.
304
+ * @param {boolean} [opts.requirePeerBinding=true] - With `identity`: the connection only becomes
305
+ * `connected`, and application messages are only accepted, once the peer's proof verified;
306
+ * a peer that sends none is closed after `bindingTimeoutMs`. With `false`, a peer that sends
307
+ * no proof (an older build) is accepted unbound (`bound` stays false); a proof that fails is
308
+ * fatal either way.
309
+ * @param {number} [opts.bindingTimeoutMs=10000]
267
310
  * @param {RTCIceServer[]} [opts.iceServers]
268
311
  * @param {'all'|'relay'} [opts.iceTransportPolicy] - Forwarded verbatim to
269
312
  * `RTCPeerConnection`. `'relay'` gathers TURN candidates only, so host and
@@ -276,9 +319,21 @@ export class WebRTCPeerConnection {
276
319
  * through `onError()`. `failed` is reported immediately and is not
277
320
  * subject to this delay.
278
321
  */
279
- constructor({ localPodId, remotePodId, iceServers, iceTransportPolicy, onLog, disconnectedGraceMs = 5000 } = {}) {
322
+ constructor({
323
+ localPodId, remotePodId, iceServers, iceTransportPolicy, onLog, disconnectedGraceMs = 5000,
324
+ identity, requirePeerBinding = true, bindingTimeoutMs = DEFAULT_BINDING_TIMEOUT_MS,
325
+ } = {}) {
280
326
  if (!localPodId) throw new Error('localPodId is required')
281
327
  if (!remotePodId) throw new Error('remotePodId is required')
328
+ if (identity) {
329
+ if (typeof identity.sign !== 'function' || typeof identity.rawPublicKey !== 'function') {
330
+ throw new Error('identity must be able to sign (a PodIdentity)')
331
+ }
332
+ if (identity.podId !== localPodId) throw new Error('identity.podId must equal localPodId')
333
+ this.#identity = identity
334
+ this.#bindingRequired = requirePeerBinding !== false
335
+ this.#bindingTimeoutMs = bindingTimeoutMs
336
+ }
282
337
  this.#localPodId = localPodId
283
338
  this.#remotePodId = remotePodId
284
339
  this.#iceServers = iceServers || [...DEFAULT_ICE_SERVERS]
@@ -301,6 +356,18 @@ export class WebRTCPeerConnection {
301
356
  /** Byte-level stats (copy). */
302
357
  get stats() { return { ...this.#stats } }
303
358
 
359
+ /**
360
+ * True once the peer proved possession of the key behind `remotePodId` over
361
+ * this connection's own DTLS fingerprints. Always false without `identity`.
362
+ */
363
+ get bound() { return this.#bound }
364
+
365
+ /** Why identity binding failed (the connection was closed), or null. */
366
+ get bindingFailure() { return this.#bindingFailure }
367
+
368
+ /** Messages dropped because they arrived before the peer was verified. */
369
+ get droppedUnbound() { return this.#droppedUnbound }
370
+
304
371
  /** True when the DataChannel is open and usable. */
305
372
  get isOpen() {
306
373
  return this.#state === 'connected' &&
@@ -356,6 +423,7 @@ export class WebRTCPeerConnection {
356
423
 
357
424
  const offer = await this.#pc.createOffer()
358
425
  await this.#pc.setLocalDescription(offer)
426
+ this.#resetBinding('offerer', offer.sdp, null)
359
427
  this.#setState('connecting')
360
428
  this.#log(`Created offer for ${this.#remotePodId}`)
361
429
  return { type: 'offer', sdp: offer.sdp }
@@ -453,6 +521,7 @@ export class WebRTCPeerConnection {
453
521
  await this.#flushPendingCandidates()
454
522
  const answer = await this.#pc.createAnswer()
455
523
  await this.#pc.setLocalDescription(answer)
524
+ this.#resetBinding('answerer', offer.sdp, answer.sdp)
456
525
  this.#setState('connecting')
457
526
  this.#log(`Created answer for ${this.#remotePodId}`)
458
527
  return { type: 'answer', sdp: answer.sdp }
@@ -467,6 +536,8 @@ export class WebRTCPeerConnection {
467
536
  if (!this.#pc) throw new Error('No peer connection — call createOffer() first')
468
537
  if (!answer || !answer.sdp) throw new Error('Invalid answer: missing sdp')
469
538
  await this.#pc.setRemoteDescription({ type: 'answer', sdp: answer.sdp })
539
+ this.#answerSdp = answer.sdp
540
+ this.#maybeStartBinding()
470
541
  await this.#flushPendingCandidates()
471
542
  this.#log(`Applied answer from ${this.#remotePodId}`)
472
543
  }
@@ -616,6 +687,9 @@ export class WebRTCPeerConnection {
616
687
  * unknown, or the channel that was actually selected is not open.
617
688
  */
618
689
  send(data, { channel = 'control' } = {}) {
690
+ if (this.#identity && this.#bindingRequired && !this.#bound) {
691
+ throw new Error('Peer identity not verified yet')
692
+ }
619
693
  const extra = (channel !== 'control' && channel !== 'bulk') ? this.#extraChannels.get(channel) : undefined
620
694
  if (channel !== 'control' && channel !== 'bulk' && !extra) {
621
695
  throw new Error(`Unknown channel: ${channel}`)
@@ -674,7 +748,7 @@ export class WebRTCPeerConnection {
674
748
  const dc = this.#extraChannels.get(name)
675
749
  if (!dc) return false
676
750
  this.#extraChannels.delete(name)
677
- try { dc.close() } catch (e) { silentCatch('clawser-mesh-webrtc', 'close-extra', e) }
751
+ try { dc.close() } catch (e) { silentCatch('webrtc', 'close-extra', e) }
678
752
  return true
679
753
  }
680
754
 
@@ -831,21 +905,23 @@ export class WebRTCPeerConnection {
831
905
  // real browser and surfaces against a synchronous mock or binding.
832
906
  if (this.#closing) return
833
907
  this.#closing = true
908
+ clearTimeout(this.#bindingTimer)
909
+ this.#bindingTimer = null
834
910
  try {
835
911
  if (this.#dataChannel) {
836
- try { this.#dataChannel.close() } catch (e) { silentCatch('clawser-mesh-webrtc', 'this', e) }
912
+ try { this.#dataChannel.close() } catch (e) { silentCatch('webrtc', 'this', e) }
837
913
  this.#dataChannel = null
838
914
  }
839
915
  if (this.#bulkChannel) {
840
- try { this.#bulkChannel.close() } catch (e) { silentCatch('clawser-mesh-webrtc', 'this', e) }
916
+ try { this.#bulkChannel.close() } catch (e) { silentCatch('webrtc', 'this', e) }
841
917
  this.#bulkChannel = null
842
918
  }
843
919
  for (const [name, dc] of [...this.#extraChannels]) {
844
920
  this.#extraChannels.delete(name)
845
- try { dc.close() } catch (e) { silentCatch('clawser-mesh-webrtc', 'close-extra', e) }
921
+ try { dc.close() } catch (e) { silentCatch('webrtc', 'close-extra', e) }
846
922
  }
847
923
  if (this.#pc) {
848
- try { this.#pc.close() } catch (e) { silentCatch('clawser-mesh-webrtc', 'this', e) }
924
+ try { this.#pc.close() } catch (e) { silentCatch('webrtc', 'this', e) }
849
925
  this.#pc = null
850
926
  }
851
927
  } finally {
@@ -917,22 +993,22 @@ export class WebRTCPeerConnection {
917
993
  this.#extraChannels.clear()
918
994
  for (const x of extras) {
919
995
  x.onopen = null; x.onmessage = null; x.onclose = null; x.onerror = null
920
- try { x.close() } catch (e) { silentCatch('clawser-mesh-webrtc', 'release-extra', e) }
996
+ try { x.close() } catch (e) { silentCatch('webrtc', 'release-extra', e) }
921
997
  }
922
998
  this.#dataChannel = null
923
999
  this.#bulkChannel = null
924
1000
  this.#pc = null
925
1001
  if (dc) {
926
1002
  dc.onopen = null; dc.onmessage = null; dc.onclose = null; dc.onerror = null
927
- try { dc.close() } catch (e) { silentCatch('clawser-mesh-webrtc', 'release-dc', e) }
1003
+ try { dc.close() } catch (e) { silentCatch('webrtc', 'release-dc', e) }
928
1004
  }
929
1005
  if (bulkDc) {
930
1006
  bulkDc.onopen = null; bulkDc.onmessage = null; bulkDc.onclose = null; bulkDc.onerror = null
931
- try { bulkDc.close() } catch (e) { silentCatch('clawser-mesh-webrtc', 'release-bulk-dc', e) }
1007
+ try { bulkDc.close() } catch (e) { silentCatch('webrtc', 'release-bulk-dc', e) }
932
1008
  }
933
1009
  if (pc) {
934
1010
  pc.onicecandidate = null; pc.ondatachannel = null; pc.onconnectionstatechange = null
935
- try { pc.close() } catch (e) { silentCatch('clawser-mesh-webrtc', 'release-pc', e) }
1011
+ try { pc.close() } catch (e) { silentCatch('webrtc', 'release-pc', e) }
936
1012
  }
937
1013
  }
938
1014
 
@@ -962,7 +1038,7 @@ export class WebRTCPeerConnection {
962
1038
  if (next === 'closed') this.#clearDisconnectedGrace()
963
1039
  this.#state = next
964
1040
  for (const cb of this.#stateChangeCbs) {
965
- try { cb(next) } catch (e) { silentCatch('clawser-mesh-webrtc', 'swallow', e) }
1041
+ try { cb(next) } catch (e) { silentCatch('webrtc', 'swallow', e) }
966
1042
  }
967
1043
  }
968
1044
 
@@ -970,7 +1046,7 @@ export class WebRTCPeerConnection {
970
1046
  this.#pc.onicecandidate = (event) => {
971
1047
  if (event.candidate) {
972
1048
  for (const cb of this.#iceCandidateCbs) {
973
- try { cb(event.candidate) } catch (e) { silentCatch('clawser-mesh-webrtc', 'swallow', e) }
1049
+ try { cb(event.candidate) } catch (e) { silentCatch('webrtc', 'swallow', e) }
974
1050
  }
975
1051
  }
976
1052
  }
@@ -1026,6 +1102,11 @@ export class WebRTCPeerConnection {
1026
1102
  * 'connecting' on a connection that has terminally failed.
1027
1103
  */
1028
1104
  if (this.#state !== 'closed') this.#setState('failed')
1105
+ if (this.#iceServers.length === 0 && !_noIceServersNoted) {
1106
+ _noIceServersNoted = true
1107
+ if (this.#onLog) this.#onLog(NO_ICE_SERVERS_NOTE)
1108
+ else console.warn(`[browsermesh-transport] ${NO_ICE_SERVERS_NOTE}`)
1109
+ }
1029
1110
  this.#fireError(new Error('PeerConnection state: failed'))
1030
1111
  return
1031
1112
  }
@@ -1116,7 +1197,15 @@ export class WebRTCPeerConnection {
1116
1197
  */
1117
1198
  #setupDataChannel(dc, kind, name = kind) {
1118
1199
  dc.onopen = () => {
1119
- if (kind === 'control') this.#setState('connected')
1200
+ if (kind === 'control') {
1201
+ // With identity binding required the connection is not usable until
1202
+ // the peer's proof has verified (see #onBindingFrame).
1203
+ if (this.#identity && this.#bindingRequired) this.#maybeStartBinding()
1204
+ else {
1205
+ this.#setState('connected')
1206
+ this.#maybeStartBinding()
1207
+ }
1208
+ }
1120
1209
  this.#log(`DataChannel (${kind}) open with ${this.#remotePodId}`)
1121
1210
  }
1122
1211
  dc.onmessage = (event) => {
@@ -1125,8 +1214,19 @@ export class WebRTCPeerConnection {
1125
1214
  this.#stats.messagesIn += 1
1126
1215
  let parsed = event.data
1127
1216
  try { parsed = JSON.parse(event.data) } catch { /* keep as string */ }
1217
+ if (this.#identity) {
1218
+ if (kind === 'control' && parsed && typeof parsed === 'object' && parsed.type === BINDING_FRAME_TYPE) {
1219
+ this.#onBindingFrame(parsed)
1220
+ return
1221
+ }
1222
+ if (this.#bindingRequired && !this.#bound) {
1223
+ // Nothing but the proof is accepted before the peer is verified.
1224
+ this.#droppedUnbound++
1225
+ return
1226
+ }
1227
+ }
1128
1228
  for (const cb of this.#messageCbs) {
1129
- try { cb(parsed, name) } catch (e) { silentCatch('clawser-mesh-webrtc', 'swallow', e) }
1229
+ try { cb(parsed, name) } catch (e) { silentCatch('webrtc', 'swallow', e) }
1130
1230
  }
1131
1231
  }
1132
1232
  dc.onclose = () => {
@@ -1167,15 +1267,110 @@ export class WebRTCPeerConnection {
1167
1267
  }
1168
1268
  }
1169
1269
 
1270
+ // -- Identity binding -----------------------------------------------------
1271
+
1272
+ /** @param {'offerer'|'answerer'} role @param {string|null} offerSdp @param {string|null} answerSdp */
1273
+ #resetBinding(role, offerSdp, answerSdp) {
1274
+ if (!this.#identity) return
1275
+ clearTimeout(this.#bindingTimer)
1276
+ this.#bindingTimer = null
1277
+ this.#role = role
1278
+ this.#offerSdp = offerSdp
1279
+ this.#answerSdp = answerSdp
1280
+ this.#bound = false
1281
+ this.#bindingFailure = null
1282
+ this.#bindingStarted = false
1283
+ this.#pendingProof = null
1284
+ }
1285
+
1286
+ #bindingStarted = false
1287
+ #pendingProof = null
1288
+
1289
+ /** The transcript inputs, or null until both descriptions are known. */
1290
+ #bindingParams() {
1291
+ if (!this.#offerSdp || !this.#answerSdp) return null
1292
+ const offerer = this.#role === 'offerer'
1293
+ return {
1294
+ offererPodId: offerer ? this.#localPodId : this.#remotePodId,
1295
+ answererPodId: offerer ? this.#remotePodId : this.#localPodId,
1296
+ offerFingerprints: extractDtlsFingerprints(this.#offerSdp),
1297
+ answerFingerprints: extractDtlsFingerprints(this.#answerSdp),
1298
+ }
1299
+ }
1300
+
1301
+ /** Send our proof once both descriptions are known and the control channel is open. */
1302
+ #maybeStartBinding() {
1303
+ if (!this.#identity || this.#bindingStarted || this.#state === 'closed') return
1304
+ const params = this.#bindingParams()
1305
+ if (!params || this.#dataChannel?.readyState !== 'open') return
1306
+ this.#bindingStarted = true
1307
+ if (!params.offerFingerprints.length || !params.answerFingerprints.length) {
1308
+ this.#failBinding('no-fingerprint')
1309
+ return
1310
+ }
1311
+ if (this.#bindingRequired) {
1312
+ this.#bindingTimer = setTimeout(() => {
1313
+ if (!this.#bound) this.#failBinding('timeout')
1314
+ }, this.#bindingTimeoutMs)
1315
+ if (typeof this.#bindingTimer?.unref === 'function') this.#bindingTimer.unref()
1316
+ }
1317
+ const dc = this.#dataChannel
1318
+ createBindingProof(this.#identity, { ...params, signer: this.#role })
1319
+ .then((proof) => {
1320
+ if (this.#state !== 'closed' && dc.readyState === 'open') dc.send(JSON.stringify(proof))
1321
+ })
1322
+ .catch((err) => this.#failBinding(`could not sign: ${err?.message || err}`))
1323
+ if (this.#pendingProof) {
1324
+ const held = this.#pendingProof
1325
+ this.#pendingProof = null
1326
+ this.#onBindingFrame(held)
1327
+ }
1328
+ }
1329
+
1330
+ async #onBindingFrame(frame) {
1331
+ if (this.#bound || this.#state === 'closed') return
1332
+ const params = this.#bindingParams()
1333
+ if (!params) {
1334
+ this.#pendingProof = frame // the descriptions are not both applied yet
1335
+ return
1336
+ }
1337
+ const verdict = await verifyBindingProof(frame, {
1338
+ ...params,
1339
+ expectedPodId: this.#remotePodId,
1340
+ peerRole: this.#role === 'offerer' ? 'answerer' : 'offerer',
1341
+ })
1342
+ if (this.#state === 'closed' || this.#bound) return
1343
+ if (!verdict.ok) {
1344
+ this.#failBinding(verdict.reason)
1345
+ return
1346
+ }
1347
+ this.#bound = true
1348
+ clearTimeout(this.#bindingTimer)
1349
+ this.#bindingTimer = null
1350
+ this.#log(`Verified identity of ${this.#remotePodId}`)
1351
+ if (this.#state === 'connecting') this.#setState('connected')
1352
+ }
1353
+
1354
+ /** A connection that fails the proof is closed and reported. */
1355
+ #failBinding(reason) {
1356
+ if (this.#state === 'closed') return
1357
+ this.#bindingFailure = reason
1358
+ clearTimeout(this.#bindingTimer)
1359
+ this.#bindingTimer = null
1360
+ this.#log(`Identity binding with ${this.#remotePodId} failed: ${reason}`)
1361
+ this.#fireError(new Error(`identity binding failed: ${reason}`))
1362
+ this.close()
1363
+ }
1364
+
1170
1365
  #fireClose() {
1171
1366
  for (const cb of this.#closeCbs) {
1172
- try { cb() } catch (e) { silentCatch('clawser-mesh-webrtc', 'swallow', e) }
1367
+ try { cb() } catch (e) { silentCatch('webrtc', 'swallow', e) }
1173
1368
  }
1174
1369
  }
1175
1370
 
1176
1371
  #fireError(err) {
1177
1372
  for (const cb of this.#errorCbs) {
1178
- try { cb(err) } catch (e) { silentCatch('clawser-mesh-webrtc', 'swallow', e) }
1373
+ try { cb(err) } catch (e) { silentCatch('webrtc', 'swallow', e) }
1179
1374
  }
1180
1375
  }
1181
1376
 
@@ -1219,6 +1414,9 @@ export class WebRTCMeshManager {
1219
1414
  #maxReconnectAttempts
1220
1415
  #reconnectBaseDelayMs
1221
1416
  #disconnectedGraceMs
1417
+ #identity
1418
+ #requirePeerBinding
1419
+ #bindingTimeoutMs
1222
1420
  #lastStats = []
1223
1421
 
1224
1422
  /**
@@ -1234,12 +1432,20 @@ export class WebRTCMeshManager {
1234
1432
  * @param {number} [opts.disconnectedGraceMs=5000] - Passed to every connection:
1235
1433
  * how long a peer connection may sit in the transient `disconnected` state
1236
1434
  * before it counts as an error worth reconnecting over.
1435
+ * @param {object} [opts.identity] - This pod's `PodIdentity`; passed to every connection to
1436
+ * enable identity binding (see `WebRTCPeerConnection`). `requirePeerBinding` and
1437
+ * `bindingTimeoutMs` are passed along with it.
1237
1438
  */
1238
1439
  constructor({
1239
1440
  localPodId, iceServers, iceTransportPolicy, onLog,
1240
1441
  maxReconnectAttempts = 5, reconnectBaseDelayMs = 1000, disconnectedGraceMs = 5000,
1442
+ identity, requirePeerBinding = true, bindingTimeoutMs = DEFAULT_BINDING_TIMEOUT_MS,
1241
1443
  } = {}) {
1242
1444
  if (!localPodId) throw new Error('localPodId is required')
1445
+ if (identity && identity.podId !== localPodId) throw new Error('identity.podId must equal localPodId')
1446
+ this.#identity = identity ?? null
1447
+ this.#requirePeerBinding = requirePeerBinding
1448
+ this.#bindingTimeoutMs = bindingTimeoutMs
1243
1449
  this.#localPodId = localPodId
1244
1450
  this.#iceServers = iceServers || [...DEFAULT_ICE_SERVERS]
1245
1451
  this.#iceTransportPolicy = resolveIceTransportPolicy(iceTransportPolicy, this.#iceServers)
@@ -1314,11 +1520,16 @@ export class WebRTCMeshManager {
1314
1520
  iceTransportPolicy: this.#iceTransportPolicy,
1315
1521
  onLog: this.#onLog,
1316
1522
  disconnectedGraceMs: this.#disconnectedGraceMs,
1523
+ ...(this.#identity ? {
1524
+ identity: this.#identity,
1525
+ requirePeerBinding: this.#requirePeerBinding,
1526
+ bindingTimeoutMs: this.#bindingTimeoutMs,
1527
+ } : {}),
1317
1528
  })
1318
1529
  // Forward messages to manager-level listeners
1319
1530
  conn.onMessage((data) => {
1320
1531
  for (const cb of this.#messageCbs) {
1321
- try { cb(data, remotePodId, connectionId) } catch (e) { silentCatch('clawser-mesh-webrtc', 'swallow', e) }
1532
+ try { cb(data, remotePodId, connectionId) } catch (e) { silentCatch('webrtc', 'swallow', e) }
1322
1533
  }
1323
1534
  })
1324
1535
  // Auto-remove on close
@@ -1372,7 +1583,7 @@ export class WebRTCMeshManager {
1372
1583
 
1373
1584
  #notifyReconnectOffer(offer, remotePodId, connectionId) {
1374
1585
  for (const cb of this.#reconnectOfferCbs) {
1375
- try { cb(offer, remotePodId, connectionId) } catch (e) { silentCatch('clawser-mesh-webrtc', 'swallow', e) }
1586
+ try { cb(offer, remotePodId, connectionId) } catch (e) { silentCatch('webrtc', 'swallow', e) }
1376
1587
  }
1377
1588
  }
1378
1589
 
@@ -1399,7 +1610,7 @@ export class WebRTCMeshManager {
1399
1610
  // Refund the backoff rather than counting it against the peer.
1400
1611
  this.#clearReconnectState(remotePodId, connectionId)
1401
1612
  }
1402
- } catch (e) { silentCatch('clawser-mesh-webrtc', 'reconnect-attempt', e) }
1613
+ } catch (e) { silentCatch('webrtc', 'reconnect-attempt', e) }
1403
1614
  }, delay)
1404
1615
  this.#reconnectTimers.set(key, timer)
1405
1616
  }
@@ -1551,7 +1762,7 @@ export class WebRTCMeshManager {
1551
1762
  closeAll() {
1552
1763
  for (const byConnectionId of this.#connections.values()) {
1553
1764
  for (const conn of byConnectionId.values()) {
1554
- try { conn.close() } catch (e) { silentCatch('clawser-mesh-webrtc', 'conn.close', e) }
1765
+ try { conn.close() } catch (e) { silentCatch('webrtc', 'conn.close', e) }
1555
1766
  }
1556
1767
  }
1557
1768
  this.#connections.clear()