@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 +87 -1
- package/package.json +2 -2
- package/src/grant-log.mjs +6 -2
- package/src/internal/torrent-store.mjs +141 -0
- package/src/internal/verify-order.mjs +149 -0
- package/src/key-distribution.mjs +15 -2
- package/src/mesh-bootstrap.mjs +10 -1
- package/src/mesh-torrent.mjs +476 -166
- package/src/payments.mjs +7 -2
- package/src/peer-chat.mjs +4 -1
- package/src/peer-ipfs.mjs +51 -112
- package/src/peer-timestamp.mjs +15 -4
- package/src/peer-torrent.mjs +145 -13
- package/src/peer-verification.mjs +4 -2
package/src/payments.mjs
CHANGED
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
|
|
13
13
|
import { MESH_TYPE } from '@johnhenry/browsermesh-primitives';
|
|
14
14
|
import { silentCatch } from './silent-catch.mjs'
|
|
15
|
+
import { guardVerifyFn, isVerifyOrderError } from './internal/verify-order.mjs'
|
|
15
16
|
|
|
16
17
|
// ---------------------------------------------------------------------------
|
|
17
18
|
// Wire constants — imported from canonical registry
|
|
@@ -64,6 +65,9 @@ function generateEscrowId() {
|
|
|
64
65
|
// dependency on it. Shape matches peer-chat.mjs's convention:
|
|
65
66
|
// signFn: async (data: Uint8Array) => Uint8Array
|
|
66
67
|
// verifyFn: async (pubKey: Uint8Array, sig: Uint8Array, data: Uint8Array) => boolean
|
|
68
|
+
// (canonical (publicKey, signature, data) order; an old-order callback is
|
|
69
|
+
// detected by a one-time self-test and throws a TypeError, see
|
|
70
|
+
// internal/verify-order.mjs)
|
|
67
71
|
|
|
68
72
|
/**
|
|
69
73
|
* Encode a Uint8Array to a base64 string.
|
|
@@ -456,7 +460,7 @@ export class PaymentChannel {
|
|
|
456
460
|
this.#ttlMs = opts.ttlMs || DEFAULT_TTL_MS;
|
|
457
461
|
this.#createdAt = Date.now();
|
|
458
462
|
this.#signFn = opts.signFn || null;
|
|
459
|
-
this.#verifyFn = opts.verifyFn || null;
|
|
463
|
+
this.#verifyFn = guardVerifyFn(opts.verifyFn, 'PaymentChannel') || null;
|
|
460
464
|
this.#remotePublicKey = opts.remotePublicKey || null;
|
|
461
465
|
}
|
|
462
466
|
|
|
@@ -683,7 +687,8 @@ export class PaymentChannel {
|
|
|
683
687
|
const data = canonicalBytes(fields);
|
|
684
688
|
const sigBytes = base64ToBytes(signatureB64);
|
|
685
689
|
return await this.#verifyFn(this.#remotePublicKey, sigBytes, data);
|
|
686
|
-
} catch {
|
|
690
|
+
} catch (err) {
|
|
691
|
+
if (isVerifyOrderError(err)) throw err;
|
|
687
692
|
return false;
|
|
688
693
|
}
|
|
689
694
|
}
|
package/src/peer-chat.mjs
CHANGED
|
@@ -147,6 +147,8 @@ function base64ToBytes(b64) {
|
|
|
147
147
|
// ---------------------------------------------------------------------------
|
|
148
148
|
// PeerChat
|
|
149
149
|
// ---------------------------------------------------------------------------
|
|
150
|
+
import { guardVerifyFn, isVerifyOrderError } from './internal/verify-order.mjs'
|
|
151
|
+
|
|
150
152
|
|
|
151
153
|
/**
|
|
152
154
|
* P2P chat, transport-agnostic beyond a caller-supplied `send()` function.
|
|
@@ -211,7 +213,7 @@ export class PeerChat {
|
|
|
211
213
|
this.#localPubKey = localPubKey
|
|
212
214
|
this.#send = send
|
|
213
215
|
this.#signFn = signFn || null
|
|
214
|
-
this.#verifyFn = verifyFn || null
|
|
216
|
+
this.#verifyFn = guardVerifyFn(verifyFn, 'ChatService') || null
|
|
215
217
|
this.#maxHistory = maxHistory ?? 1000
|
|
216
218
|
this.#autoResponder = autoResponder || null
|
|
217
219
|
this.#onLog = onLog || (() => {})
|
|
@@ -351,6 +353,7 @@ export class PeerChat {
|
|
|
351
353
|
const sigBytes = base64ToBytes(message.signature)
|
|
352
354
|
message.verified = await this.#verifyFn(fromPubKey, sigBytes, data)
|
|
353
355
|
} catch (err) {
|
|
356
|
+
if (isVerifyOrderError(err)) throw err
|
|
354
357
|
this.#onLog(1, `Signature verification failed: ${err.message}`)
|
|
355
358
|
message.verified = false
|
|
356
359
|
}
|
package/src/peer-ipfs.mjs
CHANGED
|
@@ -10,44 +10,29 @@
|
|
|
10
10
|
* the `MeshService` wrapper.
|
|
11
11
|
*
|
|
12
12
|
* ---------------------------------------------------------------------------
|
|
13
|
-
*
|
|
14
|
-
* name, or the word "IPFS" in this file's own history, implies real public
|
|
15
|
-
* IPFS-network interop):
|
|
13
|
+
* WHAT THIS CLASS IS (and is not):
|
|
16
14
|
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
* without Helia" test, the only Helia-adjacent behavior anyone has
|
|
27
|
-
* actually verified here.
|
|
28
|
-
* 2. Even setting (1) aside and assuming a real Helia node did load
|
|
29
|
-
* successfully: `add()`, `get()`, `pin()`, `unpin()`, `remove()`,
|
|
30
|
-
* `listCids()`, and `getStats()` below NEVER touch `this.#helia`. Read
|
|
31
|
-
* them -- every one reads/writes `this.#storedCids`, the same in-memory
|
|
32
|
-
* `Map`, unconditionally. The only place `#helia` is referenced again
|
|
33
|
-
* after being set is `close()`, which calls `.stop()` on it. So even a
|
|
34
|
-
* successfully-loaded Helia node is constructed and then never used for
|
|
35
|
-
* a single actual storage operation -- there is no code path in this
|
|
36
|
-
* class, today, that stores or retrieves a byte via Helia/IPFS.
|
|
37
|
-
* 3. The "CID" this class produces is a raw SHA-256 hex digest
|
|
38
|
-
* (`ChunkStore.computeCid()`), NOT a real IPFS CID (a multihash +
|
|
39
|
-
* multibase-encoded identifier, e.g. a `Qm...`/`bafy...` string) -- it's
|
|
40
|
-
* exactly the same format `ChunkStore`/`CloudStorage` already use
|
|
41
|
-
* elsewhere in this repo, not an IPFS-native one.
|
|
15
|
+
* `IPFSStore` is a MESH-LOCAL CONTENT-ADDRESSED STORE. The "CID" it produces
|
|
16
|
+
* is a raw SHA-256 hex digest (`ChunkStore.computeCid()`), the same format
|
|
17
|
+
* `ChunkStore`/`CloudStorage` use elsewhere in this repo. It is NOT an IPFS
|
|
18
|
+
* CID (no multihash/multibase, no `Qm...`/`bafy...`), and nothing here speaks
|
|
19
|
+
* to the public IPFS network: there is no Helia, libp2p, or bitswap code in
|
|
20
|
+
* this package, and `helia`/`@helia/*` is not a dependency of any package in
|
|
21
|
+
* this monorepo. The `IPFSStore` name and the `ipfs_store`/`ipfs_retrieve`
|
|
22
|
+
* agent tools predate this clarification and are kept for compatibility;
|
|
23
|
+
* `MeshLocalCidStore` is exported as an alias that says what the class is.
|
|
42
24
|
*
|
|
43
|
-
*
|
|
44
|
-
*
|
|
45
|
-
*
|
|
46
|
-
*
|
|
47
|
-
* `
|
|
48
|
-
*
|
|
49
|
-
*
|
|
50
|
-
*
|
|
25
|
+
* Earlier revisions carried a hook in `ensureLoaded()` that tried to
|
|
26
|
+
* `import()` a Helia bundle from a CDN when `{ enabled: true }`. It could
|
|
27
|
+
* never activate (the bundle is an IIFE so `globalThis.Helia` was never set,
|
|
28
|
+
* the namespace exports `createHelia` rather than `create`, and the
|
|
29
|
+
* `typeof === 'function'` guard failed for a namespace), and even a loaded
|
|
30
|
+
* node was never used by `add()`/`get()`/`pin()`. It was removed (#197); a
|
|
31
|
+
* library should not fetch a 900 KB third-party bundle on its host's behalf.
|
|
32
|
+
* `enabled` is therefore accepted and reported but has no effect, and
|
|
33
|
+
* `available` is always `false`; both remain so existing callers keep
|
|
34
|
+
* working. A consumer who wants real IPFS should run their own Helia and
|
|
35
|
+
* keep it separate from this class.
|
|
51
36
|
*
|
|
52
37
|
* WHAT THIS ACTUALLY OFFERS OVER `CloudStorage` (`cloud-storage.mjs`), given
|
|
53
38
|
* the above: `CloudStorage` is encrypted, `PeerRegistry`-gated, and
|
|
@@ -59,11 +44,9 @@
|
|
|
59
44
|
* `IPFSStore` (there is no wire protocol here at all; each `IPFSStore`
|
|
60
45
|
* instance is a private, local cache, and `createIpfsService()` below does
|
|
61
46
|
* not add one -- see its own "NO WIRE PROTOCOL" note). Its genuinely
|
|
62
|
-
* distinct value
|
|
63
|
-
*
|
|
64
|
-
*
|
|
65
|
-
* require someone to actually add `helia` as a dependency and rewire the
|
|
66
|
-
* storage operations to call through to it, neither of which has happened.
|
|
47
|
+
* distinct value is a lightweight, dependency-light local scratch cache
|
|
48
|
+
* with pin/unpin/storage-cap bookkeeping and an `ensureLoaded()`/`close()`
|
|
49
|
+
* lifecycle -- not an IPFS-network-interop story.
|
|
67
50
|
*
|
|
68
51
|
* ---------------------------------------------------------------------------
|
|
69
52
|
* No browser-only imports at module level.
|
|
@@ -88,25 +71,15 @@ export const IPFS_DEFAULTS = Object.freeze({
|
|
|
88
71
|
// ---------------------------------------------------------------------------
|
|
89
72
|
|
|
90
73
|
/**
|
|
91
|
-
*
|
|
92
|
-
*
|
|
93
|
-
*
|
|
94
|
-
*
|
|
95
|
-
* `add`/`get`/`pin`/`unpin`/`remove`/`listCids`/`getStats` always read and
|
|
96
|
-
* write the in-memory `#storedCids` map, keyed by SHA-256 CID (same format
|
|
97
|
-
* used by `ChunkStore` in `browsermesh-sync`), regardless of whether
|
|
98
|
-
* `ensureLoaded()` happened to load a Helia instance.
|
|
74
|
+
* Mesh-local content-addressed store. CIDs are SHA-256 hex digests (the
|
|
75
|
+
* `ChunkStore` format), not IPFS CIDs, and nothing here talks to the public
|
|
76
|
+
* IPFS network -- see the module doc comment. Also exported as
|
|
77
|
+
* `MeshLocalCidStore`.
|
|
99
78
|
*/
|
|
100
79
|
export class IPFSStore {
|
|
101
|
-
/** @type {object|null} Helia node instance (lazy-loaded) */
|
|
102
|
-
#helia = null
|
|
103
|
-
|
|
104
80
|
/** @type {boolean} */
|
|
105
81
|
#loaded = false
|
|
106
82
|
|
|
107
|
-
/** @type {boolean} */
|
|
108
|
-
#heliaAvailable = false
|
|
109
|
-
|
|
110
83
|
/** @type {boolean} */
|
|
111
84
|
#enabled
|
|
112
85
|
|
|
@@ -124,7 +97,9 @@ export class IPFSStore {
|
|
|
124
97
|
|
|
125
98
|
/**
|
|
126
99
|
* @param {object} [opts]
|
|
127
|
-
* @param {boolean} [opts.enabled=false] -
|
|
100
|
+
* @param {boolean} [opts.enabled=false] - Accepted and reported by
|
|
101
|
+
* `enabled`/`toJSON()` for compatibility; it has no effect on behaviour
|
|
102
|
+
* (there is no IPFS backend to enable).
|
|
128
103
|
* @param {number} [opts.maxStorageMb=100] - Maximum storage in MB
|
|
129
104
|
* @param {Function} [opts.onLog] - Logging callback
|
|
130
105
|
*/
|
|
@@ -134,43 +109,14 @@ export class IPFSStore {
|
|
|
134
109
|
this.#onLog = opts.onLog || (() => {})
|
|
135
110
|
}
|
|
136
111
|
|
|
137
|
-
// ──
|
|
112
|
+
// ── Lifecycle ────────────────────────────────────────────────────────
|
|
138
113
|
|
|
139
114
|
/**
|
|
140
|
-
*
|
|
141
|
-
*
|
|
115
|
+
* Mark the store as loaded. Kept for lifecycle compatibility; there is
|
|
116
|
+
* nothing to load (the CDN Helia hook was removed, see the module doc
|
|
117
|
+
* comment). Idempotent.
|
|
142
118
|
*/
|
|
143
119
|
async ensureLoaded() {
|
|
144
|
-
if (this.#loaded) return
|
|
145
|
-
if (!this.#enabled) {
|
|
146
|
-
this.#loaded = true
|
|
147
|
-
return
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
try {
|
|
151
|
-
if (typeof globalThis.Helia === 'function') {
|
|
152
|
-
this.#helia = await globalThis.Helia.create()
|
|
153
|
-
this.#heliaAvailable = true
|
|
154
|
-
this.#onLog(2, 'Helia node initialized from globalThis')
|
|
155
|
-
} else {
|
|
156
|
-
try {
|
|
157
|
-
// CDN URL verified current 2026-05-03 against npm registry latest (helia@6.1.4).
|
|
158
|
-
await import('https://cdn.jsdelivr.net/npm/helia@6.1.4/dist/index.min.js')
|
|
159
|
-
if (typeof globalThis.Helia === 'function') {
|
|
160
|
-
this.#helia = await globalThis.Helia.create()
|
|
161
|
-
this.#heliaAvailable = true
|
|
162
|
-
this.#onLog(2, 'Helia loaded from CDN')
|
|
163
|
-
}
|
|
164
|
-
} catch {
|
|
165
|
-
this.#heliaAvailable = false
|
|
166
|
-
this.#onLog(1, 'Helia CDN load failed -- using memory-backed CID store')
|
|
167
|
-
}
|
|
168
|
-
}
|
|
169
|
-
} catch (err) {
|
|
170
|
-
this.#heliaAvailable = false
|
|
171
|
-
this.#onLog(1, `Helia initialization failed: ${err.message}`)
|
|
172
|
-
}
|
|
173
|
-
|
|
174
120
|
this.#loaded = true
|
|
175
121
|
}
|
|
176
122
|
|
|
@@ -181,12 +127,16 @@ export class IPFSStore {
|
|
|
181
127
|
return this.#loaded
|
|
182
128
|
}
|
|
183
129
|
|
|
184
|
-
/**
|
|
130
|
+
/**
|
|
131
|
+
* Always `false`: there is no IPFS/Helia backend. Retained so callers that
|
|
132
|
+
* checked it keep working.
|
|
133
|
+
* @deprecated
|
|
134
|
+
*/
|
|
185
135
|
get available() {
|
|
186
|
-
return
|
|
136
|
+
return false
|
|
187
137
|
}
|
|
188
138
|
|
|
189
|
-
/**
|
|
139
|
+
/** The `enabled` option as passed in (informational only; see constructor). */
|
|
190
140
|
get enabled() {
|
|
191
141
|
return this.#enabled
|
|
192
142
|
}
|
|
@@ -402,23 +352,12 @@ export class IPFSStore {
|
|
|
402
352
|
// ── Lifecycle ────────────────────────────────────────────────────────
|
|
403
353
|
|
|
404
354
|
/**
|
|
405
|
-
* Close the
|
|
355
|
+
* Close the store. Clears all stored data and listeners.
|
|
406
356
|
*/
|
|
407
357
|
async close() {
|
|
408
358
|
this.#storedCids.clear()
|
|
409
359
|
this.#listeners.clear()
|
|
410
|
-
|
|
411
|
-
if (this.#helia) {
|
|
412
|
-
try {
|
|
413
|
-
await this.#helia.stop()
|
|
414
|
-
} catch {
|
|
415
|
-
// best effort
|
|
416
|
-
}
|
|
417
|
-
this.#helia = null
|
|
418
|
-
}
|
|
419
|
-
|
|
420
360
|
this.#loaded = false
|
|
421
|
-
this.#heliaAvailable = false
|
|
422
361
|
}
|
|
423
362
|
|
|
424
363
|
// ── Serialization ────────────────────────────────────────────────────
|
|
@@ -431,7 +370,7 @@ export class IPFSStore {
|
|
|
431
370
|
return {
|
|
432
371
|
enabled: this.#enabled,
|
|
433
372
|
loaded: this.#loaded,
|
|
434
|
-
available:
|
|
373
|
+
available: false,
|
|
435
374
|
maxStorageMb: this.#maxStorageMb,
|
|
436
375
|
stats: this.getStats(),
|
|
437
376
|
cids: this.listCids().map(c => ({ cid: c.cid, size: c.size, pinned: c.pinned })),
|
|
@@ -439,6 +378,9 @@ export class IPFSStore {
|
|
|
439
378
|
}
|
|
440
379
|
}
|
|
441
380
|
|
|
381
|
+
/** Accurate name for `IPFSStore`: a mesh-local content-addressed store. */
|
|
382
|
+
export { IPFSStore as MeshLocalCidStore }
|
|
383
|
+
|
|
442
384
|
// ---------------------------------------------------------------------------
|
|
443
385
|
// createIpfsService -- MeshService wiring (Phase 6 consumer, issue #123)
|
|
444
386
|
// ---------------------------------------------------------------------------
|
|
@@ -458,8 +400,7 @@ export class IPFSStore {
|
|
|
458
400
|
* network in the first place -- every one of its methods
|
|
459
401
|
* (`add`/`get`/`pin`/`unpin`/`remove`/`listCids`/`getStats`) is a purely
|
|
460
402
|
* local operation on its own in-memory `#storedCids` map (see this file's
|
|
461
|
-
* "
|
|
462
|
-
* why that's true even when Helia loads). Attaching this service to two
|
|
403
|
+
* "WHAT THIS CLASS IS" header comment). Attaching this service to two
|
|
463
404
|
* different `PeerNode`s therefore produces two entirely independent stores:
|
|
464
405
|
* content `add()`ed through peer A's `api.add()` is never visible via peer
|
|
465
406
|
* B's `api.get()`, with no `ctx.sendTo()` call anywhere in this file able to
|
|
@@ -489,7 +430,7 @@ export class IPFSStore {
|
|
|
489
430
|
* listening to.
|
|
490
431
|
*
|
|
491
432
|
* `teardown()` calls `store.close()` -- clearing all locally-stored content
|
|
492
|
-
*
|
|
433
|
+
* -- since the
|
|
493
434
|
* store is entirely owned by this `attach()` call (a fresh `IPFSStore` is
|
|
494
435
|
* constructed every time `createIpfsService()`'s descriptor is attached; see
|
|
495
436
|
* `mesh-service.mjs`'s own "teardown() only reverses what attach() itself
|
|
@@ -501,10 +442,8 @@ export class IPFSStore {
|
|
|
501
442
|
/**
|
|
502
443
|
* @param {object} [opts]
|
|
503
444
|
* @param {boolean} [opts.enabled] - Forwarded to `new IPFSStore()` (default
|
|
504
|
-
* `false` -- see `IPFS_DEFAULTS`).
|
|
505
|
-
*
|
|
506
|
-
* `ensureLoaded()` attempts (and, per the module doc comment, still never
|
|
507
|
-
* actually uses) a CDN-loaded Helia instance.
|
|
445
|
+
* `false` -- see `IPFS_DEFAULTS`). Informational only: it does not enable
|
|
446
|
+
* any IPFS behaviour (see the module doc comment).
|
|
508
447
|
* @param {number} [opts.maxStorageMb] - Forwarded to `new IPFSStore()`
|
|
509
448
|
* (default 100).
|
|
510
449
|
* @param {Function} [opts.onLog] - `(event: string, data: object) => void`,
|
package/src/peer-timestamp.mjs
CHANGED
|
@@ -16,6 +16,8 @@
|
|
|
16
16
|
* node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-timestamp.test.mjs
|
|
17
17
|
*/
|
|
18
18
|
|
|
19
|
+
import { assertIdentityFirst, isVerifyOrderError } from './internal/verify-order.mjs'
|
|
20
|
+
|
|
19
21
|
// ---------------------------------------------------------------------------
|
|
20
22
|
// Constants
|
|
21
23
|
// ---------------------------------------------------------------------------
|
|
@@ -95,7 +97,10 @@ export class TimestampProof {
|
|
|
95
97
|
* themselves -- so `issuedBy` is the pod whose key `verifyFn` must resolve,
|
|
96
98
|
* for witness entries as much as for the proof itself.
|
|
97
99
|
*
|
|
98
|
-
* @param {Function} [verifyFn] - async (
|
|
100
|
+
* @param {Function} [verifyFn] - async (signerPodId: string, signature: Uint8Array, data: string) => boolean
|
|
101
|
+
* (identity, signature, data) -- the same order as `PodIdentity.verify` and
|
|
102
|
+
* `crypto.subtle.verify`. BREAKING: this was (signature, data, signerPodId).
|
|
103
|
+
* A 64-byte signature in the first position throws a TypeError.
|
|
99
104
|
* @returns {Promise<{ valid: boolean, confidence: number, checked: 'structure'|'signatures', reason?: string }>}
|
|
100
105
|
*/
|
|
101
106
|
async verify(verifyFn) {
|
|
@@ -119,10 +124,12 @@ export class TimestampProof {
|
|
|
119
124
|
}
|
|
120
125
|
|
|
121
126
|
const check = async (signature, data, what) => {
|
|
127
|
+
assertIdentityFirst(this.issuedBy, 'TimestampProof.verify')
|
|
122
128
|
let ok
|
|
123
129
|
try {
|
|
124
|
-
ok = await verifyFn(fromBase64(signature), data
|
|
130
|
+
ok = await verifyFn(this.issuedBy, fromBase64(signature), data)
|
|
125
131
|
} catch (err) {
|
|
132
|
+
if (isVerifyOrderError(err)) throw err
|
|
126
133
|
return `verifying ${what} threw: ${err.message}`
|
|
127
134
|
}
|
|
128
135
|
return ok === true ? null : `${what} failed verification`
|
|
@@ -348,7 +355,8 @@ export class TimestampAuthority {
|
|
|
348
355
|
* Verify a TimestampProof.
|
|
349
356
|
*
|
|
350
357
|
* Checks every signature in the proof against the key of the pod that
|
|
351
|
-
* issued it. This requires `identity.verify(signature, data
|
|
358
|
+
* issued it. This requires `identity.verify(signerPodId, signature, data)` (BREAKING:
|
|
359
|
+
* was `(signature, data, signerPodId)`).
|
|
352
360
|
* Without it the only check available is re-signing with THIS authority's
|
|
353
361
|
* own key, which answers a different question -- "did I issue this?" -- and
|
|
354
362
|
* is reported as such rather than as authenticity.
|
|
@@ -363,7 +371,10 @@ export class TimestampAuthority {
|
|
|
363
371
|
|
|
364
372
|
if (this.#identity.verify) {
|
|
365
373
|
const result = await proof.verify(
|
|
366
|
-
(signature, data
|
|
374
|
+
(signerPodId, signature, data) => {
|
|
375
|
+
assertIdentityFirst(signerPodId, 'TimestampAuthority identity.verify')
|
|
376
|
+
return this.#identity.verify(signerPodId, signature, data)
|
|
377
|
+
},
|
|
367
378
|
)
|
|
368
379
|
if (!result.valid) {
|
|
369
380
|
return { valid: false, checked: result.checked, reason: result.reason }
|
package/src/peer-torrent.mjs
CHANGED
|
@@ -5,11 +5,29 @@
|
|
|
5
5
|
* CDN-loads webtorrent browser bundle for swarm-based file sharing.
|
|
6
6
|
* Falls back to direct chunked transfer when WebTorrent unavailable.
|
|
7
7
|
*
|
|
8
|
+
* DURABILITY (fallback path only): by default the fallback keeps whole blobs
|
|
9
|
+
* in a private in-memory map. Pass `chunkStore` and/or `manifestStore`
|
|
10
|
+
* (the same objects you give `createTorrentService()` in mesh-torrent.mjs)
|
|
11
|
+
* and the fallback instead stores content as SHA-256-addressed pieces in
|
|
12
|
+
* `chunkStore` plus one manifest per torrent in `manifestStore`, and
|
|
13
|
+
* `ensureLoaded()` restores `listTorrents()` from the manifests -- so seeded
|
|
14
|
+
* content survives a reload when those stores are durable (for example
|
|
15
|
+
* `IndexedDBChunkStore` from browsermesh-sync). Injected stores belong to the
|
|
16
|
+
* caller: `destroy()` never clears them. The real-WebTorrent path keeps its
|
|
17
|
+
* own storage and ignores both.
|
|
18
|
+
*
|
|
8
19
|
* Run tests:
|
|
9
20
|
* node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-torrent.test.mjs
|
|
10
21
|
*/
|
|
11
22
|
|
|
12
23
|
import { ChunkStore } from '@johnhenry/browsermesh-sync'
|
|
24
|
+
import {
|
|
25
|
+
MemoryManifestStore,
|
|
26
|
+
toSeedBytes,
|
|
27
|
+
releaseChunks,
|
|
28
|
+
splitIntoChunks,
|
|
29
|
+
saveChunks,
|
|
30
|
+
} from './internal/torrent-store.mjs'
|
|
13
31
|
|
|
14
32
|
// ---------------------------------------------------------------------------
|
|
15
33
|
// Constants
|
|
@@ -127,6 +145,18 @@ export class TorrentManager {
|
|
|
127
145
|
/** @type {FallbackStore} */
|
|
128
146
|
#fallback = new FallbackStore()
|
|
129
147
|
|
|
148
|
+
/** Injected (or defaulted, when only one was injected) piece store; null = legacy in-memory blob map. */
|
|
149
|
+
#chunkStore = null
|
|
150
|
+
|
|
151
|
+
/** @type {object|null} manifest store paired with #chunkStore */
|
|
152
|
+
#manifestStore = null
|
|
153
|
+
|
|
154
|
+
/** @type {number} piece size used when writing to #chunkStore */
|
|
155
|
+
#chunkSize
|
|
156
|
+
|
|
157
|
+
/** @type {Set<Promise<void>>} in-flight best-effort store cleanups */
|
|
158
|
+
#cleanups = new Set()
|
|
159
|
+
|
|
130
160
|
/** @type {Function} */
|
|
131
161
|
#onLog
|
|
132
162
|
|
|
@@ -143,10 +173,22 @@ export class TorrentManager {
|
|
|
143
173
|
* @param {object} [opts]
|
|
144
174
|
* @param {string} [opts.trackerUrl] - Custom tracker URL
|
|
145
175
|
* @param {Function} [opts.onLog] - Logging callback
|
|
176
|
+
* @param {object} [opts.chunkStore] - Piece store with the `ChunkStore`
|
|
177
|
+
* contract (`save/get/has/remove`, sync or async), e.g. browsermesh-sync's
|
|
178
|
+
* `IndexedDBChunkStore`. Fallback path only; see the module comment.
|
|
179
|
+
* @param {object} [opts.manifestStore] - `{ get, set, delete, entries }`
|
|
180
|
+
* keyed by magnet URI (sync or async). Defaults to in-memory when only
|
|
181
|
+
* `chunkStore` is given.
|
|
182
|
+
* @param {number} [opts.chunkSize=65536] - Piece size when `chunkStore` is used.
|
|
146
183
|
*/
|
|
147
184
|
constructor(opts = {}) {
|
|
148
185
|
this.#trackerUrl = opts.trackerUrl ?? TORRENT_DEFAULTS.trackerUrl
|
|
149
186
|
this.#onLog = opts.onLog || (() => {})
|
|
187
|
+
this.#chunkSize = opts.chunkSize ?? TORRENT_DEFAULTS.chunkSize
|
|
188
|
+
if (opts.chunkStore || opts.manifestStore) {
|
|
189
|
+
this.#chunkStore = opts.chunkStore || new ChunkStore()
|
|
190
|
+
this.#manifestStore = opts.manifestStore || new MemoryManifestStore()
|
|
191
|
+
}
|
|
150
192
|
}
|
|
151
193
|
|
|
152
194
|
// ── CDN Loading ──────────────────────────────────────────────────────
|
|
@@ -190,6 +232,31 @@ export class TorrentManager {
|
|
|
190
232
|
}
|
|
191
233
|
|
|
192
234
|
this.#loaded = true
|
|
235
|
+
|
|
236
|
+
if (!this.#wtAvailable && this.#manifestStore) {
|
|
237
|
+
try {
|
|
238
|
+
await this.#restoreFromStores()
|
|
239
|
+
} catch (err) {
|
|
240
|
+
this.#onLog(1, `Restoring torrents from manifestStore failed: ${err.message}`)
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** Rebuild #activeTorrents from persisted manifests (fallback path only). */
|
|
246
|
+
async #restoreFromStores() {
|
|
247
|
+
for (const [magnetURI, m] of await this.#manifestStore.entries()) {
|
|
248
|
+
if (!m || this.#activeTorrents.has(magnetURI)) continue
|
|
249
|
+
this.#activeTorrents.set(magnetURI, {
|
|
250
|
+
magnetURI,
|
|
251
|
+
infoHash: m.infoHash,
|
|
252
|
+
name: m.name,
|
|
253
|
+
size: m.size,
|
|
254
|
+
peers: 0,
|
|
255
|
+
progress: 1,
|
|
256
|
+
speed: 0,
|
|
257
|
+
state: 'seeding',
|
|
258
|
+
})
|
|
259
|
+
}
|
|
193
260
|
}
|
|
194
261
|
|
|
195
262
|
/** Whether ensureLoaded() has been called. */
|
|
@@ -207,23 +274,23 @@ export class TorrentManager {
|
|
|
207
274
|
/**
|
|
208
275
|
* Seed a file — make it available for download.
|
|
209
276
|
*
|
|
210
|
-
* @param {Uint8Array|Blob|ArrayBuffer} data - File
|
|
277
|
+
* @param {string|Uint8Array|ArrayBufferView|Blob|ArrayBuffer} data - File
|
|
278
|
+
* content. A string is encoded as UTF-8; anything that is not one of the
|
|
279
|
+
* listed types throws a `TypeError` (it is never seeded as empty content).
|
|
211
280
|
* @param {object} [opts]
|
|
212
281
|
* @param {string} [opts.name] - File name
|
|
213
282
|
* @param {string[]} [opts.announce] - Tracker URLs
|
|
283
|
+
* @param {number} [opts.chunkSize] - Piece size for this torrent when
|
|
284
|
+
* `chunkStore` is injected (default: the constructor's `chunkSize`).
|
|
214
285
|
* @returns {Promise<TorrentInfo>}
|
|
215
286
|
*/
|
|
216
287
|
async seed(data, opts = {}) {
|
|
217
288
|
if (!this.#loaded) await this.ensureLoaded()
|
|
218
289
|
|
|
219
|
-
const rawData = data
|
|
220
|
-
? new Uint8Array(data)
|
|
221
|
-
: data instanceof Uint8Array
|
|
222
|
-
? data
|
|
223
|
-
: data
|
|
290
|
+
const rawData = await toSeedBytes(data)
|
|
224
291
|
|
|
225
292
|
const name = opts.name || `file_${Date.now()}`
|
|
226
|
-
const size = rawData.byteLength
|
|
293
|
+
const size = rawData.byteLength
|
|
227
294
|
|
|
228
295
|
// Real WebTorrent path
|
|
229
296
|
if (this.#wtAvailable && this.#client) {
|
|
@@ -231,7 +298,7 @@ export class TorrentManager {
|
|
|
231
298
|
}
|
|
232
299
|
|
|
233
300
|
// Fallback: generate pseudo-torrent info
|
|
234
|
-
return this.#seedFallback(rawData, name, size)
|
|
301
|
+
return this.#seedFallback(rawData, name, size, opts)
|
|
235
302
|
}
|
|
236
303
|
|
|
237
304
|
/**
|
|
@@ -276,13 +343,19 @@ export class TorrentManager {
|
|
|
276
343
|
* Seed via fallback in-memory store.
|
|
277
344
|
* @returns {Promise<TorrentInfo>}
|
|
278
345
|
*/
|
|
279
|
-
async #seedFallback(data, name, size) {
|
|
280
|
-
const bytes = data
|
|
346
|
+
async #seedFallback(data, name, size, opts = {}) {
|
|
347
|
+
const bytes = data
|
|
281
348
|
const cid = await ChunkStore.computeCid(bytes)
|
|
282
349
|
const infoHash = cid.slice(0, 40) // Use first 40 hex chars as pseudo info hash
|
|
283
350
|
const magnetURI = generateMagnetURI(infoHash)
|
|
284
351
|
|
|
285
|
-
this.#
|
|
352
|
+
if (this.#chunkStore) {
|
|
353
|
+
const chunkSize = opts.chunkSize ?? this.#chunkSize
|
|
354
|
+
const chunkCids = await saveChunks(this.#chunkStore, splitIntoChunks(bytes, chunkSize), (p) => ChunkStore.computeCid(p))
|
|
355
|
+
await this.#manifestStore.set(magnetURI, { infoHash, name, size, chunkSize, chunkCids, cid })
|
|
356
|
+
} else {
|
|
357
|
+
this.#fallback.set(infoHash, { data: bytes, name, size })
|
|
358
|
+
}
|
|
286
359
|
|
|
287
360
|
const info = {
|
|
288
361
|
magnetURI,
|
|
@@ -399,7 +472,9 @@ export class TorrentManager {
|
|
|
399
472
|
|
|
400
473
|
this.#emit('download:start', { magnetURI })
|
|
401
474
|
|
|
402
|
-
const entry = this.#
|
|
475
|
+
const entry = this.#chunkStore
|
|
476
|
+
? await this.#readFromStores(infoHash, magnetURI)
|
|
477
|
+
: this.#fallback.get(infoHash)
|
|
403
478
|
if (!entry) {
|
|
404
479
|
throw new Error(`Content not found for magnet: ${magnetURI}`)
|
|
405
480
|
}
|
|
@@ -424,6 +499,45 @@ export class TorrentManager {
|
|
|
424
499
|
return { data: entry.data, info }
|
|
425
500
|
}
|
|
426
501
|
|
|
502
|
+
/**
|
|
503
|
+
* The stored manifest for a torrent seeded through the injected stores:
|
|
504
|
+
* `{ infoHash, name, size, chunkSize, chunkCids, cid }`, or `null` when no
|
|
505
|
+
* stores were injected, the torrent is unknown, or the real-WebTorrent path
|
|
506
|
+
* is in use (which keeps its own storage).
|
|
507
|
+
*
|
|
508
|
+
* @param {string} magnetURI
|
|
509
|
+
* @returns {Promise<object|null>}
|
|
510
|
+
*/
|
|
511
|
+
async getManifest(magnetURI) {
|
|
512
|
+
if (!this.#manifestStore) return null
|
|
513
|
+
return (await this.#manifestStore.get(magnetURI)) ?? null
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
/**
|
|
517
|
+
* Reassemble a torrent's bytes from the injected stores.
|
|
518
|
+
* @returns {Promise<{ data: Uint8Array, name: string, size: number }|null>} null when no manifest is held
|
|
519
|
+
*/
|
|
520
|
+
async #readFromStores(infoHash, magnetURI) {
|
|
521
|
+
const manifest = await this.#manifestStore.get(generateMagnetURI(infoHash))
|
|
522
|
+
?? await this.#manifestStore.get(magnetURI)
|
|
523
|
+
if (!manifest) return null
|
|
524
|
+
const data = new Uint8Array(manifest.size)
|
|
525
|
+
let offset = 0
|
|
526
|
+
for (const cid of manifest.chunkCids) {
|
|
527
|
+
const piece = await this.#chunkStore.get(cid)
|
|
528
|
+
if (!piece) throw new Error(`Content incomplete for magnet ${magnetURI}: piece ${cid} is missing from the chunk store`)
|
|
529
|
+
if (!(await ChunkStore.computeCid(piece) === cid)) {
|
|
530
|
+
throw new Error(`Content corrupt for magnet ${magnetURI}: piece ${cid} failed integrity verification`)
|
|
531
|
+
}
|
|
532
|
+
data.set(piece, offset)
|
|
533
|
+
offset += piece.length
|
|
534
|
+
}
|
|
535
|
+
if (offset !== manifest.size) {
|
|
536
|
+
throw new Error(`Content incomplete for magnet ${magnetURI}: ${offset} of ${manifest.size} bytes present`)
|
|
537
|
+
}
|
|
538
|
+
return { data, name: manifest.name, size: manifest.size }
|
|
539
|
+
}
|
|
540
|
+
|
|
427
541
|
// ── Mesh sharing ─────────────────────────────────────────────────────
|
|
428
542
|
|
|
429
543
|
/**
|
|
@@ -502,6 +616,19 @@ export class TorrentManager {
|
|
|
502
616
|
this.#fallback.delete(infoHash)
|
|
503
617
|
}
|
|
504
618
|
|
|
619
|
+
// Injected stores: drop the manifest, then any pieces no other torrent
|
|
620
|
+
// still lists. Best-effort and asynchronous (the return value stays sync).
|
|
621
|
+
if (this.#chunkStore) {
|
|
622
|
+
const cleanup = (async () => {
|
|
623
|
+
const manifest = await this.#manifestStore.get(magnetURI)
|
|
624
|
+
if (!manifest) return
|
|
625
|
+
await this.#manifestStore.delete(magnetURI)
|
|
626
|
+
await releaseChunks(this.#chunkStore, this.#manifestStore, manifest, magnetURI)
|
|
627
|
+
})().catch((err) => this.#onLog(1, `Store cleanup failed for ${magnetURI}: ${err.message}`))
|
|
628
|
+
.finally(() => this.#cleanups.delete(cleanup))
|
|
629
|
+
this.#cleanups.add(cleanup)
|
|
630
|
+
}
|
|
631
|
+
|
|
505
632
|
this.#activeTorrents.delete(magnetURI)
|
|
506
633
|
return true
|
|
507
634
|
}
|
|
@@ -578,9 +705,14 @@ export class TorrentManager {
|
|
|
578
705
|
// ── Lifecycle ────────────────────────────────────────────────────────
|
|
579
706
|
|
|
580
707
|
/**
|
|
581
|
-
* Destroy the manager:
|
|
708
|
+
* Destroy the manager: forget all torrents in memory, close the client.
|
|
709
|
+
* Content in injected `chunkStore`/`manifestStore` is left intact.
|
|
582
710
|
*/
|
|
583
711
|
async destroy() {
|
|
712
|
+
// Let any in-flight removeTorrent() store cleanup finish first. Injected
|
|
713
|
+
// stores themselves are never cleared: they belong to the caller.
|
|
714
|
+
await Promise.all([...this.#cleanups])
|
|
715
|
+
|
|
584
716
|
// Clear active torrents
|
|
585
717
|
this.#activeTorrents.clear()
|
|
586
718
|
this.#fallback.clear()
|
|
@@ -97,11 +97,13 @@ export class Attestation {
|
|
|
97
97
|
/**
|
|
98
98
|
* Verify this attestation using the provided verification function.
|
|
99
99
|
*
|
|
100
|
-
* @param {Function} verifyFn - (podId,
|
|
100
|
+
* @param {Function} verifyFn - (podId, signature, resultHash) => boolean
|
|
101
|
+
* (identity, signature, data), the same order as every other verify in
|
|
102
|
+
* BrowserMesh. BREAKING: this was (podId, resultHash, signature).
|
|
101
103
|
* @returns {boolean}
|
|
102
104
|
*/
|
|
103
105
|
verify(verifyFn) {
|
|
104
|
-
return verifyFn(this.podId, this.
|
|
106
|
+
return verifyFn(this.podId, this.signature, this.resultHash)
|
|
105
107
|
}
|
|
106
108
|
|
|
107
109
|
/**
|