@johnhenry/browsermesh-apps 0.8.0 → 0.10.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
@@ -17,6 +17,7 @@ Application layer for BrowserMesh: marketplace, chat, payments, compute orchestr
17
17
  - [Sharing a `VirtualNetwork` with specific peers: mesh relay](#sharing-a-virtualnetwork-with-specific-peers-mesh-relay)
18
18
  - [CloudStorage bucket authorization and key distribution](#cloudstorage-bucket-authorization-and-key-distribution)
19
19
  - [CloudStorage: the ergonomic SDK](#cloudstorage-the-ergonomic-sdk)
20
+ - [Torrent service: durable stores, authorization and serve limits](#torrent-service-durable-stores-authorization-and-serve-limits)
20
21
  - [Putting it all together: sync + kernel-gated mesh + relay on one connection](#putting-it-all-together-sync--kernel-gated-mesh--relay-on-one-connection)
21
22
  - [`fetch()`/`WebSocket`-shaped mesh access: `browserMeshFetch` and `BrowserMeshWebSocket`](#fetchwebsocket-shaped-mesh-access-browsermeshfetch-and-browsermeshwebsocket)
22
23
  - [`browserMeshFetch`](#browsermeshfetch)
@@ -59,7 +60,7 @@ Extracted from the private `clawser` monorepo (previously `packages/browsermesh-
59
60
  | peer-escrow | `EscrowContract`, `EscrowManager` |
60
61
  | peer-files | `FileHost`, `FileClient` |
61
62
  | peer-health | `HealthMonitor`, `AutoMigrator` |
62
- | peer-ipfs | `IPFSStore` |
63
+ | peer-ipfs | `IPFSStore` (also exported as `MeshLocalCidStore`): a mesh-local content-addressed store. CIDs are SHA-256 hex digests, not IPFS CIDs, and nothing talks to the IPFS network |
63
64
  | peer-node | `PeerNode` |
64
65
  | peer-payments | `CreditLedger`, `WebLNProvider` |
65
66
  | peer-registry | `PeerRegistry` |
@@ -68,6 +69,7 @@ Extracted from the private `clawser` monorepo (previously `packages/browsermesh-
68
69
  | peer-terminal | `TerminalHost`, `TerminalClient` |
69
70
  | peer-timestamp | `TimestampAuthority`, `TimestampProof` |
70
71
  | peer-torrent | `TorrentManager` |
72
+ | mesh-torrent | `createTorrentService` (swarm piece exchange as a `MeshService`; injectable durable stores, `authorize` hook, serve caps) |
71
73
  | peer-verification | `VerificationQuorum`, `Attestation` |
72
74
  | marketplace-ui | `SkillMarketplace` |
73
75
  | mesh-relay-host | `MeshRelayHost` |
@@ -343,6 +345,55 @@ GrantLog pattern, and the key-distribution pattern, each with pointers to
343
345
  the real code, written so the *next* mesh-native service doesn't have to
344
346
  rediscover these same design questions from scratch.
345
347
 
348
+ ## Torrent service: durable stores, authorization and serve limits
349
+
350
+ `createTorrentService()` (`mesh-torrent.mjs`) distributes content in
351
+ SHA-256-addressed pieces: a downloader fetches each piece from whichever peer
352
+ holds it, and a finished downloader becomes a seeder. By default everything is
353
+ in memory and open to any peer that knows the magnet URI. These options change
354
+ that; all are optional.
355
+
356
+ ```js
357
+ import { createTorrentService, attachService } from '@johnhenry/browsermesh-apps'
358
+ import { IndexedDBChunkStore } from '@johnhenry/browsermesh-sync'
359
+
360
+ const torrent = attachService(peerNode, undefined, createTorrentService({
361
+ // Durable pieces and manifests: a seeder that reloads keeps serving.
362
+ chunkStore: new IndexedDBChunkStore({ dbName: 'my-app-pieces' }),
363
+ manifestStore: myManifestStore,
364
+ // Who may fetch what. Return true to allow; false, a throw, or anything else denies.
365
+ authorize: async (fromPubKey, { kind, magnetURI, infoHash, cid, chunkCid }) =>
366
+ registry.checkAccess(fromPubKey, `share:${cid}`, 'read'),
367
+ maxConcurrentServes: 16, // chunk-responses in flight, all peers (0 = unlimited)
368
+ maxConcurrentServesPerPeer: 4, // ... per requesting peer
369
+ maxBytesPerPeerPerSec: 4 * 1024 * 1024, // served-bytes budget per peer (default 0 = unlimited)
370
+ maxAnnouncesPerPeerPerMinute: 30, // inbound announces accepted per peer
371
+ }))
372
+
373
+ await torrent.api.ensureLoaded() // after a reload: also restores listTorrents()
374
+ const info = await torrent.api.seed('some text') // strings are UTF-8 encoded
375
+ ```
376
+
377
+ - **`chunkStore`** is any object with `save(cid, bytes)`, `get(cid)`,
378
+ `has(cid)` and `remove(cid)`, each sync or returning a Promise. The in-memory
379
+ `ChunkStore` and the IndexedDB-backed `IndexedDBChunkStore` from
380
+ `@johnhenry/browsermesh-sync` both fit; the service is tested against both.
381
+ - **`manifestStore`** is `{ get(magnetURI), set(magnetURI, manifest),
382
+ delete(magnetURI), entries() }` (sync or async). Each manifest is a small
383
+ JSON-safe record. It is the index of what the node holds, and a node only
384
+ serves pieces that one of its manifests lists, so persist both stores or
385
+ neither. `TorrentManager` accepts the same two options (plus `chunkSize`).
386
+ - Stores you pass in belong to you: `destroy()` never clears them.
387
+ - **`authorize`** runs before every manifest and piece is served. A refused
388
+ request gets exactly the reply an unknown one gets (`manifest: null` /
389
+ `error: 'not-found'`), so a peer cannot probe what exists. `cid` is the
390
+ SHA-256 hex CID of the whole content; `chunkCid` is set for `kind: 'chunk'`.
391
+ - Over a serve cap a requester is told `busy` (whatever it asked for) and
392
+ downloaders back off and retry. Caps and `authorize` never apply to the
393
+ downloading side.
394
+ - Events: `torrent:chunk-served`, `torrent:chunk-received` (as before), plus
395
+ `torrent:request-denied` and `torrent:serve-busy`.
396
+
346
397
  ## Putting it all together: sync + kernel-gated mesh + relay on one connection
347
398
 
348
399
  Every composition layer above (`enableSync`, a `Kernel` wired via
@@ -522,6 +573,41 @@ agent runtime" section for the full design writeup, including two real bugs
522
573
  found while building it and the recommended DI pattern for new tools going
523
574
  forward.
524
575
 
576
+ ## Verify argument order (caller-supplied callbacks)
577
+
578
+ Every signature check in BrowserMesh takes `(identity, signature, data)`, the
579
+ same as `crypto.subtle.verify`. This applies to the callbacks you hand in:
580
+
581
+ | Where | Callback shape |
582
+ |-------|----------------|
583
+ | `PaymentChannel` `opts.verifyFn` | `(publicKey, signature, data) => boolean` |
584
+ | chat service / `PeerChat` `verifyFn` | `(fromPubKey, signature, data) => boolean` |
585
+ | `GrantLog` / key-distribution `wallet.verify` | `(publicKeyBytes, signature, data) => boolean` |
586
+ | `TimestampProof.verify(verifyFn)` and `identity.verify` on `TimestampAuthority` | `(signerPodId, signature, data) => boolean` |
587
+ | `Attestation.verify(verifyFn)` | `(podId, signature, resultHash) => boolean` |
588
+
589
+ **BREAKING (apps 0.9.0):** `peer-timestamp` previously used
590
+ `(signature, data, signerPodId)` and `Attestation.verify` used
591
+ `(podId, resultHash, signature)`. Update those callbacks; swap the arguments.
592
+
593
+ An old-order callback used to return `false` for every message, silently,
594
+ because the library catches errors around callbacks. To make that loud, the
595
+ `PaymentChannel`, chat, `GrantLog` and key-distribution paths run a one-time
596
+ self-test the first time a callback is used (the probe is started when the
597
+ callback is passed in): the callback is called with a known-good Ed25519 test
598
+ vector (RFC 8032, test 2) in the new order. If it rejects that but accepts
599
+ `(publicKey, data, signature)`, a `TypeError` naming the new order is thrown
600
+ from the call that used it (for example `channel.receive()` or
601
+ `chat.receiveEnvelope()`), and every later call rejects the same way. A
602
+ callback that accepts the new order, or that rejects both orders (for example
603
+ it looks keys up in a directory the test key is not in), is left alone. The
604
+ self-test is skipped when `NODE_ENV` is `production`. Because the test vector
605
+ is fed to your callback once, spies on `verifyFn` see one extra call with
606
+ `Uint8Array` arguments.
607
+
608
+ The `peer-timestamp` paths also throw a `TypeError` if the first argument is a
609
+ 64-byte signature.
610
+
525
611
  ## License
526
612
 
527
613
  MIT
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/browsermesh-apps",
3
- "version": "0.8.0",
3
+ "version": "0.10.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",
@@ -27,7 +27,7 @@
27
27
  "directory": "packages/browsermesh-apps"
28
28
  },
29
29
  "peerDependencies": {
30
- "@johnhenry/browsermesh-primitives": ">=0.0.1 <1.0.0",
30
+ "@johnhenry/browsermesh-primitives": ">=0.2.0 <1.0.0",
31
31
  "@johnhenry/browsermesh-core": ">=0.5.0 <1.0.0",
32
32
  "@johnhenry/browsermesh-transport": ">=0.1.0 <1.0.0",
33
33
  "@johnhenry/browsermesh-sync": ">=0.0.0 <1.0.0",
package/src/grant-log.mjs CHANGED
@@ -218,6 +218,7 @@
218
218
  */
219
219
 
220
220
  import { ORSet, encodeBase64url, decodeBase64url } from '@johnhenry/browsermesh-primitives'
221
+ import { guardVerifyMethod, isVerifyOrderError } from './internal/verify-order.mjs'
221
222
 
222
223
  /** Default `envelope.type` used to route GrantLog payloads on the shared `onIncomingData()` bus. */
223
224
  const DEFAULT_ENVELOPE_TYPE = 'grant-log'
@@ -308,6 +309,7 @@ export class GrantLog {
308
309
  * `.getPublicKeyBytes(podId)` are used (the real `IdentityWallet`'s
309
310
  * confirmed API, see identity-wallet.mjs / identity.mjs). */
310
311
  #wallet
312
+ #verifyWallet
311
313
 
312
314
  /** @type {import('./peer-registry.mjs').PeerRegistry} */
313
315
  #registry
@@ -376,6 +378,7 @@ export class GrantLog {
376
378
  throw new Error('GrantLog: registry is required and must provide grantCapabilities()/revokeCapabilities()')
377
379
  }
378
380
 
381
+ this.#verifyWallet = guardVerifyMethod(wallet, 'GrantLog wallet.verify')
379
382
  this.#resource = resource
380
383
  this.#localPodId = localPodId
381
384
  this.#wallet = wallet
@@ -550,8 +553,9 @@ export class GrantLog {
550
553
  if (derivedPodId !== signedBy) return false
551
554
 
552
555
  const payload = new TextEncoder().encode(signedPayloadOf({ pubKey, scope, action, at, signedBy }))
553
- return await this.#wallet.verify(rawPubKeyBytes, sigBytes, payload)
554
- } catch {
556
+ return await this.#verifyWallet(rawPubKeyBytes, sigBytes, payload)
557
+ } catch (err) {
558
+ if (isVerifyOrderError(err)) throw err
555
559
  // Malformed base64url, wrong-length keys/signatures, etc. are all
556
560
  // "reject", never a thrown error the caller has to remember to catch.
557
561
  return false
@@ -0,0 +1,141 @@
1
+ // Shared helpers for TorrentManager (peer-torrent.mjs) and
2
+ // createTorrentService (mesh-torrent.mjs): byte-input normalisation, the
3
+ // default in-memory manifest store, and reference-counted chunk release.
4
+ //
5
+ // No browser-only imports at module level.
6
+
7
+ /**
8
+ * Normalise anything `seed()` accepts to a `Uint8Array`.
9
+ *
10
+ * string -> UTF-8 bytes
11
+ * Blob -> its bytes
12
+ * ArrayBuffer -> a view over it
13
+ * TypedArray / DataView -> a Uint8Array over the same bytes (Uint8Array is returned as-is)
14
+ *
15
+ * Anything else throws a `TypeError`. It must not fall through to
16
+ * `new Uint8Array(x)`: for a string or a plain object that yields an EMPTY
17
+ * array, which silently seeded zero bytes (#195).
18
+ *
19
+ * @param {unknown} data
20
+ * @returns {Promise<Uint8Array>}
21
+ */
22
+ export async function toSeedBytes(data) {
23
+ if (data instanceof Uint8Array) return data
24
+ if (typeof data === 'string') return new TextEncoder().encode(data)
25
+ if (data instanceof ArrayBuffer) return new Uint8Array(data)
26
+ if (ArrayBuffer.isView(data)) return new Uint8Array(data.buffer, data.byteOffset, data.byteLength)
27
+ if (typeof Blob !== 'undefined' && data instanceof Blob) return new Uint8Array(await data.arrayBuffer())
28
+ if (typeof SharedArrayBuffer !== 'undefined' && data instanceof SharedArrayBuffer) return new Uint8Array(data)
29
+ const got = data === null ? 'null' : Array.isArray(data) ? 'Array' : typeof data === 'object' ? (data.constructor?.name || 'object') : typeof data
30
+ throw new TypeError(
31
+ `seed(): data must be a string, Uint8Array, other TypedArray, ArrayBuffer or Blob (got ${got})`,
32
+ )
33
+ }
34
+
35
+ /**
36
+ * Default `manifestStore`: a `Map` behind the async-tolerant contract
37
+ *
38
+ * get(key) -> manifest | undefined | null
39
+ * set(key, manifest) -> void
40
+ * delete(key) -> void
41
+ * entries() -> Iterable<[key, manifest]> | Array<[key, manifest]>
42
+ *
43
+ * (every method may be sync or return a Promise). Keys are magnet URIs;
44
+ * values are JSON-safe `{ infoHash, name, size, chunkSize, chunkCids, cid }`
45
+ * records, so a durable implementation can simply JSON-serialise them.
46
+ */
47
+ export class MemoryManifestStore {
48
+ #m = new Map()
49
+ get(key) { return this.#m.get(key) }
50
+ set(key, manifest) { this.#m.set(key, manifest) }
51
+ delete(key) { this.#m.delete(key) }
52
+ entries() { return [...this.#m.entries()] }
53
+ clear() { this.#m.clear() }
54
+ get size() { return this.#m.size }
55
+ }
56
+
57
+ /**
58
+ * Remove the chunks of `manifest` from `chunkStore`, except any that another
59
+ * manifest in `manifestStore` (other than `exceptKey`) still lists -- chunks
60
+ * are content-addressed and shared between torrents that contain identical
61
+ * pieces.
62
+ *
63
+ * @param {object} chunkStore
64
+ * @param {object} manifestStore
65
+ * @param {{ chunkCids: string[] }} manifest
66
+ * @param {string} exceptKey magnet URI being removed
67
+ * @returns {Promise<number>} chunks removed
68
+ */
69
+ export async function releaseChunks(chunkStore, manifestStore, manifest, exceptKey) {
70
+ const stillUsed = new Set()
71
+ for (const [key, other] of await manifestStore.entries()) {
72
+ if (key === exceptKey || !other || !Array.isArray(other.chunkCids)) continue
73
+ for (const cid of other.chunkCids) stillUsed.add(cid)
74
+ }
75
+ let removed = 0
76
+ for (const cid of new Set(manifest.chunkCids)) {
77
+ if (stillUsed.has(cid)) continue
78
+ if (await chunkStore.remove(cid)) removed++
79
+ }
80
+ return removed
81
+ }
82
+
83
+ /**
84
+ * Split `bytes` into `chunkSize` pieces (zero pieces for empty input).
85
+ * @param {Uint8Array} bytes
86
+ * @param {number} chunkSize
87
+ * @returns {Uint8Array[]}
88
+ */
89
+ export function splitIntoChunks(bytes, chunkSize) {
90
+ const pieces = []
91
+ for (let offset = 0; offset < bytes.length; offset += chunkSize) {
92
+ pieces.push(bytes.subarray(offset, Math.min(offset + chunkSize, bytes.length)))
93
+ }
94
+ return pieces
95
+ }
96
+
97
+ /**
98
+ * @param {object} store a ChunkStore-contract object (sync or async)
99
+ * @param {Uint8Array[]} pieces
100
+ * @param {(piece: Uint8Array) => Promise<string>} computeCid
101
+ * @returns {Promise<string[]>} the pieces' CIDs, in order. Pieces already in the store are not re-written.
102
+ */
103
+ export async function saveChunks(store, pieces, computeCid) {
104
+ const cids = []
105
+ for (const piece of pieces) {
106
+ const cid = await computeCid(piece)
107
+ if (!(await store.has(cid))) await store.save(cid, piece)
108
+ cids.push(cid)
109
+ }
110
+ return cids
111
+ }
112
+
113
+ /**
114
+ * Token bucket: `rate` bytes/second with a one-second burst. `take(n)` waits
115
+ * until `n` bytes of budget exist (a single piece larger than one second's
116
+ * budget waits for a full bucket, never forever). `rate <= 0` or `Infinity`
117
+ * disables the limit.
118
+ *
119
+ * @param {object} opts
120
+ * @param {number} opts.rate
121
+ * @param {() => number} [opts.now]
122
+ * @param {(ms: number) => Promise<void>} [opts.sleep]
123
+ */
124
+ export function createByteBucket({ rate, now = Date.now, sleep = (ms) => new Promise((r) => setTimeout(r, ms)) }) {
125
+ const unlimited = !(rate > 0) || !Number.isFinite(rate)
126
+ let tokens = rate
127
+ let last = now()
128
+ return {
129
+ async take(bytes) {
130
+ if (unlimited) return
131
+ const need = Math.min(bytes, rate)
132
+ for (;;) {
133
+ const t = now()
134
+ tokens = Math.min(rate, tokens + ((t - last) / 1000) * rate)
135
+ last = t
136
+ if (tokens >= need) { tokens -= need; return }
137
+ await sleep(Math.ceil(((need - tokens) / rate) * 1000))
138
+ }
139
+ },
140
+ }
141
+ }
@@ -0,0 +1,149 @@
1
+ // Guards for the Ed25519 verify argument order.
2
+ //
3
+ // The canonical order everywhere in BrowserMesh is (identity, signature, data):
4
+ // verify(publicKey, signature, data)
5
+ // verify(signerPodId, signature, data)
6
+ //
7
+ // Library entry points throw a TypeError when they see a 64-byte signature
8
+ // where the identity belongs. Caller-supplied callbacks are different: the
9
+ // library hands THEM the arguments, and callers of callbacks usually catch, so
10
+ // an old-order callback just returns false. `guardVerifyFn` probes a callback
11
+ // once with a known-good vector to turn that silent failure into a TypeError.
12
+
13
+ /** Ed25519 signatures are exactly this many bytes. */
14
+ export const ED25519_SIGNATURE_BYTES = 64
15
+
16
+ /** `err.code` of every TypeError raised by this module. Catch blocks rethrow it. */
17
+ export const VERIFY_ORDER_ERROR_CODE = 'ERR_VERIFY_ARG_ORDER'
18
+
19
+ // RFC 8032 section 7.1, TEST 2 (1-byte message 0x72).
20
+ const VECTOR_PUBLIC_KEY = hex('3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c')
21
+ const VECTOR_MESSAGE = hex('72')
22
+ const VECTOR_SIGNATURE = hex(
23
+ '92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da' +
24
+ '085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00',
25
+ )
26
+
27
+ function hex(s) {
28
+ const out = new Uint8Array(s.length / 2)
29
+ for (let i = 0; i < out.length; i++) out[i] = parseInt(s.slice(i * 2, i * 2 + 2), 16)
30
+ return out
31
+ }
32
+
33
+ function orderError(message) {
34
+ const err = new TypeError(message)
35
+ err.code = VERIFY_ORDER_ERROR_CODE
36
+ return err
37
+ }
38
+
39
+ /** @param {unknown} err */
40
+ export function isVerifyOrderError(err) {
41
+ return err instanceof TypeError && err.code === VERIFY_ORDER_ERROR_CODE
42
+ }
43
+
44
+ /** @param {unknown} v */
45
+ function isSignatureSized(v) {
46
+ return (v instanceof ArrayBuffer || ArrayBuffer.isView(v)) && v.byteLength === ED25519_SIGNATURE_BYTES
47
+ }
48
+
49
+ /**
50
+ * Throw a TypeError when the identity argument is a 64-byte signature, i.e.
51
+ * the caller used the pre-canonical `(signature, data, identity)` order.
52
+ *
53
+ * @param {unknown} identity - what should be a public key or signer pod ID
54
+ * @param {string} label - e.g. 'identity.verify'
55
+ */
56
+ export function assertIdentityFirst(identity, label) {
57
+ if (isSignatureSized(identity)) {
58
+ throw orderError(
59
+ `${label}: argument order is (signerPodId, signature, data); ` +
60
+ 'the first argument is a 64-byte signature, which looks like the old (signature, data, signerPodId) order',
61
+ )
62
+ }
63
+ }
64
+
65
+ /** Dev mode unless NODE_ENV is explicitly 'production'. */
66
+ function devMode() {
67
+ try {
68
+ return globalThis.process?.env?.NODE_ENV !== 'production'
69
+ } catch {
70
+ return true
71
+ }
72
+ }
73
+
74
+ /**
75
+ * Probe `verifyFn` with a known-good Ed25519 vector in the canonical order
76
+ * `(publicKey, signature, data)`. If it rejects that but accepts the OLD order
77
+ * `(publicKey, data, signature)`, it is an old-order callback: throw.
78
+ *
79
+ * A callback that accepts the canonical order, rejects both (for instance it
80
+ * resolves keys from a directory the vector is not in), or throws on the
81
+ * probe passes: only a provable old-order callback is an error.
82
+ *
83
+ * @param {Function} verifyFn
84
+ * @param {string} label
85
+ * @returns {Promise<void>}
86
+ */
87
+ export async function selfTestVerifyFn(verifyFn, label) {
88
+ const attempt = async (...args) => {
89
+ try {
90
+ return (await verifyFn(...args)) === true
91
+ } catch {
92
+ return false
93
+ }
94
+ }
95
+ if (await attempt(VECTOR_PUBLIC_KEY.slice(), VECTOR_SIGNATURE.slice(), VECTOR_MESSAGE.slice())) return
96
+ if (await attempt(VECTOR_PUBLIC_KEY.slice(), VECTOR_MESSAGE.slice(), VECTOR_SIGNATURE.slice())) {
97
+ throw orderError(
98
+ `${label}: verifyFn uses the old argument order. It must now be ` +
99
+ '(publicKey, signature, data), the same as crypto.subtle.verify; ' +
100
+ 'it accepted (publicKey, data, signature) for a known-good vector and rejected the new order',
101
+ )
102
+ }
103
+ }
104
+
105
+ /**
106
+ * Wrap a caller-supplied `verifyFn` so the first use runs the one-time order
107
+ * self-test (kicked off now, awaited before the first real call). The probe
108
+ * result is sticky: once an old-order callback is detected every call rejects
109
+ * with the same TypeError. Skipped when NODE_ENV is 'production'.
110
+ *
111
+ * Callers that catch errors around the wrapped function must rethrow when
112
+ * `isVerifyOrderError(err)` is true.
113
+ *
114
+ * @template {Function|null|undefined} F
115
+ * @param {F} verifyFn
116
+ * @param {string} label
117
+ * @returns {F}
118
+ */
119
+ export function guardVerifyFn(verifyFn, label) {
120
+ if (typeof verifyFn !== 'function' || !devMode()) return verifyFn
121
+ const probe = selfTestVerifyFn(verifyFn, label)
122
+ probe.catch(() => {}) // surfaced on first use, never as an unhandled rejection
123
+ const guarded = async (...args) => {
124
+ await probe
125
+ return verifyFn(...args)
126
+ }
127
+ return /** @type {F} */ (guarded)
128
+ }
129
+
130
+ /**
131
+ * Same as {@link guardVerifyFn} for an object exposing `verify(publicKey,
132
+ * signature, data)` (a wallet). Returns a function to call instead of
133
+ * `obj.verify(...)`. The probe is created lazily, once per object.
134
+ *
135
+ * @param {{ verify: Function }} obj
136
+ * @param {string} label
137
+ * @returns {(...args: any[]) => Promise<any>}
138
+ */
139
+ export function guardVerifyMethod(obj, label) {
140
+ let probe = null
141
+ return async (...args) => {
142
+ if (probe === null) {
143
+ probe = devMode() ? selfTestVerifyFn((...a) => obj.verify(...a), label) : Promise.resolve()
144
+ probe.catch(() => {})
145
+ }
146
+ await probe
147
+ return obj.verify(...args)
148
+ }
149
+ }
@@ -168,6 +168,18 @@
168
168
  */
169
169
 
170
170
  import { encodeBase64url, decodeBase64url } from '@johnhenry/browsermesh-primitives'
171
+ import { guardVerifyMethod, isVerifyOrderError } from './internal/verify-order.mjs'
172
+
173
+ // One order self-test per wallet object (see internal/verify-order.mjs).
174
+ const guardedWalletVerify = new WeakMap()
175
+ function verifyViaWallet(wallet) {
176
+ let fn = guardedWalletVerify.get(wallet)
177
+ if (!fn) {
178
+ fn = guardVerifyMethod(wallet, 'key-distribution wallet.verify')
179
+ guardedWalletVerify.set(wallet, fn)
180
+ }
181
+ return fn
182
+ }
171
183
  // @johnhenry/browsermesh-core (an optional peerDependency) is imported
172
184
  // lazily, at each of the three call sites below, rather than eagerly here
173
185
  // -- so this module doesn't force it on every consumer of this package's
@@ -452,8 +464,9 @@ export function createKeyDistributionService({
452
464
  const payload = new TextEncoder().encode(signedPayloadOf({ resource, ephemeralPublicKey: envelope.ephemeralPublicKey, wrappedKey: envelope.wrappedKey, iv: envelope.iv, at, signedBy }))
453
465
  let validSig = false
454
466
  try {
455
- validSig = await peerNode.wallet.verify(rawPubKeyBytes, sigBytes, payload)
456
- } catch {
467
+ validSig = await verifyViaWallet(peerNode.wallet)(rawPubKeyBytes, sigBytes, payload)
468
+ } catch (err) {
469
+ if (isVerifyOrderError(err)) throw err
457
470
  validSig = false
458
471
  }
459
472
  if (!validSig) {
@@ -576,7 +576,9 @@ import { registerOrchestratorTools } from './mesh-orchestrator-tools.mjs'
576
576
  * `node.services.get('torrent')`).
577
577
  * @param {object} [options.torrentOptions] - Only used when `enableTorrent`.
578
578
  * Passed straight through to `createTorrentService()`
579
- * (`trackerUrl`/`chunkSize`/`envelopeType`/`manifestTimeoutMs`/`chunkTimeoutMs`).
579
+ * (`trackerUrl`/`chunkSize`/`envelopeType`/`manifestTimeoutMs`/`chunkTimeoutMs`,
580
+ * plus the hooks `chunkStore`/`manifestStore`/`authorize`/`maxConcurrentServes`/
581
+ * `maxConcurrentServesPerPeer`/`maxBytesPerPeerPerSec`/`maxAnnouncesPerPeerPerMinute`).
580
582
  * @param {boolean} [options.enableEscrow=false] - Attach `peer-escrow.mjs`'s
581
583
  * `createEscrowService()` (issue #117): real escrow-contract create/
582
584
  * release/refund/dispute against `escrowOptions.creditLedger`, with
@@ -1220,6 +1222,13 @@ export async function createMeshNode(options = {}) {
1220
1222
  envelopeType: torrentOptions?.envelopeType,
1221
1223
  manifestTimeoutMs: torrentOptions?.manifestTimeoutMs,
1222
1224
  chunkTimeoutMs: torrentOptions?.chunkTimeoutMs,
1225
+ chunkStore: torrentOptions?.chunkStore,
1226
+ manifestStore: torrentOptions?.manifestStore,
1227
+ authorize: torrentOptions?.authorize,
1228
+ maxConcurrentServes: torrentOptions?.maxConcurrentServes,
1229
+ maxConcurrentServesPerPeer: torrentOptions?.maxConcurrentServesPerPeer,
1230
+ maxBytesPerPeerPerSec: torrentOptions?.maxBytesPerPeerPerSec,
1231
+ maxAnnouncesPerPeerPerMinute: torrentOptions?.maxAnnouncesPerPeerPerMinute,
1223
1232
  onLog,
1224
1233
  })
1225
1234
  const torrentHandle = attachService(node, servicesNetwork, torrentDescriptor)