@johnhenry/browsermesh-apps 0.11.0 → 0.13.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/src/payments.mjs CHANGED
@@ -138,7 +138,10 @@ function canonicalBytes(fields) {
138
138
  // ---------------------------------------------------------------------------
139
139
 
140
140
  /**
141
- * Double-entry accounting ledger for a single pod.
141
+ * Double-entry accounting ledger for a single pod -- the package's canonical
142
+ * `CreditLedger` (one owner, one balance, `credit(amount, from)` /
143
+ * `debit(amount, to)` / `transfer(peerLedger, amount)`). For a book that holds
144
+ * every peer's balance see `MultiPartyCreditLedger` in `peer-payments.mjs`.
142
145
  *
143
146
  * Every mutation produces an immutable LedgerEntry recording amount,
144
147
  * counterparty, running balance, and optional memo.
@@ -985,14 +988,22 @@ export class PaymentChannel {
985
988
  */
986
989
 
987
990
  // ---------------------------------------------------------------------------
988
- // EscrowManager
991
+ // SimpleEscrowBook
989
992
  // ---------------------------------------------------------------------------
990
993
 
991
994
  /**
992
- * Manages escrow holds between pods. Funds are locked until
993
- * explicitly released, refunded, or expired.
995
+ * A flat record of escrow holds between pods: `held` then `released`,
996
+ * `refunded` or `expired`. It is a book only -- it does NOT move any balance,
997
+ * and has no release conditions, disputes or ledger hook. `PaymentRouter` keeps
998
+ * one (`getEscrow()`) to track the `ESCROW_CREATE` wire messages it receives.
999
+ *
1000
+ * It is NOT the package's `EscrowManager`: that name is the conditional escrow
1001
+ * in `peer-escrow.mjs`, which does move funds and supports conditions,
1002
+ * disputes and a `mutateLedger` hook. This class was also called
1003
+ * `EscrowManager` before 0.13, which collided with it; see the README's
1004
+ * "Ledgers and escrow" table.
994
1005
  */
995
- export class EscrowManager {
1006
+ export class SimpleEscrowBook {
996
1007
  /** @type {Map<string, object>} escrowId -> Escrow */
997
1008
  #escrows = new Map();
998
1009
 
@@ -1155,7 +1166,7 @@ export class PaymentRouter {
1155
1166
  /** @type {Map<string, PaymentChannel>} remotePodId -> channel */
1156
1167
  #channels = new Map();
1157
1168
 
1158
- /** @type {EscrowManager} */
1169
+ /** @type {SimpleEscrowBook} */
1159
1170
  #escrow;
1160
1171
 
1161
1172
  /** @type {function|null} */
@@ -1179,7 +1190,7 @@ export class PaymentRouter {
1179
1190
  }
1180
1191
  this.#localPodId = localPodId;
1181
1192
  this.#ledger = new CreditLedger(localPodId);
1182
- this.#escrow = new EscrowManager();
1193
+ this.#escrow = new SimpleEscrowBook();
1183
1194
  }
1184
1195
 
1185
1196
  /**
@@ -1297,7 +1308,7 @@ export class PaymentRouter {
1297
1308
  /**
1298
1309
  * Get the escrow manager.
1299
1310
  *
1300
- * @returns {EscrowManager}
1311
+ * @returns {SimpleEscrowBook}
1301
1312
  */
1302
1313
  getEscrow() {
1303
1314
  return this.#escrow;
@@ -1305,7 +1316,7 @@ export class PaymentRouter {
1305
1316
 
1306
1317
  /**
1307
1318
  * Start periodic escrow-timeout enforcement. Without this,
1308
- * `EscrowManager.pruneExpired()` exists but nothing ever calls it, so
1319
+ * `SimpleEscrowBook.pruneExpired()` exists but nothing ever calls it, so
1309
1320
  * timed-out escrows sit in `held` status forever.
1310
1321
  *
1311
1322
  * There is no dedicated wire message for escrow expiry in the mesh
@@ -4,8 +4,11 @@
4
4
  * Enables trustless compute marketplace, dispute resolution, and
5
5
  * guaranteed payment for services.
6
6
  *
7
- * `EscrowManager` itself is plain and dependency-injected (`{creditLedger,
8
- * onLog}`), with no `PeerNode`/mesh-transport awareness of its own -- see
7
+ * `EscrowManager` is the package's one escrow implementation under that name:
8
+ * conditional release, disputes, expiry, and real balance movement through the
9
+ * ledger it is given. (`payments.mjs`'s flat `SimpleEscrowBook`, which
10
+ * `PaymentRouter` keeps, only records holds and moves nothing.) It is plain and
11
+ * dependency-injected (`{creditLedger, onLog}`), with no `PeerNode`/mesh-transport awareness of its own -- see
9
12
  * `createEscrowService()` below (issue #117, `mesh-service.mjs`'s `MeshService`
10
13
  * convention) for the wrapper that wires it onto a real `PeerNode`'s
11
14
  * `ctx.sendTo()`/`ctx.onIncomingData()`/`ctx.registry.checkAccess()`.
@@ -235,8 +238,20 @@ export class EscrowContract {
235
238
  /**
236
239
  * Manages escrow contracts — creation, funding, release, refund, dispute.
237
240
  *
238
- * Works with a credit ledger (e.g. CreditLedger from clawser-peer-payments.js)
239
- * to hold funds in escrow until conditions are met.
241
+ * Works with a credit ledger to hold funds in escrow until conditions are met.
242
+ * Two ledgers are understood out of the box:
243
+ *
244
+ * - `CreditLedger` (`payments.mjs`, one pod's own balance): `create()` calls
245
+ * `debit(amount, payerPodId, memo)`, release/refund call
246
+ * `credit(amount, podId, memo)`. That ledger has a single balance, so every
247
+ * mutation lands on it whatever `podId` says -- use it when the local pod is
248
+ * the payer, or supply `mutateLedger` to account for the counterparty.
249
+ * - `MultiPartyCreditLedger` (`peer-payments.mjs`, a balance per pod):
250
+ * `create()` calls `charge(payerPodId, amount, memo)` (an insufficient balance
251
+ * throws, as the single-owner `debit()` does) and release/refund call
252
+ * `credit(podId, amount, memo)`, so payer and payee each move their own balance.
253
+ *
254
+ * Anything else can be wired with `mutateLedger`.
240
255
  */
241
256
  export class EscrowManager {
242
257
  /** @type {Map<string, EscrowContract>} */
@@ -256,7 +271,9 @@ export class EscrowManager {
256
271
 
257
272
  /**
258
273
  * @param {object} opts
259
- * @param {object} opts.creditLedger - Must have charge(), credit(), getBalance()
274
+ * @param {object} opts.creditLedger - A `CreditLedger` (`debit()`/`credit()`) or a
275
+ * `MultiPartyCreditLedger` (`charge()`/`credit()`); see the class comment.
276
+ * Without a `mutateLedger` hook it must be one of those two shapes.
260
277
  * @param {Function} [opts.onLog] - Logging callback (level, msg)
261
278
  * @param {(op: 'debit'|'credit', amount: number, podId: string, memo: string) => (any|Promise<any>)} [opts.mutateLedger] -
262
279
  * Async (or sync) hook invoked in place of a direct `creditLedger.debit()`/`.credit()`
@@ -281,11 +298,32 @@ export class EscrowManager {
281
298
  }
282
299
  this.#creditLedger = opts.creditLedger
283
300
  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
- ))
301
+ if (opts.mutateLedger) {
302
+ this.#mutateLedger = opts.mutateLedger
303
+ return
304
+ }
305
+ const ledger = this.#creditLedger
306
+ if (typeof ledger.debit === 'function' && typeof ledger.credit === 'function') {
307
+ // Single-owner CreditLedger: debit(amount, toPodId, memo) / credit(amount, fromPodId, memo)
308
+ this.#mutateLedger = (op, amount, podId, memo) => (
309
+ op === 'debit' ? ledger.debit(amount, podId, memo) : ledger.credit(amount, podId, memo)
310
+ )
311
+ } else if (typeof ledger.charge === 'function' && typeof ledger.credit === 'function') {
312
+ // MultiPartyCreditLedger: charge(podId, amount, memo) / credit(podId, amount, memo)
313
+ this.#mutateLedger = (op, amount, podId, memo) => {
314
+ if (op === 'credit') return ledger.credit(podId, amount, memo)
315
+ const result = ledger.charge(podId, amount, memo)
316
+ if (!result.success) {
317
+ throw new Error(`Insufficient balance: ${podId} needs ${amount}, has ${result.balance}`)
318
+ }
319
+ return result
320
+ }
321
+ } else {
322
+ throw new Error(
323
+ 'EscrowManager: creditLedger must implement debit()/credit() (CreditLedger) or ' +
324
+ 'charge()/credit() (MultiPartyCreditLedger), or pass a mutateLedger hook',
325
+ )
326
+ }
289
327
  }
290
328
 
291
329
  // ── Create ─────────────────────────────────────────────────────
@@ -755,7 +793,7 @@ const DEFAULT_ESCROW_REQUEST_TIMEOUT_MS = 10000
755
793
 
756
794
  /**
757
795
  * @param {object} opts
758
- * @param {object} opts.creditLedger - Must have charge(), credit(), getBalance() -- forwarded to `new EscrowManager()`.
796
+ * @param {object} opts.creditLedger - A `CreditLedger` or `MultiPartyCreditLedger` (see `EscrowManager`) -- forwarded to `new EscrowManager()`.
759
797
  * @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).
760
798
  * @param {string} [opts.envelopeType='escrow'] - `envelope.type` used for request/response traffic.
761
799
  * @param {number} [opts.requestTimeoutMs=10000] - How long `requestCreate()`/`requestRelease()`/`requestRefund()`/`requestDispute()` wait for a response.
@@ -2,11 +2,15 @@
2
2
  * clawser-peer-payments.js -- Payment mechanisms for resource sharing.
3
3
  *
4
4
  * Provides a PaymentProvider abstraction with two implementations:
5
- * 1. CreditLedger — internal credit system (no real money)
5
+ * 1. MultiPartyCreditLedger — internal credit system (no real money)
6
6
  * 2. WebLNProvider — Lightning Network payments (optional, requires browser extension)
7
7
  *
8
- * CreditLedger manages multi-peer balances and transaction history with
9
- * resource-based cost calculation. WebLNProvider wraps the WebLN browser API
8
+ * MultiPartyCreditLedger manages every peer's balance in one book, with a
9
+ * transaction history and resource-based cost calculation. It is NOT the
10
+ * package's `CreditLedger`: that name is the single-owner ledger in
11
+ * `payments.mjs` (one pod, one balance). This class was also called
12
+ * `CreditLedger` before 0.13, which collided with it; see the README's
13
+ * "Ledgers and escrow" table. WebLNProvider wraps the WebLN browser API
10
14
  * for optional real-money Lightning payments.
11
15
  *
12
16
  * No browser-only imports at module level. All dependencies injected.
@@ -43,16 +47,19 @@ function generateTxId() {
43
47
  }
44
48
 
45
49
  // ---------------------------------------------------------------------------
46
- // CreditLedger
50
+ // MultiPartyCreditLedger
47
51
  // ---------------------------------------------------------------------------
48
52
 
49
53
  /**
50
- * Multi-peer credit ledger for resource sharing.
54
+ * Multi-peer credit ledger for resource sharing: one book holding a balance
55
+ * per pod (`charge(podId, amount)` / `credit(podId, amount)` /
56
+ * `transfer(from, to, amount)`). For one pod's own balance see `CreditLedger`
57
+ * in `payments.mjs`.
51
58
  *
52
59
  * Tracks per-pod balances with automatic initialization at a configurable
53
60
  * credit amount. Maintains a transaction log with optional capping.
54
61
  */
55
- export class CreditLedger {
62
+ export class MultiPartyCreditLedger {
56
63
  /** @type {Map<string, number>} podId -> balance */
57
64
  #balances = new Map()
58
65
 
@@ -336,12 +343,12 @@ export class CreditLedger {
336
343
  }
337
344
 
338
345
  /**
339
- * Restore a CreditLedger from serialized data.
346
+ * Restore a MultiPartyCreditLedger from serialized data.
340
347
  * @param {object} data
341
- * @returns {CreditLedger}
348
+ * @returns {MultiPartyCreditLedger}
342
349
  */
343
350
  static fromJSON(data) {
344
- const ledger = new CreditLedger({
351
+ const ledger = new MultiPartyCreditLedger({
345
352
  initialCredits: data.initialCredits,
346
353
  maxTransactions: data.maxTransactions,
347
354
  })
@@ -252,6 +252,7 @@ export class TimestampAuthority {
252
252
  #identity
253
253
  #clockSkewMs
254
254
  #onLog
255
+ #now
255
256
 
256
257
  /**
257
258
  * @param {object} opts
@@ -259,8 +260,11 @@ export class TimestampAuthority {
259
260
  * @param {object} opts.identity - Object with sign(data) and podId
260
261
  * @param {number} [opts.clockSkewMs] - Max allowed clock skew in ms (default 30000)
261
262
  * @param {Function} [opts.onLog] - Logging callback (level, msg)
263
+ * @param {() => number} [opts.now] - Local clock in ms, default `Date.now`.
264
+ * Injected by tests so outlier rejection (which compares peer clocks to the
265
+ * local one) does not depend on how long the test took to run.
262
266
  */
263
- constructor({ sessions, identity, clockSkewMs, onLog }) {
267
+ constructor({ sessions, identity, clockSkewMs, onLog, now }) {
264
268
  if (!sessions || typeof sessions.listSessions !== 'function') {
265
269
  throw new Error('sessions is required and must have listSessions()')
266
270
  }
@@ -272,6 +276,10 @@ export class TimestampAuthority {
272
276
  this.#identity = identity
273
277
  this.#clockSkewMs = clockSkewMs ?? TIMESTAMP_DEFAULTS.clockSkewMs
274
278
  this.#onLog = onLog ?? (() => {})
279
+ if (now !== undefined && typeof now !== 'function') {
280
+ throw new Error('now must be a function returning milliseconds')
281
+ }
282
+ this.#now = now ?? Date.now
275
283
  }
276
284
 
277
285
  /**
@@ -290,7 +298,7 @@ export class TimestampAuthority {
290
298
  throw new Error('eventHash is required and must be a non-empty string')
291
299
  }
292
300
 
293
- const localTime = Date.now()
301
+ const localTime = this.#now()
294
302
  const localPodId = this.#identity.podId
295
303
 
296
304
  // Build the full timestamp map: local + peers
@@ -423,7 +431,7 @@ export class TimestampAuthority {
423
431
  * @returns {number} Median timestamp in ms
424
432
  */
425
433
  getNetworkTime(peerTimestamps) {
426
- const values = [Date.now()]
434
+ const values = [this.#now()]
427
435
 
428
436
  if (peerTimestamps) {
429
437
  for (const ts of peerTimestamps.values()) {
@@ -2,8 +2,12 @@
2
2
  // STATUS: INTEGRATED — wired into ClawserPod lifecycle, proven via E2E testing
3
3
  * clawser-peer-torrent.js -- WebTorrent integration for P2P file distribution.
4
4
  *
5
- * CDN-loads webtorrent browser bundle for swarm-based file sharing.
6
- * Falls back to direct chunked transfer when WebTorrent unavailable.
5
+ * Uses a WebTorrent client the caller supplies (`new TorrentManager({
6
+ * webtorrent })`: the `WebTorrent` constructor or a ready client) or one
7
+ * already on `window.WebTorrent`/`globalThis.WebTorrent`, for swarm-based file
8
+ * sharing. This module never fetches WebTorrent itself -- there is no CDN or
9
+ * other runtime import -- so it works offline and under a strict CSP. Without
10
+ * a client it falls back to direct chunked transfer.
7
11
  *
8
12
  * DURABILITY (fallback path only): by default the fallback keeps whole blobs
9
13
  * in a private in-memory map. Pass `chunkStore` and/or `manifestStore`
@@ -122,14 +126,21 @@ class FallbackStore {
122
126
  /**
123
127
  * Manages WebTorrent-based file sharing across the mesh.
124
128
  *
125
- * When WebTorrent is available (browser with CDN access), uses real
126
- * BitTorrent swarming. When unavailable (Node.js tests, offline), falls
127
- * back to an in-memory store that mimics the seed/download API.
129
+ * When a WebTorrent client is available (injected through the `webtorrent`
130
+ * option, or on `window`/`globalThis`), uses real BitTorrent swarming. When
131
+ * none is (Node.js tests, offline), falls back to an in-memory store that
132
+ * mimics the seed/download API.
128
133
  */
129
134
  export class TorrentManager {
130
- /** @type {object|null} WebTorrent client instance (lazy-loaded) */
135
+ /** @type {object|null} WebTorrent client instance (created on ensureLoaded) */
131
136
  #client = null
132
137
 
138
+ /** @type {Function|object|null} Injected WebTorrent constructor or client */
139
+ #webtorrent = null
140
+
141
+ /** @type {boolean} True when `#client` was built here (from a constructor/global), so destroy() may destroy it */
142
+ #ownsClient = false
143
+
133
144
  /** @type {Map<string, TorrentInfo>} magnetURI -> TorrentInfo */
134
145
  #activeTorrents = new Map()
135
146
 
@@ -180,8 +191,20 @@ export class TorrentManager {
180
191
  * keyed by magnet URI (sync or async). Defaults to in-memory when only
181
192
  * `chunkStore` is given.
182
193
  * @param {number} [opts.chunkSize=65536] - Piece size when `chunkStore` is used.
194
+ * @param {Function|object} [opts.webtorrent] - The WebTorrent library to use
195
+ * for real BitTorrent swarming: either the `WebTorrent` constructor (this
196
+ * class instantiates and later destroys the client) or an already-built
197
+ * client with `seed()`/`add()`/`remove()`/`destroy()` (yours; `destroy()`
198
+ * here leaves it running). Nothing is ever loaded from the network. Omit it
199
+ * and `window.WebTorrent`/`globalThis.WebTorrent` is used if present,
200
+ * otherwise the in-memory fallback.
183
201
  */
184
202
  constructor(opts = {}) {
203
+ if (opts.webtorrent !== undefined && opts.webtorrent !== null
204
+ && typeof opts.webtorrent !== 'function' && typeof opts.webtorrent !== 'object') {
205
+ throw new TypeError('TorrentManager: webtorrent must be the WebTorrent constructor or a client instance')
206
+ }
207
+ this.#webtorrent = opts.webtorrent ?? null
185
208
  this.#trackerUrl = opts.trackerUrl ?? TORRENT_DEFAULTS.trackerUrl
186
209
  this.#onLog = opts.onLog || (() => {})
187
210
  this.#chunkSize = opts.chunkSize ?? TORRENT_DEFAULTS.chunkSize
@@ -191,42 +214,48 @@ export class TorrentManager {
191
214
  }
192
215
  }
193
216
 
194
- // ── CDN Loading ──────────────────────────────────────────────────────
217
+ // ── WebTorrent client ─────────────────────────────────────────────────
195
218
 
196
219
  /**
197
- * Lazy-load WebTorrent from CDN.
198
- * Sets #wtAvailable based on whether the load succeeded.
220
+ * Set up the WebTorrent client from what the caller provided, and restore
221
+ * persisted torrents when running on the fallback store.
222
+ *
223
+ * Order: the injected `webtorrent` option, then `window.WebTorrent`, then
224
+ * `globalThis.WebTorrent`. Nothing is fetched; with none of them present
225
+ * `available` stays false and the in-memory fallback is used.
226
+ * Sets #wtAvailable based on whether a client was created.
199
227
  */
200
228
  async ensureLoaded() {
201
229
  if (this.#loaded) return
202
230
 
203
231
  try {
204
- // Only attempt in browser-like environments with dynamic import support
205
- if (typeof window !== 'undefined' && typeof window.WebTorrent === 'function') {
232
+ const injected = this.#webtorrent
233
+ if (injected && typeof injected === 'object') {
234
+ this.#client = injected
235
+ this.#ownsClient = false
236
+ this.#wtAvailable = true
237
+ this.#onLog(2, 'WebTorrent client supplied by the caller')
238
+ } else if (typeof injected === 'function') {
239
+ this.#client = new injected()
240
+ this.#ownsClient = true
241
+ this.#wtAvailable = true
242
+ this.#onLog(2, 'WebTorrent client created from the injected constructor')
243
+ } else if (typeof window !== 'undefined' && typeof window.WebTorrent === 'function') {
206
244
  this.#client = new window.WebTorrent()
245
+ this.#ownsClient = true
207
246
  this.#wtAvailable = true
208
247
  this.#onLog(2, 'WebTorrent client initialized from window.WebTorrent')
209
248
  } else if (typeof globalThis.WebTorrent === 'function') {
210
249
  this.#client = new globalThis.WebTorrent()
250
+ this.#ownsClient = true
211
251
  this.#wtAvailable = true
212
252
  this.#onLog(2, 'WebTorrent client initialized from globalThis.WebTorrent')
213
253
  } else {
214
- // Try CDN load via esm.sh — this will fail in Node.js test env
215
- try {
216
- const mod = await import('https://esm.sh/webtorrent@2.8.5')
217
- const WT = mod.default || mod.WebTorrent
218
- if (typeof WT === 'function') {
219
- globalThis.WebTorrent = WT
220
- this.#client = new WT()
221
- this.#wtAvailable = true
222
- this.#onLog(2, 'WebTorrent loaded from CDN (esm.sh)')
223
- }
224
- } catch {
225
- this.#wtAvailable = false
226
- this.#onLog(1, 'WebTorrent CDN load failed — using fallback store')
227
- }
254
+ this.#wtAvailable = false
255
+ this.#onLog(1, 'No WebTorrent client supplied (pass { webtorrent }) — using fallback store')
228
256
  }
229
257
  } catch (err) {
258
+ this.#client = null
230
259
  this.#wtAvailable = false
231
260
  this.#onLog(1, `WebTorrent initialization failed: ${err.message}`)
232
261
  }
@@ -718,8 +747,8 @@ export class TorrentManager {
718
747
  this.#fallback.clear()
719
748
  this.#listeners.clear()
720
749
 
721
- // Destroy real client if present
722
- if (this.#client) {
750
+ // Destroy the real client if we built it; one the caller passed in stays theirs.
751
+ if (this.#client && this.#ownsClient) {
723
752
  try {
724
753
  await new Promise((resolve, reject) => {
725
754
  this.#client.destroy((err) => {
@@ -730,8 +759,9 @@ export class TorrentManager {
730
759
  } catch {
731
760
  // best effort
732
761
  }
733
- this.#client = null
734
762
  }
763
+ this.#client = null
764
+ this.#ownsClient = false
735
765
 
736
766
  this.#loaded = false
737
767
  this.#wtAvailable = false