@johnhenry/browsermesh-apps 0.4.2 → 0.5.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/package.json CHANGED
@@ -1,12 +1,16 @@
1
1
  {
2
2
  "name": "@johnhenry/browsermesh-apps",
3
- "version": "0.4.2",
3
+ "version": "0.5.0",
4
4
  "description": "Application layer: marketplace, chat, payments, compute, orchestration, and agent tools for BrowserMesh",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
7
7
  "exports": {
8
8
  ".": "./src/index.mjs",
9
- "./compat": "./src/compat.mjs"
9
+ "./compat": "./src/compat.mjs",
10
+ "./mesh-rpc": "./src/mesh-rpc.mjs",
11
+ "./mesh-fetch": "./src/mesh-fetch.mjs",
12
+ "./mesh-service": "./src/mesh-service.mjs",
13
+ "./peer-registry": "./src/peer-registry.mjs"
10
14
  },
11
15
  "files": [
12
16
  "src",
@@ -1006,10 +1006,11 @@ export async function createMeshNode(options = {}) {
1006
1006
  // give it the same PeerNode-level session bookkeeping connectToPeer()
1007
1007
  // gives the caller side, so sendTo()/onIncomingData() work symmetrically
1008
1008
  // regardless of which side dialed.
1009
- onIncomingConnection: (remotePodId, adapter) => {
1010
- node.adoptIncomingSession(remotePodId, adapter, 'webrtc').catch((err) => {
1009
+ onIncomingConnection: (remotePodId, adapter, connectionId) => {
1010
+ node.adoptIncomingSession(remotePodId, adapter, 'webrtc', { connectionId }).catch((err) => {
1011
1011
  onLog('mesh-bootstrap:adopt-incoming-session-failed', {
1012
1012
  remotePodId,
1013
+ connectionId,
1013
1014
  error: err?.message || String(err),
1014
1015
  })
1015
1016
  })
@@ -57,15 +57,31 @@
57
57
  * here without a real peer-side pong responder would just be a timer
58
58
  * that always reports "unhealthy" after `maxMissed` misses no matter how
59
59
  * healthy the connection actually is -- worse than not wiring it.
60
- * - `ConnectionPool`: `PeerNode` keeps exactly one active session per peer
61
- * today (`#sessions` in peer-node.mjs, keyed by a fresh session per
62
- * `connectToPeer()`/`adoptIncomingSession()` call) -- there is no
63
- * multiple-connections-per-peer call site for `ConnectionPool`'s
64
- * `add()`/`acquire()`/`release()` cycle to attach to without a deeper
65
- * change to `PeerNode`'s session model itself.
60
+ * - `ConnectionPool`: as of issue #116, `PeerNode` *can* hold more than one
61
+ * active session per peer (`connectToPeer()`/`adoptIncomingSession()`
62
+ * both take a `connectionId`, tagging the `#sessions` entry they create
63
+ * in peer-node.mjs), but those sessions are still named/addressed
64
+ * explicitly by the caller, not pooled/acquired opaquely -- `sendTo()`
65
+ * picks either "most recently created" or an exact `connectionId`, never
66
+ * "whichever idle one `ConnectionPool.acquire()` hands back". Wiring
67
+ * `ConnectionPool` itself here would mean layering a second, different
68
+ * connection-selection model (acquire/release semantics for reused,
69
+ * anonymous pooled connections) on top of the named-session model
70
+ * `PeerNode` now has, for no concretely-needed benefit yet.
66
71
  * Both remain exported from `@johnhenry/browsermesh-core` for callers who
67
72
  * want to build that wiring themselves.
68
73
  *
74
+ * ## Multiple connections per peer (issue #116)
75
+ * `endpointsKey(endpoints, auth)` folds `auth.connectionId` into the key
76
+ * (when present) precisely so two `PeerNode.connectToPeer()` calls for the
77
+ * same peer with *different* `connectionId`s get their own `RetryWithBackoff`
78
+ * / `TransportFailover` / metrics instance apiece, each independently
79
+ * `.connect()`-ing rather than the second call silently reusing the first's
80
+ * already-active `TransportFailover` and `.failover()`-ing (renegotiating)
81
+ * *that* connection instead of ever establishing its own. Calls that never
82
+ * pass `auth.connectionId` are unaffected -- same key as before this was
83
+ * added.
84
+ *
69
85
  * No browser-only imports at module level.
70
86
  */
71
87
 
@@ -81,17 +97,26 @@ const DEFAULT_METRICS_KEY = 'unknown'
81
97
  * can derive the SAME key to look up this file's `failovers` map for a given
82
98
  * peer's pubKey -- see that file's own header comment for why this is a
83
99
  * best-effort, webrtc-convention-specific correlation rather than a real
84
- * shared index keyed by pubKey.
100
+ * shared index keyed by pubKey. `mesh-keepalive.mjs` only ever calls this
101
+ * with one argument, correlating against the peer's `DEFAULT_CONNECTION_ID`
102
+ * connection specifically -- see this file's header comment on `auth`, below.
85
103
  *
86
104
  * @param {object} [endpoints]
105
+ * @param {object} [auth] - If `auth.connectionId` is present (issue #116:
106
+ * `PeerNode.connectToPeer()`'s `auth.connectionId`, threaded straight
107
+ * through to `negotiate(endpoints, auth)`), it's folded into the key so
108
+ * independent connections to the same peer get independent retry/failover/
109
+ * metrics state. Omitting it (or `connectionId`) reproduces the exact key
110
+ * this function returned before that parameter existed.
87
111
  * @returns {string}
88
112
  */
89
- export function endpointsKey(endpoints) {
113
+ export function endpointsKey(endpoints, auth) {
90
114
  if (!endpoints) return DEFAULT_METRICS_KEY
91
115
  const values = Object.keys(endpoints)
92
116
  .sort()
93
117
  .map((type) => `${type}=${endpoints[type]}`)
94
- return values.length > 0 ? values.join('&') : DEFAULT_METRICS_KEY
118
+ const base = values.length > 0 ? values.join('&') : DEFAULT_METRICS_KEY
119
+ return auth?.connectionId ? `${base}::connectionId=${auth.connectionId}` : base
95
120
  }
96
121
 
97
122
  /**
@@ -202,7 +227,7 @@ export function createHardenedNegotiator({ negotiator, retryOptions, onLog }) {
202
227
  }
203
228
 
204
229
  async function negotiate(endpoints, auth) {
205
- const key = endpointsKey(endpoints)
230
+ const key = endpointsKey(endpoints, auth)
206
231
  const failover = getFailover(key, endpoints, auth)
207
232
  const transportMetrics = metrics.getOrCreate(key)
208
233
  const startedAt = Date.now()
@@ -248,6 +248,9 @@ export class EscrowManager {
248
248
  /** @type {Function} */
249
249
  #onLog
250
250
 
251
+ /** @type {(op: 'debit'|'credit', amount: number, podId: string, memo: string) => (any|Promise<any>)} */
252
+ #mutateLedger
253
+
251
254
  /** @type {Map<string, Function[]>} */
252
255
  #listeners = new Map()
253
256
 
@@ -255,6 +258,22 @@ export class EscrowManager {
255
258
  * @param {object} opts
256
259
  * @param {object} opts.creditLedger - Must have charge(), credit(), getBalance()
257
260
  * @param {Function} [opts.onLog] - Logging callback (level, msg)
261
+ * @param {(op: 'debit'|'credit', amount: number, podId: string, memo: string) => (any|Promise<any>)} [opts.mutateLedger] -
262
+ * Async (or sync) hook invoked in place of a direct `creditLedger.debit()`/`.credit()`
263
+ * call at every ledger-mutation point in `create()`/`release()`/`refund()`/`checkExpired()`.
264
+ * `op` is `'debit'` (payer loses funds, in `create()`) or `'credit'` (a pod gains funds,
265
+ * in `release()`/`refund()`/`checkExpired()`); `amount`/`podId`/`memo` are the exact
266
+ * arguments `CreditLedger.debit(amount, toPodId, memo)`/`.credit(amount, fromPodId, memo)`
267
+ * already take (amount first, podId second — see payments.mjs), just with an `op`
268
+ * discriminator prepended so one hook can stand in for both methods. Defaults to calling
269
+ * `creditLedger.debit()`/`.credit()` directly — today's exact behavior — so any existing
270
+ * caller that does not pass this option sees no change at all. Callers that DO pass it
271
+ * (e.g. to route the mutation through an awaited PBFT consensus round instead) are
272
+ * responsible for actually performing the debit/credit against `creditLedger` themselves
273
+ * (or an equivalent ledger) inside the hook; if the hook throws or its returned promise
274
+ * rejects, that rejection propagates out of `create()`/`release()`/`refund()`/
275
+ * `checkExpired()` exactly the way a synchronous `creditLedger.debit()`/`.credit()` throw
276
+ * already did before this change (e.g. insufficient balance).
258
277
  */
259
278
  constructor(opts) {
260
279
  if (!opts?.creditLedger) {
@@ -262,6 +281,11 @@ export class EscrowManager {
262
281
  }
263
282
  this.#creditLedger = opts.creditLedger
264
283
  this.#onLog = opts.onLog ?? (() => {})
284
+ this.#mutateLedger = opts.mutateLedger ?? ((op, amount, podId, memo) => (
285
+ op === 'debit'
286
+ ? this.#creditLedger.debit(amount, podId, memo)
287
+ : this.#creditLedger.credit(amount, podId, memo)
288
+ ))
265
289
  }
266
290
 
267
291
  // ── Create ─────────────────────────────────────────────────────
@@ -276,16 +300,17 @@ export class EscrowManager {
276
300
  * @param {string} [opts.description]
277
301
  * @param {Array<{ type: string, params?: object }>} [opts.conditions]
278
302
  * @param {number} [opts.timeoutMs]
279
- * @returns {EscrowContract}
280
- * @throws {Error} If payer has insufficient balance
303
+ * @returns {Promise<EscrowContract>}
304
+ * @throws {Error} If payer has insufficient balance (or the `mutateLedger` hook rejects)
281
305
  */
282
- create(opts) {
306
+ async create(opts) {
283
307
  const { payerPodId, payeePodId, amount, description, conditions, timeoutMs } = opts
284
308
 
285
- // Debit payer — throws on insufficient balance. CreditLedger's real
286
- // signature is debit(amount, toPodId, memo) -- no charge() method
287
- // exists; amount comes first, not the podId.
288
- this.#creditLedger.debit(amount, payerPodId, `escrow: ${description || 'contract'}`)
309
+ // Debit payer — throws (or rejects) on insufficient balance. CreditLedger's
310
+ // real signature is debit(amount, toPodId, memo) -- no charge() method
311
+ // exists; amount comes first, not the podId. Routed through #mutateLedger,
312
+ // which defaults to calling creditLedger.debit() directly (see constructor).
313
+ await this.#mutateLedger('debit', amount, payerPodId, `escrow: ${description || 'contract'}`)
289
314
 
290
315
  const contract = new EscrowContract({
291
316
  payer: payerPodId,
@@ -311,10 +336,11 @@ export class EscrowManager {
311
336
  *
312
337
  * @param {string} contractId
313
338
  * @param {object} [proof] - Proof object for condition checking
314
- * @returns {{ success: boolean, txId?: string }}
315
- * @throws {Error} If contract not found, not funded, expired, or conditions not met
339
+ * @returns {Promise<{ success: boolean, txId?: string }>}
340
+ * @throws {Error} If contract not found, not funded, expired, conditions not met
341
+ * (or the `mutateLedger` hook rejects)
316
342
  */
317
- release(contractId, proof) {
343
+ async release(contractId, proof) {
318
344
  const contract = this.#getValidContract(contractId, 'release')
319
345
 
320
346
  if (contract.status !== 'funded') {
@@ -334,8 +360,9 @@ export class EscrowManager {
334
360
  }
335
361
 
336
362
  // Credit payee. CreditLedger's real signature is credit(amount,
337
- // fromPodId, memo) -- amount first, not the podId.
338
- this.#creditLedger.credit(contract.amount, contract.payee, `escrow release: ${contractId}`)
363
+ // fromPodId, memo) -- amount first, not the podId. Routed through
364
+ // #mutateLedger, which defaults to calling creditLedger.credit() directly.
365
+ await this.#mutateLedger('credit', contract.amount, contract.payee, `escrow release: ${contractId}`)
339
366
  contract.status = 'released'
340
367
 
341
368
  this.#onLog('info', `Escrow released: ${contractId} (${contract.amount} to ${contract.payee})`)
@@ -351,10 +378,10 @@ export class EscrowManager {
351
378
  *
352
379
  * @param {string} contractId
353
380
  * @param {string} [reason]
354
- * @returns {{ success: boolean, txId?: string }}
355
- * @throws {Error} If contract not found or not funded
381
+ * @returns {Promise<{ success: boolean, txId?: string }>}
382
+ * @throws {Error} If contract not found or not funded (or the `mutateLedger` hook rejects)
356
383
  */
357
- refund(contractId, reason) {
384
+ async refund(contractId, reason) {
358
385
  const contract = this.#getValidContract(contractId, 'refund')
359
386
 
360
387
  if (contract.status !== 'funded') {
@@ -362,7 +389,9 @@ export class EscrowManager {
362
389
  }
363
390
 
364
391
  // Credit payer. Same real signature as release() above: amount first.
365
- this.#creditLedger.credit(contract.amount, contract.payer, `escrow refund: ${reason || contractId}`)
392
+ // Routed through #mutateLedger, which defaults to calling
393
+ // creditLedger.credit() directly.
394
+ await this.#mutateLedger('credit', contract.amount, contract.payer, `escrow refund: ${reason || contractId}`)
366
395
  contract.status = 'refunded'
367
396
 
368
397
  this.#onLog('info', `Escrow refunded: ${contractId} (${contract.amount} to ${contract.payer})`)
@@ -400,9 +429,9 @@ export class EscrowManager {
400
429
  * and still funded.
401
430
  *
402
431
  * @param {number} [now] - Current timestamp (default: Date.now())
403
- * @returns {number} Count of expired contracts
432
+ * @returns {Promise<number>} Count of expired contracts
404
433
  */
405
- checkExpired(now) {
434
+ async checkExpired(now) {
406
435
  let count = 0
407
436
  const ts = now ?? Date.now()
408
437
 
@@ -410,7 +439,12 @@ export class EscrowManager {
410
439
  if (contract.status === 'funded' && contract.isExpired(ts)) {
411
440
  // Auto-refund expired contracts. Same real signature as release()/
412
441
  // refund() above: credit(amount, fromPodId, memo), amount first.
413
- this.#creditLedger.credit(
442
+ // Routed through #mutateLedger, which defaults to calling
443
+ // creditLedger.credit() directly. Awaited sequentially (not
444
+ // Promise.all) so events fire in the same deterministic order as
445
+ // the original synchronous sweep.
446
+ await this.#mutateLedger(
447
+ 'credit',
414
448
  contract.amount,
415
449
  contract.payer,
416
450
  `escrow expired: ${contract.id}`,
@@ -725,6 +759,9 @@ const DEFAULT_ESCROW_REQUEST_TIMEOUT_MS = 10000
725
759
  * @param {Function} [opts.onLog] - Logging callback (level, msg) -- forwarded to `EscrowManager`'s own `onLog`, PLUS this wrapper's own wire-level logging (send/handling failures, denied requests).
726
760
  * @param {string} [opts.envelopeType='escrow'] - `envelope.type` used for request/response traffic.
727
761
  * @param {number} [opts.requestTimeoutMs=10000] - How long `requestCreate()`/`requestRelease()`/`requestRefund()`/`requestDispute()` wait for a response.
762
+ * @param {Function} [opts.mutateLedger] - Forwarded verbatim to `new EscrowManager()` -- see that
763
+ * class's constructor doc comment. Omitted by default, so `EscrowManager` falls back to its
764
+ * own default (direct `creditLedger.debit()`/`.credit()` calls) -- today's exact behavior.
728
765
  * @returns {import('./mesh-service.mjs').MeshService}
729
766
  */
730
767
  export function createEscrowService(opts = {}) {
@@ -733,6 +770,7 @@ export function createEscrowService(opts = {}) {
733
770
  onLog,
734
771
  envelopeType = DEFAULT_ESCROW_ENVELOPE_TYPE,
735
772
  requestTimeoutMs = DEFAULT_ESCROW_REQUEST_TIMEOUT_MS,
773
+ mutateLedger,
736
774
  } = opts
737
775
  const log = onLog || (() => {})
738
776
 
@@ -743,6 +781,7 @@ export function createEscrowService(opts = {}) {
743
781
  const manager = new EscrowManager({
744
782
  creditLedger,
745
783
  onLog: (level, msg) => log('escrow:manager-log', { level, message: msg }),
784
+ mutateLedger,
746
785
  })
747
786
 
748
787
  // -- Bridge EscrowManager's own on()/off() events through ctx.emit() --
@@ -777,8 +816,8 @@ export function createEscrowService(opts = {}) {
777
816
  }
778
817
  }
779
818
 
780
- function doCreate(createOpts) {
781
- const contract = manager.create(createOpts)
819
+ async function doCreate(createOpts) {
820
+ const contract = await manager.create(createOpts)
782
821
  grantContractAccess(contract)
783
822
  return contract
784
823
  }
@@ -807,7 +846,7 @@ export function createEscrowService(opts = {}) {
807
846
  if (op === 'create') {
808
847
  const { allowed } = ctx.registry.checkAccess(fromPubKey, 'escrow', 'create')
809
848
  if (!allowed) throw new Error('access denied')
810
- const contract = doCreate({
849
+ const contract = await doCreate({
811
850
  payerPodId: fromPubKey,
812
851
  payeePodId: payload?.payeePodId,
813
852
  amount: payload?.amount,
@@ -823,8 +862,8 @@ export function createEscrowService(opts = {}) {
823
862
  }
824
863
  const { allowed } = ctx.registry.checkAccess(fromPubKey, `escrow:${contractId}`, op)
825
864
  if (!allowed) throw new Error('access denied')
826
- if (op === 'release') result = manager.release(contractId, payload?.proof)
827
- else if (op === 'refund') result = manager.refund(contractId, payload?.reason)
865
+ if (op === 'release') result = await manager.release(contractId, payload?.proof)
866
+ else if (op === 'refund') result = await manager.refund(contractId, payload?.reason)
828
867
  else result = manager.dispute(contractId, payload?.evidence)
829
868
  } else {
830
869
  throw new Error(`unknown op: ${op}`)
package/src/peer-node.mjs CHANGED
@@ -23,6 +23,18 @@ const PEER_NODE_STATES = Object.freeze([
23
23
  'shutting_down',
24
24
  ])
25
25
 
26
+ /**
27
+ * Connection identifier a session is tagged with when the caller doesn't
28
+ * request a specific one (issue #116). `#sessions` has always structurally
29
+ * supported multiple entries per pubKey (it's keyed by sessionId, not
30
+ * pubKey), but nothing before this ever created more than one -- this tag
31
+ * is what makes a second, independently-negotiated session for the same
32
+ * pubKey addressable (`sendTo(pubKey, data, { connectionId })`) rather than
33
+ * just an untargetable extra entry that `sendTo()`'s "most recent" fallback
34
+ * happens to shadow.
35
+ */
36
+ const DEFAULT_CONNECTION_ID = 'default'
37
+
26
38
  // ---------------------------------------------------------------------------
27
39
  // PeerNode
28
40
  // ---------------------------------------------------------------------------
@@ -331,8 +343,16 @@ export class PeerNode {
331
343
  *
332
344
  * @param {string} pubKey - Peer fingerprint / public key hash
333
345
  * @param {object} [endpoints] - Map of transport type -> endpoint string
334
- * @param {object} [auth] - Auth credentials for transport negotiation
335
- * @returns {Promise<object>} Session info
346
+ * @param {object} [auth] - Auth credentials for transport negotiation.
347
+ * `auth.connectionId` (issue #116), if present, both (a) is threaded
348
+ * through to `transportNegotiator.negotiate(endpoints, auth)` -- for the
349
+ * `'webrtc'` adapter (`webrtc-negotiator.mjs`) this opens a fully
350
+ * independent `RTCPeerConnection` to a peer already connected to under a
351
+ * different `connectionId` -- and (b) tags the resulting session, so
352
+ * `sendTo()`/`hasActiveSession()` can address it specifically afterward.
353
+ * Omit it to get (or add another anonymous session sharing) the peer's
354
+ * `DEFAULT_CONNECTION_ID` session, exactly as before this was added.
355
+ * @returns {Promise<object>} Session info (includes `connectionId`)
336
356
  */
337
357
  async connectToPeer(pubKey, endpoints, auth) {
338
358
  this.#ensureRunning('connectToPeer')
@@ -369,7 +389,8 @@ export class PeerNode {
369
389
  // Create session (and wire its inbound data fan-out) via the same
370
390
  // helper `adoptIncomingSession()` uses for the callee side, so both
371
391
  // sides of a connection end up with identically-shaped bookkeeping.
372
- const session = this.#createSession(pubKey, transportType, transport)
392
+ const connectionId = auth?.connectionId ?? DEFAULT_CONNECTION_ID
393
+ const session = this.#createSession(pubKey, transportType, transport, connectionId)
373
394
 
374
395
  this.#onLog('peer-node:session:created', {
375
396
  sessionId: session.sessionId,
@@ -412,9 +433,16 @@ export class PeerNode {
412
433
  * @param {object} transportInstance - An already-open MeshTransport-shaped
413
434
  * object: must implement `send(data)`, should implement `onMessage(cb)`.
414
435
  * @param {string} transportType - e.g. `'webrtc'`
436
+ * @param {object} [opts]
437
+ * @param {string} [opts.connectionId] - Which of possibly-several
438
+ * independent connections to `pubKey` this is (issue #116); see
439
+ * `connectToPeer()`'s `auth.connectionId` doc. Defaults to
440
+ * `DEFAULT_CONNECTION_ID`. `webrtc-negotiator.mjs`'s
441
+ * `onIncomingConnection` hook passes through whichever connectionId the
442
+ * inbound offer carried.
415
443
  * @returns {Promise<object>} Session info (same shape as `connectToPeer()`'s)
416
444
  */
417
- async adoptIncomingSession(pubKey, transportInstance, transportType) {
445
+ async adoptIncomingSession(pubKey, transportInstance, transportType, { connectionId = DEFAULT_CONNECTION_ID } = {}) {
418
446
  this.#ensureRunning('adoptIncomingSession')
419
447
  if (!pubKey || typeof pubKey !== 'string') {
420
448
  throw new Error('adoptIncomingSession: pubKey is required')
@@ -425,7 +453,7 @@ export class PeerNode {
425
453
 
426
454
  this.#registry.connect(pubKey, { transport: transportType })
427
455
 
428
- const session = this.#createSession(pubKey, transportType, transportInstance)
456
+ const session = this.#createSession(pubKey, transportType, transportInstance, connectionId)
429
457
 
430
458
  this.#onLog('peer-node:session:adopted', {
431
459
  sessionId: session.sessionId,
@@ -453,14 +481,16 @@ export class PeerNode {
453
481
  * @param {string} pubKey
454
482
  * @param {string|null} transportType
455
483
  * @param {object|null} transportInstance
484
+ * @param {string} [connectionId] - Defaults to `DEFAULT_CONNECTION_ID`.
456
485
  * @returns {object} The new session entry (includes `transportInstance`;
457
486
  * callers strip it before returning to their own caller)
458
487
  */
459
- #createSession(pubKey, transportType, transportInstance) {
488
+ #createSession(pubKey, transportType, transportInstance, connectionId = DEFAULT_CONNECTION_ID) {
460
489
  const sessionId = crypto.randomUUID()
461
490
  const session = {
462
491
  sessionId,
463
492
  pubKey,
493
+ connectionId,
464
494
  transport: transportType,
465
495
  transportInstance,
466
496
  connectedAt: Date.now(),
@@ -471,7 +501,7 @@ export class PeerNode {
471
501
  if (transportInstance && typeof transportInstance.onMessage === 'function') {
472
502
  transportInstance.onMessage((data) => {
473
503
  for (const cb of this.#dataListeners) {
474
- try { cb(pubKey, data, { sessionId, transport: transportType }) }
504
+ try { cb(pubKey, data, { sessionId, transport: transportType, connectionId }) }
475
505
  catch (err) { this.#onLog('peer-node:data-listener-error', { error: err?.message || String(err) }) }
476
506
  }
477
507
  })
@@ -505,15 +535,24 @@ export class PeerNode {
505
535
 
506
536
  /**
507
537
  * Send raw bytes/data to a connected peer via its current transport
508
- * session. Looks up the most recently-created active session for the
509
- * given pubKey and calls `transport.send(data)`.
538
+ * session, and calls `transport.send(data)`.
510
539
  *
511
- * Throws when no active session exists for the peer (caller should
512
- * either connect first or surface the error to the user).
540
+ * Without `opts.connectionId`, looks up the most recently-created active
541
+ * session for the given pubKey -- exactly the pre-#116 behavior, which
542
+ * is unambiguous as long as a peer has at most one session (still true
543
+ * unless a caller deliberately opened another one via `connectToPeer()`'s
544
+ * or `adoptIncomingSession()`'s `connectionId`). With multiple sessions
545
+ * per pubKey, pass `opts.connectionId` to target one specifically.
546
+ *
547
+ * Throws when no matching active session exists for the peer (caller
548
+ * should either connect first or surface the error to the user).
513
549
  *
514
550
  * @param {string} pubKey - Peer fingerprint / public key hash
515
551
  * @param {*} data - Wire payload to send. Format is transport-defined;
516
552
  * typical callers stringify a JSON envelope first.
553
+ * @param {object} [opts]
554
+ * @param {string} [opts.connectionId] - Target this specific connection's
555
+ * session (issue #116) rather than "most recently created".
517
556
  * @returns {Promise<void>} Resolves when the underlying transport
518
557
  * has accepted the send (transport-defined; some are fire-and-
519
558
  * forget, others await an ack).
@@ -521,14 +560,14 @@ export class PeerNode {
521
560
  * @example
522
561
  * await peerNode.sendTo('podid_abc', JSON.stringify({ type: 'ping' }));
523
562
  */
524
- async sendTo(pubKey, data) {
563
+ async sendTo(pubKey, data, { connectionId } = {}) {
525
564
  this.#ensureRunning('sendTo');
526
565
  let session = null;
527
566
  for (const [, s] of this.#sessions) {
528
- if (s.pubKey === pubKey && s.state === 'active') {
529
- // Prefer the most recently-created active session
530
- if (!session || (s.connectedAt || 0) > (session.connectedAt || 0)) session = s;
531
- }
567
+ if (s.pubKey !== pubKey || s.state !== 'active') continue;
568
+ if (connectionId !== undefined && s.connectionId !== connectionId) continue;
569
+ // Prefer the most recently-created active (matching) session
570
+ if (!session || (s.connectedAt || 0) > (session.connectedAt || 0)) session = s;
532
571
  }
533
572
  if (!session) {
534
573
  throw new Error(`PeerNode.sendTo: no active session for pubKey ${pubKey}`);
@@ -558,15 +597,35 @@ export class PeerNode {
558
597
  * Whether the peer has an active session ready for `sendTo`.
559
598
  *
560
599
  * @param {string} pubKey
600
+ * @param {object} [opts]
601
+ * @param {string} [opts.connectionId] - If given, check that specific
602
+ * connection's session (issue #116) rather than "any session".
561
603
  * @returns {boolean}
562
604
  */
563
- hasActiveSession(pubKey) {
605
+ hasActiveSession(pubKey, { connectionId } = {}) {
564
606
  for (const [, s] of this.#sessions) {
565
- if (s.pubKey === pubKey && s.state === 'active') return true;
607
+ if (s.pubKey !== pubKey || s.state !== 'active') continue;
608
+ if (connectionId !== undefined && s.connectionId !== connectionId) continue;
609
+ return true;
566
610
  }
567
611
  return false;
568
612
  }
569
613
 
614
+ /**
615
+ * List every session for a peer (issue #116) -- e.g. to discover what
616
+ * `connectionId`s are currently live before addressing one via `sendTo()`.
617
+ *
618
+ * @param {string} pubKey
619
+ * @returns {object[]} Session info array (without transport instances),
620
+ * most-recently-created first.
621
+ */
622
+ sessionsFor(pubKey) {
623
+ return [...this.#sessions.values()]
624
+ .filter((s) => s.pubKey === pubKey)
625
+ .sort((a, b) => (b.connectedAt || 0) - (a.connectedAt || 0))
626
+ .map((s) => ({ ...s, transportInstance: undefined }));
627
+ }
628
+
570
629
  /**
571
630
  * Disconnect a peer and clean up its sessions.
572
631
  *
package/src/signaling.mjs CHANGED
@@ -14,7 +14,16 @@
14
14
  * implementation the real `test/real-peer/` suite exercises), this is a
15
15
  * small, new, transport-agnostic relay: it wraps whatever bidirectional bus
16
16
  * is already in hand and speaks exactly three message shapes over it --
17
- * `{type: 'webrtc-offer'|'webrtc-answer'|'webrtc-ice', from, to, payload}`.
17
+ * `{type: 'webrtc-offer'|'webrtc-answer'|'webrtc-ice', from, to, payload,
18
+ * connectionId}`.
19
+ *
20
+ * `connectionId` (issue #116) lets `webrtc-negotiator.mjs` run more than one
21
+ * independent offer/answer/ICE exchange with the same peer at once --
22
+ * e.g. two concurrent `negotiate()` calls, each opening its own
23
+ * `RTCPeerConnection` to the same remote podId. It defaults to `'default'`
24
+ * on both `send()` and every `on*()` callback, so callers that never pass
25
+ * one see the original single-exchange-per-peer wire shape and behavior
26
+ * unchanged.
18
27
  *
19
28
  * The injected `transport` only needs to implement `send(msg)` and
20
29
  * `onMessage(cb)` (optionally `open()`/`close()`) -- the same minimal shape
@@ -32,6 +41,9 @@
32
41
  /** @type {readonly string[]} */
33
42
  const SIGNAL_TYPES = Object.freeze(['webrtc-offer', 'webrtc-answer', 'webrtc-ice'])
34
43
 
44
+ /** Connection identifier used when a caller doesn't pass one explicitly. */
45
+ const DEFAULT_CONNECTION_ID = 'default'
46
+
35
47
  // ---------------------------------------------------------------------------
36
48
  // MeshSignalingChannel
37
49
  // ---------------------------------------------------------------------------
@@ -123,20 +135,23 @@ export class MeshSignalingChannel {
123
135
  * @param {'webrtc-offer'|'webrtc-answer'|'webrtc-ice'} type
124
136
  * @param {string} to - Target pod identifier
125
137
  * @param {*} payload - The offer/answer/candidate object
138
+ * @param {string} [connectionId] - Which of possibly-several independent
139
+ * offer/answer/ICE exchanges with `to` this message belongs to (issue
140
+ * #116). Defaults to `'default'`.
126
141
  */
127
- send(type, to, payload) {
142
+ send(type, to, payload, connectionId = DEFAULT_CONNECTION_ID) {
128
143
  if (!SIGNAL_TYPES.includes(type)) {
129
144
  throw new Error(`Unknown signal type: ${type}`)
130
145
  }
131
146
  if (!to || typeof to !== 'string') {
132
147
  throw new Error('to is required and must be a non-empty string')
133
148
  }
134
- this.#transport.send({ type, from: this.#localPodId, to, payload })
149
+ this.#transport.send({ type, from: this.#localPodId, to, payload, connectionId })
135
150
  }
136
151
 
137
152
  /**
138
- * Subscribe to incoming offers. Callback receives `(fromPodId, offer)`.
139
- * @param {(fromPodId: string, offer: object) => void} cb
153
+ * Subscribe to incoming offers. Callback receives `(fromPodId, offer, connectionId)`.
154
+ * @param {(fromPodId: string, offer: object, connectionId: string) => void} cb
140
155
  * @returns {() => void} Unsubscribe function.
141
156
  */
142
157
  onOffer(cb) {
@@ -144,8 +159,8 @@ export class MeshSignalingChannel {
144
159
  }
145
160
 
146
161
  /**
147
- * Subscribe to incoming answers. Callback receives `(fromPodId, answer)`.
148
- * @param {(fromPodId: string, answer: object) => void} cb
162
+ * Subscribe to incoming answers. Callback receives `(fromPodId, answer, connectionId)`.
163
+ * @param {(fromPodId: string, answer: object, connectionId: string) => void} cb
149
164
  * @returns {() => void} Unsubscribe function.
150
165
  */
151
166
  onAnswer(cb) {
@@ -153,8 +168,8 @@ export class MeshSignalingChannel {
153
168
  }
154
169
 
155
170
  /**
156
- * Subscribe to incoming ICE candidates. Callback receives `(fromPodId, candidate)`.
157
- * @param {(fromPodId: string, candidate: object) => void} cb
171
+ * Subscribe to incoming ICE candidates. Callback receives `(fromPodId, candidate, connectionId)`.
172
+ * @param {(fromPodId: string, candidate: object, connectionId: string) => void} cb
158
173
  * @returns {() => void} Unsubscribe function.
159
174
  */
160
175
  onIce(cb) {
@@ -179,7 +194,7 @@ export class MeshSignalingChannel {
179
194
 
180
195
  for (const cb of [...this.#listeners[msg.type]]) {
181
196
  try {
182
- cb(msg.from, msg.payload)
197
+ cb(msg.from, msg.payload, msg.connectionId ?? DEFAULT_CONNECTION_ID)
183
198
  } catch (err) {
184
199
  this.#onLog('signaling:listener-error', {
185
200
  type: msg.type,
@@ -228,4 +243,4 @@ export function createBroadcastChannelSignalingTransport(channelName = 'mesh-sig
228
243
  }
229
244
  }
230
245
 
231
- export { SIGNAL_TYPES }
246
+ export { SIGNAL_TYPES, DEFAULT_CONNECTION_ID }
@@ -29,10 +29,26 @@
29
29
  * ICE candidates are relayed in both directions for every connection,
30
30
  * regardless of which side initiated it.
31
31
  *
32
+ * ## Multiple connections per peer (issue #116)
33
+ * `auth.connectionId` (default `DEFAULT_CONNECTION_ID`, re-exported from
34
+ * `@johnhenry/browsermesh-transport`) selects which of possibly-several
35
+ * independent `RTCPeerConnection`s to `endpoint` this call negotiates --
36
+ * `PeerNode.connectToPeer(pubKey, endpoints, auth)` already threads `auth`
37
+ * straight through to `negotiator.negotiate(endpoints, auth)`, so callers
38
+ * can request a second, fully independent connection to a peer already
39
+ * connected to (its own ICE/STUN/DTLS negotiation, own DataChannel) simply
40
+ * by calling `connectToPeer()` again with a different `auth.connectionId`.
41
+ * Every signaling message (`webrtc-offer`/`webrtc-answer`/`webrtc-ice`)
42
+ * carries that same `connectionId` so concurrent exchanges with the same
43
+ * peer never cross-route an answer or ICE candidate meant for the other
44
+ * connection. Calls that never pass `connectionId` are unaffected -- they
45
+ * all resolve to the peer's single `DEFAULT_CONNECTION_ID` connection, same
46
+ * as before this was added.
47
+ *
32
48
  * No browser-only imports at module level.
33
49
  */
34
50
 
35
- import { WebRTCTransportAdapter } from '@johnhenry/browsermesh-transport'
51
+ import { WebRTCTransportAdapter, DEFAULT_CONNECTION_ID } from '@johnhenry/browsermesh-transport'
36
52
 
37
53
  /** Default time to wait for an SDP answer before giving up. */
38
54
  const DEFAULT_ANSWER_TIMEOUT_MS = 15_000
@@ -49,7 +65,7 @@ const DEFAULT_OPEN_TIMEOUT_MS = 15_000
49
65
  * @param {import('@johnhenry/browsermesh-transport').WebRTCMeshManager} opts.meshManager
50
66
  * @param {import('./signaling.mjs').MeshSignalingChannel} opts.signaling
51
67
  * @param {Function} [opts.onLog]
52
- * @param {(remotePodId: string, adapter: import('@johnhenry/browsermesh-transport').WebRTCTransportAdapter) => void} [opts.onIncomingConnection]
68
+ * @param {(remotePodId: string, adapter: import('@johnhenry/browsermesh-transport').WebRTCTransportAdapter, connectionId: string) => void} [opts.onIncomingConnection]
53
69
  * Called once the DataChannel for a *callee-side* (auto-answered) inbound
54
70
  * offer actually opens, with a ready `WebRTCTransportAdapter` wrapping it.
55
71
  * Optional: without it, inbound-only connections still come up at the
@@ -61,7 +77,8 @@ const DEFAULT_OPEN_TIMEOUT_MS = 15_000
61
77
  * @returns {(endpoint: string, auth?: object) => Promise<import('@johnhenry/browsermesh-transport').WebRTCTransportAdapter>}
62
78
  * Factory suitable for `negotiator.registerAdapter('webrtc', factory)`.
63
79
  * `endpoint` is the remote peer's podId; `auth` may carry
64
- * `{ answerTimeoutMs, openTimeoutMs }` overrides.
80
+ * `{ answerTimeoutMs, openTimeoutMs, connectionId }` overrides -- see this
81
+ * file's header comment for `connectionId` (issue #116).
65
82
  */
66
83
  export function createWebRTCTransportFactory({
67
84
  localPodId, meshManager, signaling, onLog, onIncomingConnection, openTimeoutMs: defaultOpenTimeoutMs,
@@ -71,26 +88,28 @@ export function createWebRTCTransportFactory({
71
88
  if (!signaling) throw new Error('signaling is required')
72
89
  const log = onLog || (() => {})
73
90
 
74
- /** @type {Set<string>} remotePodIds whose ICE relay is already wired */
91
+ /** @type {Set<string>} "remotePodId connectionId" pairs whose ICE relay is already wired */
75
92
  const wiredIce = new Set()
93
+ const iceKey = (remotePodId, connectionId) => `${remotePodId} ${connectionId}`
76
94
 
77
95
  /**
78
- * Get (or create) the WebRTCPeerConnection for a peer, and make sure its
79
- * locally-gathered ICE candidates get relayed exactly once, no matter
80
- * which side (offerer or answerer) first touches this remotePodId.
96
+ * Get (or create) the WebRTCPeerConnection for a peer + connectionId, and
97
+ * make sure its locally-gathered ICE candidates get relayed exactly once,
98
+ * no matter which side (offerer or answerer) first touches this pair.
81
99
  */
82
- async function getWiredConnection(remotePodId) {
83
- const conn = await meshManager.connectToPeer(remotePodId)
84
- if (!wiredIce.has(remotePodId)) {
85
- wiredIce.add(remotePodId)
100
+ async function getWiredConnection(remotePodId, connectionId = DEFAULT_CONNECTION_ID) {
101
+ const conn = await meshManager.connectToPeer(remotePodId, { connectionId })
102
+ const key = iceKey(remotePodId, connectionId)
103
+ if (!wiredIce.has(key)) {
104
+ wiredIce.add(key)
86
105
  conn.onIceCandidate((candidate) => {
87
106
  try {
88
- signaling.send('webrtc-ice', remotePodId, candidate)
107
+ signaling.send('webrtc-ice', remotePodId, candidate, connectionId)
89
108
  } catch (err) {
90
- log('webrtc-negotiator:ice-send-failed', { remotePodId, error: err?.message || String(err) })
109
+ log('webrtc-negotiator:ice-send-failed', { remotePodId, connectionId, error: err?.message || String(err) })
91
110
  }
92
111
  })
93
- conn.onClose(() => wiredIce.delete(remotePodId))
112
+ conn.onClose(() => wiredIce.delete(key))
94
113
  }
95
114
  return conn
96
115
  }
@@ -126,12 +145,12 @@ export function createWebRTCTransportFactory({
126
145
  // Callee side: answer any inbound offer automatically. Registered once,
127
146
  // for the lifetime of this factory, so a peer that only ever receives
128
147
  // connections (never calls negotiate() itself) still gets connected.
129
- signaling.onOffer(async (fromPodId, offer) => {
148
+ signaling.onOffer(async (fromPodId, offer, connectionId = DEFAULT_CONNECTION_ID) => {
130
149
  try {
131
- const conn = await getWiredConnection(fromPodId)
150
+ const conn = await getWiredConnection(fromPodId, connectionId)
132
151
  const answer = await conn.handleOffer(offer)
133
- signaling.send('webrtc-answer', fromPodId, answer)
134
- log('webrtc-negotiator:answered', { from: fromPodId })
152
+ signaling.send('webrtc-answer', fromPodId, answer, connectionId)
153
+ log('webrtc-negotiator:answered', { from: fromPodId, connectionId })
135
154
 
136
155
  // Hand the callee side a ready transport adapter too, once its
137
156
  // DataChannel actually opens, so callers (mesh-bootstrap.mjs) can
@@ -141,22 +160,22 @@ export function createWebRTCTransportFactory({
141
160
  await waitForOpen(conn, defaultOpenTimeoutMs ?? DEFAULT_OPEN_TIMEOUT_MS)
142
161
  const adapter = new WebRTCTransportAdapter(conn)
143
162
  await adapter.connect()
144
- onIncomingConnection(fromPodId, adapter)
163
+ onIncomingConnection(fromPodId, adapter, connectionId)
145
164
  }
146
165
  } catch (err) {
147
- log('webrtc-negotiator:offer-failed', { from: fromPodId, error: err?.message || String(err) })
166
+ log('webrtc-negotiator:offer-failed', { from: fromPodId, connectionId, error: err?.message || String(err) })
148
167
  }
149
168
  })
150
169
 
151
170
  // ICE candidates arriving from either side of any connection.
152
- signaling.onIce((fromPodId, candidate) => {
153
- const conn = meshManager.getConnection(fromPodId)
171
+ signaling.onIce((fromPodId, candidate, connectionId = DEFAULT_CONNECTION_ID) => {
172
+ const conn = meshManager.getConnection(fromPodId, connectionId)
154
173
  if (!conn) {
155
- log('webrtc-negotiator:ice-no-connection', { from: fromPodId })
174
+ log('webrtc-negotiator:ice-no-connection', { from: fromPodId, connectionId })
156
175
  return
157
176
  }
158
177
  conn.addIceCandidate(candidate).catch((err) => {
159
- log('webrtc-negotiator:ice-add-failed', { from: fromPodId, error: err?.message || String(err) })
178
+ log('webrtc-negotiator:ice-add-failed', { from: fromPodId, connectionId, error: err?.message || String(err) })
160
179
  })
161
180
  })
162
181
 
@@ -174,16 +193,17 @@ export function createWebRTCTransportFactory({
174
193
 
175
194
  const answerTimeoutMs = auth?.answerTimeoutMs ?? DEFAULT_ANSWER_TIMEOUT_MS
176
195
  const openTimeoutMs = auth?.openTimeoutMs ?? DEFAULT_OPEN_TIMEOUT_MS
196
+ const connectionId = auth?.connectionId ?? DEFAULT_CONNECTION_ID
177
197
 
178
- const conn = await getWiredConnection(remotePodId)
198
+ const conn = await getWiredConnection(remotePodId, connectionId)
179
199
 
180
200
  const answerPromise = new Promise((resolve, reject) => {
181
201
  const timer = setTimeout(() => {
182
202
  unsubscribe()
183
203
  reject(new Error(`WebRTC negotiation with ${remotePodId} timed out waiting for an answer`))
184
204
  }, answerTimeoutMs)
185
- const unsubscribe = signaling.onAnswer((fromPodId, answer) => {
186
- if (fromPodId !== remotePodId) return
205
+ const unsubscribe = signaling.onAnswer((fromPodId, answer, answerConnectionId = DEFAULT_CONNECTION_ID) => {
206
+ if (fromPodId !== remotePodId || answerConnectionId !== connectionId) return
187
207
  clearTimeout(timer)
188
208
  unsubscribe()
189
209
  resolve(answer)
@@ -191,7 +211,7 @@ export function createWebRTCTransportFactory({
191
211
  })
192
212
 
193
213
  const offer = await conn.createOffer()
194
- signaling.send('webrtc-offer', remotePodId, offer)
214
+ signaling.send('webrtc-offer', remotePodId, offer, connectionId)
195
215
 
196
216
  const answer = await answerPromise
197
217
  await conn.handleAnswer(answer)