@johnhenry/browsermesh-apps 0.1.0 → 0.2.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.
@@ -1,4 +1,5 @@
1
1
  import { silentCatch } from './silent-catch.mjs'
2
+ import { matchScope } from '@johnhenry/browsermesh-primitives'
2
3
  /**
3
4
  * clawser-peer-registry.js -- Unified peer registry with permission management.
4
5
  *
@@ -13,6 +14,51 @@ import { silentCatch } from './silent-catch.mjs'
13
14
  * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-registry.test.mjs
14
15
  */
15
16
 
17
+ // ---------------------------------------------------------------------------
18
+ // Capability tokens (Phase 5 -- real granting/revocation, layered under the
19
+ // existing ACL template mechanism, not replacing it)
20
+ // ---------------------------------------------------------------------------
21
+
22
+ /**
23
+ * Duck-typed default token, used only when no `tokenFactory` is injected.
24
+ * Shaped to satisfy both this module's own default `CapabilityValidator`
25
+ * fallback below AND the real `@johnhenry/browsermesh-core` `CapabilityValidator`
26
+ * (whose `register()`/`revokeTree()`/`validate()` only ever touch `.id`,
27
+ * `.revoked`, `.parentId`, `.resource`, `.permissions`, `.constraints`,
28
+ * `.isExpired()`, `.hasPermission()`, `.revoke()` -- nothing constructor-specific)
29
+ * -- so real callers (see `mesh-bootstrap.mjs`) can inject the real
30
+ * `CapabilityToken` class as `tokenFactory` for the genuine, tested class,
31
+ * while this file itself stays decoupled from `-core` at the module level,
32
+ * matching the existing peerManager/trustGraph/acl DI pattern in this class.
33
+ */
34
+ let _localCapTokenSeq = 0
35
+ class _DefaultCapabilityToken {
36
+ constructor({ issuer, holder, resource, permissions, constraints = {}, parentId = null, createdAt, expiresAt = null }) {
37
+ this.id = `peercap_${Date.now()}_${++_localCapTokenSeq}`
38
+ this.issuer = issuer
39
+ this.holder = holder
40
+ this.resource = resource
41
+ this.permissions = [...permissions]
42
+ this.constraints = { ...constraints }
43
+ this.parentId = parentId
44
+ this.createdAt = createdAt || Date.now()
45
+ this.expiresAt = expiresAt
46
+ this.revoked = false
47
+ }
48
+
49
+ isExpired(now = Date.now()) {
50
+ return this.expiresAt !== null && this.expiresAt !== undefined && now >= this.expiresAt
51
+ }
52
+
53
+ hasPermission(perm) {
54
+ return this.permissions.includes(perm)
55
+ }
56
+
57
+ revoke() {
58
+ this.revoked = true
59
+ }
60
+ }
61
+
16
62
  // ---------------------------------------------------------------------------
17
63
  // PeerRegistry
18
64
  // ---------------------------------------------------------------------------
@@ -41,15 +87,48 @@ export class PeerRegistry {
41
87
  /** @type {Map<string, number>} */
42
88
  #observedTrust = new Map()
43
89
 
90
+ /**
91
+ * Real capability tokens issued through `grantCapabilities()`, tracked so
92
+ * `revokeCapabilities()` can find and revoke the matching token(s) later,
93
+ * and so `checkAccess()` can consult live revocation status. Keyed by
94
+ * peer pubKey -> (exact granted scope string -> token). Only scopes
95
+ * granted via `grantCapabilities()` get an entry here; peers configured
96
+ * purely via `updatePermissions()`/`addEntry()`/default templates have no
97
+ * tracked tokens and are therefore governed by the ACL alone, unaffected
98
+ * by this mechanism (see checkAccess()).
99
+ *
100
+ * @type {Map<string, Map<string, object>>}
101
+ */
102
+ #capabilityTokens = new Map()
103
+
104
+ /** Validates/revokes tokens -- real `CapabilityValidator` when injected, a
105
+ * duck-typed equivalent otherwise. @type {{ register: Function, revokeTree: Function }} */
106
+ #capabilityValidator
107
+
108
+ /** Constructs a token object for grantCapabilities() -- real `CapabilityToken`
109
+ * when injected, `_DefaultCapabilityToken` otherwise. @type {Function} */
110
+ #tokenFactory
111
+
44
112
  /**
45
113
  * @param {object} opts
46
114
  * @param {string} opts.localPodId - Owner identity used for ACL and trust edges
47
115
  * @param {import('@johnhenry/browsermesh-core').MeshPeerManager} [opts.peerManager]
48
116
  * @param {import('@johnhenry/browsermesh-core').TrustGraph} [opts.trustGraph]
49
117
  * @param {import('@johnhenry/browsermesh-core').MeshACL} [opts.acl]
118
+ * @param {import('@johnhenry/browsermesh-core').CapabilityValidator} [opts.capabilityValidator]
119
+ * Backs the real granting/revocation path for `grantCapabilities()`/
120
+ * `revokeCapabilities()` (Phase 5). Defaults to a lightweight in-package
121
+ * equivalent when omitted, so this class stays usable without `-core`
122
+ * installed -- inject the real class (see `mesh-bootstrap.mjs`) for the
123
+ * genuine, tested implementation.
124
+ * @param {Function} [opts.tokenFactory] - `(opts) => token`, used to construct
125
+ * the token registered with `capabilityValidator` on each grant. Defaults to
126
+ * a small duck-typed equivalent of `@johnhenry/browsermesh-core`'s
127
+ * `CapabilityToken`; pass `(opts) => new CapabilityToken(opts)` to use the
128
+ * real class.
50
129
  * @param {Function} [opts.onLog] - Logging callback (level, msg)
51
130
  */
52
- constructor({ localPodId, peerManager, trustGraph, acl, onLog }) {
131
+ constructor({ localPodId, peerManager, trustGraph, acl, capabilityValidator, tokenFactory, onLog }) {
53
132
  if (!localPodId || typeof localPodId !== 'string') {
54
133
  throw new Error('localPodId is required and must be a non-empty string')
55
134
  }
@@ -63,6 +142,8 @@ export class PeerRegistry {
63
142
  this.#peerManager = peerManager ?? this.#createDefaultPeerManager()
64
143
  this.#trustGraph = trustGraph ?? this.#createDefaultTrustGraph()
65
144
  this.#acl = acl ?? this.#createDefaultACL()
145
+ this.#capabilityValidator = capabilityValidator ?? this.#createDefaultCapabilityValidator()
146
+ this.#tokenFactory = tokenFactory ?? ((tokenOpts) => new _DefaultCapabilityToken(tokenOpts))
66
147
  }
67
148
 
68
149
  // ── Peer CRUD ───────────────────────────────────────────────────────
@@ -104,6 +185,17 @@ export class PeerRegistry {
104
185
  // Remove ACL roster entry
105
186
  this.#acl.revokeAll(pubKey)
106
187
 
188
+ // Revoke any live capability tokens issued to this peer and stop
189
+ // tracking them -- a removed peer must not retain live tokens that a
190
+ // later re-add under the same pubKey could otherwise inherit.
191
+ const peerTokens = this.#capabilityTokens.get(pubKey)
192
+ if (peerTokens) {
193
+ for (const token of peerTokens.values()) {
194
+ if (!token.revoked) this.#capabilityValidator.revokeTree(token.id)
195
+ }
196
+ this.#capabilityTokens.delete(pubKey)
197
+ }
198
+
107
199
  if (existed) {
108
200
  this.#onLog(2, `PeerRegistry: removed ${pubKey}`)
109
201
  }
@@ -148,14 +240,22 @@ export class PeerRegistry {
148
240
  }
149
241
 
150
242
  /**
151
- * Grant additional capability scopes to a peer via a dynamic ACL template.
152
- * Creates a per-peer template named `_peer_{pubKey}` that merges with
153
- * any existing scopes.
243
+ * Grant additional capability scopes to a peer via a dynamic ACL template,
244
+ * AND issue a real capability token per scope through the injected (or
245
+ * default) `CapabilityValidator` (Phase 5). The ACL template remains the
246
+ * mechanism `checkAccess()` primarily checks -- fully backward compatible
247
+ * with any caller that only cares about the pre-Phase-5 ACL behavior --
248
+ * while the token gives `revokeCapabilities()` a live revocation target
249
+ * that `checkAccess()` additionally consults, independent of whether/when
250
+ * the ACL template itself gets re-read.
154
251
  *
155
252
  * @param {string} pubKey
156
253
  * @param {string[]} scopes - Scopes to add (e.g. ['files:read', 'chat:write'])
254
+ * @param {object} [opts]
255
+ * @param {number|null} [opts.expiresAt] - Optional expiry (ms epoch) applied
256
+ * to newly-issued tokens for this call. Omit for no expiry.
157
257
  */
158
- grantCapabilities(pubKey, scopes) {
258
+ grantCapabilities(pubKey, scopes, opts = {}) {
159
259
  const templateName = `_peer_${pubKey}`
160
260
  const existing = this.#acl.getTemplate(templateName)
161
261
  const merged = existing
@@ -171,12 +271,44 @@ export class PeerRegistry {
171
271
  this.#acl.addEntry(pubKey, templateName)
172
272
  }
173
273
 
274
+ // Issue a real capability token per scope so revocation has a live
275
+ // target beyond the ACL template. Skip scopes that already have a live
276
+ // (non-revoked, non-expired) token -- re-granting an already-granted
277
+ // scope is a no-op at the token layer, matching the ACL's own
278
+ // dedup/additive behavior above. A scope whose prior token was revoked
279
+ // gets a fresh token (tokens are one-way revocable, never un-revoked).
280
+ let peerTokens = this.#capabilityTokens.get(pubKey)
281
+ if (!peerTokens) {
282
+ peerTokens = new Map()
283
+ this.#capabilityTokens.set(pubKey, peerTokens)
284
+ }
285
+ for (const scope of scopes) {
286
+ const current = peerTokens.get(scope)
287
+ const currentLive = current && !current.revoked &&
288
+ !(typeof current.isExpired === 'function' && current.isExpired())
289
+ if (currentLive) continue
290
+
291
+ const token = this.#tokenFactory({
292
+ issuer: this.#localPodId,
293
+ holder: pubKey,
294
+ resource: scope,
295
+ permissions: ['use'],
296
+ expiresAt: opts.expiresAt ?? null,
297
+ })
298
+ this.#capabilityValidator.register(token)
299
+ peerTokens.set(scope, token)
300
+ }
301
+
174
302
  this.#onLog(3, `PeerRegistry: granted ${scopes.join(', ')} to ${pubKey}`)
175
303
  }
176
304
 
177
305
  /**
178
- * Revoke specific capability scopes from a peer.
179
- * If no scopes remain, removes the per-peer template and roster entry.
306
+ * Revoke specific capability scopes from a peer: removes them from the ACL
307
+ * template (if no scopes remain, removes the per-peer template and roster
308
+ * entry -- unchanged from pre-Phase-5 behavior) AND revokes the matching
309
+ * capability token(s) issued by `grantCapabilities()` through the
310
+ * `CapabilityValidator`, so `checkAccess()`'s live check denies immediately
311
+ * regardless of ACL template state.
180
312
  *
181
313
  * @param {string} pubKey
182
314
  * @param {string[]} scopes - Scopes to remove
@@ -184,18 +316,32 @@ export class PeerRegistry {
184
316
  revokeCapabilities(pubKey, scopes) {
185
317
  const templateName = `_peer_${pubKey}`
186
318
  const existing = this.#acl.getTemplate(templateName)
187
- if (!existing) return
188
319
 
189
- const remaining = existing.scopes.filter(s => !scopes.includes(s))
320
+ if (existing) {
321
+ const remaining = existing.scopes.filter(s => !scopes.includes(s))
322
+
323
+ if (remaining.length === 0) {
324
+ this.#acl.removeEntry(pubKey)
325
+ this.#acl.removeTemplate(templateName)
326
+ } else {
327
+ this.#acl.addTemplate(templateName, remaining, `Auto-generated for ${pubKey}`)
328
+ // Re-sync the roster entry
329
+ this.#acl.removeEntry(pubKey)
330
+ this.#acl.addEntry(pubKey, templateName)
331
+ }
332
+ }
190
333
 
191
- if (remaining.length === 0) {
192
- this.#acl.removeEntry(pubKey)
193
- this.#acl.removeTemplate(templateName)
194
- } else {
195
- this.#acl.addTemplate(templateName, remaining, `Auto-generated for ${pubKey}`)
196
- // Re-sync the roster entry
197
- this.#acl.removeEntry(pubKey)
198
- this.#acl.addEntry(pubKey, templateName)
334
+ // Revoke the matching token(s), if any were issued via grantCapabilities().
335
+ // Scoped precisely: only the exact scopes named here are touched, so a
336
+ // different, still-granted scope for the same peer is unaffected.
337
+ const peerTokens = this.#capabilityTokens.get(pubKey)
338
+ if (peerTokens) {
339
+ for (const scope of scopes) {
340
+ const token = peerTokens.get(scope)
341
+ if (token && !token.revoked) {
342
+ this.#capabilityValidator.revokeTree(token.id)
343
+ }
344
+ }
199
345
  }
200
346
 
201
347
  this.#onLog(3, `PeerRegistry: revoked ${scopes.join(', ')} from ${pubKey}`)
@@ -221,13 +367,39 @@ export class PeerRegistry {
221
367
  /**
222
368
  * Check if a peer is allowed to perform an action on a resource.
223
369
  *
370
+ * First checks the ACL template (unchanged, pre-Phase-5 behavior -- owner
371
+ * bypass, roster/template scope matching). If the ACL allows it, ALSO
372
+ * consults live revocation status for any capability token issued via
373
+ * `grantCapabilities()` whose scope covers this resource/action (Phase 5):
374
+ * a token that was granted then revoked denies access on this check, even
375
+ * if the ACL template itself hasn't been re-read or doesn't (e.g. a
376
+ * broader wildcard scope that revokeCapabilities()'s exact-match ACL
377
+ * removal didn't touch). Peers/scopes never routed through
378
+ * `grantCapabilities()` (e.g. `updatePermissions()`/`addEntry()` callers,
379
+ * default templates) have no tracked token and are therefore governed by
380
+ * the ACL alone, exactly as before.
381
+ *
224
382
  * @param {string} pubKey
225
383
  * @param {string} resource
226
384
  * @param {string} action
227
385
  * @returns {{ allowed: boolean, reason?: string }}
228
386
  */
229
387
  checkAccess(pubKey, resource, action) {
230
- return this.#acl.check(pubKey, resource, action)
388
+ const aclResult = this.#acl.check(pubKey, resource, action)
389
+ if (!aclResult.allowed) return aclResult
390
+
391
+ const scope = `${resource}:${action}`
392
+ const peerTokens = this.#capabilityTokens.get(pubKey)
393
+ if (peerTokens) {
394
+ for (const [grantedScope, token] of peerTokens) {
395
+ if (!matchScope(grantedScope, scope)) continue
396
+ if (token.revoked || (typeof token.isExpired === 'function' && token.isExpired())) {
397
+ return { allowed: false, reason: 'capability_revoked' }
398
+ }
399
+ }
400
+ }
401
+
402
+ return aclResult
231
403
  }
232
404
 
233
405
  // ── Trust management ────────────────────────────────────────────────
@@ -592,4 +764,56 @@ export class PeerRegistry {
592
764
  },
593
765
  }
594
766
  }
767
+
768
+ /**
769
+ * Create a minimal duck-typed CapabilityValidator when none is injected.
770
+ * Mirrors the subset of `@johnhenry/browsermesh-core`'s real
771
+ * `CapabilityValidator` that `grantCapabilities()`/`revokeCapabilities()`/
772
+ * `checkAccess()` actually use: `register()`, `revokeTree()` (revokes a
773
+ * token and, transitively, any tracked token whose `parentId` chains up to
774
+ * it -- unused by this class today since tokens here are always
775
+ * root/flat, but kept for parity with the real class and any future
776
+ * attenuation use), and `validate()` for completeness/introspection.
777
+ * @returns {object}
778
+ */
779
+ #createDefaultCapabilityValidator() {
780
+ const tokens = new Map()
781
+ const revokedIds = new Set()
782
+
783
+ const validator = {
784
+ register(token) {
785
+ tokens.set(token.id, token)
786
+ if (token.revoked) revokedIds.add(token.id)
787
+ },
788
+ revokeTree(tokenId) {
789
+ revokedIds.add(tokenId)
790
+ const token = tokens.get(tokenId)
791
+ if (token) token.revoke()
792
+ for (const [id, t] of tokens) {
793
+ if (t.parentId === tokenId && !revokedIds.has(id)) {
794
+ validator.revokeTree(id)
795
+ }
796
+ }
797
+ },
798
+ validate(tokenId, resource, permission) {
799
+ const token = tokens.get(tokenId)
800
+ if (!token) return { allowed: false, reason: 'Token not found' }
801
+ if (revokedIds.has(tokenId)) return { allowed: false, reason: 'Token revoked' }
802
+ if (token.isExpired()) return { allowed: false, reason: 'Token expired' }
803
+ if (!token.hasPermission(permission)) {
804
+ return { allowed: false, reason: `Permission "${permission}" not granted` }
805
+ }
806
+ const pattern = token.resource
807
+ const matches = pattern === resource || pattern === '*' ||
808
+ (pattern.endsWith('*') && resource.startsWith(pattern.slice(0, -1)))
809
+ if (!matches) {
810
+ return { allowed: false, reason: `Resource "${resource}" not covered by "${pattern}"` }
811
+ }
812
+ return { allowed: true }
813
+ },
814
+ get size() { return tokens.size },
815
+ listTokens() { return [...tokens.values()] },
816
+ }
817
+ return validator
818
+ }
595
819
  }
@@ -0,0 +1,231 @@
1
+ /**
2
+ * signaling.mjs -- MeshSignalingChannel: WebRTC offer/answer/ICE relay.
3
+ *
4
+ * `webrtc-negotiator.mjs`'s adapter factory needs some way to hand an SDP
5
+ * offer to a remote peer and get an SDP answer (and ICE candidates) back,
6
+ * before the WebRTC connection itself exists to carry that traffic. That
7
+ * bootstrap channel is "signaling", and WebRTC deliberately doesn't specify
8
+ * one -- it's left to the application.
9
+ *
10
+ * Rather than adopting `browsermesh-core`'s `SignalingClient` (needs an
11
+ * external WebSocket signaling server that isn't implemented anywhere in
12
+ * this repo) or `browsermesh-transport/websocket.mjs`'s separate
13
+ * `WebRTCTransport`/`TransportFactory` pair (same requirement, and not the
14
+ * implementation the real `test/real-peer/` suite exercises), this is a
15
+ * small, new, transport-agnostic relay: it wraps whatever bidirectional bus
16
+ * is already in hand and speaks exactly three message shapes over it --
17
+ * `{type: 'webrtc-offer'|'webrtc-answer'|'webrtc-ice', from, to, payload}`.
18
+ *
19
+ * The injected `transport` only needs to implement `send(msg)` and
20
+ * `onMessage(cb)` (optionally `open()`/`close()`) -- the same minimal shape
21
+ * `browsermesh-pod`'s `EventEmitterTransport` already exposes, and the shape
22
+ * `createBroadcastChannelSignalingTransport()` below adapts a real
23
+ * `BroadcastChannel` to. Messages not addressed to this channel's
24
+ * `localPodId` (or echoed from itself) are ignored, so many peers can safely
25
+ * share one broadcast-style bus -- exactly how BroadcastChannel and the
26
+ * existing Pod example's `EventEmitterTransport` bus already work in this
27
+ * repo.
28
+ *
29
+ * No browser-only imports at module level.
30
+ */
31
+
32
+ /** @type {readonly string[]} */
33
+ const SIGNAL_TYPES = Object.freeze(['webrtc-offer', 'webrtc-answer', 'webrtc-ice'])
34
+
35
+ // ---------------------------------------------------------------------------
36
+ // MeshSignalingChannel
37
+ // ---------------------------------------------------------------------------
38
+
39
+ /**
40
+ * Relays WebRTC offer/answer/ICE-candidate messages between peers over an
41
+ * injectable transport.
42
+ */
43
+ export class MeshSignalingChannel {
44
+ /** @type {string} */
45
+ #localPodId
46
+
47
+ /** @type {{send: Function, onMessage: Function, open?: Function, close?: Function}} */
48
+ #transport
49
+
50
+ /** @type {Function} */
51
+ #onLog
52
+
53
+ /** @type {Record<string, Set<Function>>} */
54
+ #listeners
55
+
56
+ /** @type {boolean} */
57
+ #opened = false
58
+
59
+ /**
60
+ * @param {object} opts
61
+ * @param {string} opts.localPodId - This node's pod identifier; messages
62
+ * not addressed to this id (`msg.to !== localPodId`) are ignored.
63
+ * @param {{send: Function, onMessage: Function, open?: Function, close?: Function}} opts.transport
64
+ * Injectable bidirectional bus. Must implement `send(msg)` and
65
+ * `onMessage(cb)`. `open()`/`close()` are called if present.
66
+ * @param {Function} [opts.onLog]
67
+ */
68
+ constructor({ localPodId, transport, onLog } = {}) {
69
+ if (!localPodId || typeof localPodId !== 'string') {
70
+ throw new Error('localPodId is required and must be a non-empty string')
71
+ }
72
+ if (!transport || typeof transport.send !== 'function') {
73
+ throw new Error('transport is required and must implement send(msg)')
74
+ }
75
+ if (typeof transport.onMessage !== 'function') {
76
+ throw new Error('transport is required and must implement onMessage(cb)')
77
+ }
78
+
79
+ this.#localPodId = localPodId
80
+ this.#transport = transport
81
+ this.#onLog = onLog || (() => {})
82
+ this.#listeners = {
83
+ 'webrtc-offer': new Set(),
84
+ 'webrtc-answer': new Set(),
85
+ 'webrtc-ice': new Set(),
86
+ }
87
+
88
+ this.#transport.onMessage((msg) => this.#handleMessage(msg))
89
+ }
90
+
91
+ /** This channel's local pod identifier. */
92
+ get localPodId() {
93
+ return this.#localPodId
94
+ }
95
+
96
+ /**
97
+ * Open the underlying transport (no-op if it has no `open()`).
98
+ * @returns {Promise<void>}
99
+ */
100
+ async open() {
101
+ if (this.#opened) return
102
+ if (typeof this.#transport.open === 'function') {
103
+ await this.#transport.open()
104
+ }
105
+ this.#opened = true
106
+ }
107
+
108
+ /**
109
+ * Close the underlying transport (no-op if it has no `close()`).
110
+ * @returns {Promise<void>}
111
+ */
112
+ async close() {
113
+ if (!this.#opened) return
114
+ if (typeof this.#transport.close === 'function') {
115
+ await this.#transport.close()
116
+ }
117
+ this.#opened = false
118
+ }
119
+
120
+ /**
121
+ * Send a signaling message to a specific peer.
122
+ *
123
+ * @param {'webrtc-offer'|'webrtc-answer'|'webrtc-ice'} type
124
+ * @param {string} to - Target pod identifier
125
+ * @param {*} payload - The offer/answer/candidate object
126
+ */
127
+ send(type, to, payload) {
128
+ if (!SIGNAL_TYPES.includes(type)) {
129
+ throw new Error(`Unknown signal type: ${type}`)
130
+ }
131
+ if (!to || typeof to !== 'string') {
132
+ throw new Error('to is required and must be a non-empty string')
133
+ }
134
+ this.#transport.send({ type, from: this.#localPodId, to, payload })
135
+ }
136
+
137
+ /**
138
+ * Subscribe to incoming offers. Callback receives `(fromPodId, offer)`.
139
+ * @param {(fromPodId: string, offer: object) => void} cb
140
+ * @returns {() => void} Unsubscribe function.
141
+ */
142
+ onOffer(cb) {
143
+ return this.#on('webrtc-offer', cb)
144
+ }
145
+
146
+ /**
147
+ * Subscribe to incoming answers. Callback receives `(fromPodId, answer)`.
148
+ * @param {(fromPodId: string, answer: object) => void} cb
149
+ * @returns {() => void} Unsubscribe function.
150
+ */
151
+ onAnswer(cb) {
152
+ return this.#on('webrtc-answer', cb)
153
+ }
154
+
155
+ /**
156
+ * Subscribe to incoming ICE candidates. Callback receives `(fromPodId, candidate)`.
157
+ * @param {(fromPodId: string, candidate: object) => void} cb
158
+ * @returns {() => void} Unsubscribe function.
159
+ */
160
+ onIce(cb) {
161
+ return this.#on('webrtc-ice', cb)
162
+ }
163
+
164
+ // -- Internal -------------------------------------------------------------
165
+
166
+ #on(type, cb) {
167
+ if (typeof cb !== 'function') {
168
+ throw new Error('callback must be a function')
169
+ }
170
+ this.#listeners[type].add(cb)
171
+ return () => this.#listeners[type].delete(cb)
172
+ }
173
+
174
+ #handleMessage(msg) {
175
+ if (!msg || typeof msg !== 'object') return
176
+ if (!SIGNAL_TYPES.includes(msg.type)) return
177
+ if (msg.to !== this.#localPodId) return // not addressed to us
178
+ if (msg.from === this.#localPodId) return // ignore our own broadcast echo
179
+
180
+ for (const cb of [...this.#listeners[msg.type]]) {
181
+ try {
182
+ cb(msg.from, msg.payload)
183
+ } catch (err) {
184
+ this.#onLog('signaling:listener-error', {
185
+ type: msg.type,
186
+ error: err?.message || String(err),
187
+ })
188
+ }
189
+ }
190
+ }
191
+ }
192
+
193
+ // ---------------------------------------------------------------------------
194
+ // BroadcastChannel adapter
195
+ // ---------------------------------------------------------------------------
196
+
197
+ /**
198
+ * Wrap a real `BroadcastChannel` as a `{send, onMessage, close}` transport
199
+ * suitable for `MeshSignalingChannel`. Browser-only (throws if
200
+ * `BroadcastChannel` is not on the global scope) -- for Node, supply a
201
+ * different transport (e.g. an `EventEmitterTransport`-shaped bus) instead.
202
+ *
203
+ * @param {string} [channelName='mesh-signaling']
204
+ * @returns {{send: Function, onMessage: Function, close: Function}}
205
+ */
206
+ export function createBroadcastChannelSignalingTransport(channelName = 'mesh-signaling') {
207
+ if (typeof BroadcastChannel === 'undefined') {
208
+ throw new Error(
209
+ 'createBroadcastChannelSignalingTransport() requires a global BroadcastChannel ' +
210
+ '(browser-only). Supply a Node-safe transport instead.',
211
+ )
212
+ }
213
+ const channel = new BroadcastChannel(channelName)
214
+ let handler = null
215
+ channel.onmessage = (event) => {
216
+ if (handler) handler(event.data)
217
+ }
218
+ return {
219
+ send(msg) {
220
+ channel.postMessage(msg)
221
+ },
222
+ onMessage(cb) {
223
+ handler = cb
224
+ },
225
+ close() {
226
+ channel.close()
227
+ },
228
+ }
229
+ }
230
+
231
+ export { SIGNAL_TYPES }