@johnhenry/browsermesh-apps 0.15.0 → 0.17.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.
Files changed (55) hide show
  1. package/README.md +298 -17
  2. package/package.json +13 -9
  3. package/src/apps.mjs +4 -4
  4. package/src/audit.mjs +2 -2
  5. package/src/chat.mjs +3 -3
  6. package/src/cloud-storage-backend.mjs +5 -7
  7. package/src/cloud-storage.mjs +5 -4
  8. package/src/compat.mjs +2 -2
  9. package/src/consensus.mjs +7 -7
  10. package/src/devtools.mjs +3 -3
  11. package/src/gpu.mjs +2 -2
  12. package/src/index.mjs +12 -0
  13. package/src/internal/channel-codec.mjs +179 -0
  14. package/src/internal/json-message.mjs +49 -0
  15. package/src/internal/relay-flow.mjs +178 -0
  16. package/src/internal/request-target.mjs +280 -0
  17. package/src/internal/rpc-body.mjs +33 -0
  18. package/src/marketplace-ui.mjs +1 -1
  19. package/src/mesh-agent-swarm.mjs +1 -1
  20. package/src/mesh-bootstrap.mjs +47 -1
  21. package/src/mesh-channel.mjs +716 -0
  22. package/src/mesh-fetch.mjs +77 -263
  23. package/src/mesh-hardening.mjs +8 -1
  24. package/src/mesh-relay-backend.mjs +116 -22
  25. package/src/mesh-relay-host.mjs +296 -55
  26. package/src/mesh-rpc.mjs +126 -265
  27. package/src/mesh-sync.mjs +1 -1
  28. package/src/orchestrator.mjs +54 -29
  29. package/src/payments.mjs +56 -14
  30. package/src/peer-agent-swarm.mjs +2 -2
  31. package/src/peer-agent.mjs +7 -7
  32. package/src/peer-compute.mjs +2 -2
  33. package/src/peer-encrypted-store.mjs +3 -3
  34. package/src/peer-escrow.mjs +2 -2
  35. package/src/peer-health.mjs +3 -3
  36. package/src/peer-node.mjs +8 -5
  37. package/src/peer-payments.mjs +2 -2
  38. package/src/peer-registry.mjs +45 -3
  39. package/src/peer-routing.mjs +158 -21
  40. package/src/peer-services.mjs +3 -3
  41. package/src/peer-timestamp.mjs +3 -3
  42. package/src/peer-torrent.mjs +112 -47
  43. package/src/peer-verification.mjs +3 -3
  44. package/src/pod-host-service.mjs +48 -7
  45. package/src/pod-placement.mjs +582 -0
  46. package/src/pod-supervisor.mjs +9 -30
  47. package/src/protocol-channel.mjs +327 -0
  48. package/src/resources.mjs +2 -2
  49. package/src/restart-policy.mjs +67 -0
  50. package/src/scheduler.mjs +3 -3
  51. package/src/serverless-proxy.mjs +58 -7
  52. package/src/silent-catch.mjs +22 -9
  53. package/src/tools.mjs +3 -3
  54. package/src/visualizations.mjs +2 -2
  55. package/src/wsh-negotiator.mjs +97 -0
package/src/payments.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * clawser-mesh-payments.js -- Payment channels for BrowserMesh.
2
+ * payments.mjs --Payment channels for BrowserMesh.
3
3
  *
4
4
  * Double-entry credit ledger, bidirectional micropayment channels,
5
5
  * escrow management, and a payment router that ties them together.
@@ -7,7 +7,7 @@
7
7
  * No browser-only imports at module level.
8
8
  *
9
9
  * Run tests:
10
- * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-payments.test.mjs
10
+ * cd packages/browsermesh-apps && node --import ./test/_setup-globals.mjs --test test/payments.test.mjs
11
11
  */
12
12
 
13
13
  import { MESH_TYPE } from '@johnhenry/browsermesh-primitives';
@@ -914,7 +914,7 @@ export class PaymentChannel {
914
914
  const set = this.#listeners.get(event);
915
915
  if (!set) return;
916
916
  for (const cb of set) {
917
- try { cb(data); } catch (e) { silentCatch('clawser-mesh-payments', 'channel-listener', e) }
917
+ try { cb(data); } catch (e) { silentCatch('payments', 'channel-listener', e) }
918
918
  }
919
919
  }
920
920
 
@@ -1189,6 +1189,9 @@ export class PaymentRouter {
1189
1189
  /** @type {object|null} Optional conditional EscrowManager (peer-escrow.mjs), see attachEscrowManager(). */
1190
1190
  #escrowManager = null;
1191
1191
 
1192
+ /** @type {boolean} Hand inbound ESCROW_CREATE to the manager (attachEscrowManager `delegateWire`). */
1193
+ #delegateWireEscrow = false;
1194
+
1192
1195
  /** @type {function|null} */
1193
1196
  #broadcastFn = null;
1194
1197
 
@@ -1312,7 +1315,7 @@ export class PaymentRouter {
1312
1315
  #recordDispute(dispute) {
1313
1316
  this.#disputes.push(dispute);
1314
1317
  for (const cb of this.#disputeListeners) {
1315
- try { cb(dispute); } catch (e) { silentCatch('clawser-mesh-payments', 'onPaymentDispute-callback', e) }
1318
+ try { cb(dispute); } catch (e) { silentCatch('payments', 'onPaymentDispute-callback', e) }
1316
1319
  }
1317
1320
  }
1318
1321
 
@@ -1342,15 +1345,30 @@ export class PaymentRouter {
1342
1345
  * ledger. After attaching, `listEscrows()` / `getEscrowById()` show both, and
1343
1346
  * the escrow sweeper also expires (and refunds) the manager's due contracts.
1344
1347
  *
1348
+ * With `{ delegateWire: true }` an inbound `ESCROW_CREATE` is handed to
1349
+ * `manager.create()` instead of being recorded in the wire book: the sending
1350
+ * pod is the payer, so the manager must debit a per-pod balance. Give it a
1351
+ * `MultiPartyCreditLedger`, or a `mutateLedger` hook that debits that pod; a
1352
+ * single-owner `CreditLedger` would debit the local balance whoever sent the
1353
+ * message. Off by default, so nothing changes for an existing caller. An
1354
+ * escrow the payer cannot fund (or a malformed message) creates nothing.
1355
+ *
1345
1356
  * @param {object} manager - An `EscrowManager`
1357
+ * @param {object} [opts]
1358
+ * @param {boolean} [opts.delegateWire=false]
1346
1359
  * @returns {this}
1347
1360
  */
1348
- attachEscrowManager(manager) {
1361
+ attachEscrowManager(manager, opts = {}) {
1349
1362
  if (!manager || typeof manager.create !== 'function' || typeof manager.listContracts !== 'function'
1350
1363
  || typeof manager.checkExpired !== 'function' || typeof manager.getContract !== 'function') {
1351
1364
  throw new TypeError('attachEscrowManager requires an EscrowManager');
1352
1365
  }
1366
+ const delegateWire = opts?.delegateWire ?? false;
1367
+ if (typeof delegateWire !== 'boolean') {
1368
+ throw new TypeError('attachEscrowManager: delegateWire must be a boolean');
1369
+ }
1353
1370
  this.#escrowManager = manager;
1371
+ this.#delegateWireEscrow = delegateWire;
1354
1372
  return this;
1355
1373
  }
1356
1374
 
@@ -1409,7 +1427,7 @@ export class PaymentRouter {
1409
1427
  this.stopEscrowSweeper();
1410
1428
  const report = (expired) => {
1411
1429
  if (expired.length > 0 && onExpired) {
1412
- try { onExpired(expired); } catch (e) { silentCatch('clawser-mesh-payments', 'onExpired', e) }
1430
+ try { onExpired(expired); } catch (e) { silentCatch('payments', 'onExpired', e) }
1413
1431
  }
1414
1432
  };
1415
1433
  this.#escrowSweeperTimer = setInterval(() => {
@@ -1424,7 +1442,7 @@ export class PaymentRouter {
1424
1442
  if (due.length > 0) {
1425
1443
  mgr.checkExpired(now)
1426
1444
  .then(() => report(due.map((id) => mgr.getContract(id)).filter((c) => c && c.status === 'expired').map(normalizeManagerContract)))
1427
- .catch((e) => silentCatch('clawser-mesh-payments', 'manager-checkExpired', e));
1445
+ .catch((e) => silentCatch('payments', 'manager-checkExpired', e));
1428
1446
  }
1429
1447
  }
1430
1448
  }, intervalMs);
@@ -1480,7 +1498,7 @@ export class PaymentRouter {
1480
1498
  if (typeof deposit === 'number' && Number.isFinite(deposit) && deposit > 0) {
1481
1499
  ch.open(0, deposit);
1482
1500
  }
1483
- } catch (e) { silentCatch('clawser-mesh-payments', 'ignore-duplicate-or-invalid-opens', e) }
1501
+ } catch (e) { silentCatch('payments', 'ignore-duplicate-or-invalid-opens', e) }
1484
1502
  });
1485
1503
 
1486
1504
  // Inbound: channel payment update
@@ -1493,10 +1511,10 @@ export class PaymentRouter {
1493
1511
  // on an unsigned/invalid update when verification is active.
1494
1512
  const result = ch.receive(payload);
1495
1513
  if (result && typeof result.then === 'function') {
1496
- result.catch((e) => silentCatch('clawser-mesh-payments', 'ignore-invalid-signed-update', e));
1514
+ result.catch((e) => silentCatch('payments', 'ignore-invalid-signed-update', e));
1497
1515
  }
1498
1516
  }
1499
- } catch (e) { silentCatch('clawser-mesh-payments', 'ignore-invalid-updates', e) }
1517
+ } catch (e) { silentCatch('payments', 'ignore-invalid-updates', e) }
1500
1518
  });
1501
1519
 
1502
1520
  // Inbound: channel close
@@ -1518,7 +1536,7 @@ export class PaymentRouter {
1518
1536
  this.#recordDispute(result.dispute);
1519
1537
  }
1520
1538
  })
1521
- .catch((e) => silentCatch('clawser-mesh-payments', 'handleCloseMessage', e));
1539
+ .catch((e) => silentCatch('payments', 'handleCloseMessage', e));
1522
1540
  return;
1523
1541
  }
1524
1542
 
@@ -1533,24 +1551,48 @@ export class PaymentRouter {
1533
1551
  this.#recordDispute(result.dispute);
1534
1552
  }
1535
1553
  })
1536
- .catch((e) => silentCatch('clawser-mesh-payments', 'finalizeClose', e));
1554
+ .catch((e) => silentCatch('payments', 'finalizeClose', e));
1537
1555
  return;
1538
1556
  }
1539
1557
 
1540
1558
  // Legacy unilateral close (no signing configured on this channel).
1541
1559
  this.closeChannel(fromPodId);
1542
- } catch (e) { silentCatch('clawser-mesh-payments', 'this.closeChannel', e) }
1560
+ } catch (e) { silentCatch('payments', 'this.closeChannel', e) }
1543
1561
  });
1544
1562
 
1545
1563
  // Inbound: escrow creation
1546
1564
  subscribeFn(ESCROW_CREATE, (payload, fromPodId) => {
1547
1565
  try {
1548
1566
  const { payeePodId, amount, conditions } = payload;
1567
+ if (this.#delegateWireEscrow && this.#escrowManager) {
1568
+ // Returns the promise so a caller (or test) can await the outcome;
1569
+ // a failure (insufficient balance, bad input) creates nothing.
1570
+ return this.#createManagerEscrow(fromPodId, payeePodId, amount, conditions);
1571
+ }
1549
1572
  this.#escrow.create(fromPodId, payeePodId, amount, conditions);
1550
- } catch (e) { silentCatch('clawser-mesh-payments', 'ignore-invalid-escrow', e) }
1573
+ } catch (e) { silentCatch('payments', 'ignore-invalid-escrow', e) }
1551
1574
  });
1552
1575
  }
1553
1576
 
1577
+ /** Validate an inbound ESCROW_CREATE and create it in the attached manager. */
1578
+ async #createManagerEscrow(payerPodId, payeePodId, amount, conditions) {
1579
+ try {
1580
+ if (typeof payerPodId !== 'string' || !payerPodId
1581
+ || typeof payeePodId !== 'string' || !payeePodId
1582
+ || typeof amount !== 'number' || !Number.isFinite(amount) || amount <= 0) {
1583
+ return;
1584
+ }
1585
+ const timeout = conditions?.timeout;
1586
+ await this.#escrowManager.create({
1587
+ payerPodId,
1588
+ payeePodId,
1589
+ amount,
1590
+ description: typeof conditions?.description === 'string' ? conditions.description : undefined,
1591
+ timeoutMs: typeof timeout === 'number' && timeout > 0 ? timeout : undefined,
1592
+ });
1593
+ } catch (e) { silentCatch('payments', 'manager-escrow-create', e) }
1594
+ }
1595
+
1554
1596
  /**
1555
1597
  * Broadcast a channel open over the transport.
1556
1598
  *
@@ -1,5 +1,5 @@
1
1
  /**
2
- * clawser-peer-agent-swarm.js — Multi-agent coordination protocol.
2
+ * peer-agent-swarm.mjs —Multi-agent coordination protocol.
3
3
  *
4
4
  * Agents share goals, decompose tasks, divide work, merge results,
5
5
  * and achieve collective objectives across the mesh.
@@ -17,7 +17,7 @@
17
17
  * what makes remote dispatch real).
18
18
  *
19
19
  * Run tests:
20
- * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-agent-swarm.test.mjs
20
+ * cd packages/browsermesh-apps && node --import ./test/_setup-globals.mjs --test test/peer-agent-swarm.test.mjs
21
21
  */
22
22
 
23
23
  // ---------------------------------------------------------------------------
@@ -1,8 +1,8 @@
1
1
  /**
2
- * clawser-peer-agent.js -- Remote agent interaction over peer sessions.
2
+ * peer-agent.mjs --Remote agent interaction over peer sessions.
3
3
  *
4
4
  * Allows one peer to chat with, invoke tools on, and query memories of
5
- * another peer's AI agent. AgentHost serves the local ClawserAgent to
5
+ * another peer's AI agent. AgentHost serves the local agent to
6
6
  * remote peers, while AgentClient provides a promise-based interface for
7
7
  * interacting with a remote peer's agent. Built on top of PeerSession's
8
8
  * service handler system using the 'agent' service type.
@@ -11,7 +11,7 @@
11
11
  * No browser-only imports at module level.
12
12
  *
13
13
  * Run tests:
14
- * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-agent.test.mjs
14
+ * cd packages/browsermesh-apps && node --import ./test/_setup-globals.mjs --test test/peer-agent.test.mjs
15
15
  */
16
16
 
17
17
  // ---------------------------------------------------------------------------
@@ -49,7 +49,7 @@ const ACTION_CAPABILITY = Object.freeze({
49
49
  // ---------------------------------------------------------------------------
50
50
 
51
51
  /**
52
- * Serves agent operations from the local ClawserAgent to remote peers.
52
+ * Serves agent operations from the local agent to remote peers.
53
53
  *
54
54
  * Registers a handler on the PeerSession for the 'agent' service type.
55
55
  * Incoming requests are validated against capability requirements before
@@ -71,7 +71,7 @@ export class AgentHost {
71
71
  */
72
72
  #agent
73
73
 
74
- /** @type {import('./clawser-gateway.js').ChannelGateway|null} */
74
+ /** @type {object|null} */
75
75
  #gateway
76
76
 
77
77
  /** @type {object|null} { recordUsage(peerId, usage) } */
@@ -87,7 +87,7 @@ export class AgentHost {
87
87
  * @param {object} opts
88
88
  * @param {object} opts.session - PeerSession instance
89
89
  * @param {object} opts.agent - Agent interface with run/executeTool/searchMemories
90
- * @param {import('./clawser-gateway.js').ChannelGateway} [opts.gateway] - Channel gateway for unified routing
90
+ * @param {object} [opts.gateway] - Channel gateway for unified routing
91
91
  * @param {object} [opts.costTracker] - Cost tracker with recordUsage(peerId, usage)
92
92
  * @param {Function} [opts.onLog] - Logging callback
93
93
  */
@@ -514,7 +514,7 @@ export class AgentClient {
514
514
  *
515
515
  * @param {object} session - PeerSession instance
516
516
  * @param {object} agent - Agent with run/executeTool/searchMemories
517
- * @param {import('./clawser-gateway.js').ChannelGateway} gateway - Channel gateway
517
+ * @param {object} gateway - Channel gateway
518
518
  * @param {Function} [onLog] - Logging callback
519
519
  * @returns {AgentHost}
520
520
  */
@@ -1,5 +1,5 @@
1
1
  /**
2
- * clawser-peer-compute.js — Federated compute orchestration.
2
+ * peer-compute.mjs —Federated compute orchestration.
3
3
  *
4
4
  * Split large compute jobs across multiple peers (map/reduce pattern).
5
5
  * Combines scheduling, verification, escrow, and result merging.
@@ -16,7 +16,7 @@
16
16
  * settled by issue #86's resolved design pass).
17
17
  *
18
18
  * Run tests:
19
- * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-compute.test.mjs
19
+ * cd packages/browsermesh-apps && node --import ./test/_setup-globals.mjs --test test/peer-compute.test.mjs
20
20
  */
21
21
 
22
22
  // ---------------------------------------------------------------------------
@@ -1,6 +1,6 @@
1
1
  /**
2
- // STATUS: INTEGRATED — wired into ClawserPod lifecycle, proven via E2E testing
3
- * clawser-peer-encrypted-store.js -- Encrypt blobs before uploading to peers.
2
+ // STATUS: INTEGRATED — wired into the Pod lifecycle (@johnhenry/browsermesh-pod), proven via E2E testing
3
+ * peer-encrypted-store.mjs --Encrypt blobs before uploading to peers.
4
4
  *
5
5
  * Peers store opaque ciphertext — they cannot read content. Enables
6
6
  * "borrow storage from friends" scenario.
@@ -11,7 +11,7 @@
11
11
  * No browser-only imports at module level.
12
12
  *
13
13
  * Run tests:
14
- * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-encrypted-store.test.mjs
14
+ * cd packages/browsermesh-apps && node --import ./test/_setup-globals.mjs --test test/peer-encrypted-store.test.mjs
15
15
  */
16
16
 
17
17
  // ---------------------------------------------------------------------------
@@ -1,5 +1,5 @@
1
1
  /**
2
- * clawser-peer-escrow.js — Hold credits in escrow until consensus confirms delivery.
2
+ * peer-escrow.mjs —Hold credits in escrow until consensus confirms delivery.
3
3
  *
4
4
  * Enables trustless compute marketplace, dispute resolution, and
5
5
  * guaranteed payment for services.
@@ -14,7 +14,7 @@
14
14
  * `ctx.sendTo()`/`ctx.onIncomingData()`/`ctx.registry.checkAccess()`.
15
15
  *
16
16
  * Run tests:
17
- * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-escrow.test.mjs
17
+ * cd packages/browsermesh-apps && node --import ./test/_setup-globals.mjs --test test/peer-escrow.test.mjs
18
18
  */
19
19
 
20
20
  // ---------------------------------------------------------------------------
@@ -1,12 +1,12 @@
1
1
  /**
2
- // STATUS: INTEGRATED — wired into ClawserPod lifecycle, proven via E2E testing
3
- * clawser-peer-health.js — Automatic health monitoring with self-healing.
2
+ // STATUS: INTEGRATED — wired into the Pod lifecycle (@johnhenry/browsermesh-pod), proven via E2E testing
3
+ * peer-health.mjs —Automatic health monitoring with self-healing.
4
4
  *
5
5
  * Watches heartbeats, detects failures, triggers workload migration.
6
6
  * Enables "self-healing personal mesh infrastructure" scenario.
7
7
  *
8
8
  * Run tests:
9
- * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-health.test.mjs
9
+ * cd packages/browsermesh-apps && node --import ./test/_setup-globals.mjs --test test/peer-health.test.mjs
10
10
  */
11
11
 
12
12
  // ---------------------------------------------------------------------------
package/src/peer-node.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * clawser-peer-node.js -- Top-level P2P mesh orchestrator.
2
+ * peer-node.mjs --Top-level P2P mesh orchestrator.
3
3
  *
4
4
  * Wires together IdentityWallet, PeerRegistry, DiscoveryManager,
5
5
  * MeshTransportNegotiator, and AuditChain into a unified PeerNode
@@ -9,7 +9,7 @@
9
9
  * No browser-only imports at module level.
10
10
  *
11
11
  * Run tests:
12
- * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-node.test.mjs
12
+ * cd packages/browsermesh-apps && node --import ./test/_setup-globals.mjs --test test/peer-node.test.mjs
13
13
  */
14
14
 
15
15
  // ---------------------------------------------------------------------------
@@ -81,7 +81,7 @@ export class PeerNode {
81
81
  #listeners = new Map()
82
82
 
83
83
  /** @type {Set<Function>} listeners for raw incoming session data
84
- * (cb(pubKey, data, {sessionId, transport})). Used by ClawserPod
84
+ * (cb(pubKey, data, {sessionId, transport})). Used by `Pod`
85
85
  * to surface a pod-level message bus on top of per-transport
86
86
  * inbound bytes. */
87
87
  #dataListeners = new Set()
@@ -376,6 +376,9 @@ export class PeerNode {
376
376
  pubKey,
377
377
  error: err.message,
378
378
  })
379
+ // A negotiator told to require one transport (`require: 'wsh'`) must
380
+ // never fall through to a session on something else.
381
+ if (this.#transportNeg.required) throw err
379
382
  // Fall through to direct registry connection
380
383
  }
381
384
  }
@@ -480,7 +483,7 @@ export class PeerNode {
480
483
  * Shared session-bookkeeping helper for both `connectToPeer()` (caller
481
484
  * side) and `adoptIncomingSession()` (callee side): creates the
482
485
  * `#sessions` entry and wires inbound data fan-out to `onIncomingData()`
483
- * subscribers -- this is what backs `ClawserPod.onMessage` so workspace
486
+ * subscribers -- this is what backs `Pod.onMessage` so workspace
484
487
  * consumers can route incoming sync/deploy envelopes by `envelope.type`.
485
488
  *
486
489
  * @param {string} pubKey
@@ -685,7 +688,7 @@ export class PeerNode {
685
688
  /**
686
689
  * Subscribe to raw incoming data from any session. The callback
687
690
  * receives `(pubKey, data, {sessionId, transport})`. Used by
688
- * `ClawserPod.onMessage` to fan an envelope-level dispatch on
691
+ * `Pod.onMessage` to fan an envelope-level dispatch on
689
692
  * top of per-transport bytes. Returns an unsubscribe function.
690
693
  *
691
694
  * @param {(pubKey:string, data:any, meta:{sessionId:string, transport:string}) => void} cb
@@ -1,5 +1,5 @@
1
1
  /**
2
- * clawser-peer-payments.js -- Payment mechanisms for resource sharing.
2
+ * peer-payments.mjs --Payment mechanisms for resource sharing.
3
3
  *
4
4
  * Provides a PaymentProvider abstraction with two implementations:
5
5
  * 1. MultiPartyCreditLedger — internal credit system (no real money)
@@ -16,7 +16,7 @@
16
16
  * No browser-only imports at module level. All dependencies injected.
17
17
  *
18
18
  * Run tests:
19
- * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-payments.test.mjs
19
+ * cd packages/browsermesh-apps && node --import ./test/_setup-globals.mjs --test test/peer-payments.test.mjs
20
20
  */
21
21
 
22
22
  // ---------------------------------------------------------------------------
@@ -1,7 +1,7 @@
1
1
  import { silentCatch } from './silent-catch.mjs'
2
2
  import { matchScope } from '@johnhenry/browsermesh-primitives'
3
3
  /**
4
- * clawser-peer-registry.js -- Unified peer registry with permission management.
4
+ * peer-registry.mjs --Unified peer registry with permission management.
5
5
  *
6
6
  * Wraps MeshPeerManager, TrustGraph, and MeshACL into a single facade that
7
7
  * coordinates peer lifecycle, trust, and access control. All three subsystems
@@ -11,7 +11,7 @@ import { matchScope } from '@johnhenry/browsermesh-primitives'
11
11
  * No browser-only imports at module level.
12
12
  *
13
13
  * Run tests:
14
- * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-registry.test.mjs
14
+ * cd packages/browsermesh-apps && node --import ./test/_setup-globals.mjs --test test/peer-registry.test.mjs
15
15
  */
16
16
 
17
17
  // ---------------------------------------------------------------------------
@@ -101,6 +101,9 @@ export class PeerRegistry {
101
101
  */
102
102
  #capabilityTokens = new Map()
103
103
 
104
+ /** @type {Set<Function>} */
105
+ #accessListeners = new Set()
106
+
104
107
  /** Validates/revokes tokens -- real `CapabilityValidator` when injected, a
105
108
  * duck-typed equivalent otherwise. @type {{ register: Function, revokeTree: Function }} */
106
109
  #capabilityValidator
@@ -199,6 +202,7 @@ export class PeerRegistry {
199
202
  if (existed) {
200
203
  this.#onLog(2, `PeerRegistry: removed ${pubKey}`)
201
204
  }
205
+ this.#emitAccessChange(pubKey, 'removed')
202
206
  return existed
203
207
  }
204
208
 
@@ -237,6 +241,7 @@ export class PeerRegistry {
237
241
  this.#acl.removeEntry(pubKey)
238
242
  this.#acl.addEntry(pubKey, templateName)
239
243
  this.#onLog(3, `PeerRegistry: set template '${templateName}' for ${pubKey}`)
244
+ this.#emitAccessChange(pubKey, 'updated')
240
245
  }
241
246
 
242
247
  /**
@@ -345,6 +350,7 @@ export class PeerRegistry {
345
350
  }
346
351
 
347
352
  this.#onLog(3, `PeerRegistry: revoked ${scopes.join(', ')} from ${pubKey}`)
353
+ this.#emitAccessChange(pubKey, 'revoked')
348
354
  }
349
355
 
350
356
  /**
@@ -508,6 +514,42 @@ export class PeerRegistry {
508
514
  this.#peerManager.disconnectAll()
509
515
  }
510
516
 
517
+ // ── Access-change events ────────────────────────────────────────────
518
+
519
+ /**
520
+ * Subscribe to changes that can reduce what a peer is allowed to do:
521
+ * `revokeCapabilities()`, `removePeer()`, `updatePermissions()` and
522
+ * `notifyAccessChange()`. Long-lived users of `checkAccess()` (relayed
523
+ * connections, for example) re-check on this event instead of on every use.
524
+ *
525
+ * @param {(event: { pubKey: string, kind: string }) => void} cb
526
+ * @returns {() => void} unsubscribe
527
+ */
528
+ onAccessChange(cb) {
529
+ if (typeof cb !== 'function') return () => {}
530
+ this.#accessListeners.add(cb)
531
+ return () => this.#accessListeners.delete(cb)
532
+ }
533
+
534
+ /**
535
+ * Announce that a peer's access may have changed through a path this class
536
+ * did not see (for example a direct change to the injected ACL).
537
+ *
538
+ * @param {string} pubKey
539
+ */
540
+ notifyAccessChange(pubKey) {
541
+ this.#emitAccessChange(pubKey, 'changed')
542
+ }
543
+
544
+ /** @param {string} pubKey @param {string} kind */
545
+ #emitAccessChange(pubKey, kind) {
546
+ for (const cb of [...this.#accessListeners]) {
547
+ try { cb({ pubKey, kind }) } catch (err) {
548
+ this.#onLog(1, `PeerRegistry: access-change listener threw: ${err?.message || err}`)
549
+ }
550
+ }
551
+ }
552
+
511
553
  // ── Events ──────────────────────────────────────────────────────────
512
554
 
513
555
  /**
@@ -604,7 +646,7 @@ export class PeerRegistry {
604
646
 
605
647
  const fire = (event, data) => {
606
648
  for (const cb of [...(callbacks[event] || [])]) {
607
- try { cb(data) } catch (e) { silentCatch('clawser-peer-registry', 'swallow', e) }
649
+ try { cb(data) } catch (e) { silentCatch('peer-registry', 'swallow', e) }
608
650
  }
609
651
  }
610
652