@johnhenry/browsermesh-apps 0.15.0 → 0.17.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 (55) hide show
  1. package/README.md +298 -17
  2. package/package.json +13 -9
  3. package/src/apps.mjs +4 -4
  4. package/src/audit.mjs +2 -2
  5. package/src/chat.mjs +3 -3
  6. package/src/cloud-storage-backend.mjs +5 -7
  7. package/src/cloud-storage.mjs +5 -4
  8. package/src/compat.mjs +2 -2
  9. package/src/consensus.mjs +7 -7
  10. package/src/devtools.mjs +3 -3
  11. package/src/gpu.mjs +2 -2
  12. package/src/index.mjs +12 -0
  13. package/src/internal/channel-codec.mjs +179 -0
  14. package/src/internal/json-message.mjs +49 -0
  15. package/src/internal/relay-flow.mjs +178 -0
  16. package/src/internal/request-target.mjs +280 -0
  17. package/src/internal/rpc-body.mjs +33 -0
  18. package/src/marketplace-ui.mjs +1 -1
  19. package/src/mesh-agent-swarm.mjs +1 -1
  20. package/src/mesh-bootstrap.mjs +47 -1
  21. package/src/mesh-channel.mjs +716 -0
  22. package/src/mesh-fetch.mjs +77 -263
  23. package/src/mesh-hardening.mjs +8 -1
  24. package/src/mesh-relay-backend.mjs +116 -22
  25. package/src/mesh-relay-host.mjs +296 -55
  26. package/src/mesh-rpc.mjs +126 -265
  27. package/src/mesh-sync.mjs +1 -1
  28. package/src/orchestrator.mjs +54 -29
  29. package/src/payments.mjs +56 -14
  30. package/src/peer-agent-swarm.mjs +2 -2
  31. package/src/peer-agent.mjs +7 -7
  32. package/src/peer-compute.mjs +2 -2
  33. package/src/peer-encrypted-store.mjs +3 -3
  34. package/src/peer-escrow.mjs +2 -2
  35. package/src/peer-health.mjs +3 -3
  36. package/src/peer-node.mjs +8 -5
  37. package/src/peer-payments.mjs +2 -2
  38. package/src/peer-registry.mjs +45 -3
  39. package/src/peer-routing.mjs +158 -21
  40. package/src/peer-services.mjs +3 -3
  41. package/src/peer-timestamp.mjs +3 -3
  42. package/src/peer-torrent.mjs +112 -47
  43. package/src/peer-verification.mjs +3 -3
  44. package/src/pod-host-service.mjs +48 -7
  45. package/src/pod-placement.mjs +582 -0
  46. package/src/pod-supervisor.mjs +9 -30
  47. package/src/protocol-channel.mjs +327 -0
  48. package/src/resources.mjs +2 -2
  49. package/src/restart-policy.mjs +67 -0
  50. package/src/scheduler.mjs +3 -3
  51. package/src/serverless-proxy.mjs +58 -7
  52. package/src/silent-catch.mjs +22 -9
  53. package/src/tools.mjs +3 -3
  54. package/src/visualizations.mjs +2 -2
  55. package/src/wsh-negotiator.mjs +97 -0
@@ -25,6 +25,20 @@
25
25
  * node --import ./test/_setup-globals.mjs --test test/peer-routing.test.mjs
26
26
  */
27
27
 
28
+ import {
29
+ PROXY_LIMITS_DEFAULTS,
30
+ DEFAULT_ALLOWED_METHODS,
31
+ DEFAULT_ALLOWED_REQUEST_HEADERS,
32
+ configuredOrigin,
33
+ resolveTarget,
34
+ checkHeaderShape,
35
+ selectRequestHeaders,
36
+ checkRequestBody,
37
+ copyResponseHeaders,
38
+ readBoundedBody,
39
+ responseLeftOrigin,
40
+ } from './internal/request-target.mjs'
41
+
28
42
  // ---------------------------------------------------------------------------
29
43
  // Constants
30
44
  // ---------------------------------------------------------------------------
@@ -401,11 +415,38 @@ export class ServerSharing {
401
415
  /** @type {Function} */
402
416
  #onLog
403
417
 
418
+ /** @type {{ checkAccess: Function }|null} */
419
+ #registry
420
+
421
+ /** @type {Map<string, { origin: string, headers: Record<string, string>, allowedMethods: Set<string>|null }>} name -> private share state */
422
+ #shareState = new Map()
423
+
424
+ /** @type {Set<string>} */
425
+ #allowedMethods
426
+
427
+ /** @type {Set<string>} */
428
+ #allowedHeaders
429
+
430
+ /** @type {typeof PROXY_LIMITS_DEFAULTS} */
431
+ #limits
432
+
404
433
  /**
405
434
  * @param {object} opts
406
435
  * @param {string} opts.localPodId - This pod's identifier
407
436
  * @param {Function} [opts.fetchFn] - (url, init?) => Response, defaults to globalThis.fetch
408
437
  * @param {Function} [opts.onLog] - Logging callback
438
+ * @param {{ checkAccess: Function }} [opts.registry] - `PeerRegistry`-shaped. Every request that
439
+ * names a calling peer (see `handleRequest()`) must pass
440
+ * `registry.checkAccess(peerKey, 'server-share:<name>', 'request')`; without a registry such
441
+ * requests are refused.
442
+ * @param {string[]} [opts.allowedMethods] - Methods a peer may use (default: GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS)
443
+ * @param {string[]} [opts.allowedRequestHeaders] - Extra request header names a peer may set, added to the defaults
444
+ * @param {number} [opts.maxPathLength=2048]
445
+ * @param {number} [opts.maxRequestBodyBytes=1048576]
446
+ * @param {number} [opts.maxResponseBytes=8388608]
447
+ * @param {number} [opts.maxHeaderCount=32]
448
+ * @param {number} [opts.maxHeaderBytes=8192]
449
+ * @param {number} [opts.requestTimeoutMs=30000]
409
450
  */
410
451
  constructor(opts) {
411
452
  const { localPodId, fetchFn, onLog } = opts
@@ -417,6 +458,20 @@ export class ServerSharing {
417
458
  ? fetchFn
418
459
  : (typeof globalThis.fetch === 'function' ? globalThis.fetch : null)
419
460
  this.#onLog = onLog ?? (() => {})
461
+ this.#registry = opts.registry ?? null
462
+ this.#allowedMethods = new Set((opts.allowedMethods ?? DEFAULT_ALLOWED_METHODS).map((m) => String(m).toUpperCase()))
463
+ this.#allowedHeaders = new Set([
464
+ ...DEFAULT_ALLOWED_REQUEST_HEADERS,
465
+ ...(opts.allowedRequestHeaders ?? []).map((h) => String(h).toLowerCase()),
466
+ ])
467
+ const limits = { ...PROXY_LIMITS_DEFAULTS }
468
+ for (const key of Object.keys(limits)) {
469
+ if (opts[key] !== undefined) {
470
+ if (!Number.isFinite(opts[key]) || opts[key] <= 0) throw new Error(`${key} must be a positive number`)
471
+ limits[key] = opts[key]
472
+ }
473
+ }
474
+ this.#limits = Object.freeze(limits)
420
475
  }
421
476
 
422
477
  // ── Expose / Unexpose ─────────────────────────────────────────────
@@ -429,6 +484,8 @@ export class ServerSharing {
429
484
  * @param {object} [opts]
430
485
  * @param {string} [opts.hostname='localhost'] - Local hostname
431
486
  * @param {string} [opts.protocol='http'] - Protocol (http or https)
487
+ * @param {Record<string, string>} [opts.headers] - Headers sent with every request to this
488
+ * server (for example a credential the sharer chooses to attach). A peer cannot override them.
432
489
  * @returns {object} ServerConfig
433
490
  */
434
491
  expose(port, name, opts = {}) {
@@ -438,9 +495,17 @@ export class ServerSharing {
438
495
  if (!name || typeof name !== 'string') {
439
496
  throw new Error('name is required and must be a non-empty string')
440
497
  }
498
+ if (/[:*]/.test(name)) {
499
+ throw new Error('name must not contain ":" or "*"')
500
+ }
441
501
 
442
502
  const hostname = opts.hostname ?? 'localhost'
443
503
  const protocol = opts.protocol ?? 'http'
504
+ const origin = configuredOrigin(protocol, hostname, port)
505
+ const headerCheck = checkHeaderShape(opts.headers, { maxHeaderCount: this.#limits.maxHeaderCount, maxHeaderBytes: this.#limits.maxHeaderBytes })
506
+ if (!headerCheck.ok) throw new Error(`headers: ${headerCheck.reason}`)
507
+ const configured = {}
508
+ for (const [k, v] of headerCheck.entries) configured[k.toLowerCase()] = v
444
509
  const address = `mesh://${this.#localPodId}/http/${name}`
445
510
 
446
511
  const config = {
@@ -453,6 +518,7 @@ export class ServerSharing {
453
518
  }
454
519
 
455
520
  this.#exposedServers.set(name, config)
521
+ this.#shareState.set(name, { origin, headers: configured })
456
522
  this.#onLog(`Exposed server "${name}" at port ${port} → ${address}`)
457
523
 
458
524
  return config
@@ -465,6 +531,7 @@ export class ServerSharing {
465
531
  */
466
532
  unexpose(name) {
467
533
  const existed = this.#exposedServers.delete(name)
534
+ this.#shareState.delete(name)
468
535
  if (existed) {
469
536
  this.#onLog(`Unexposed server "${name}"`)
470
537
  }
@@ -481,45 +548,93 @@ export class ServerSharing {
481
548
  * @param {string} request.method - HTTP method
482
549
  * @param {string} request.path - Request path
483
550
  * @param {object} [request.headers] - Request headers
484
- * @param {*} [request.body] - Request body
551
+ * @param {*} [request.body] - Request body (string or bytes)
552
+ * @param {object} [caller]
553
+ * @param {string} [caller.fromPubKey] - The key of the peer that sent the request, taken
554
+ * from the session it arrived on and never from the message. When `caller` is given the
555
+ * request must pass `registry.checkAccess(fromPubKey, 'server-share:<name>', 'request')`.
556
+ * Omit `caller` only for a call made by this process itself.
485
557
  * @returns {Promise<{ status: number, headers: object, body: * }>}
486
558
  */
487
- async handleRequest(request) {
559
+ async handleRequest(request, caller) {
488
560
  if (!request || typeof request !== 'object') {
489
561
  return { status: 400, headers: {}, body: 'Invalid request' }
490
562
  }
491
563
 
564
+ if (caller !== undefined) {
565
+ const key = caller?.fromPubKey
566
+ const nameOk = typeof request.name === 'string' && request.name !== '' && !/[:*]/.test(request.name)
567
+ const allowed = nameOk
568
+ && typeof key === 'string' && key !== ''
569
+ && this.#registry !== null
570
+ && this.#registry.checkAccess(key, `server-share:${request.name}`, 'request')?.allowed === true
571
+ if (!allowed) {
572
+ this.#onLog(`Refused request from ${typeof key === 'string' ? key : '(no key)'} for share "${String(request.name).slice(0, 64)}"`)
573
+ return { status: 403, headers: {}, body: 'Access denied' }
574
+ }
575
+ }
576
+
492
577
  const config = this.#exposedServers.get(request.name)
493
- if (!config) {
578
+ const state = this.#shareState.get(request.name)
579
+ if (!config || !state) {
494
580
  return { status: 404, headers: {}, body: `Server "${request.name}" not found` }
495
581
  }
496
582
 
497
- const url = `${config.protocol}://${config.hostname}:${config.port}${request.path || '/'}`
583
+ const method = request.method === undefined || request.method === null || request.method === ''
584
+ ? 'GET'
585
+ : (typeof request.method === 'string' ? request.method.toUpperCase() : null)
586
+ if (method === null || !this.#allowedMethods.has(method)) {
587
+ return { status: 405, headers: {}, body: 'Method not allowed' }
588
+ }
589
+
590
+ const target = resolveTarget(state.origin, request.path, { maxPathLength: this.#limits.maxPathLength })
591
+ if (!target.ok) {
592
+ return { status: 400, headers: {}, body: `Invalid request target: ${target.reason}` }
593
+ }
594
+
595
+ const headerCheck = checkHeaderShape(request.headers, this.#limits)
596
+ if (!headerCheck.ok) {
597
+ return { status: 400, headers: {}, body: `Invalid headers: ${headerCheck.reason}` }
598
+ }
599
+
600
+ const bodyCheck = checkRequestBody(request.body, this.#limits.maxRequestBodyBytes)
601
+ if (!bodyCheck.ok) {
602
+ return { status: bodyCheck.status, headers: {}, body: bodyCheck.reason }
603
+ }
604
+ if (bodyCheck.body !== undefined && (method === 'GET' || method === 'HEAD')) {
605
+ return { status: 400, headers: {}, body: `A ${method} request cannot carry a body` }
606
+ }
498
607
 
499
608
  if (!this.#fetchFn) {
500
609
  return { status: 503, headers: {}, body: 'Fetch not available' }
501
610
  }
502
611
 
503
612
  try {
504
- const response = await this.#fetchFn(url, {
505
- method: request.method || 'GET',
506
- headers: request.headers || {},
507
- body: request.body,
508
- })
613
+ const init = {
614
+ method,
615
+ headers: selectRequestHeaders(headerCheck.entries, this.#allowedHeaders, state.headers),
616
+ // A redirect is returned to the peer as it is; it is never followed,
617
+ // so the request cannot leave the configured origin.
618
+ redirect: 'manual',
619
+ signal: AbortSignal.timeout(this.#limits.requestTimeoutMs),
620
+ }
621
+ if (bodyCheck.body !== undefined) init.body = bodyCheck.body
622
+ const response = await this.#fetchFn(target.url.href, init)
509
623
 
510
- const responseHeaders = {}
511
- if (response.headers && typeof response.headers.forEach === 'function') {
512
- response.headers.forEach((value, key) => {
513
- responseHeaders[key] = value
514
- })
624
+ if (responseLeftOrigin(response, state.origin)) {
625
+ try { await response.body?.cancel?.() } catch { /* already closed */ }
626
+ return { status: 502, headers: {}, body: 'Proxy error: response did not come from the configured origin' }
515
627
  }
516
628
 
517
- const body = await (typeof response.text === 'function' ? response.text() : response.body)
629
+ const read = await readBoundedBody(response, this.#limits.maxResponseBytes)
630
+ if (!read.ok) {
631
+ return { status: 502, headers: {}, body: 'Proxy error: response too large' }
632
+ }
518
633
 
519
634
  return {
520
635
  status: response.status,
521
- headers: responseHeaders,
522
- body,
636
+ headers: copyResponseHeaders(response.headers),
637
+ body: read.body,
523
638
  }
524
639
  } catch (err) {
525
640
  return {
@@ -727,6 +842,15 @@ export function createMeshRoutingService(opts = {}) {
727
842
  fetchFn,
728
843
  serverShareEnvelopeType = DEFAULT_SERVER_SHARE_ENVELOPE_TYPE,
729
844
  proxyTimeoutMs = DEFAULT_PROXY_TIMEOUT_MS,
845
+ registry,
846
+ allowedMethods,
847
+ allowedRequestHeaders,
848
+ maxPathLength,
849
+ maxRequestBodyBytes,
850
+ maxResponseBytes,
851
+ maxHeaderCount,
852
+ maxHeaderBytes,
853
+ requestTimeoutMs,
730
854
  onLog,
731
855
  } = opts
732
856
  const wireServerSharing = 'fetchFn' in opts
@@ -798,6 +922,15 @@ export function createMeshRoutingService(opts = {}) {
798
922
  serverSharing = new ServerSharing({
799
923
  localPodId,
800
924
  fetchFn,
925
+ registry: registry ?? peerNode.registry ?? null,
926
+ allowedMethods,
927
+ allowedRequestHeaders,
928
+ maxPathLength,
929
+ maxRequestBodyBytes,
930
+ maxResponseBytes,
931
+ maxHeaderCount,
932
+ maxHeaderBytes,
933
+ requestTimeoutMs,
801
934
  onLog: (msg) => log('mesh-routing:server-share-log', { message: msg }),
802
935
  })
803
936
 
@@ -808,13 +941,15 @@ export function createMeshRoutingService(opts = {}) {
808
941
  const { requestId } = msg
809
942
  let result
810
943
  try {
944
+ // The caller is the key of the session the message arrived on;
945
+ // nothing in `msg` can name a different one.
811
946
  result = await serverSharing.handleRequest({
812
947
  name: msg.name,
813
948
  method: msg.method,
814
949
  path: msg.path,
815
950
  headers: msg.headers,
816
951
  body: msg.body,
817
- })
952
+ }, { fromPubKey })
818
953
  } catch (err) {
819
954
  // handleRequest() already catches its own fetchFn errors (see
820
955
  // ServerSharing.handleRequest()'s 502 path) -- reaching here
@@ -836,9 +971,11 @@ export function createMeshRoutingService(opts = {}) {
836
971
  }
837
972
  }
838
973
 
839
- function handleProxyResponse(msg) {
974
+ function handleProxyResponse(fromPubKey, msg) {
840
975
  const pending = pendingProxyRequests.get(msg.requestId)
841
976
  if (!pending) return // no longer waiting (already timed out, or not ours) -- ignore
977
+ // Only the peer the request was sent to can answer it.
978
+ if (pending.podId !== fromPubKey) return
842
979
  pendingProxyRequests.delete(msg.requestId)
843
980
  clearTimeout(pending.timer)
844
981
  pending.resolve({ status: msg.status, headers: msg.headers || {}, body: msg.body })
@@ -851,7 +988,7 @@ export function createMeshRoutingService(opts = {}) {
851
988
  log('mesh-routing:server-share-request-handling-failed', { from: fromPubKey, requestId: msg.requestId, error: err?.message || String(err) })
852
989
  })
853
990
  } else if (msg.kind === 'proxy-response') {
854
- handleProxyResponse(msg)
991
+ handleProxyResponse(fromPubKey, msg)
855
992
  }
856
993
  })
857
994
 
@@ -871,7 +1008,7 @@ export function createMeshRoutingService(opts = {}) {
871
1008
  ctx.emit('mesh-routing:server-share-timeout', { to: podId, name, method, path })
872
1009
  reject(new Error(`mesh-routing: proxy request ${method} ${path} (server "${name}") to ${podId} timed out after ${proxyTimeoutMs}ms`))
873
1010
  }, proxyTimeoutMs)
874
- pendingProxyRequests.set(requestId, { resolve, reject, timer })
1011
+ pendingProxyRequests.set(requestId, { resolve, reject, timer, podId })
875
1012
  })
876
1013
 
877
1014
  try {
@@ -1,6 +1,6 @@
1
1
  /**
2
- // STATUS: INTEGRATED — wired into ClawserPod lifecycle, proven via E2E testing
3
- * clawser-peer-services.js -- Service advertising and discovery for P2P mesh.
2
+ // STATUS: INTEGRATED — wired into the Pod lifecycle (@johnhenry/browsermesh-pod), proven via E2E testing
3
+ * peer-services.mjs --Service advertising and discovery for P2P mesh.
4
4
  *
5
5
  * Peers advertise capabilities (agent, terminal, files, compute, http-proxy, model)
6
6
  * and others can discover and connect to them.
@@ -11,7 +11,7 @@
11
11
  * No browser-only imports at module level. All dependencies injected.
12
12
  *
13
13
  * Run tests:
14
- * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-services.test.mjs
14
+ * cd packages/browsermesh-apps && node --import ./test/_setup-globals.mjs --test test/peer-services.test.mjs
15
15
  */
16
16
 
17
17
  // ---------------------------------------------------------------------------
@@ -1,6 +1,6 @@
1
1
  /**
2
- // STATUS: INTEGRATED — wired into ClawserPod lifecycle, proven via E2E testing
3
- * clawser-peer-timestamp.js — Distributed timestamp consensus.
2
+ // STATUS: INTEGRATED — wired into the Pod lifecycle (@johnhenry/browsermesh-pod), proven via E2E testing
3
+ * peer-timestamp.mjs —Distributed timestamp consensus.
4
4
  *
5
5
  * Peers propose timestamps, network agrees on canonical order via
6
6
  * median computation and outlier rejection. Enables legal-grade
@@ -13,7 +13,7 @@
13
13
  * No browser-only imports at module level.
14
14
  *
15
15
  * Run tests:
16
- * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-timestamp.test.mjs
16
+ * cd packages/browsermesh-apps && node --import ./test/_setup-globals.mjs --test test/peer-timestamp.test.mjs
17
17
  */
18
18
 
19
19
  import { assertIdentityFirst, isVerifyOrderError } from './internal/verify-order.mjs'
@@ -1,6 +1,6 @@
1
1
  /**
2
- // STATUS: INTEGRATED — wired into ClawserPod lifecycle, proven via E2E testing
3
- * clawser-peer-torrent.js -- WebTorrent integration for P2P file distribution.
2
+ // STATUS: INTEGRATED — wired into the Pod lifecycle (@johnhenry/browsermesh-pod), proven via E2E testing
3
+ * peer-torrent.mjs --WebTorrent integration for P2P file distribution.
4
4
  *
5
5
  * Uses a WebTorrent client the caller supplies (`new TorrentManager({
6
6
  * webtorrent })`: the `WebTorrent` constructor or a ready client) or one
@@ -21,7 +21,7 @@
21
21
  * own storage and ignores both.
22
22
  *
23
23
  * Run tests:
24
- * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-torrent.test.mjs
24
+ * cd packages/browsermesh-apps && node --import ./test/_setup-globals.mjs --test test/peer-torrent.test.mjs
25
25
  */
26
26
 
27
27
  import { ChunkStore } from '@johnhenry/browsermesh-sync'
@@ -42,8 +42,62 @@ export const TORRENT_DEFAULTS = Object.freeze({
42
42
  maxPeers: 10,
43
43
  announceIntervalMs: 30000,
44
44
  trackerUrl: null, // Use signaling server as tracker if set
45
+ maxDownloadBytes: 256 * 1024 * 1024, // largest file download() buffers; per-call `maxBytes` overrides
45
46
  })
46
47
 
48
+ /**
49
+ * Read a WebTorrent `File` into memory, never holding more than `maxBytes`.
50
+ *
51
+ * WebTorrent 2.x/3.x: `file.stream()` (a W3C ReadableStream) is read chunk by
52
+ * chunk into one buffer sized from `file.length`, and the running total is
53
+ * checked as well, so a file that claims to be small cannot grow past the cap.
54
+ * Otherwise `file.arrayBuffer()`, and for a 1.x client the callback-style
55
+ * `file.getBuffer()`. The size is checked before anything is read.
56
+ *
57
+ * @param {object} file - WebTorrent File
58
+ * @param {number} maxBytes - Pass Infinity for no cap
59
+ * @returns {Promise<Uint8Array>}
60
+ */
61
+ async function readTorrentFile(file, maxBytes) {
62
+ const length = file.length
63
+ const tooBig = (n) => new Error(`Torrent file is ${n} bytes, which exceeds maxBytes (${maxBytes})`)
64
+ if (Number.isFinite(length) && length > maxBytes) throw tooBig(length)
65
+
66
+ if (typeof file.stream === 'function') {
67
+ const reader = file.stream().getReader()
68
+ const known = Number.isFinite(length)
69
+ let out = known ? new Uint8Array(length) : new Uint8Array(0)
70
+ let used = 0
71
+ try {
72
+ for (;;) {
73
+ const { done, value } = await reader.read()
74
+ if (done) break
75
+ if (used + value.length > maxBytes) throw tooBig(used + value.length)
76
+ if (used + value.length > out.length) {
77
+ const grown = new Uint8Array(Math.max(out.length * 2, used + value.length))
78
+ grown.set(out.subarray(0, used))
79
+ out = grown
80
+ }
81
+ out.set(value, used)
82
+ used += value.length
83
+ }
84
+ } catch (err) {
85
+ try { await reader.cancel() } catch { /* already closed */ }
86
+ throw err
87
+ }
88
+ return used === out.length ? out : out.slice(0, used)
89
+ }
90
+ if (typeof file.arrayBuffer === 'function') {
91
+ return new Uint8Array(await file.arrayBuffer())
92
+ }
93
+ if (typeof file.getBuffer === 'function') {
94
+ return new Promise((resolve, reject) => {
95
+ file.getBuffer((err, buffer) => (err ? reject(err) : resolve(new Uint8Array(buffer))))
96
+ })
97
+ }
98
+ throw new Error('Unsupported WebTorrent File: no stream(), arrayBuffer() or getBuffer()')
99
+ }
100
+
47
101
  // ---------------------------------------------------------------------------
48
102
  // Helpers
49
103
  // ---------------------------------------------------------------------------
@@ -430,61 +484,72 @@ export class TorrentManager {
430
484
  * @returns {Promise<{ data: Uint8Array, info: TorrentInfo }>}
431
485
  */
432
486
  #downloadReal(magnetURI, opts) {
487
+ const maxBytes = opts.maxBytes ?? TORRENT_DEFAULTS.maxDownloadBytes
433
488
  return new Promise((resolve, reject) => {
434
489
  const timeout = opts.timeout || 60000
435
- const timer = setTimeout(() => {
436
- reject(new Error(`Download timed out after ${timeout}ms`))
490
+ let settled = false
491
+ let timer = null
492
+ const removeTorrent = async () => {
493
+ // A failed or timed-out download must not linger in the client.
494
+ // (remove() returns a promise in WebTorrent 2.x+.)
495
+ try {
496
+ await this.#client.remove(magnetURI)
497
+ } catch { /* already gone */ }
498
+ }
499
+ const fail = (err) => {
500
+ if (settled) return
501
+ settled = true
502
+ clearTimeout(timer)
503
+ removeTorrent().then(() => reject(err))
504
+ }
505
+ timer = setTimeout(() => {
506
+ fail(new Error(`Download timed out after ${timeout}ms`))
437
507
  }, timeout)
438
508
 
439
509
  this.#emit('download:start', { magnetURI })
440
510
 
441
- try {
442
- const torrent = this.#client.add(magnetURI, (torrent) => {
443
- torrent.on('download', () => {
444
- if (opts.onProgress) {
445
- opts.onProgress(torrent.progress)
446
- }
447
- })
511
+ const finish = async (torrent) => {
512
+ try {
513
+ const file = torrent.files[0]
514
+ if (!file) throw new Error('Torrent has no files')
515
+ const data = await readTorrentFile(file, maxBytes)
516
+ if (settled) return
517
+ settled = true
518
+ clearTimeout(timer)
519
+ const info = {
520
+ magnetURI,
521
+ infoHash: torrent.infoHash,
522
+ name: file.name,
523
+ size: file.length,
524
+ peers: torrent.numPeers,
525
+ progress: 1,
526
+ speed: 0,
527
+ state: 'seeding',
528
+ }
529
+ this.#activeTorrents.set(magnetURI, info)
530
+ this.#totalDown += data.length
531
+ this.#emit('download:complete', info)
532
+ resolve({ data, info })
533
+ } catch (err) {
534
+ fail(err)
535
+ }
536
+ }
448
537
 
449
- torrent.on('done', () => {
450
- clearTimeout(timer)
451
- const file = torrent.files[0]
452
- if (!file) {
453
- reject(new Error('Torrent has no files'))
454
- return
455
- }
456
- file.getBuffer((err, buffer) => {
457
- if (err) {
458
- reject(err)
459
- return
460
- }
461
- const data = new Uint8Array(buffer)
462
- const info = {
463
- magnetURI,
464
- infoHash: torrent.infoHash,
465
- name: file.name,
466
- size: file.length,
467
- peers: torrent.numPeers,
468
- progress: 1,
469
- speed: 0,
470
- state: 'seeding',
471
- }
472
- this.#activeTorrents.set(magnetURI, info)
473
- this.#totalDown += data.length
474
- this.#emit('download:complete', info)
475
- resolve({ data, info })
476
- })
477
- })
538
+ try {
539
+ const onProgress = opts.onProgress
540
+ const torrent = this.#client.add(magnetURI, (t) => {
541
+ // A fast (local) transfer can finish before add() returns control.
542
+ if (t.done || t.progress === 1) finish(t)
543
+ else t.on('done', () => finish(t))
478
544
  })
479
545
  if (torrent && torrent.on) {
480
- torrent.on('error', (err) => {
481
- clearTimeout(timer)
482
- reject(err)
483
- })
546
+ // Attached on the returned torrent, not inside the add callback, so
547
+ // a fast transfer cannot emit its progress before we listen.
548
+ if (onProgress) torrent.on('download', () => onProgress(torrent.progress))
549
+ torrent.on('error', fail)
484
550
  }
485
551
  } catch (err) {
486
- clearTimeout(timer)
487
- reject(err)
552
+ fail(err)
488
553
  }
489
554
  })
490
555
  }
@@ -1,12 +1,12 @@
1
1
  /**
2
- // STATUS: INTEGRATED — wired into ClawserPod lifecycle, proven via E2E testing
3
- * clawser-peer-verification.js — Verification quorum protocol.
2
+ // STATUS: INTEGRATED — wired into the Pod lifecycle (@johnhenry/browsermesh-pod), proven via E2E testing
3
+ * peer-verification.mjs —Verification quorum protocol.
4
4
  *
5
5
  * Run the same job on N peers, collect results, vote on correctness.
6
6
  * Enables trustless compute verification without TEEs.
7
7
  *
8
8
  * Run tests:
9
- * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-verification.test.mjs
9
+ * cd packages/browsermesh-apps && node --import ./test/_setup-globals.mjs --test test/peer-verification.test.mjs
10
10
  */
11
11
 
12
12
  // ---------------------------------------------------------------------------
@@ -95,6 +95,26 @@ import { decodeWireData } from './internal/wire-envelope.mjs'
95
95
  /** Envelope type of a host-metadata request. Not one of the eight verbs -- see the module doc comment. */
96
96
  export const POD_HOST_DESCRIBE = 'pod-host:describe'
97
97
 
98
+ /** What an env value or `run.input` becomes for a requester that did not spawn the pod. */
99
+ const REDACTED = '[redacted]'
100
+
101
+ /**
102
+ * A podspec with its `env` values and `run.input` replaced by a marker: the
103
+ * names, the module, the limits and the labels stay visible.
104
+ * @param {object} spec
105
+ * @returns {object}
106
+ */
107
+ function redactSpec(spec) {
108
+ const out = { ...spec }
109
+ if (spec.env && typeof spec.env === 'object') {
110
+ out.env = Object.fromEntries(Object.keys(spec.env).map((key) => [key, REDACTED]))
111
+ }
112
+ if (spec.run && typeof spec.run === 'object' && spec.run.input !== undefined) {
113
+ out.run = { ...spec.run, input: REDACTED }
114
+ }
115
+ return out
116
+ }
117
+
98
118
  /** Default ACL resource every verb is checked against. */
99
119
  export const DEFAULT_POD_HOST_RESOURCE = 'pod-host'
100
120
 
@@ -135,15 +155,14 @@ const LANE_SHELL_BACKEND = Object.freeze({
135
155
  * pod can be registered for placement scoring without that function
136
156
  * learning anything about pod hosts.
137
157
  *
138
- * KNOWN LIMITATION, worth stating plainly rather than papering over:
139
158
  * `runtimePeerToComputeDescriptor()` returns `null` for any peer whose
140
159
  * capabilities do not include `shell`/`exec`/`tools` (that is what it turns
141
160
  * into the `compute` capability every scored descriptor needs). An
142
- * ISOLATE-lane pod host has no `exec` by definition, so it produces no
143
- * compute descriptor today and can only be reached through this service
144
- * directly, not through `dispatchCompute()`. Fixing that means teaching the
145
- * orchestrator that "can spawn" is a kind of compute even without a shell
146
- * -- a change to WP4's scoring surface, deliberately out of scope here.
161
+ * ISOLATE-lane pod host has no `exec` by definition, so by default it is not
162
+ * a compute candidate and nothing that needs a shell can reach it. Placement
163
+ * asks for spawn hosts explicitly (`includeSpawnHosts`), which surfaces a
164
+ * host that serves `spawn` as a `spawn` + `runtime:<lane>` descriptor
165
+ * without ever granting it `compute`.
147
166
  *
148
167
  * @param {PodHostDescription} description
149
168
  * @param {object} [extra]
@@ -231,6 +250,27 @@ export function createPodHostService({
231
250
  */
232
251
  const interested = new Map()
233
252
 
253
+ /**
254
+ * Who spawned each pod through this service, by pod name. Only the
255
+ * spawner sees a pod's `env` values and `run.input` in `status`/`list`
256
+ * results; everyone else sees the names with the values redacted. A pod
257
+ * the service did not spawn has no owner, so it is redacted for all.
258
+ * @type {Map<string, string>} pod name -> pubKey
259
+ */
260
+ const owners = new Map()
261
+
262
+ /**
263
+ * A copy of a pod status as `pubKey` may see it.
264
+ * @param {string} pubKey
265
+ * @param {*} status
266
+ * @returns {*}
267
+ */
268
+ function presentStatus(pubKey, status) {
269
+ if (!status || typeof status !== 'object' || !status.spec) return status
270
+ if (owners.get(status.name) === pubKey) return status
271
+ return { ...status, spec: redactSpec(status.spec) }
272
+ }
273
+
234
274
  /**
235
275
  * @param {string} operation - A `PLACEMENT_AUDIT` value.
236
276
  * @param {object} data
@@ -456,6 +496,7 @@ export function createPodHostService({
456
496
  // 4. Dispatch.
457
497
  try {
458
498
  const result = await dispatch(verb, validated.value)
499
+ if (verb === POD_HOST_VERB.SPAWN) owners.set(validated.value.name, pubKey)
459
500
  if (verb === POD_HOST_VERB.SPAWN) {
460
501
  await recordAudit(PLACEMENT_AUDIT.READY, {
461
502
  requester: pubKey, requestId, name: validated.value.name, state: result?.state ?? null,
@@ -466,7 +507,7 @@ export function createPodHostService({
466
507
  })
467
508
  }
468
509
  ctx.emit('pod-host:completed', { from: pubKey, verb, requestId, ok: true, code: null })
469
- return result
510
+ return Array.isArray(result) ? result.map((entry) => presentStatus(pubKey, entry)) : presentStatus(pubKey, result)
470
511
  } catch (err) {
471
512
  const driverError = PodHostDriverError.from(err)
472
513
  log('pod-host:verb-failed', { from: pubKey, verb, code: driverError.code, error: driverError.message })