@johnhenry/browsermesh-apps 0.1.1 → 0.3.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 (50) hide show
  1. package/README.md +443 -1
  2. package/package.json +18 -3
  3. package/src/agent-runtime.mjs +342 -0
  4. package/src/chunk-replication.mjs +751 -0
  5. package/src/cloud-storage-backend.mjs +932 -0
  6. package/src/cloud-storage.mjs +799 -0
  7. package/src/compat.mjs +98 -0
  8. package/src/gpu-kernel.mjs +242 -0
  9. package/src/gpu.mjs +101 -7
  10. package/src/grant-log.mjs +840 -0
  11. package/src/index.mjs +32 -2
  12. package/src/kernel-mesh.mjs +56 -0
  13. package/src/key-distribution.mjs +525 -0
  14. package/src/manifest-sync.mjs +363 -0
  15. package/src/mesh-agent-swarm.mjs +376 -0
  16. package/src/mesh-bootstrap.mjs +1481 -0
  17. package/src/mesh-compute.mjs +397 -0
  18. package/src/mesh-dht.mjs +182 -0
  19. package/src/mesh-fetch.mjs +246 -0
  20. package/src/mesh-hardening.mjs +226 -0
  21. package/src/mesh-health.mjs +282 -0
  22. package/src/mesh-keepalive.mjs +353 -0
  23. package/src/mesh-kv.mjs +673 -0
  24. package/src/mesh-orchestrator-tools.mjs +251 -0
  25. package/src/mesh-orchestrator.mjs +343 -0
  26. package/src/mesh-relay-backend.mjs +289 -0
  27. package/src/mesh-relay-host.mjs +362 -0
  28. package/src/mesh-rpc.mjs +300 -0
  29. package/src/mesh-service.mjs +403 -0
  30. package/src/mesh-swarm.mjs +677 -0
  31. package/src/mesh-sync.mjs +253 -0
  32. package/src/mesh-timestamp.mjs +265 -0
  33. package/src/mesh-torrent.mjs +683 -0
  34. package/src/mesh-verification.mjs +367 -0
  35. package/src/mesh-websocket.mjs +722 -0
  36. package/src/observability-bridge.mjs +453 -0
  37. package/src/orchestrator.mjs +18 -5
  38. package/src/peer-agent-swarm.mjs +12 -1
  39. package/src/peer-chat.mjs +230 -61
  40. package/src/peer-compute.mjs +66 -3
  41. package/src/peer-escrow.mjs +350 -1
  42. package/src/peer-files.mjs +362 -168
  43. package/src/peer-ipfs.mjs +205 -10
  44. package/src/peer-node.mjs +127 -19
  45. package/src/peer-registry.mjs +242 -18
  46. package/src/peer-routing.mjs +369 -5
  47. package/src/peer-terminal.mjs +400 -130
  48. package/src/signaling.mjs +231 -0
  49. package/src/webrtc-negotiator.mjs +209 -0
  50. package/src/peer-session.mjs +0 -937
@@ -0,0 +1,683 @@
1
+ /**
2
+ * mesh-torrent.mjs -- Phase 5 of the browsermesh-app-layer-migration plan
3
+ * (issue #122): wraps `peer-torrent.mjs`'s `TorrentManager` as a `MeshService`
4
+ * (`mesh-service.mjs`, Phase C's `attach()`/`ctx` convention).
5
+ *
6
+ * ---------------------------------------------------------------------------
7
+ * WHAT `TorrentManager` ALREADY DOES, AND WHAT IT DOESN'T (read this first --
8
+ * this determined this file's whole design):
9
+ *
10
+ * `TorrentManager` is real, tested, and NOT touched by this file beyond
11
+ * calling its existing public methods -- its real-WebTorrent path
12
+ * (`#seedReal`/`#downloadReal`, used only when `window.WebTorrent`/a CDN load
13
+ * succeeds, i.e. only in a browser) is a genuine, unmodified BitTorrent
14
+ * client integration. But its Node/offline FALLBACK path (`FallbackStore`,
15
+ * `#seedFallback`/`#downloadFallback`) -- the ONLY path that ever runs in
16
+ * this repo's tests, and the one every `MeshService` in this family runs
17
+ * under (no browser, no CDN) -- is a private, single-process, in-memory
18
+ * `Map` keyed by infoHash. It has NO awareness of other peers at all:
19
+ * `seed()` stores the whole blob locally; `download()` only ever looks in
20
+ * THIS SAME instance's own private store. Two separate `TorrentManager`
21
+ * instances (i.e. two separate peers) never exchange a single byte through
22
+ * `seed()`/`download()` alone.
23
+ *
24
+ * `shareWithPeers(magnetURI, peerIds, sendFn)` -- the one method that looks
25
+ * network-shaped -- was checked carefully (per this phase's own brief) and
26
+ * confirmed to be A NOTIFICATION HOOK, NOT A TRANSFER: it calls
27
+ * `sendFn(peerId, { type: 'torrent:share', magnetURI, info })` once per
28
+ * peer and returns. No chunk, and no byte of the underlying content, is
29
+ * ever part of that message -- `info` is just `{name, size}`. Nothing in
30
+ * `peer-torrent.mjs` moves piece bytes between peers. So unlike
31
+ * `peer-routing.mjs`'s `MeshRouter` (Phase 2 precedent for this file, whose
32
+ * ENTIRE multi-hop mechanic already lived inside the wrapped class -- this
33
+ * file only had to plug `forwardFn` into `ctx.sendTo()`), a mechanical
34
+ * `sendFn -> ctx.sendTo()` swap here would produce peers that politely tell
35
+ * each other "I have this" and then have no way to actually get it.
36
+ *
37
+ * Issue #122's whole stated value proposition -- "swarm-style distribution
38
+ * to many peers... a genuinely different topology" from CloudStorage -- is
39
+ * exactly the piece `TorrentManager` itself doesn't implement in this
40
+ * environment. Closing that gap for real (not just wiring an existing
41
+ * mechanic onto `ctx`) is this file's actual job. `TorrentManager`'s own
42
+ * internal logic (ID/magnet generation, its own local store, its `on`/`off`
43
+ * events, `getStats()`/`listTorrents()`/`toJSON()`/`destroy()`) is reused
44
+ * completely as-is, unmodified, exactly per this plan's "thin wrapper, not a
45
+ * rewrite" rule -- this file adds a NEW piece-exchange wire protocol
46
+ * alongside it, the same shape of addition `mesh-timestamp.mjs` made for
47
+ * witness collection and `chunk-replication.mjs` made for CloudStorage's own
48
+ * chunk transport (this file's closest in-repo precedent for the actual
49
+ * wire protocol below -- request/response chunk fetch over `ctx.sendTo()`/
50
+ * `ctx.onIncomingData()`, base64-in-JSON, content-hash-verified on receipt).
51
+ *
52
+ * ---------------------------------------------------------------------------
53
+ * WHAT MAKES THIS A REAL SWARM, NOT JUST ORIGIN-TO-MANY FAN-OUT:
54
+ *
55
+ * Content is split into `chunkSize`-byte pieces (default `TORRENT_DEFAULTS
56
+ * .chunkSize`, 64KB) and stored by this file in its OWN `ChunkStore`
57
+ * (content-addressed, SHA-256 CIDs -- see "CHUNKSTORE DURABILITY DECISION"
58
+ * below), separate from `TorrentManager`'s own opaque whole-blob store. A
59
+ * peer that finishes downloading calls `tm.seed()` on the reassembled bytes
60
+ * (see `download()`'s own comment for why this is exactly correct, not a
61
+ * hack) and can immediately answer `chunk-request`s for any piece it holds
62
+ * -- there is no "origin" role encoded anywhere in the wire protocol, only
63
+ * "whoever currently has piece X". `api.download()`'s per-chunk provider
64
+ * selection (`fetchChunk()`) tries every peer this node currently believes
65
+ * holds a given CID (`chunkOwners`, populated by `announce`s AND by
66
+ * successful fetches), in no particular preference order -- a downloader
67
+ * that finished can be, and in this file's own tests IS, the source another
68
+ * peer downloads from with the ORIGINAL seeder never involved in that
69
+ * transfer at all.
70
+ *
71
+ * ---------------------------------------------------------------------------
72
+ * WIRE PROTOCOL -- one envelope `type` (default `'mesh-torrent'`), five
73
+ * `kind`s:
74
+ *
75
+ * Announce (fire-and-forget, from `api.share()`, bridging `shareWithPeers`):
76
+ * `{ type, kind: 'announce', magnetURI, manifest, info }`
77
+ * -- `manifest` is `{ infoHash, name, size, chunkCids }` (undefined if
78
+ * the announcer doesn't actually hold the content -- see `share()`).
79
+ * The RECEIVER records the sender as a known provider for every
80
+ * `chunkCids` entry -- this is how `chunkOwners` bootstraps without
81
+ * a separate discovery round trip.
82
+ *
83
+ * Manifest request/response (only needed if a downloader never received an
84
+ * `announce` for this magnetURI -- e.g. it learned the magnetURI out of
85
+ * band):
86
+ * `{ type, kind: 'manifest-request', requestId, magnetURI }`
87
+ * `{ type, kind: 'manifest-response', requestId, magnetURI, manifest }`
88
+ * -- a peer with no manifest for that magnetURI stays silent (matches
89
+ * `chunk-replication.mjs`'s established "don't have it" = silence
90
+ * convention); the requester's `requestManifest()` is timeout-bounded.
91
+ *
92
+ * Chunk request/response (the actual piece exchange):
93
+ * `{ type, kind: 'chunk-request', requestId, cid }`
94
+ * `{ type, kind: 'chunk-response', requestId, cid, data }` (`data` base64)
95
+ * or `{ ..., error: 'not-found' }`.
96
+ *
97
+ * DELIBERATELY NO AUTHORIZATION GATE on any of the above (the one explicit
98
+ * divergence from `chunk-replication.mjs`'s otherwise-identical shape, which
99
+ * gates every chunk transfer on `registry.checkAccess()`): issue #122's own
100
+ * framing is "swarm-distribute one large payload to many anonymous/
101
+ * unauthorized downloaders at once" -- an admin-designated-replica-style ACL
102
+ * gate would contradict the entire reason this module exists alongside
103
+ * CloudStorage rather than being redundant with it. A caller that DOES want
104
+ * access control on top of swarm distribution can still gate WHO gets handed
105
+ * a magnetURI in the first place (outside this file, e.g. via `api.share()`'s
106
+ * explicit `peerIds` list) -- once a peer legitimately has a magnetURI, this
107
+ * protocol does not additionally gate serving its pieces.
108
+ *
109
+ * Every fetched chunk is verified against its own CID (`ChunkStore.verify()`)
110
+ * before being trusted/stored/re-served -- content-addressing's integrity
111
+ * property holds regardless of which swarm peer relayed a piece, exactly
112
+ * `chunk-replication.mjs`'s own reasoning for why its wire messages need no
113
+ * signature.
114
+ *
115
+ * ---------------------------------------------------------------------------
116
+ * CHUNKSTORE DURABILITY DECISION (explicitly flagged as open by the
117
+ * migration plan's Phase 5 section -- resolved here, not left arbitrary):
118
+ *
119
+ * This file's own piece store uses the in-memory `ChunkStore`
120
+ * (`@johnhenry/browsermesh-sync`'s `files.mjs`), NOT the durable
121
+ * `IndexedDBChunkStore` (`storage-indexeddb-chunks.mjs`) CloudStorage uses.
122
+ * Reasoning, concretely:
123
+ *
124
+ * - Torrent-style swarm participation is inherently ephemeral BY DESIGN,
125
+ * not by accident: a peer seeds or downloads while it's online and
126
+ * interested; once it closes the tab, there is no expectation -- in
127
+ * real BitTorrent OR here -- that its pieces "belong" to it across a
128
+ * reload the way a CloudStorage object durably belongs to a bucket.
129
+ * Nothing reads this file's `ChunkStore` as a source of truth the way
130
+ * `CloudStorageBackend` treats its manifest+chunks; losing it on reload
131
+ * just means this peer re-fetches pieces from the swarm next time it's
132
+ * relevant, exactly the self-healing property a swarm is supposed to
133
+ * have.
134
+ * - The counter-argument is real and was weighed: a peer mid-download
135
+ * that reloads loses partial progress, and a long-lived seeder loses
136
+ * its ability to serve after a reload without re-seeding. Both are
137
+ * genuine costs, not nothing.
138
+ * - But `TorrentManager` ITSELF already made this exact call for its own
139
+ * `FallbackStore` (`peer-torrent.mjs`, unmodified by this phase) -- it's
140
+ * a private in-memory `Map`, same non-durable shape, same module. Making
141
+ * ONLY this file's piece store durable while the class it wraps stays
142
+ * resolutely in-memory would produce a torrent service that's durable
143
+ * exactly until `tm.seed()`'s own bookkeeping (magnetURI/infoHash
144
+ * generation, `listTorrents()`, `getStats()`) resets on reload anyway --
145
+ * inconsistent durability that doesn't actually deliver "survives a
146
+ * reload" for the feature as a whole, only for raw chunk bytes with no
147
+ * index pointing at them.
148
+ * - Per the plan's own explicit guidance for this exact decision ("if
149
+ * unsure, default to keeping in-memory `ChunkStore` as the lower-risk,
150
+ * smaller change"): this is the call made here. A future revision that
151
+ * wants "resume a partial download/reseed after reload" as a real,
152
+ * deliberate feature should swap BOTH this file's chunk store AND
153
+ * `TorrentManager`'s own `FallbackStore`/`#activeTorrents` together, as
154
+ * one coherent durability upgrade -- not something to back into
155
+ * one-sidedly here.
156
+ *
157
+ * ---------------------------------------------------------------------------
158
+ * Observability events (`ctx.emit()`, see `mesh-service.mjs`'s module doc
159
+ * comment for the full convention):
160
+ *
161
+ * - `torrent:seed` -- `TorrentManager`'s own `'seed'` event, bridged
162
+ * verbatim (fires both when this peer originates content via `api.seed()`
163
+ * AND when `api.download()` registers this peer as a new full holder --
164
+ * see `download()`'s own comment).
165
+ * - `torrent:announce-received` `{from, magnetURI, name}` -- an `announce`
166
+ * arrived (whether or not it carried a usable manifest).
167
+ * - `torrent:download-start` / `torrent:download-complete`
168
+ * `{magnetURI, name?, size?}` -- this peer's own `api.download()` call.
169
+ * - `torrent:chunk-received` `{from, cid, size}` -- one piece fetched and
170
+ * verified during a download.
171
+ * - `torrent:chunk-served` `{to, cid, size}` -- this peer answered another
172
+ * peer's `chunk-request` from its own local piece store -- the direct,
173
+ * observable proof of peer-to-peer (not origin-only) exchange.
174
+ *
175
+ * No browser-only imports at module level.
176
+ */
177
+
178
+ import { TorrentManager } from './peer-torrent.mjs'
179
+ import { ChunkStore } from '@johnhenry/browsermesh-sync'
180
+
181
+ /** Default `envelope.type` used to route all mesh-torrent wire traffic. */
182
+ const DEFAULT_ENVELOPE_TYPE = 'mesh-torrent'
183
+
184
+ /** Default piece size for this file's own chunking (independent of `TorrentManager`'s own, unused-in-fallback, `TORRENT_DEFAULTS.chunkSize` constant -- same numeric default, 64KB). */
185
+ const DEFAULT_CHUNK_SIZE = 65536
186
+
187
+ /** How long `requestManifest()` waits for the first `manifest-response` before giving up. */
188
+ const DEFAULT_MANIFEST_TIMEOUT_MS = 5000
189
+
190
+ /** How long a single `fetchChunkFrom()` call waits for its `chunk-response` before treating that peer as unreachable for this attempt. */
191
+ const DEFAULT_CHUNK_TIMEOUT_MS = 5000
192
+
193
+ // ---------------------------------------------------------------------------
194
+ // Base64 helpers -- deliberately duplicated rather than shared, matching
195
+ // this family's established convention (see chunk-replication.mjs's /
196
+ // cloud-storage-backend.mjs's own identical duplication).
197
+ // ---------------------------------------------------------------------------
198
+
199
+ /** @param {Uint8Array} bytes @returns {string} */
200
+ function toBase64(bytes) {
201
+ if (typeof Buffer !== 'undefined') return Buffer.from(bytes).toString('base64')
202
+ let bin = ''
203
+ for (const b of bytes) bin += String.fromCharCode(b)
204
+ return btoa(bin)
205
+ }
206
+
207
+ /** @param {string} str @returns {Uint8Array} */
208
+ function fromBase64(str) {
209
+ if (typeof Buffer !== 'undefined') return new Uint8Array(Buffer.from(str, 'base64'))
210
+ const bin = atob(str)
211
+ const bytes = new Uint8Array(bin.length)
212
+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
213
+ return bytes
214
+ }
215
+
216
+ /**
217
+ * Normalize seed() input to a Uint8Array for chunking/hashing. Unlike
218
+ * `TorrentManager.seed()` itself (which also tolerates a `Blob`, for its
219
+ * real-WebTorrent browser path), this file's own manifest/piece-exchange
220
+ * logic needs synchronous byte access, so a `Blob` is not supported here.
221
+ * @param {Uint8Array|ArrayBuffer} data
222
+ * @returns {Uint8Array}
223
+ */
224
+ function normalizeToUint8Array(data) {
225
+ if (data instanceof Uint8Array) return data
226
+ if (data instanceof ArrayBuffer) return new Uint8Array(data)
227
+ throw new Error(
228
+ 'mesh-torrent: seed() requires Uint8Array or ArrayBuffer data for this service\'s own ' +
229
+ 'chunking/manifest logic (a Blob is only usable via TorrentManager\'s own real-WebTorrent path directly).',
230
+ )
231
+ }
232
+
233
+ /**
234
+ * @param {Uint8Array} bytes
235
+ * @param {number} chunkSize
236
+ * @returns {Uint8Array[]}
237
+ */
238
+ function splitIntoChunks(bytes, chunkSize) {
239
+ const pieces = []
240
+ for (let offset = 0; offset < bytes.length; offset += chunkSize) {
241
+ pieces.push(bytes.subarray(offset, Math.min(offset + chunkSize, bytes.length)))
242
+ }
243
+ return pieces
244
+ }
245
+
246
+ /**
247
+ * @param {Uint8Array[]} pieces
248
+ * @returns {Uint8Array}
249
+ */
250
+ function concatChunks(pieces) {
251
+ const total = pieces.reduce((sum, p) => sum + p.length, 0)
252
+ const out = new Uint8Array(total)
253
+ let offset = 0
254
+ for (const p of pieces) {
255
+ out.set(p, offset)
256
+ offset += p.length
257
+ }
258
+ return out
259
+ }
260
+
261
+ // ---------------------------------------------------------------------------
262
+ // createTorrentService
263
+ // ---------------------------------------------------------------------------
264
+
265
+ /**
266
+ * Build a `MeshService` descriptor (`mesh-service.mjs`, Phase C) wrapping
267
+ * `TorrentManager` with a real, mesh-native swarm piece-exchange protocol.
268
+ * See this file's module doc comment for the full design writeup.
269
+ *
270
+ * @param {object} [opts]
271
+ * @param {string} [opts.trackerUrl] - Forwarded to `new TorrentManager()`.
272
+ * @param {number} [opts.chunkSize=65536] - Piece size for this file's own
273
+ * chunking (independent of `TorrentManager`'s own internals).
274
+ * @param {string} [opts.envelopeType='mesh-torrent']
275
+ * @param {number} [opts.manifestTimeoutMs=5000]
276
+ * @param {number} [opts.chunkTimeoutMs=5000]
277
+ * @param {Function} [opts.onLog]
278
+ * @returns {import('./mesh-service.mjs').MeshService}
279
+ */
280
+ export function createTorrentService({
281
+ trackerUrl,
282
+ chunkSize = DEFAULT_CHUNK_SIZE,
283
+ envelopeType = DEFAULT_ENVELOPE_TYPE,
284
+ manifestTimeoutMs = DEFAULT_MANIFEST_TIMEOUT_MS,
285
+ chunkTimeoutMs = DEFAULT_CHUNK_TIMEOUT_MS,
286
+ onLog,
287
+ } = {}) {
288
+ const log = onLog || (() => {})
289
+
290
+ return {
291
+ name: 'torrent',
292
+
293
+ attach(peerNode, ctx) {
294
+ const tm = new TorrentManager({
295
+ trackerUrl,
296
+ onLog: (level, msg) => log('mesh-torrent:internal', { level, msg }),
297
+ })
298
+
299
+ /** This file's own piece store -- see module doc comment's "CHUNKSTORE DURABILITY DECISION". */
300
+ const chunkStore = new ChunkStore()
301
+
302
+ /** @type {Map<string, {infoHash: string, name: string, size: number, chunkCids: string[]}>} magnetURI -> manifest */
303
+ const manifests = new Map()
304
+
305
+ /** @type {Map<string, Set<string>>} cid -> pubKeys known to currently hold that piece */
306
+ const chunkOwners = new Map()
307
+
308
+ let reqSeq = 0
309
+ const nextRequestId = () => `${peerNode.podId}:${Date.now()}:${++reqSeq}`
310
+
311
+ /** @param {string} pubKey @param {string[]} cids */
312
+ function recordOwner(pubKey, cids) {
313
+ for (const cid of cids) {
314
+ let set = chunkOwners.get(cid)
315
+ if (!set) {
316
+ set = new Set()
317
+ chunkOwners.set(cid, set)
318
+ }
319
+ set.add(pubKey)
320
+ }
321
+ }
322
+
323
+ // Bridge TorrentManager's own 'seed' event -- the only tm event this
324
+ // wrapper's own api can actually trigger (api.download() never calls
325
+ // tm.download(), see module doc comment -- so tm's 'download:start'/
326
+ // 'download:complete' events never fire through this service, and
327
+ // bridging them would be misleading).
328
+ const onTmSeed = (info) => ctx.emit('torrent:seed', info)
329
+ tm.on('seed', onTmSeed)
330
+
331
+ // -----------------------------------------------------------------
332
+ // In-flight request tracking
333
+ // -----------------------------------------------------------------
334
+
335
+ /** @type {Map<string, {resolve: (manifest: object|null) => void, timer: ReturnType<typeof setTimeout>, magnetURI: string}>} */
336
+ const pendingManifestRequests = new Map()
337
+
338
+ /** @type {Map<string, {resolve: (bytes: Uint8Array) => void, reject: (err: Error) => void, timer: ReturnType<typeof setTimeout>}>} */
339
+ const pendingChunkFetches = new Map()
340
+
341
+ // -----------------------------------------------------------------
342
+ // Inbound dispatch
343
+ // -----------------------------------------------------------------
344
+
345
+ function handleAnnounce(fromPubKey, msg) {
346
+ if (typeof msg.magnetURI !== 'string') return
347
+ if (msg.manifest && Array.isArray(msg.manifest.chunkCids)) {
348
+ manifests.set(msg.magnetURI, msg.manifest)
349
+ recordOwner(fromPubKey, msg.manifest.chunkCids)
350
+ }
351
+ ctx.emit('torrent:announce-received', {
352
+ from: fromPubKey,
353
+ magnetURI: msg.magnetURI,
354
+ name: msg.manifest?.name ?? msg.info?.name,
355
+ })
356
+ }
357
+
358
+ function handleManifestRequest(fromPubKey, msg) {
359
+ if (typeof msg.magnetURI !== 'string' || typeof msg.requestId !== 'string') return
360
+ const manifest = manifests.get(msg.magnetURI)
361
+ if (!manifest) return // silent "don't have it" -- matches chunk-replication.mjs's own convention
362
+ ctx.sendTo(fromPubKey, envelopeType, {
363
+ kind: 'manifest-response', requestId: msg.requestId, magnetURI: msg.magnetURI, manifest,
364
+ }).catch((err) => {
365
+ log('mesh-torrent:manifest-response-send-failed', { to: fromPubKey, magnetURI: msg.magnetURI, error: err?.message || String(err) })
366
+ })
367
+ }
368
+
369
+ function handleManifestResponse(fromPubKey, msg) {
370
+ const pending = pendingManifestRequests.get(msg.requestId)
371
+ if (!pending) return
372
+ clearTimeout(pending.timer)
373
+ pendingManifestRequests.delete(msg.requestId)
374
+ if (msg.manifest && Array.isArray(msg.manifest.chunkCids)) {
375
+ manifests.set(pending.magnetURI, msg.manifest)
376
+ recordOwner(fromPubKey, msg.manifest.chunkCids)
377
+ }
378
+ pending.resolve(msg.manifest || null)
379
+ }
380
+
381
+ async function handleChunkRequest(fromPubKey, msg) {
382
+ if (typeof msg.cid !== 'string' || typeof msg.requestId !== 'string') return
383
+ const bytes = chunkStore.get(msg.cid)
384
+ if (!bytes) {
385
+ await ctx.sendTo(fromPubKey, envelopeType, {
386
+ kind: 'chunk-response', requestId: msg.requestId, cid: msg.cid, error: 'not-found',
387
+ }).catch(() => {})
388
+ return
389
+ }
390
+ await ctx.sendTo(fromPubKey, envelopeType, {
391
+ kind: 'chunk-response', requestId: msg.requestId, cid: msg.cid, data: toBase64(bytes),
392
+ }).catch((err) => {
393
+ log('mesh-torrent:chunk-response-send-failed', { to: fromPubKey, cid: msg.cid, error: err?.message || String(err) })
394
+ })
395
+ ctx.emit('torrent:chunk-served', { to: fromPubKey, cid: msg.cid, size: bytes.length })
396
+ }
397
+
398
+ function handleChunkResponse(fromPubKey, msg) {
399
+ const pending = pendingChunkFetches.get(msg.requestId)
400
+ if (!pending) return
401
+ clearTimeout(pending.timer)
402
+ pendingChunkFetches.delete(msg.requestId)
403
+ if (msg.error) {
404
+ pending.reject(new Error(`mesh-torrent: chunk ${msg.cid} fetch from ${fromPubKey} failed: ${msg.error}`))
405
+ return
406
+ }
407
+ if (typeof msg.data !== 'string') {
408
+ pending.reject(new Error(`mesh-torrent: malformed chunk response from ${fromPubKey}`))
409
+ return
410
+ }
411
+ pending.resolve(fromBase64(msg.data))
412
+ }
413
+
414
+ const handlers = {
415
+ 'announce': handleAnnounce,
416
+ 'manifest-request': handleManifestRequest,
417
+ 'manifest-response': handleManifestResponse,
418
+ 'chunk-request': handleChunkRequest,
419
+ 'chunk-response': handleChunkResponse,
420
+ }
421
+
422
+ const unsubscribe = ctx.onIncomingData(envelopeType, (fromPubKey, msg) => {
423
+ if (!msg || typeof msg.kind !== 'string') return
424
+ const handler = handlers[msg.kind]
425
+ if (!handler) return
426
+ Promise.resolve(handler(fromPubKey, msg)).catch((err) => {
427
+ log('mesh-torrent:handler-error', { kind: msg.kind, from: fromPubKey, error: err?.message || String(err) })
428
+ })
429
+ })
430
+
431
+ // -----------------------------------------------------------------
432
+ // Manifest / chunk fetch (the actual swarm mechanics)
433
+ // -----------------------------------------------------------------
434
+
435
+ /**
436
+ * @param {string} magnetURI
437
+ * @param {string[]} [candidatePeers]
438
+ * @returns {Promise<object|null>}
439
+ */
440
+ async function requestManifest(magnetURI, candidatePeers) {
441
+ const known = manifests.get(magnetURI)
442
+ if (known) return known
443
+ const targets = candidatePeers && candidatePeers.length ? candidatePeers : []
444
+ if (targets.length === 0) return null
445
+
446
+ const requestId = nextRequestId()
447
+ const promise = new Promise((resolve) => {
448
+ const timer = setTimeout(() => {
449
+ pendingManifestRequests.delete(requestId)
450
+ resolve(null)
451
+ }, manifestTimeoutMs)
452
+ pendingManifestRequests.set(requestId, { resolve, timer, magnetURI })
453
+ })
454
+
455
+ await Promise.all(targets.map((pubKey) =>
456
+ ctx.sendTo(pubKey, envelopeType, { kind: 'manifest-request', requestId, magnetURI }).catch((err) => {
457
+ log('mesh-torrent:manifest-request-send-failed', { to: pubKey, magnetURI, error: err?.message || String(err) })
458
+ }),
459
+ ))
460
+
461
+ return promise
462
+ }
463
+
464
+ /**
465
+ * @param {string} pubKey
466
+ * @param {string} cid
467
+ * @returns {Promise<Uint8Array>}
468
+ */
469
+ async function fetchChunkFrom(pubKey, cid) {
470
+ const requestId = nextRequestId()
471
+ const promise = new Promise((resolve, reject) => {
472
+ const timer = setTimeout(() => {
473
+ pendingChunkFetches.delete(requestId)
474
+ reject(new Error(`mesh-torrent: chunk ${cid} fetch from ${pubKey} timed out after ${chunkTimeoutMs}ms`))
475
+ }, chunkTimeoutMs)
476
+ pendingChunkFetches.set(requestId, { resolve, reject, timer })
477
+ })
478
+
479
+ try {
480
+ await ctx.sendTo(pubKey, envelopeType, { kind: 'chunk-request', requestId, cid })
481
+ } catch (err) {
482
+ const pending = pendingChunkFetches.get(requestId)
483
+ if (pending) {
484
+ clearTimeout(pending.timer)
485
+ pendingChunkFetches.delete(requestId)
486
+ }
487
+ throw err
488
+ }
489
+
490
+ return promise
491
+ }
492
+
493
+ /**
494
+ * Fetch (and locally cache, content-hash-verified) one piece from
495
+ * whichever known/candidate provider actually delivers it.
496
+ * @param {string} cid
497
+ * @param {string[]} [candidatePeers]
498
+ * @returns {Promise<Uint8Array>}
499
+ */
500
+ async function fetchChunk(cid, candidatePeers) {
501
+ const already = chunkStore.get(cid)
502
+ if (already) return already
503
+
504
+ const owners = new Set([...(chunkOwners.get(cid) || []), ...(candidatePeers || [])])
505
+ if (owners.size === 0) {
506
+ throw new Error(`mesh-torrent: no known provider for chunk ${cid} (supply opts.peers)`)
507
+ }
508
+
509
+ let lastErr = null
510
+ for (const pubKey of owners) {
511
+ try {
512
+ const bytes = await fetchChunkFrom(pubKey, cid)
513
+ const valid = await chunkStore.verify(cid, bytes)
514
+ if (!valid) {
515
+ lastErr = new Error(`mesh-torrent: chunk ${cid} from ${pubKey} failed integrity verification`)
516
+ log('mesh-torrent:chunk-integrity-failed', { cid, from: pubKey })
517
+ continue
518
+ }
519
+ chunkStore.save(cid, bytes)
520
+ recordOwner(pubKey, [cid])
521
+ ctx.emit('torrent:chunk-received', { from: pubKey, cid, size: bytes.length })
522
+ return bytes
523
+ } catch (err) {
524
+ lastErr = err
525
+ log('mesh-torrent:fetch-attempt-failed', { cid, from: pubKey, error: err?.message || String(err) })
526
+ }
527
+ }
528
+ throw lastErr || new Error(`mesh-torrent: failed to fetch chunk ${cid} from any known provider`)
529
+ }
530
+
531
+ // -----------------------------------------------------------------
532
+ // api.seed / api.share / api.download
533
+ // -----------------------------------------------------------------
534
+
535
+ /**
536
+ * Seed content: reuses `TorrentManager.seed()` verbatim for real
537
+ * magnet/infoHash generation and its own bookkeeping, then chunks the
538
+ * data into this file's own content-addressed piece store and records
539
+ * a manifest, so this peer can answer `chunk-request`s for it.
540
+ * @param {Uint8Array|ArrayBuffer} data
541
+ * @param {object} [opts] - Forwarded to `TorrentManager.seed()`.
542
+ * @returns {Promise<import('./peer-torrent.mjs').TorrentInfo>}
543
+ */
544
+ async function seed(data, opts = {}) {
545
+ const bytes = normalizeToUint8Array(data)
546
+ const info = await tm.seed(data, opts)
547
+
548
+ const chunkCids = []
549
+ for (const piece of splitIntoChunks(bytes, chunkSize)) {
550
+ const cid = await ChunkStore.computeCid(piece)
551
+ chunkStore.save(cid, piece)
552
+ chunkCids.push(cid)
553
+ }
554
+
555
+ manifests.set(info.magnetURI, { infoHash: info.infoHash, name: info.name, size: info.size, chunkCids })
556
+ return info
557
+ }
558
+
559
+ /**
560
+ * Announce a magnetURI to specific peers, embedding this peer's
561
+ * manifest (if it holds one) so the receiver can immediately start
562
+ * fetching pieces -- see module doc comment's "WIRE PROTOCOL" section.
563
+ * Delegates argument validation to `TorrentManager.shareWithPeers()`
564
+ * itself (throws its own errors for bad `magnetURI`/`peerIds`).
565
+ * @param {string} magnetURI
566
+ * @param {string[]} peerIds
567
+ */
568
+ function share(magnetURI, peerIds) {
569
+ const manifest = manifests.get(magnetURI)
570
+ tm.shareWithPeers(magnetURI, peerIds, (peerId, message) => {
571
+ ctx.sendTo(peerId, envelopeType, {
572
+ kind: 'announce', magnetURI, manifest, info: message.info,
573
+ }).catch((err) => {
574
+ log('mesh-torrent:announce-send-failed', { to: peerId, magnetURI, error: err?.message || String(err) })
575
+ })
576
+ })
577
+ }
578
+
579
+ /**
580
+ * Download content from the swarm: piece-by-piece, from whichever
581
+ * peer(s) are known (via a prior `announce`, or `opts.peers`) to hold
582
+ * each piece -- not necessarily the original seeder. See module doc
583
+ * comment's "WHAT MAKES THIS A REAL SWARM" section.
584
+ * @param {string} magnetURI
585
+ * @param {object} [opts]
586
+ * @param {string[]} [opts.peers] - Candidate peers to ask for the
587
+ * manifest (if not already known) and/or any piece with no other
588
+ * known provider.
589
+ * @returns {Promise<{data: Uint8Array, info: import('./peer-torrent.mjs').TorrentInfo}>}
590
+ */
591
+ async function download(magnetURI, opts = {}) {
592
+ ctx.emit('torrent:download-start', { magnetURI })
593
+
594
+ const manifest = manifests.get(magnetURI) || await requestManifest(magnetURI, opts.peers)
595
+ if (!manifest) {
596
+ throw new Error(
597
+ `mesh-torrent: no manifest known for ${magnetURI} (no prior announce, and no peer responded -- supply opts.peers)`,
598
+ )
599
+ }
600
+
601
+ const pieces = []
602
+ for (const cid of manifest.chunkCids) {
603
+ pieces.push(await fetchChunk(cid, opts.peers))
604
+ }
605
+ const data = concatChunks(pieces)
606
+ if (data.length !== manifest.size) {
607
+ throw new Error(
608
+ `mesh-torrent: reassembled ${data.length} bytes but manifest for ${magnetURI} declares size ${manifest.size}`,
609
+ )
610
+ }
611
+
612
+ // Register this peer as a full holder via TorrentManager's own
613
+ // seed() -- genuinely correct, not a hack: a peer with every piece
614
+ // of a torrent IS, in real BitTorrent terms, now a seed for it, and
615
+ // content-addressing makes this self-consistent -- tm.seed() on
616
+ // these identical bytes deterministically reproduces the SAME
617
+ // magnetURI/infoHash (same hash, same truncation), so this doesn't
618
+ // create a second, different torrent identity for the same content.
619
+ const info = await tm.seed(data, { name: manifest.name })
620
+ if (info.magnetURI !== magnetURI) {
621
+ log('mesh-torrent:magnet-mismatch-after-reassembly', { expected: magnetURI, got: info.magnetURI })
622
+ }
623
+
624
+ ctx.emit('torrent:download-complete', { magnetURI, name: manifest.name, size: data.length })
625
+ return { data, info }
626
+ }
627
+
628
+ async function destroy() {
629
+ await tm.destroy()
630
+ chunkStore.clear()
631
+ manifests.clear()
632
+ chunkOwners.clear()
633
+ }
634
+
635
+ const api = {
636
+ ensureLoaded: () => tm.ensureLoaded(),
637
+ get loaded() { return tm.loaded },
638
+ get available() { return tm.available },
639
+ seed,
640
+ share,
641
+ download,
642
+ listTorrents: () => tm.listTorrents(),
643
+ getTorrent: (magnetURI) => tm.getTorrent(magnetURI),
644
+ removeTorrent: (magnetURI) => {
645
+ const removed = tm.removeTorrent(magnetURI)
646
+ manifests.delete(magnetURI)
647
+ return removed
648
+ },
649
+ getStats: () => tm.getStats(),
650
+ getManifest: (magnetURI) => manifests.get(magnetURI) ?? null,
651
+ /** @param {string} cid @returns {string[]} pubKeys this peer currently believes hold `cid`, for introspection/tests. */
652
+ listKnownProviders: (cid) => [...(chunkOwners.get(cid) || [])],
653
+ toJSON: () => tm.toJSON(),
654
+ destroy,
655
+ }
656
+
657
+ return {
658
+ api,
659
+ teardown() {
660
+ unsubscribe()
661
+ tm.off('seed', onTmSeed)
662
+ for (const pending of pendingManifestRequests.values()) {
663
+ clearTimeout(pending.timer)
664
+ pending.resolve(null)
665
+ }
666
+ pendingManifestRequests.clear()
667
+ for (const pending of pendingChunkFetches.values()) {
668
+ clearTimeout(pending.timer)
669
+ pending.reject(new Error('mesh-torrent: service torn down while a chunk fetch was still in flight'))
670
+ }
671
+ pendingChunkFetches.clear()
672
+ },
673
+ }
674
+ },
675
+ }
676
+ }
677
+
678
+ export {
679
+ DEFAULT_ENVELOPE_TYPE,
680
+ DEFAULT_CHUNK_SIZE,
681
+ DEFAULT_MANIFEST_TIMEOUT_MS,
682
+ DEFAULT_CHUNK_TIMEOUT_MS,
683
+ }