@johnhenry/browsermesh-pod 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.
@@ -16,7 +16,8 @@
16
16
  * forwarded by the signaling server as: { type: 'signal', source, envelope }
17
17
  * (the signaling server spreads the forwarded payload and injects `source`,
18
18
  * so any extra keys like `envelope` survive the hop unchanged)
19
- * - peers: { type: 'peers', peers: string[] } (signaling only, sent once on registration)
19
+ * - peers: { type: 'peers', peers: string[] } (signaling only, sent once on registration,
20
+ * in a frame AFTER `registered`: `open()` can resolve before it is handled)
20
21
  * - peer-joined / peer-left: { type: 'peer-joined'|'peer-left', podId } (signaling only)
21
22
  * - ping / pong: { type: 'ping' } / { type: 'pong' }
22
23
  * - error: { type: 'error', message }
@@ -56,6 +57,7 @@ export class WebSocketTransport {
56
57
  #ready = false
57
58
  #closed = true
58
59
  #knownPeers = new Set()
60
+ #peerJoinedHandlers = new Set()
59
61
 
60
62
  #primaryReconnect = { attempts: 0, timer: null }
61
63
  #sigReconnect = { attempts: 0, timer: null }
@@ -93,6 +95,13 @@ export class WebSocketTransport {
93
95
  this.#onLog = onLog || (() => {})
94
96
  }
95
97
 
98
+ /**
99
+ * The relay stamps `source` and can rewrite or inject envelopes, so nothing
100
+ * about a message is authenticated by this link. A pod requires signed
101
+ * messages over it unless told otherwise (`allowUnsigned`).
102
+ */
103
+ get trust() { return 'untrusted' }
104
+
96
105
  /** @returns {boolean} true once the primary connection is registered */
97
106
  get ready() { return this.#ready }
98
107
 
@@ -106,6 +115,19 @@ export class WebSocketTransport {
106
115
  this.#handler = handler
107
116
  }
108
117
 
118
+ /**
119
+ * Be told about each peer id the server announces (`peers`, `peer-joined`)
120
+ * that this transport did not know yet. `peers` follows `registered` in a
121
+ * later frame, and pods can join at any time, so discovery must react to
122
+ * these rather than assume the list is complete when `open()` resolves.
123
+ * @param {(podId: string) => void} handler
124
+ * @returns {() => void} unsubscribe
125
+ */
126
+ onPeerJoined(handler) {
127
+ this.#peerJoinedHandlers.add(handler)
128
+ return () => this.#peerJoinedHandlers.delete(handler)
129
+ }
130
+
109
131
  /**
110
132
  * Connect to the relay server (and, if configured, the signaling server)
111
133
  * and complete registration. Resolves once `registered` arrives on the
@@ -229,8 +251,7 @@ export class WebSocketTransport {
229
251
  const onOpen = () => {
230
252
  this.#send(ws, { type: 'register', podId: this.#podId })
231
253
  }
232
- const onMessage = (event) => {
233
- const data = this.#parse(event)
254
+ const handle = (data) => {
234
255
  if (!data) return
235
256
  if (isPrimary) this.#handlePrimaryMessage(data)
236
257
  else this.#handleSignalingMessage(data)
@@ -241,6 +262,29 @@ export class WebSocketTransport {
241
262
  finishReject(new Error(data.message || `WebSocketTransport: ${kind} registration error`))
242
263
  }
243
264
  }
265
+ // A Blob frame can only be read asynchronously. Once one is in flight,
266
+ // every later frame on this socket queues behind it so frames are still
267
+ // handled in arrival order; with no Blob in flight nothing changes and
268
+ // frames are handled synchronously.
269
+ let blobQueue = null
270
+ const onMessage = (event) => {
271
+ if (typeof Blob !== 'undefined' && event.data instanceof Blob) {
272
+ const prior = blobQueue ?? Promise.resolve()
273
+ const mine = prior
274
+ .then(() => event.data.arrayBuffer())
275
+ .then((buf) => handle(this.#parse({ data: buf })), () => {})
276
+ blobQueue = mine
277
+ mine.then(() => { if (blobQueue === mine) blobQueue = null })
278
+ return
279
+ }
280
+ if (blobQueue) {
281
+ const mine = blobQueue.then(() => handle(this.#parse(event)))
282
+ blobQueue = mine
283
+ mine.then(() => { if (blobQueue === mine) blobQueue = null })
284
+ return
285
+ }
286
+ handle(this.#parse(event))
287
+ }
244
288
  const onClose = () => {
245
289
  if (isPrimary) { this.#ready = false; this.#ws = null }
246
290
  else { this.#sigWs = null }
@@ -271,7 +315,7 @@ export class WebSocketTransport {
271
315
  if (typeof d === 'string') raw = d
272
316
  else if (d instanceof ArrayBuffer) raw = new TextDecoder().decode(d)
273
317
  else if (ArrayBuffer.isView(d)) raw = new TextDecoder().decode(d)
274
- else return null // Blob (async read) or anything else: not a frame we can read
318
+ else return null // anything else (Blobs are read by the caller first): not a frame we can read
275
319
  return JSON.parse(raw)
276
320
  } catch {
277
321
  return null
@@ -305,6 +349,8 @@ export class WebSocketTransport {
305
349
  // ── Private: inbound ──────────────────────────────────────────────
306
350
 
307
351
  #handlePrimaryMessage(data) {
352
+ // A signaling server used as the primary connection announces peers on it.
353
+ if (this.#protocol === 'signaling' && this.#handlePeerFrame(data)) return
308
354
  switch (data.type) {
309
355
  case 'relayed':
310
356
  case 'signal': {
@@ -323,22 +369,41 @@ export class WebSocketTransport {
323
369
  }
324
370
  }
325
371
 
326
- #handleSignalingMessage(data) {
372
+ /**
373
+ * Apply a `peers` / `peer-joined` / `peer-left` frame to `knownPeers`.
374
+ * Newly learned peers are announced to `onPeerJoined` handlers.
375
+ * @returns {boolean} true if the frame was one of those three
376
+ */
377
+ #handlePeerFrame(data) {
327
378
  switch (data.type) {
328
379
  case 'peers': {
329
- for (const id of data.peers || []) {
330
- if (id !== this.#podId) this.#knownPeers.add(id)
331
- }
332
- return
380
+ for (const id of data.peers || []) this.#learnPeer(id)
381
+ return true
333
382
  }
334
383
  case 'peer-joined': {
335
- if (data.podId && data.podId !== this.#podId) this.#knownPeers.add(data.podId)
336
- return
384
+ this.#learnPeer(data.podId)
385
+ return true
337
386
  }
338
387
  case 'peer-left': {
339
388
  if (data.podId) this.#knownPeers.delete(data.podId)
340
- return
389
+ return true
341
390
  }
391
+ default:
392
+ return false
393
+ }
394
+ }
395
+
396
+ #learnPeer(id) {
397
+ if (!id || id === this.#podId || this.#knownPeers.has(id)) return
398
+ this.#knownPeers.add(id)
399
+ for (const handler of this.#peerJoinedHandlers) {
400
+ try { handler(id) } catch { /* a handler error must not break frame handling */ }
401
+ }
402
+ }
403
+
404
+ #handleSignalingMessage(data) {
405
+ if (this.#handlePeerFrame(data)) return
406
+ switch (data.type) {
342
407
  case 'ping':
343
408
  this.#send(this.#sigWs, { type: 'pong' })
344
409
  return
@@ -352,7 +417,10 @@ export class WebSocketTransport {
352
417
 
353
418
  #deliver(source, envelope) {
354
419
  if (!this.#handler || !envelope || typeof envelope !== 'object') return
355
- const msg = ('from' in envelope) ? envelope : { ...envelope, from: source }
420
+ // `source` is written by the relay. It is passed on as `relaySource` for
421
+ // diagnostics and is never used as the sender's identity: the envelope's
422
+ // own `from` is a claim too, and a pod checks it against a signature.
423
+ const msg = { ...envelope, relaySource: source }
356
424
  this.#handler(msg)
357
425
  }
358
426
  }