@johnhenry/browsermesh-apps 0.0.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.
@@ -0,0 +1,628 @@
1
+ /**
2
+ // STATUS: INTEGRATED — wired into ClawserPod lifecycle, proven via E2E testing
3
+ * clawser-peer-torrent.js -- WebTorrent integration for P2P file distribution.
4
+ *
5
+ * CDN-loads webtorrent browser bundle for swarm-based file sharing.
6
+ * Falls back to direct chunked transfer when WebTorrent unavailable.
7
+ *
8
+ * Run tests:
9
+ * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-torrent.test.mjs
10
+ */
11
+
12
+ import { ChunkStore } from '@johnhenry/browsermesh-sync'
13
+
14
+ // ---------------------------------------------------------------------------
15
+ // Constants
16
+ // ---------------------------------------------------------------------------
17
+
18
+ export const TORRENT_DEFAULTS = Object.freeze({
19
+ chunkSize: 65536, // 64KB chunks
20
+ maxPeers: 10,
21
+ announceIntervalMs: 30000,
22
+ trackerUrl: null, // Use signaling server as tracker if set
23
+ })
24
+
25
+ // ---------------------------------------------------------------------------
26
+ // Helpers
27
+ // ---------------------------------------------------------------------------
28
+
29
+ let _torrentIdCounter = 0
30
+
31
+ function generateInfoHash() {
32
+ return `hash_${Date.now().toString(36)}_${(++_torrentIdCounter).toString(36)}`
33
+ }
34
+
35
+ function generateMagnetURI(infoHash) {
36
+ return `magnet:?xt=urn:btih:${infoHash}`
37
+ }
38
+
39
+ function infoHashFromMagnet(magnetURI) {
40
+ const match = magnetURI.match(/btih:([^&]+)/)
41
+ return match ? match[1] : null
42
+ }
43
+
44
+ // ---------------------------------------------------------------------------
45
+ // TorrentInfo
46
+ // ---------------------------------------------------------------------------
47
+
48
+ /**
49
+ * @typedef {object} TorrentInfo
50
+ * @property {string} magnetURI
51
+ * @property {string} infoHash
52
+ * @property {string} name
53
+ * @property {number} size
54
+ * @property {number} peers
55
+ * @property {number} progress - 0-1
56
+ * @property {number} speed - bytes/sec
57
+ * @property {'seeding'|'downloading'|'paused'} state
58
+ */
59
+
60
+ // ---------------------------------------------------------------------------
61
+ // FallbackStore — used when WebTorrent is not available
62
+ // ---------------------------------------------------------------------------
63
+
64
+ /**
65
+ * Simple in-memory store keyed by infoHash. Provides seed/download
66
+ * semantics without actual BitTorrent protocol.
67
+ */
68
+ class FallbackStore {
69
+ #data = new Map() // infoHash -> { data: Uint8Array, name, size }
70
+
71
+ set(infoHash, entry) {
72
+ this.#data.set(infoHash, entry)
73
+ }
74
+
75
+ get(infoHash) {
76
+ return this.#data.get(infoHash) || null
77
+ }
78
+
79
+ has(infoHash) {
80
+ return this.#data.has(infoHash)
81
+ }
82
+
83
+ delete(infoHash) {
84
+ return this.#data.delete(infoHash)
85
+ }
86
+
87
+ values() {
88
+ return [...this.#data.values()]
89
+ }
90
+
91
+ get size() {
92
+ return this.#data.size
93
+ }
94
+
95
+ clear() {
96
+ this.#data.clear()
97
+ }
98
+ }
99
+
100
+ // ---------------------------------------------------------------------------
101
+ // TorrentManager
102
+ // ---------------------------------------------------------------------------
103
+
104
+ /**
105
+ * Manages WebTorrent-based file sharing across the mesh.
106
+ *
107
+ * When WebTorrent is available (browser with CDN access), uses real
108
+ * BitTorrent swarming. When unavailable (Node.js tests, offline), falls
109
+ * back to an in-memory store that mimics the seed/download API.
110
+ */
111
+ export class TorrentManager {
112
+ /** @type {object|null} WebTorrent client instance (lazy-loaded) */
113
+ #client = null
114
+
115
+ /** @type {Map<string, TorrentInfo>} magnetURI -> TorrentInfo */
116
+ #activeTorrents = new Map()
117
+
118
+ /** @type {string|null} */
119
+ #trackerUrl
120
+
121
+ /** @type {boolean} */
122
+ #loaded = false
123
+
124
+ /** @type {boolean} */
125
+ #wtAvailable = false
126
+
127
+ /** @type {FallbackStore} */
128
+ #fallback = new FallbackStore()
129
+
130
+ /** @type {Function} */
131
+ #onLog
132
+
133
+ /** @type {Map<string, Set<Function>>} event -> callbacks */
134
+ #listeners = new Map()
135
+
136
+ /** @type {number} */
137
+ #totalDown = 0
138
+
139
+ /** @type {number} */
140
+ #totalUp = 0
141
+
142
+ /**
143
+ * @param {object} [opts]
144
+ * @param {string} [opts.trackerUrl] - Custom tracker URL
145
+ * @param {Function} [opts.onLog] - Logging callback
146
+ */
147
+ constructor(opts = {}) {
148
+ this.#trackerUrl = opts.trackerUrl ?? TORRENT_DEFAULTS.trackerUrl
149
+ this.#onLog = opts.onLog || (() => {})
150
+ }
151
+
152
+ // ── CDN Loading ──────────────────────────────────────────────────────
153
+
154
+ /**
155
+ * Lazy-load WebTorrent from CDN.
156
+ * Sets #wtAvailable based on whether the load succeeded.
157
+ */
158
+ async ensureLoaded() {
159
+ if (this.#loaded) return
160
+
161
+ try {
162
+ // Only attempt in browser-like environments with dynamic import support
163
+ if (typeof window !== 'undefined' && typeof window.WebTorrent === 'function') {
164
+ this.#client = new window.WebTorrent()
165
+ this.#wtAvailable = true
166
+ this.#onLog(2, 'WebTorrent client initialized from window.WebTorrent')
167
+ } else if (typeof globalThis.WebTorrent === 'function') {
168
+ this.#client = new globalThis.WebTorrent()
169
+ this.#wtAvailable = true
170
+ this.#onLog(2, 'WebTorrent client initialized from globalThis.WebTorrent')
171
+ } else {
172
+ // Try CDN load via esm.sh — this will fail in Node.js test env
173
+ try {
174
+ const mod = await import('https://esm.sh/webtorrent@2.8.5')
175
+ const WT = mod.default || mod.WebTorrent
176
+ if (typeof WT === 'function') {
177
+ globalThis.WebTorrent = WT
178
+ this.#client = new WT()
179
+ this.#wtAvailable = true
180
+ this.#onLog(2, 'WebTorrent loaded from CDN (esm.sh)')
181
+ }
182
+ } catch {
183
+ this.#wtAvailable = false
184
+ this.#onLog(1, 'WebTorrent CDN load failed — using fallback store')
185
+ }
186
+ }
187
+ } catch (err) {
188
+ this.#wtAvailable = false
189
+ this.#onLog(1, `WebTorrent initialization failed: ${err.message}`)
190
+ }
191
+
192
+ this.#loaded = true
193
+ }
194
+
195
+ /** Whether ensureLoaded() has been called. */
196
+ get loaded() {
197
+ return this.#loaded
198
+ }
199
+
200
+ /** Whether WebTorrent is usable (true only after successful load). */
201
+ get available() {
202
+ return this.#wtAvailable
203
+ }
204
+
205
+ // ── Seed ─────────────────────────────────────────────────────────────
206
+
207
+ /**
208
+ * Seed a file — make it available for download.
209
+ *
210
+ * @param {Uint8Array|Blob|ArrayBuffer} data - File content
211
+ * @param {object} [opts]
212
+ * @param {string} [opts.name] - File name
213
+ * @param {string[]} [opts.announce] - Tracker URLs
214
+ * @returns {Promise<TorrentInfo>}
215
+ */
216
+ async seed(data, opts = {}) {
217
+ if (!this.#loaded) await this.ensureLoaded()
218
+
219
+ const rawData = data instanceof ArrayBuffer
220
+ ? new Uint8Array(data)
221
+ : data instanceof Uint8Array
222
+ ? data
223
+ : data
224
+
225
+ const name = opts.name || `file_${Date.now()}`
226
+ const size = rawData.byteLength ?? rawData.length ?? rawData.size ?? 0
227
+
228
+ // Real WebTorrent path
229
+ if (this.#wtAvailable && this.#client) {
230
+ return this.#seedReal(rawData, name, size, opts)
231
+ }
232
+
233
+ // Fallback: generate pseudo-torrent info
234
+ return this.#seedFallback(rawData, name, size)
235
+ }
236
+
237
+ /**
238
+ * Seed via real WebTorrent client.
239
+ * @returns {Promise<TorrentInfo>}
240
+ */
241
+ #seedReal(data, name, size, opts) {
242
+ return new Promise((resolve, reject) => {
243
+ const seedOpts = {}
244
+ if (opts.announce || this.#trackerUrl) {
245
+ seedOpts.announce = opts.announce || [this.#trackerUrl]
246
+ }
247
+
248
+ const file = new File([data], name)
249
+ try {
250
+ const torrent = this.#client.seed(file, seedOpts, (torrent) => {
251
+ const info = {
252
+ magnetURI: torrent.magnetURI,
253
+ infoHash: torrent.infoHash,
254
+ name,
255
+ size,
256
+ peers: 0,
257
+ progress: 1,
258
+ speed: 0,
259
+ state: 'seeding',
260
+ }
261
+ this.#activeTorrents.set(info.magnetURI, info)
262
+ this.#totalUp += size
263
+ this.#emit('seed', info)
264
+ resolve(info)
265
+ })
266
+ if (torrent && torrent.on) {
267
+ torrent.on('error', (err) => reject(err))
268
+ }
269
+ } catch (err) {
270
+ reject(err)
271
+ }
272
+ })
273
+ }
274
+
275
+ /**
276
+ * Seed via fallback in-memory store.
277
+ * @returns {Promise<TorrentInfo>}
278
+ */
279
+ async #seedFallback(data, name, size) {
280
+ const bytes = data instanceof Uint8Array ? data : new Uint8Array(data)
281
+ const cid = await ChunkStore.computeCid(bytes)
282
+ const infoHash = cid.slice(0, 40) // Use first 40 hex chars as pseudo info hash
283
+ const magnetURI = generateMagnetURI(infoHash)
284
+
285
+ this.#fallback.set(infoHash, { data: bytes, name, size })
286
+
287
+ const info = {
288
+ magnetURI,
289
+ infoHash,
290
+ name,
291
+ size,
292
+ peers: 0,
293
+ progress: 1,
294
+ speed: 0,
295
+ state: 'seeding',
296
+ }
297
+ this.#activeTorrents.set(magnetURI, info)
298
+ this.#totalUp += size
299
+ this.#emit('seed', info)
300
+ return info
301
+ }
302
+
303
+ // ── Download ─────────────────────────────────────────────────────────
304
+
305
+ /**
306
+ * Download a file by magnet URI.
307
+ *
308
+ * @param {string} magnetURI
309
+ * @param {object} [opts]
310
+ * @param {number} [opts.timeout] - Download timeout in ms
311
+ * @param {Function} [opts.onProgress] - Progress callback (0-1)
312
+ * @returns {Promise<{ data: Uint8Array, info: TorrentInfo }>}
313
+ */
314
+ async download(magnetURI, opts = {}) {
315
+ if (!this.#loaded) await this.ensureLoaded()
316
+
317
+ // Real WebTorrent path
318
+ if (this.#wtAvailable && this.#client) {
319
+ return this.#downloadReal(magnetURI, opts)
320
+ }
321
+
322
+ // Fallback: look up in memory store
323
+ return this.#downloadFallback(magnetURI, opts)
324
+ }
325
+
326
+ /**
327
+ * Download via real WebTorrent client.
328
+ * @returns {Promise<{ data: Uint8Array, info: TorrentInfo }>}
329
+ */
330
+ #downloadReal(magnetURI, opts) {
331
+ return new Promise((resolve, reject) => {
332
+ const timeout = opts.timeout || 60000
333
+ const timer = setTimeout(() => {
334
+ reject(new Error(`Download timed out after ${timeout}ms`))
335
+ }, timeout)
336
+
337
+ this.#emit('download:start', { magnetURI })
338
+
339
+ try {
340
+ const torrent = this.#client.add(magnetURI, (torrent) => {
341
+ torrent.on('download', () => {
342
+ if (opts.onProgress) {
343
+ opts.onProgress(torrent.progress)
344
+ }
345
+ })
346
+
347
+ torrent.on('done', () => {
348
+ clearTimeout(timer)
349
+ const file = torrent.files[0]
350
+ if (!file) {
351
+ reject(new Error('Torrent has no files'))
352
+ return
353
+ }
354
+ file.getBuffer((err, buffer) => {
355
+ if (err) {
356
+ reject(err)
357
+ return
358
+ }
359
+ const data = new Uint8Array(buffer)
360
+ const info = {
361
+ magnetURI,
362
+ infoHash: torrent.infoHash,
363
+ name: file.name,
364
+ size: file.length,
365
+ peers: torrent.numPeers,
366
+ progress: 1,
367
+ speed: 0,
368
+ state: 'seeding',
369
+ }
370
+ this.#activeTorrents.set(magnetURI, info)
371
+ this.#totalDown += data.length
372
+ this.#emit('download:complete', info)
373
+ resolve({ data, info })
374
+ })
375
+ })
376
+ })
377
+ if (torrent && torrent.on) {
378
+ torrent.on('error', (err) => {
379
+ clearTimeout(timer)
380
+ reject(err)
381
+ })
382
+ }
383
+ } catch (err) {
384
+ clearTimeout(timer)
385
+ reject(err)
386
+ }
387
+ })
388
+ }
389
+
390
+ /**
391
+ * Download via fallback in-memory store.
392
+ * @returns {Promise<{ data: Uint8Array, info: TorrentInfo }>}
393
+ */
394
+ async #downloadFallback(magnetURI, opts) {
395
+ const infoHash = infoHashFromMagnet(magnetURI)
396
+ if (!infoHash) {
397
+ throw new Error(`Invalid magnet URI: ${magnetURI}`)
398
+ }
399
+
400
+ this.#emit('download:start', { magnetURI })
401
+
402
+ const entry = this.#fallback.get(infoHash)
403
+ if (!entry) {
404
+ throw new Error(`Content not found for magnet: ${magnetURI}`)
405
+ }
406
+
407
+ if (opts.onProgress) {
408
+ opts.onProgress(1)
409
+ }
410
+
411
+ const info = {
412
+ magnetURI,
413
+ infoHash,
414
+ name: entry.name,
415
+ size: entry.size,
416
+ peers: 0,
417
+ progress: 1,
418
+ speed: 0,
419
+ state: 'seeding',
420
+ }
421
+ this.#activeTorrents.set(magnetURI, info)
422
+ this.#totalDown += entry.size
423
+ this.#emit('download:complete', info)
424
+ return { data: entry.data, info }
425
+ }
426
+
427
+ // ── Mesh sharing ─────────────────────────────────────────────────────
428
+
429
+ /**
430
+ * Share a magnet URI with specific peers via the mesh.
431
+ *
432
+ * @param {string} magnetURI - The magnet URI to share
433
+ * @param {string[]} peerIds - Peer IDs to notify
434
+ * @param {Function} sendFn - (peerId, message) => void
435
+ */
436
+ shareWithPeers(magnetURI, peerIds, sendFn) {
437
+ if (!magnetURI || typeof magnetURI !== 'string') {
438
+ throw new Error('magnetURI is required')
439
+ }
440
+ if (!Array.isArray(peerIds)) {
441
+ throw new Error('peerIds must be an array')
442
+ }
443
+ if (typeof sendFn !== 'function') {
444
+ throw new Error('sendFn must be a function')
445
+ }
446
+
447
+ const info = this.#activeTorrents.get(magnetURI) || null
448
+ const message = {
449
+ type: 'torrent:share',
450
+ magnetURI,
451
+ info: info ? { name: info.name, size: info.size } : null,
452
+ }
453
+
454
+ for (const peerId of peerIds) {
455
+ sendFn(peerId, message)
456
+ }
457
+
458
+ this.#onLog(2, `Shared magnet with ${peerIds.length} peers: ${magnetURI}`)
459
+ }
460
+
461
+ // ── Query ────────────────────────────────────────────────────────────
462
+
463
+ /**
464
+ * List all active torrents.
465
+ * @returns {TorrentInfo[]}
466
+ */
467
+ listTorrents() {
468
+ return [...this.#activeTorrents.values()]
469
+ }
470
+
471
+ /**
472
+ * Get a specific torrent by magnet URI.
473
+ * @param {string} magnetURI
474
+ * @returns {TorrentInfo|null}
475
+ */
476
+ getTorrent(magnetURI) {
477
+ return this.#activeTorrents.get(magnetURI) || null
478
+ }
479
+
480
+ /**
481
+ * Remove a torrent.
482
+ *
483
+ * @param {string} magnetURI
484
+ * @returns {boolean}
485
+ */
486
+ removeTorrent(magnetURI) {
487
+ const info = this.#activeTorrents.get(magnetURI)
488
+ if (!info) return false
489
+
490
+ // Remove from real client if available
491
+ if (this.#wtAvailable && this.#client) {
492
+ try {
493
+ this.#client.remove(magnetURI)
494
+ } catch {
495
+ // may already be removed
496
+ }
497
+ }
498
+
499
+ // Remove from fallback store
500
+ const infoHash = infoHashFromMagnet(magnetURI)
501
+ if (infoHash) {
502
+ this.#fallback.delete(infoHash)
503
+ }
504
+
505
+ this.#activeTorrents.delete(magnetURI)
506
+ return true
507
+ }
508
+
509
+ // ── Stats ────────────────────────────────────────────────────────────
510
+
511
+ /**
512
+ * Get aggregated download/upload stats.
513
+ *
514
+ * @returns {{ downloading: number, seeding: number, totalDown: number, totalUp: number }}
515
+ */
516
+ getStats() {
517
+ let downloading = 0
518
+ let seeding = 0
519
+
520
+ for (const info of this.#activeTorrents.values()) {
521
+ if (info.state === 'downloading') downloading++
522
+ if (info.state === 'seeding') seeding++
523
+ }
524
+
525
+ return {
526
+ downloading,
527
+ seeding,
528
+ totalDown: this.#totalDown,
529
+ totalUp: this.#totalUp,
530
+ }
531
+ }
532
+
533
+ // ── Events ───────────────────────────────────────────────────────────
534
+
535
+ /**
536
+ * Register an event listener.
537
+ * Events: 'seed', 'download:start', 'download:complete', 'error'
538
+ *
539
+ * @param {string} event
540
+ * @param {Function} cb
541
+ */
542
+ on(event, cb) {
543
+ if (!this.#listeners.has(event)) {
544
+ this.#listeners.set(event, new Set())
545
+ }
546
+ this.#listeners.get(event).add(cb)
547
+ }
548
+
549
+ /**
550
+ * Remove an event listener.
551
+ *
552
+ * @param {string} event
553
+ * @param {Function} cb
554
+ */
555
+ off(event, cb) {
556
+ const set = this.#listeners.get(event)
557
+ if (set) set.delete(cb)
558
+ }
559
+
560
+ /**
561
+ * Emit an event to all registered listeners.
562
+ * @param {string} event
563
+ * @param {*} data
564
+ */
565
+ #emit(event, data) {
566
+ const set = this.#listeners.get(event)
567
+ if (set) {
568
+ for (const cb of [...set]) {
569
+ try {
570
+ cb(data)
571
+ } catch (err) {
572
+ this.#onLog(0, `Event listener error (${event}): ${err.message}`)
573
+ }
574
+ }
575
+ }
576
+ }
577
+
578
+ // ── Lifecycle ────────────────────────────────────────────────────────
579
+
580
+ /**
581
+ * Destroy the manager: remove all torrents, close the client.
582
+ */
583
+ async destroy() {
584
+ // Clear active torrents
585
+ this.#activeTorrents.clear()
586
+ this.#fallback.clear()
587
+ this.#listeners.clear()
588
+
589
+ // Destroy real client if present
590
+ if (this.#client) {
591
+ try {
592
+ await new Promise((resolve, reject) => {
593
+ this.#client.destroy((err) => {
594
+ if (err) reject(err)
595
+ else resolve()
596
+ })
597
+ })
598
+ } catch {
599
+ // best effort
600
+ }
601
+ this.#client = null
602
+ }
603
+
604
+ this.#loaded = false
605
+ this.#wtAvailable = false
606
+ this.#totalDown = 0
607
+ this.#totalUp = 0
608
+ }
609
+
610
+ // ── Serialization ────────────────────────────────────────────────────
611
+
612
+ /**
613
+ * Serialize to a JSON-safe object.
614
+ * @returns {object}
615
+ */
616
+ toJSON() {
617
+ return {
618
+ loaded: this.#loaded,
619
+ available: this.#wtAvailable,
620
+ trackerUrl: this.#trackerUrl,
621
+ activeTorrents: [...this.#activeTorrents.entries()].map(([uri, info]) => ({
622
+ magnetURI: uri,
623
+ ...info,
624
+ })),
625
+ stats: this.getStats(),
626
+ }
627
+ }
628
+ }