@johnhenry/browsermesh-core 0.0.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.
@@ -0,0 +1,760 @@
1
+ import { silentCatch } from './silent-catch.mjs'
2
+ /**
3
+ // STATUS: INTEGRATED — wired into ClawserPod lifecycle, proven via E2E testing
4
+ * clawser-mesh-handshake.js -- Connection Handshake Protocol.
5
+ *
6
+ * Coordinates signaling, direct input exchange (QR + clipboard), and
7
+ * session establishment between two mesh peers.
8
+ *
9
+ * SignalingClient bridges a WebSocket (or MeshRelayClient) into the
10
+ * signaler interface that WebRTCTransport expects (sendOffer, sendAnswer,
11
+ * sendIceCandidate, onOffer, onAnswer, onIceCandidate).
12
+ *
13
+ * DirectInputHandshake handles manual key exchange for direct pairing
14
+ * without a signaling server -- via clipboard paste or QR code.
15
+ *
16
+ * HandshakeCoordinator orchestrates the full connection flow:
17
+ * discovery -> transport selection -> handshake -> session.
18
+ *
19
+ * No browser-only imports at module level. All dependencies injected
20
+ * via constructor.
21
+ *
22
+ * Run tests:
23
+ * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-handshake.test.mjs
24
+ */
25
+
26
+ // ---------------------------------------------------------------------------
27
+ // Helpers
28
+ // ---------------------------------------------------------------------------
29
+
30
+ /**
31
+ * Convert a Uint8Array to a base64url string (no padding).
32
+ * @param {Uint8Array} bytes
33
+ * @returns {string}
34
+ */
35
+ function toBase64Url(bytes) {
36
+ const bin = String.fromCharCode(...bytes)
37
+ const b64 = btoa(bin)
38
+ return b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
39
+ }
40
+
41
+ /**
42
+ * Decode a base64url string back to a Uint8Array.
43
+ * @param {string} str
44
+ * @returns {Uint8Array}
45
+ */
46
+ function fromBase64Url(str) {
47
+ let b64 = str.replace(/-/g, '+').replace(/_/g, '/')
48
+ while (b64.length % 4 !== 0) b64 += '='
49
+ const bin = atob(b64)
50
+ const bytes = new Uint8Array(bin.length)
51
+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
52
+ return bytes
53
+ }
54
+
55
+ /**
56
+ * Generate a random hex nonce.
57
+ * @param {number} [byteLen=16]
58
+ * @returns {string}
59
+ */
60
+ function randomHex(byteLen = 16) {
61
+ const bytes = new Uint8Array(byteLen)
62
+ crypto.getRandomValues(bytes)
63
+ return [...bytes].map(b => b.toString(16).padStart(2, '0')).join('')
64
+ }
65
+
66
+ /** Token TTL in milliseconds (5 minutes). */
67
+ const TOKEN_TTL_MS = 5 * 60 * 1000
68
+
69
+ /** Default connection timeout in milliseconds. */
70
+ const DEFAULT_TIMEOUT_MS = 30_000
71
+
72
+ // ---------------------------------------------------------------------------
73
+ // SignalingClient
74
+ // ---------------------------------------------------------------------------
75
+
76
+ /**
77
+ * Bridges a WebSocket connection (or MeshRelayClient) into the signaler
78
+ * interface that WebRTCTransport expects.
79
+ *
80
+ * Provides sendOffer, sendAnswer, sendIceCandidate plus event callbacks
81
+ * onOffer, onAnswer, onIceCandidate for signaling exchange.
82
+ */
83
+ export class SignalingClient {
84
+ /** @type {object|null} WebSocket instance */
85
+ #ws = null
86
+
87
+ /** @type {string} */
88
+ #localPodId
89
+
90
+ /** @type {Map<string, Set<Function>>} */
91
+ #listeners = new Map()
92
+
93
+ /** @type {Function} */
94
+ #onLog
95
+
96
+ /** @type {string|null} */
97
+ #url
98
+
99
+ /** @type {Function|null} */
100
+ #WebSocketCtor
101
+
102
+ /**
103
+ * @param {object} opts
104
+ * @param {string} [opts.url] - WebSocket signaling server URL
105
+ * @param {string} opts.localPodId - Local pod identifier
106
+ * @param {Function} [opts.onLog] - Logging callback (level, msg)
107
+ * @param {Function} [opts._WebSocket] - Injectable WebSocket constructor
108
+ */
109
+ constructor({ url = null, localPodId, onLog, _WebSocket } = {}) {
110
+ if (!localPodId || typeof localPodId !== 'string') {
111
+ throw new Error('localPodId is required and must be a non-empty string')
112
+ }
113
+ this.#url = url
114
+ this.#localPodId = localPodId
115
+ this.#onLog = onLog || (() => {})
116
+ this.#WebSocketCtor = _WebSocket || globalThis.WebSocket || null
117
+ }
118
+
119
+ // -- Lifecycle ------------------------------------------------------------
120
+
121
+ /**
122
+ * Open WebSocket to signaling server and register.
123
+ * @returns {Promise<void>}
124
+ */
125
+ async connect() {
126
+ if (this.#ws) return
127
+
128
+ if (!this.#url) {
129
+ throw new Error('No signaling URL configured')
130
+ }
131
+ if (!this.#WebSocketCtor) {
132
+ throw new Error('WebSocket not available')
133
+ }
134
+
135
+ return new Promise((resolve, reject) => {
136
+ const ws = new this.#WebSocketCtor(this.#url)
137
+
138
+ const onOpen = () => {
139
+ cleanup()
140
+ this.#ws = ws
141
+ ws.addEventListener('message', this.#handleMessage)
142
+ ws.addEventListener('close', this.#handleClose)
143
+ // Register with the signaling server
144
+ this.send(null, 'register', { podId: this.#localPodId })
145
+ this.#onLog(2, `SignalingClient connected to ${this.#url}`)
146
+ resolve()
147
+ }
148
+
149
+ const onError = (err) => {
150
+ cleanup()
151
+ reject(err instanceof Error ? err : new Error('WebSocket connection failed'))
152
+ }
153
+
154
+ const cleanup = () => {
155
+ ws.removeEventListener('open', onOpen)
156
+ ws.removeEventListener('error', onError)
157
+ }
158
+
159
+ ws.addEventListener('open', onOpen)
160
+ ws.addEventListener('error', onError)
161
+ })
162
+ }
163
+
164
+ /**
165
+ * Disconnect from the signaling server.
166
+ */
167
+ disconnect() {
168
+ if (!this.#ws) return
169
+ try {
170
+ this.#ws.removeEventListener('message', this.#handleMessage)
171
+ this.#ws.removeEventListener('close', this.#handleClose)
172
+ this.#ws.close()
173
+ } catch (e) { silentCatch('clawser-mesh-handshake', 'ignore-close-errors', e) }
174
+ this.#ws = null
175
+ this.#onLog(2, 'SignalingClient disconnected')
176
+ }
177
+
178
+ /** True when WebSocket is open. */
179
+ get connected() {
180
+ return this.#ws !== null
181
+ }
182
+
183
+ // -- Signaler interface for WebRTCTransport --------------------------------
184
+
185
+ /**
186
+ * Send an SDP offer to a remote peer.
187
+ * @param {string} remotePodId
188
+ * @param {object} offer
189
+ */
190
+ sendOffer(remotePodId, offer) {
191
+ this.send(remotePodId, 'offer', { offer })
192
+ }
193
+
194
+ /**
195
+ * Send an SDP answer to a remote peer.
196
+ * @param {string} remotePodId
197
+ * @param {object} answer
198
+ */
199
+ sendAnswer(remotePodId, answer) {
200
+ this.send(remotePodId, 'answer', { answer })
201
+ }
202
+
203
+ /**
204
+ * Send an ICE candidate to a remote peer.
205
+ * @param {string} remotePodId
206
+ * @param {object} candidate
207
+ */
208
+ sendIceCandidate(remotePodId, candidate) {
209
+ this.send(remotePodId, 'ice-candidate', { candidate })
210
+ }
211
+
212
+ /**
213
+ * Register callback for incoming SDP offers.
214
+ * @param {Function} cb - Receives (offer, fromPodId)
215
+ */
216
+ onOffer(cb) {
217
+ this.on('offer', cb)
218
+ }
219
+
220
+ /**
221
+ * Register callback for incoming SDP answers.
222
+ * @param {Function} cb - Receives (answer, fromPodId)
223
+ */
224
+ onAnswer(cb) {
225
+ this.on('answer', cb)
226
+ }
227
+
228
+ /**
229
+ * Register callback for incoming ICE candidates.
230
+ * @param {Function} cb - Receives (candidate, fromPodId)
231
+ */
232
+ onIceCandidate(cb) {
233
+ this.on('ice-candidate', cb)
234
+ }
235
+
236
+ // -- Generic send / event system ------------------------------------------
237
+
238
+ /**
239
+ * Send a typed message to a remote peer via the signaling server.
240
+ *
241
+ * @param {string|null} remotePodId - Target peer (null for server-only messages)
242
+ * @param {string} type - Message type
243
+ * @param {object} payload - Message payload
244
+ */
245
+ send(remotePodId, type, payload) {
246
+ if (!this.#ws) {
247
+ throw new Error('SignalingClient not connected')
248
+ }
249
+ const msg = JSON.stringify({
250
+ from: this.#localPodId,
251
+ to: remotePodId,
252
+ type,
253
+ ...payload,
254
+ })
255
+ this.#ws.send(msg)
256
+ }
257
+
258
+ /**
259
+ * Register a listener for a given event type.
260
+ * @param {string} event
261
+ * @param {Function} cb
262
+ */
263
+ on(event, cb) {
264
+ if (!this.#listeners.has(event)) {
265
+ this.#listeners.set(event, new Set())
266
+ }
267
+ this.#listeners.get(event).add(cb)
268
+ }
269
+
270
+ /**
271
+ * Remove a listener for a given event type.
272
+ * @param {string} event
273
+ * @param {Function} cb
274
+ */
275
+ off(event, cb) {
276
+ const set = this.#listeners.get(event)
277
+ if (set) set.delete(cb)
278
+ }
279
+
280
+ // -- Internal event handlers (arrow fns for stable `this`) ----------------
281
+
282
+ /** @type {(ev: { data: * }) => void} */
283
+ #handleMessage = (ev) => {
284
+ try {
285
+ const data = typeof ev.data === 'string' ? JSON.parse(ev.data) : ev.data
286
+ if (!data || !data.type) return
287
+ this.#fire(data.type, data)
288
+ } catch (e) { silentCatch('clawser-mesh-handshake', 'ignore-malformed-messages', e) }
289
+ }
290
+
291
+ /** @type {() => void} */
292
+ #handleClose = () => {
293
+ this.#ws = null
294
+ this.#onLog(2, 'SignalingClient WebSocket closed')
295
+ }
296
+
297
+ /**
298
+ * Fire all listeners for a given event type.
299
+ * @param {string} event
300
+ * @param {*} data
301
+ */
302
+ #fire(event, data) {
303
+ const set = this.#listeners.get(event)
304
+ if (!set) return
305
+ for (const cb of set) {
306
+ try { cb(data, data.from) } catch (e) { silentCatch('clawser-mesh-handshake', 'swallow-listener-errors', e) }
307
+ }
308
+ }
309
+ }
310
+
311
+ // ---------------------------------------------------------------------------
312
+ // DirectInputHandshake
313
+ // ---------------------------------------------------------------------------
314
+
315
+ /**
316
+ * Manual key exchange for direct pairing without a signaling server.
317
+ *
318
+ * Generates a connection token containing the local pod's identity
319
+ * and connection parameters. The token can be shared via clipboard
320
+ * paste or QR code. The receiving peer decodes and validates the
321
+ * token to establish a connection.
322
+ */
323
+ export class DirectInputHandshake {
324
+ /** @type {string} */
325
+ #localPodId
326
+
327
+ /** @type {Function} async () => Uint8Array */
328
+ #getPublicKeyBytes
329
+
330
+ /** @type {string|null} */
331
+ #signalingUrl
332
+
333
+ /** @type {object[]|null} */
334
+ #iceServers
335
+
336
+ /** @type {Function} */
337
+ #onLog
338
+
339
+ /**
340
+ * @param {object} opts
341
+ * @param {string} opts.localPodId - Local pod identifier
342
+ * @param {Function} opts.getPublicKeyBytes - async () => Uint8Array, returns public key bytes
343
+ * @param {string} [opts.signalingUrl] - Optional signaling server URL to include in token
344
+ * @param {object[]} [opts.iceServers] - Optional ICE server configs to include in token
345
+ * @param {Function} [opts.onLog] - Logging callback (level, msg)
346
+ */
347
+ constructor({ localPodId, getPublicKeyBytes, signalingUrl, iceServers, onLog } = {}) {
348
+ if (!localPodId || typeof localPodId !== 'string') {
349
+ throw new Error('localPodId is required and must be a non-empty string')
350
+ }
351
+ if (!getPublicKeyBytes || typeof getPublicKeyBytes !== 'function') {
352
+ throw new Error('getPublicKeyBytes is required and must be a function')
353
+ }
354
+ this.#localPodId = localPodId
355
+ this.#getPublicKeyBytes = getPublicKeyBytes
356
+ this.#signalingUrl = signalingUrl || null
357
+ this.#iceServers = iceServers || null
358
+ this.#onLog = onLog || (() => {})
359
+ }
360
+
361
+ /**
362
+ * Generate a connection token containing this peer's identity and
363
+ * connection parameters.
364
+ *
365
+ * @returns {Promise<ConnectionToken>}
366
+ */
367
+ async generateToken() {
368
+ const pubKeyBytes = await this.#getPublicKeyBytes()
369
+ const publicKey = toBase64Url(pubKeyBytes)
370
+ const nonce = randomHex(16)
371
+
372
+ /** @type {ConnectionToken} */
373
+ const token = {
374
+ podId: this.#localPodId,
375
+ publicKey,
376
+ nonce,
377
+ timestamp: Date.now(),
378
+ }
379
+
380
+ if (this.#signalingUrl) token.signalingUrl = this.#signalingUrl
381
+ if (this.#iceServers) token.iceServers = this.#iceServers
382
+
383
+ this.#onLog(2, `Generated connection token for pod ${this.#localPodId}`)
384
+ return token
385
+ }
386
+
387
+ /**
388
+ * Encode a connection token as a base64url JSON string for clipboard sharing.
389
+ *
390
+ * @param {ConnectionToken} token
391
+ * @returns {string}
392
+ */
393
+ encodeToken(token) {
394
+ const json = JSON.stringify(token)
395
+ const bytes = new TextEncoder().encode(json)
396
+ return toBase64Url(bytes)
397
+ }
398
+
399
+ /**
400
+ * Decode a base64url-encoded token string back into a ConnectionToken.
401
+ *
402
+ * @param {string} encoded - base64url-encoded JSON string
403
+ * @returns {ConnectionToken}
404
+ */
405
+ static decodeToken(encoded) {
406
+ const bytes = fromBase64Url(encoded)
407
+ const json = new TextDecoder().decode(bytes)
408
+ return JSON.parse(json)
409
+ }
410
+
411
+ /**
412
+ * Validate a received connection token.
413
+ *
414
+ * Checks: has podId, has publicKey, has nonce, not self, not expired (5min TTL).
415
+ *
416
+ * @param {ConnectionToken} token
417
+ * @returns {{ valid: boolean, error?: string }}
418
+ */
419
+ validateToken(token) {
420
+ if (!token || typeof token !== 'object') {
421
+ return { valid: false, error: 'Token is not an object' }
422
+ }
423
+ if (!token.podId || typeof token.podId !== 'string') {
424
+ return { valid: false, error: 'Token missing podId' }
425
+ }
426
+ if (!token.publicKey || typeof token.publicKey !== 'string') {
427
+ return { valid: false, error: 'Token missing publicKey' }
428
+ }
429
+ if (!token.nonce || typeof token.nonce !== 'string') {
430
+ return { valid: false, error: 'Token missing nonce' }
431
+ }
432
+ if (token.podId === this.#localPodId) {
433
+ return { valid: false, error: 'Cannot connect to self' }
434
+ }
435
+ if (typeof token.timestamp !== 'number') {
436
+ return { valid: false, error: 'Token missing timestamp' }
437
+ }
438
+ const age = Date.now() - token.timestamp
439
+ if (age > TOKEN_TTL_MS) {
440
+ return { valid: false, error: 'Token expired' }
441
+ }
442
+ // Reject tokens with future timestamps (clock skew tolerance: 30s)
443
+ if (age < -30_000) {
444
+ return { valid: false, error: 'Token timestamp is in the future' }
445
+ }
446
+ return { valid: true }
447
+ }
448
+
449
+ /**
450
+ * Generate a QR code data URL for a connection token.
451
+ *
452
+ * Returns the encoded token string suitable for an external QR library,
453
+ * or null if generation is not available in the current environment.
454
+ *
455
+ * @param {ConnectionToken} token
456
+ * @returns {Promise<string|null>}
457
+ */
458
+ async generateQRDataURL(token) {
459
+ const encoded = this.encodeToken(token)
460
+ // QR generation requires a canvas or external library.
461
+ // Return the encoded string for use with an external QR renderer.
462
+ // In a browser with a QR library loaded, this could be extended
463
+ // to produce an actual data:image/png;base64,... URL.
464
+ this.#onLog(2, 'QR generation requires external library; returning encoded token')
465
+ return encoded
466
+ }
467
+ }
468
+
469
+ /**
470
+ * @typedef {object} ConnectionToken
471
+ * @property {string} podId - Peer's pod identifier
472
+ * @property {string} publicKey - base64url-encoded public key
473
+ * @property {string} [signalingUrl] - Optional signaling server URL
474
+ * @property {object[]} [iceServers] - Optional ICE server configs
475
+ * @property {string} nonce - Random hex nonce
476
+ * @property {number} timestamp - Unix timestamp in ms
477
+ */
478
+
479
+ // ---------------------------------------------------------------------------
480
+ // HandshakeCoordinator
481
+ // ---------------------------------------------------------------------------
482
+
483
+ /**
484
+ * Orchestrates the full connection flow: discovery -> transport selection ->
485
+ * handshake -> session establishment.
486
+ *
487
+ * Brings together SignalingClient and TransportFactory to connect two peers,
488
+ * whether via a signaling server or via a direct-input connection token.
489
+ */
490
+ export class HandshakeCoordinator {
491
+ /** @type {SignalingClient|null} */
492
+ #signalingClient
493
+
494
+ /** @type {object|null} TransportFactory */
495
+ #transportFactory
496
+
497
+ /** @type {string} */
498
+ #localPodId
499
+
500
+ /** @type {Function} */
501
+ #onLog
502
+
503
+ /** @type {Map<string, Set<Function>>} */
504
+ #listeners = new Map()
505
+
506
+ /**
507
+ * @param {object} opts
508
+ * @param {string} opts.localPodId - Local pod identifier
509
+ * @param {SignalingClient} [opts.signalingClient] - Signaling client instance
510
+ * @param {object} [opts.transportFactory] - TransportFactory instance
511
+ * @param {Function} [opts.onLog] - Logging callback (level, msg)
512
+ */
513
+ constructor({ localPodId, signalingClient, transportFactory, onLog } = {}) {
514
+ if (!localPodId || typeof localPodId !== 'string') {
515
+ throw new Error('localPodId is required and must be a non-empty string')
516
+ }
517
+ this.#localPodId = localPodId
518
+ this.#signalingClient = signalingClient || null
519
+ this.#transportFactory = transportFactory || null
520
+ this.#onLog = onLog || (() => {})
521
+
522
+ // Wire incoming offer events from signaling client
523
+ if (this.#signalingClient) {
524
+ this.#signalingClient.onOffer((data, fromPodId) => {
525
+ this.#fire('incoming', { remotePodId: fromPodId, offer: data.offer })
526
+ })
527
+ }
528
+ }
529
+
530
+ /**
531
+ * Initiate a connection to a remote peer via the signaling server.
532
+ *
533
+ * Uses the transport factory to negotiate the best transport, passing
534
+ * the signaling client as the signaler bridge.
535
+ *
536
+ * @param {string} remotePodId - Target peer identifier
537
+ * @param {object} [opts]
538
+ * @param {object} [opts.endpoints] - Map of transport type -> constructor opts
539
+ * @param {object[]} [opts.iceServers] - ICE server configs
540
+ * @param {number} [opts.timeout] - Connection timeout in ms
541
+ * @returns {Promise<{ transport: object, sessionInfo: object }>}
542
+ */
543
+ async connectToPeer(remotePodId, opts = {}) {
544
+ if (!this.#transportFactory) {
545
+ throw new Error('TransportFactory is required for connectToPeer')
546
+ }
547
+ if (!this.#signalingClient) {
548
+ throw new Error('SignalingClient is required for connectToPeer')
549
+ }
550
+
551
+ const timeout = opts.timeout || DEFAULT_TIMEOUT_MS
552
+ this.#onLog(2, `Initiating connection to ${remotePodId}`)
553
+
554
+ const endpointOpts = opts.endpoints || {
555
+ webrtc: { config: { iceServers: opts.iceServers || [] } },
556
+ }
557
+
558
+ let timeoutHandle
559
+ const transport = await Promise.race([
560
+ this.#transportFactory.negotiate(
561
+ this.#localPodId,
562
+ remotePodId,
563
+ this.#signalingClient,
564
+ endpointOpts,
565
+ ),
566
+ new Promise((_, reject) => {
567
+ timeoutHandle = setTimeout(() => reject(new Error('Connection timeout')), timeout)
568
+ }),
569
+ ])
570
+ clearTimeout(timeoutHandle)
571
+
572
+ const sessionInfo = {
573
+ localPodId: this.#localPodId,
574
+ remotePodId,
575
+ transportType: transport.type,
576
+ establishedAt: Date.now(),
577
+ }
578
+
579
+ this.#onLog(2, `Connected to ${remotePodId} via ${transport.type}`)
580
+ this.#fire('connected', { remotePodId, transport, sessionInfo })
581
+ return { transport, sessionInfo }
582
+ }
583
+
584
+ /**
585
+ * Accept an incoming connection from a remote peer.
586
+ *
587
+ * Handles an incoming WebRTC offer by creating a transport via the
588
+ * factory and invoking its handleOffer method.
589
+ *
590
+ * @param {string} remotePodId - Initiating peer identifier
591
+ * @param {object} offer - SDP offer
592
+ * @returns {Promise<{ transport: object, sessionInfo: object }>}
593
+ */
594
+ async acceptConnection(remotePodId, offer) {
595
+ if (!this.#transportFactory) {
596
+ throw new Error('TransportFactory is required for acceptConnection')
597
+ }
598
+ if (!this.#signalingClient) {
599
+ throw new Error('SignalingClient is required for acceptConnection')
600
+ }
601
+
602
+ this.#onLog(2, `Accepting connection from ${remotePodId}`)
603
+
604
+ const transport = await this.#transportFactory.create('webrtc', {
605
+ localPodId: this.#localPodId,
606
+ remotePodId,
607
+ signaler: this.#signalingClient,
608
+ })
609
+
610
+ if (typeof transport.handleOffer === 'function') {
611
+ await transport.handleOffer(offer)
612
+ }
613
+
614
+ const sessionInfo = {
615
+ localPodId: this.#localPodId,
616
+ remotePodId,
617
+ transportType: transport.type,
618
+ establishedAt: Date.now(),
619
+ }
620
+
621
+ this.#onLog(2, `Accepted connection from ${remotePodId}`)
622
+ this.#fire('connected', { remotePodId, transport, sessionInfo })
623
+ return { transport, sessionInfo }
624
+ }
625
+
626
+ /**
627
+ * Connect to a peer using a DirectInputHandshake connection token.
628
+ *
629
+ * Parses the token, optionally creates a signaling client from the
630
+ * token's signalingUrl, and negotiates a transport.
631
+ *
632
+ * @param {ConnectionToken} token - Decoded connection token
633
+ * @param {object} [transportFactory] - Override transport factory
634
+ * @returns {Promise<{ transport: object, sessionInfo: object }>}
635
+ */
636
+ async connectViaToken(token, transportFactory) {
637
+ const factory = transportFactory || this.#transportFactory
638
+ if (!factory) {
639
+ throw new Error('TransportFactory is required for connectViaToken')
640
+ }
641
+
642
+ const remotePodId = token.podId
643
+ this.#onLog(2, `Connecting via token to ${remotePodId}`)
644
+
645
+ // Build a signaler — use existing client or create one from token's URL
646
+ let signaler = this.#signalingClient
647
+ let createdSignaler = false
648
+
649
+ if (!signaler && token.signalingUrl) {
650
+ signaler = new SignalingClient({
651
+ url: token.signalingUrl,
652
+ localPodId: this.#localPodId,
653
+ onLog: this.#onLog,
654
+ })
655
+ await signaler.connect()
656
+ createdSignaler = true
657
+ }
658
+
659
+ if (!signaler) {
660
+ throw new Error('No signaling channel available (provide signalingClient or token.signalingUrl)')
661
+ }
662
+
663
+ const iceServers = token.iceServers || []
664
+ const endpointOpts = {
665
+ webrtc: { config: { iceServers } },
666
+ }
667
+
668
+ try {
669
+ const transport = await factory.negotiate(
670
+ this.#localPodId,
671
+ remotePodId,
672
+ signaler,
673
+ endpointOpts,
674
+ )
675
+
676
+ const sessionInfo = {
677
+ localPodId: this.#localPodId,
678
+ remotePodId,
679
+ transportType: transport.type,
680
+ establishedAt: Date.now(),
681
+ viaToken: true,
682
+ }
683
+
684
+ this.#onLog(2, `Connected via token to ${remotePodId}`)
685
+ // Clean up signaler we created — transport is now established
686
+ if (createdSignaler && signaler) {
687
+ signaler.disconnect()
688
+ }
689
+ this.#fire('connected', { remotePodId, transport, sessionInfo })
690
+ return { transport, sessionInfo }
691
+ } catch (err) {
692
+ // Clean up signaler we created on failure
693
+ if (createdSignaler && signaler) {
694
+ signaler.disconnect()
695
+ }
696
+ this.#fire('failed', { remotePodId, error: err.message })
697
+ throw err
698
+ }
699
+ }
700
+
701
+ /**
702
+ * Register a callback for incoming connection requests.
703
+ *
704
+ * The callback receives ({ remotePodId, offer }) when another peer
705
+ * initiates a connection via the signaling server.
706
+ *
707
+ * @param {Function} cb
708
+ */
709
+ onIncomingConnection(cb) {
710
+ this.on('incoming', cb)
711
+ }
712
+
713
+ // -- Event system ---------------------------------------------------------
714
+
715
+ /**
716
+ * Register a listener for a given event.
717
+ * Events: 'connected', 'failed', 'incoming'
718
+ *
719
+ * @param {string} event
720
+ * @param {Function} cb
721
+ */
722
+ on(event, cb) {
723
+ if (!this.#listeners.has(event)) {
724
+ this.#listeners.set(event, new Set())
725
+ }
726
+ this.#listeners.get(event).add(cb)
727
+ }
728
+
729
+ /**
730
+ * Remove a listener for a given event.
731
+ * @param {string} event
732
+ * @param {Function} cb
733
+ */
734
+ off(event, cb) {
735
+ const set = this.#listeners.get(event)
736
+ if (set) set.delete(cb)
737
+ }
738
+
739
+ /** True when the signaling client is connected. */
740
+ get connected() {
741
+ return this.#signalingClient ? this.#signalingClient.connected : false
742
+ }
743
+
744
+ // -- Internal -------------------------------------------------------------
745
+
746
+ /**
747
+ * Fire all listeners for a given event, swallowing listener errors.
748
+ * @param {string} event
749
+ * @param {*} data
750
+ */
751
+ #fire(event, data) {
752
+ const set = this.#listeners.get(event)
753
+ if (!set) return
754
+ for (const cb of set) {
755
+ try { cb(data) } catch (e) { silentCatch('clawser-mesh-handshake', 'swallow-listener-errors', e) }
756
+ }
757
+ }
758
+ }
759
+
760
+ export { TOKEN_TTL_MS, DEFAULT_TIMEOUT_MS, toBase64Url, fromBase64Url }