@johnhenry/browsermesh-apps 0.13.0 → 0.15.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/README.md CHANGED
@@ -469,8 +469,13 @@ Four classes cover two ideas, and each public name belongs to exactly one:
469
469
  `debit()`/`credit()` (that ledger has one balance, so use it when the local pod
470
470
  is the payer, or pass `mutateLedger` to account for a counterparty); with a
471
471
  `MultiPartyCreditLedger` it calls `charge()`/`credit()` so payer and payee each
472
- move their own balance. `PaymentRouter`'s `SimpleEscrowBook` and an
473
- `EscrowManager` you create are separate books and do not see each other.
472
+ move their own balance. `PaymentRouter`'s `SimpleEscrowBook` stays a wire
473
+ mirror and is a separate book from an `EscrowManager` you create, but the router
474
+ can see both: `router.attachEscrowManager(manager)` makes `router.listEscrows(podId?)`
475
+ and `router.getEscrowById(id)` return one normalized view (`source: 'wire'` or
476
+ `'manager'`), and the escrow sweeper also expires the manager's due contracts.
477
+ An inbound `ESCROW_CREATE` is still only recorded in the book; it does not debit
478
+ anything (the payer is a remote pod).
474
479
 
475
480
  ## Putting it all together: sync + kernel-gated mesh + relay on one connection
476
481
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/browsermesh-apps",
3
- "version": "0.13.0",
3
+ "version": "0.15.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",
@@ -59,7 +59,7 @@
59
59
  },
60
60
  "devDependencies": {
61
61
  "@johnhenry/andbox": ">=0.0.1 <1.0.0",
62
- "@johnhenry/browsermesh-pod": "^0.1.0",
62
+ "@johnhenry/browsermesh-pod": "^0.1.1",
63
63
  "node-datachannel": "^0.33.4",
64
64
  "fake-indexeddb": "^6.2.5",
65
65
  "webgpu": "^0.6.1"
package/src/payments.mjs CHANGED
@@ -987,6 +987,18 @@ export class PaymentChannel {
987
987
  * @property {number|null} resolvedAt
988
988
  */
989
989
 
990
+ /** A conditional-manager contract as the flat record `listEscrows()` returns. */
991
+ function normalizeManagerContract(c) {
992
+ return {
993
+ escrowId: c.id,
994
+ payerPodId: c.payer,
995
+ payeePodId: c.payee,
996
+ amount: c.amount,
997
+ status: c.status,
998
+ source: 'manager',
999
+ };
1000
+ }
1001
+
990
1002
  // ---------------------------------------------------------------------------
991
1003
  // SimpleEscrowBook
992
1004
  // ---------------------------------------------------------------------------
@@ -1099,6 +1111,11 @@ export class SimpleEscrowBook {
1099
1111
  return true;
1100
1112
  }
1101
1113
 
1114
+ /** Copies of every escrow in the book. */
1115
+ listAll() {
1116
+ return [...this.#escrows.values()].map((e) => ({ ...e }));
1117
+ }
1118
+
1102
1119
  /**
1103
1120
  * List all escrows involving a pod (as payer or payee).
1104
1121
  *
@@ -1169,6 +1186,9 @@ export class PaymentRouter {
1169
1186
  /** @type {SimpleEscrowBook} */
1170
1187
  #escrow;
1171
1188
 
1189
+ /** @type {object|null} Optional conditional EscrowManager (peer-escrow.mjs), see attachEscrowManager(). */
1190
+ #escrowManager = null;
1191
+
1172
1192
  /** @type {function|null} */
1173
1193
  #broadcastFn = null;
1174
1194
 
@@ -1314,6 +1334,62 @@ export class PaymentRouter {
1314
1334
  return this.#escrow;
1315
1335
  }
1316
1336
 
1337
+ /**
1338
+ * Make a conditional `EscrowManager` (peer-escrow.mjs) visible to this
1339
+ * router. The router's own `SimpleEscrowBook` stays what it was: a
1340
+ * wire-level mirror of the `ESCROW_CREATE` messages other pods send, which
1341
+ * moves no balance. The manager is the escrow that debits and credits a
1342
+ * ledger. After attaching, `listEscrows()` / `getEscrowById()` show both, and
1343
+ * the escrow sweeper also expires (and refunds) the manager's due contracts.
1344
+ *
1345
+ * @param {object} manager - An `EscrowManager`
1346
+ * @returns {this}
1347
+ */
1348
+ attachEscrowManager(manager) {
1349
+ if (!manager || typeof manager.create !== 'function' || typeof manager.listContracts !== 'function'
1350
+ || typeof manager.checkExpired !== 'function' || typeof manager.getContract !== 'function') {
1351
+ throw new TypeError('attachEscrowManager requires an EscrowManager');
1352
+ }
1353
+ this.#escrowManager = manager;
1354
+ return this;
1355
+ }
1356
+
1357
+ /** The attached conditional EscrowManager, or null. */
1358
+ getEscrowManager() {
1359
+ return this.#escrowManager;
1360
+ }
1361
+
1362
+ /**
1363
+ * One view over every escrow this router knows about: the wire mirror
1364
+ * (`source: 'wire'`) and, if attached, the manager's contracts
1365
+ * (`source: 'manager'`). Records are normalized copies with
1366
+ * `escrowId`, `payerPodId`, `payeePodId`, `amount`, `status`, `source`.
1367
+ * Statuses are each model's own (`held`/`released`/... vs `funded`/...).
1368
+ *
1369
+ * @param {string} [podId] - Only escrows where this pod is payer or payee
1370
+ * @returns {object[]}
1371
+ */
1372
+ listEscrows(podId) {
1373
+ const out = [];
1374
+ for (const e of this.#escrow.listAll()) out.push({ ...e, source: 'wire' });
1375
+ if (this.#escrowManager) {
1376
+ for (const c of this.#escrowManager.listContracts()) out.push(normalizeManagerContract(c));
1377
+ }
1378
+ return podId ? out.filter((e) => e.payerPodId === podId || e.payeePodId === podId) : out;
1379
+ }
1380
+
1381
+ /**
1382
+ * Look up an escrow by id in either book.
1383
+ * @param {string} escrowId
1384
+ * @returns {object|null}
1385
+ */
1386
+ getEscrowById(escrowId) {
1387
+ const wire = this.#escrow.get(escrowId);
1388
+ if (wire) return { ...wire, source: 'wire' };
1389
+ const c = this.#escrowManager?.getContract(escrowId);
1390
+ return c ? normalizeManagerContract(c) : null;
1391
+ }
1392
+
1317
1393
  /**
1318
1394
  * Start periodic escrow-timeout enforcement. Without this,
1319
1395
  * `SimpleEscrowBook.pruneExpired()` exists but nothing ever calls it, so
@@ -1331,11 +1407,26 @@ export class PaymentRouter {
1331
1407
  */
1332
1408
  startEscrowSweeper(intervalMs = 30000, onExpired = null) {
1333
1409
  this.stopEscrowSweeper();
1334
- this.#escrowSweeperTimer = setInterval(() => {
1335
- const expired = this.#escrow.pruneExpiredDetailed();
1410
+ const report = (expired) => {
1336
1411
  if (expired.length > 0 && onExpired) {
1337
1412
  try { onExpired(expired); } catch (e) { silentCatch('clawser-mesh-payments', 'onExpired', e) }
1338
1413
  }
1414
+ };
1415
+ this.#escrowSweeperTimer = setInterval(() => {
1416
+ const expired = this.#escrow.pruneExpiredDetailed().map((e) => ({ ...e, source: 'wire' }));
1417
+ report(expired);
1418
+ const mgr = this.#escrowManager;
1419
+ if (mgr) {
1420
+ // Manager contracts expire by refunding the payer through its ledger,
1421
+ // which is async; report the ones that were due once that settles.
1422
+ const now = Date.now();
1423
+ const due = mgr.listContracts({ status: 'funded' }).filter((c) => c.isExpired(now)).map((c) => c.id);
1424
+ if (due.length > 0) {
1425
+ mgr.checkExpired(now)
1426
+ .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));
1428
+ }
1429
+ }
1339
1430
  }, intervalMs);
1340
1431
  }
1341
1432
 
package/src/peer-node.mjs CHANGED
@@ -39,6 +39,11 @@ const DEFAULT_CONNECTION_ID = 'default'
39
39
  // PeerNode
40
40
  // ---------------------------------------------------------------------------
41
41
 
42
+ /** A syntactically valid named-channel name (see WebRTCPeerConnection#openChannel). */
43
+ function isChannelName(v) {
44
+ return typeof v === 'string' && /^[A-Za-z0-9._-]{1,64}$/.test(v);
45
+ }
46
+
42
47
  /**
43
48
  * Top-level orchestrator for a mesh peer. Manages the full lifecycle
44
49
  * from identity bootstrap through discovery, connection, and shutdown.
@@ -553,8 +558,10 @@ export class PeerNode {
553
558
  * @param {object} [opts]
554
559
  * @param {string} [opts.connectionId] - Target this specific connection's
555
560
  * session (issue #116) rather than "most recently created".
556
- * @param {'control'|'bulk'} [opts.channel] - Which of the transport's data
557
- * channels to send on. Omit (or pass `'control'`) for the ordered control
561
+ * @param {string} [opts.channel] - Which of the transport's data
562
+ * channels to send on. Besides 'control' and 'bulk' this may be the name of
563
+ * a channel opened with `transport.openChannel(name)` (#115); a name the
564
+ * session's transport has not opened throws a `TypeError`. Omit (or pass `'control'`) for the ordered control
558
565
  * lane; `'bulk'` selects the second, unordered `mesh-bulk` channel, so
559
566
  * large payloads (file/torrent chunks) cannot queue in front of control
560
567
  * traffic. Passed through as `transport.send(data, { channel })` only
@@ -570,8 +577,8 @@ export class PeerNode {
570
577
  */
571
578
  async sendTo(pubKey, data, { connectionId, channel } = {}) {
572
579
  this.#ensureRunning('sendTo');
573
- if (channel !== undefined && channel !== 'control' && channel !== 'bulk') {
574
- throw new TypeError(`PeerNode.sendTo: unknown channel ${JSON.stringify(channel)} (expected 'control' or 'bulk')`);
580
+ if (channel !== undefined && channel !== 'control' && channel !== 'bulk' && !isChannelName(channel)) {
581
+ throw new TypeError(`PeerNode.sendTo: unknown channel ${JSON.stringify(channel)} (expected 'control', 'bulk' or a named channel)`);
575
582
  }
576
583
  let session = null;
577
584
  for (const [, s] of this.#sessions) {
@@ -586,6 +593,13 @@ export class PeerNode {
586
593
  if (!session.transportInstance || typeof session.transportInstance.send !== 'function') {
587
594
  throw new Error(`PeerNode.sendTo: session for ${pubKey} has no transport.send`);
588
595
  }
596
+ if (channel !== undefined && channel !== 'control' && channel !== 'bulk') {
597
+ // A named channel (#115) must have been opened on this session's transport.
598
+ const open = session.transportInstance.channels;
599
+ if (!Array.isArray(open) || !open.includes(channel)) {
600
+ throw new TypeError(`PeerNode.sendTo: unknown channel ${JSON.stringify(channel)} for ${pubKey} (open it with transport.openChannel())`);
601
+ }
602
+ }
589
603
  return channel === undefined
590
604
  ? session.transportInstance.send(data)
591
605
  : session.transportInstance.send(data, { channel });
@@ -624,8 +638,8 @@ export class PeerNode {
624
638
  */
625
639
  async broadcast(data, { channel, exclude, concurrency = 8 } = {}) {
626
640
  this.#ensureRunning('broadcast');
627
- if (channel !== undefined && channel !== 'control' && channel !== 'bulk') {
628
- throw new TypeError(`PeerNode.broadcast: unknown channel ${JSON.stringify(channel)} (expected 'control' or 'bulk')`);
641
+ if (channel !== undefined && channel !== 'control' && channel !== 'bulk' && !isChannelName(channel)) {
642
+ throw new TypeError(`PeerNode.broadcast: unknown channel ${JSON.stringify(channel)} (expected 'control', 'bulk' or a named channel)`);
629
643
  }
630
644
  const skip = typeof exclude === 'function'
631
645
  ? exclude