@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,289 @@
1
+ /**
2
+ * mesh-relay-backend.mjs -- Peer B's side of Phase 8 (mesh relay): a
3
+ * `browsermesh-netway` `Backend` that reaches services exposed by a
4
+ * `MeshRelayHost` (`mesh-relay-host.mjs`) on another mesh peer, over the
5
+ * real WebRTC mesh (Phases 2-4) -- no direct `wsh` connection of its own.
6
+ *
7
+ * The one file in this package that imports *from* `browsermesh-netway`,
8
+ * keeping the family's dependency graph one-directional (`-netway` stays
9
+ * dependency-free and mesh-unaware; all mesh awareness lives here in
10
+ * `-apps`).
11
+ *
12
+ * `connect(host, port)` treats `host` as a service name -- exact precedent:
13
+ * `browsermesh-netway`'s own `ServiceBackend.connect(host, port)` (`host` is
14
+ * a service name, `port` ignored). A `MeshRelayBackend` instance is bound to
15
+ * one relay-host peer's pubkey; register it on the client's own
16
+ * `VirtualNetwork` under a caller-chosen scheme (e.g.
17
+ * `network.addBackend('s3-via-alice', backend)`) so application code
18
+ * addresses the shared service via the existing, unmodified
19
+ * `VirtualNetwork.connect()` API (e.g. `network.connect('s3-via-alice://s3-local')`).
20
+ *
21
+ * TCP-only this phase: `listen()` / `bindDatagram()` / `resolve()` are left
22
+ * as `Backend`'s inherited "not implemented" throws -- see the Phase 8 plan's
23
+ * explicit "out of scope" list (UDP relay, inbound listen-relay).
24
+ *
25
+ * No browser-only imports at module level.
26
+ */
27
+
28
+ import { Backend, StreamSocket, ConnectionRefusedError } from '@johnhenry/browsermesh-netway'
29
+
30
+ /** Default `envelope.type` used to route relay payloads on the shared `onIncomingData()` bus. */
31
+ const DEFAULT_ENVELOPE_TYPE = 'mesh-relay'
32
+
33
+ /** Default timeout (ms) for a relay `connect` awaiting `ok`/`refused` from the host peer. */
34
+ const DEFAULT_CONNECT_TIMEOUT_MS = 15_000
35
+
36
+ // ---------------------------------------------------------------------------
37
+ // Base64 helpers (see mesh-relay-host.mjs -- same rationale, duplicated
38
+ // locally rather than shared, matching this family's existing convention of
39
+ // small self-contained per-file helpers, e.g. peer-encrypted-store.mjs).
40
+ // ---------------------------------------------------------------------------
41
+
42
+ /** @param {Uint8Array} bytes @returns {string} */
43
+ function toBase64(bytes) {
44
+ if (typeof Buffer !== 'undefined') {
45
+ return Buffer.from(bytes).toString('base64')
46
+ }
47
+ return btoa(String.fromCharCode(...bytes))
48
+ }
49
+
50
+ /** @param {string} str @returns {Uint8Array} */
51
+ function fromBase64(str) {
52
+ if (typeof Buffer !== 'undefined') {
53
+ return new Uint8Array(Buffer.from(str, 'base64'))
54
+ }
55
+ const bin = atob(str)
56
+ const bytes = new Uint8Array(bin.length)
57
+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
58
+ return bytes
59
+ }
60
+
61
+ // ---------------------------------------------------------------------------
62
+ // MeshRelayBackend
63
+ // ---------------------------------------------------------------------------
64
+
65
+ /**
66
+ * A `Backend` that relays TCP-like `connect()`s through one specific mesh
67
+ * peer's `MeshRelayHost`, over `PeerNode.sendTo()`/`onIncomingData()`.
68
+ *
69
+ * @extends Backend
70
+ */
71
+ export class MeshRelayBackend extends Backend {
72
+ /** @type {import('./peer-node.mjs').PeerNode} */
73
+ #node
74
+
75
+ /** @type {string} */
76
+ #relayPeerPubKey
77
+
78
+ /** @type {string} */
79
+ #envelopeType
80
+
81
+ /** @type {number} */
82
+ #connectTimeoutMs
83
+
84
+ /** @type {Function} */
85
+ #onLog
86
+
87
+ /** @type {Map<string, {resolve: Function, reject: Function, service: string}>} connId -> pending connect */
88
+ #pending = new Map()
89
+
90
+ /** @type {Map<string, import('@johnhenry/browsermesh-netway').StreamSocket>} connId -> relay-side socket */
91
+ #connections = new Map()
92
+
93
+ /** @type {(() => void)|null} */
94
+ #unsubscribeIncoming = null
95
+
96
+ /**
97
+ * @param {object} opts
98
+ * @param {import('./peer-node.mjs').PeerNode} opts.node
99
+ * @param {string} opts.relayPeerPubKey - The `MeshRelayHost` peer's fingerprint/pubkey.
100
+ * @param {string} [opts.envelopeType='mesh-relay']
101
+ * @param {number} [opts.connectTimeoutMs=15000] - `0` disables the timeout.
102
+ * @param {Function} [opts.onLog]
103
+ */
104
+ constructor({ node, relayPeerPubKey, envelopeType, connectTimeoutMs, onLog } = {}) {
105
+ super()
106
+ if (!node) throw new Error('node is required')
107
+ if (!relayPeerPubKey || typeof relayPeerPubKey !== 'string') {
108
+ throw new Error('relayPeerPubKey is required')
109
+ }
110
+
111
+ this.#node = node
112
+ this.#relayPeerPubKey = relayPeerPubKey
113
+ this.#envelopeType = envelopeType || DEFAULT_ENVELOPE_TYPE
114
+ this.#connectTimeoutMs = connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS
115
+ this.#onLog = onLog || (() => {})
116
+
117
+ this.#unsubscribeIncoming = this.#node.onIncomingData((pubKey, data) => {
118
+ if (pubKey !== this.#relayPeerPubKey) return
119
+ this.#handleIncoming(data).catch((err) => {
120
+ this.#onLog('mesh-relay-backend:handle-incoming-error', { error: err?.message || String(err) })
121
+ })
122
+ })
123
+ }
124
+
125
+ /** The relay-host peer this backend is bound to. */
126
+ get relayPeerPubKey() {
127
+ return this.#relayPeerPubKey
128
+ }
129
+
130
+ /** The `envelope.type` this backend routes on the shared dispatch bus. */
131
+ get envelopeType() {
132
+ return this.#envelopeType
133
+ }
134
+
135
+ // -----------------------------------------------------------------------
136
+ // Backend API
137
+ // -----------------------------------------------------------------------
138
+
139
+ /**
140
+ * Connect to a service exposed by the bound relay-host peer. `host` is
141
+ * treated as the service name (see `ServiceBackend` for the same
142
+ * precedent); `port` is ignored.
143
+ *
144
+ * @param {string} host - Service name (e.g. `'s3-local'`).
145
+ * @param {number} [port] - Ignored.
146
+ * @returns {Promise<import('@johnhenry/browsermesh-netway').StreamSocket>} The client-side socket.
147
+ * @throws {ConnectionRefusedError} If the host peer refuses (unauthorized,
148
+ * unknown service, or its own connect to the local service failed).
149
+ */
150
+ async connect(host, port) {
151
+ if (!host || typeof host !== 'string') {
152
+ throw new Error('MeshRelayBackend.connect: host (service name) is required')
153
+ }
154
+
155
+ const connId = crypto.randomUUID()
156
+ const pending = new Promise((resolve, reject) => {
157
+ this.#pending.set(connId, { resolve, reject, service: host })
158
+ })
159
+
160
+ await this.#send({ op: 'connect', connId, service: host })
161
+
162
+ if (!this.#connectTimeoutMs) return pending
163
+
164
+ let timer
165
+ const timeoutPromise = new Promise((_, reject) => {
166
+ timer = setTimeout(() => {
167
+ if (this.#pending.delete(connId)) {
168
+ reject(new Error(`MeshRelayBackend.connect: timed out waiting for '${host}' via ${this.#relayPeerPubKey}`))
169
+ }
170
+ }, this.#connectTimeoutMs)
171
+ })
172
+
173
+ try {
174
+ return await Promise.race([pending, timeoutPromise])
175
+ } finally {
176
+ clearTimeout(timer)
177
+ }
178
+ }
179
+
180
+ // -----------------------------------------------------------------------
181
+ // Inbound envelope handling
182
+ // -----------------------------------------------------------------------
183
+
184
+ /** @param {*} data */
185
+ async #handleIncoming(data) {
186
+ if (!data || typeof data !== 'object' || data.type !== this.#envelopeType) return
187
+ const { op, connId } = data
188
+ if (!connId || typeof connId !== 'string') return
189
+
190
+ if (op === 'ok') {
191
+ const pending = this.#pending.get(connId)
192
+ if (!pending) return
193
+ this.#pending.delete(connId)
194
+
195
+ const [userSocket, relaySocket] = StreamSocket.createPair()
196
+ this.#connections.set(connId, relaySocket)
197
+ this.#pumpToRemote(connId, relaySocket)
198
+ pending.resolve(userSocket)
199
+ return
200
+ }
201
+
202
+ if (op === 'refused') {
203
+ const pending = this.#pending.get(connId)
204
+ if (!pending) return
205
+ this.#pending.delete(connId)
206
+ pending.reject(new ConnectionRefusedError(
207
+ `mesh-relay://${this.#relayPeerPubKey}/${pending.service}${data.reason ? ` (${data.reason})` : ''}`,
208
+ ))
209
+ return
210
+ }
211
+
212
+ // 'data' / 'close' only act on connIds this backend itself originated
213
+ // and that are still open -- unrecognized connIds are ignored.
214
+ const relaySocket = this.#connections.get(connId)
215
+ if (!relaySocket) return
216
+
217
+ if (op === 'data') {
218
+ if (typeof data.data !== 'string') return
219
+ try {
220
+ await relaySocket.write(fromBase64(data.data))
221
+ } catch (err) {
222
+ this.#onLog('mesh-relay-backend:data:write-failed', { connId, error: err?.message || String(err) })
223
+ }
224
+ return
225
+ }
226
+
227
+ if (op === 'close') {
228
+ this.#connections.delete(connId)
229
+ try { await relaySocket.close() } catch { /* already closed */ }
230
+ }
231
+ }
232
+
233
+ /**
234
+ * Pump bytes written to the user-facing socket to the relay-host peer as
235
+ * `data` envelopes. Runs until the relay-side socket closes (the user
236
+ * closed their side), at which point the host is told via `close`.
237
+ *
238
+ * @param {string} connId
239
+ * @param {import('@johnhenry/browsermesh-netway').StreamSocket} relaySocket
240
+ */
241
+ #pumpToRemote(connId, relaySocket) {
242
+ (async () => {
243
+ try {
244
+ while (true) {
245
+ const chunk = await relaySocket.read()
246
+ if (chunk === null) break
247
+ await this.#send({ op: 'data', connId, data: toBase64(chunk) })
248
+ }
249
+ } catch (err) {
250
+ this.#onLog('mesh-relay-backend:pump:error', { connId, error: err?.message || String(err) })
251
+ }
252
+ if (this.#connections.delete(connId)) {
253
+ await this.#send({ op: 'close', connId }).catch(() => {})
254
+ }
255
+ })()
256
+ }
257
+
258
+ /** @param {object} payload */
259
+ async #send(payload) {
260
+ await this.#node.sendTo(this.#relayPeerPubKey, { type: this.#envelopeType, ...payload })
261
+ }
262
+
263
+ // -----------------------------------------------------------------------
264
+ // Teardown
265
+ // -----------------------------------------------------------------------
266
+
267
+ /**
268
+ * Detach from the `PeerNode` dispatch bus, close every open relayed
269
+ * connection, and reject any still-pending `connect()`s.
270
+ *
271
+ * @returns {Promise<void>}
272
+ */
273
+ async close() {
274
+ if (this.#unsubscribeIncoming) {
275
+ this.#unsubscribeIncoming()
276
+ this.#unsubscribeIncoming = null
277
+ }
278
+ for (const [connId, socket] of [...this.#connections]) {
279
+ this.#connections.delete(connId)
280
+ try { await socket.close() } catch { /* already closed */ }
281
+ }
282
+ for (const [connId, pending] of [...this.#pending]) {
283
+ this.#pending.delete(connId)
284
+ pending.reject(new Error('MeshRelayBackend closed'))
285
+ }
286
+ }
287
+ }
288
+
289
+ export { DEFAULT_ENVELOPE_TYPE }
@@ -0,0 +1,362 @@
1
+ /**
2
+ * mesh-relay-host.mjs -- Peer A's side of Phase 8 (mesh relay): share access
3
+ * to Peer A's own `VirtualNetwork` (`@johnhenry/browsermesh-netway`) with
4
+ * specific, authorized mesh peers.
5
+ *
6
+ * Real-world scenario this closes: Peer A runs a local service (e.g. an
7
+ * S3-compatible emulator) plus a `wsh` server, and already reaches that
8
+ * service via `browsermesh-netway`'s `GatewayBackend` on its own
9
+ * `VirtualNetwork` (wsh-tunneled TCP, confirmed real and working -- zero new
10
+ * work needed there). `MeshRelayHost` lets Peer A additionally share that
11
+ * *reachability* with other mesh peers, gated per-peer/per-service, without
12
+ * those peers needing their own wsh connection at all.
13
+ *
14
+ * Follows `mesh-sync.mjs`'s proven pattern exactly: a composition file that
15
+ * subscribes to `PeerNode.onIncomingData()`, filters on `envelope.type`
16
+ * (default `'mesh-relay'`), and sends replies via `node.sendTo()`. Modeled
17
+ * on `browsermesh-netway`'s `GatewayBackend` connect/data/close/multiplex
18
+ * shape, carried over `PeerNode.sendTo()`/`onIncomingData()` (JSON envelopes,
19
+ * base64-encoded byte payloads) instead of wsh's binary control protocol --
20
+ * no new dependency, zero changes to `browsermesh-netway` itself.
21
+ *
22
+ * `MeshRelayHost` never dials out over the mesh itself; it only responds to
23
+ * inbound `mesh-relay` envelopes. `exposeService()`/`hideService()` is a
24
+ * small local `Map` -- deliberately NOT `browsermesh-kernel`'s
25
+ * `ServiceRegistry` (same-process, no peer/mesh awareness, wrong tool for a
26
+ * cross-peer relationship).
27
+ *
28
+ * Authorization: each inbound `connect` is checked via
29
+ * `registry.checkAccess(fromPubKey, 'mesh-relay:' + service, 'connect')` --
30
+ * `PeerRegistry`'s existing `grantCapabilities()`/`revokeCapabilities()`/
31
+ * `checkAccess()`, zero API or schema changes. This composes a 3-segment
32
+ * `namespace:resource:action` scope (`mesh-relay:<service>:connect`) that
33
+ * the real `MeshACL`/`matchScope()` grammar already parses cleanly, wildcards
34
+ * included (e.g. `mesh-relay:*:connect`, `mesh-relay:s3-local:*`).
35
+ *
36
+ * Connections are keyed by `(fromPubKey, connId)` so concurrent peers can't
37
+ * collide or spoof-close each other's sessions.
38
+ *
39
+ * Kernel involvement: explicitly none -- this is a peer-relationship
40
+ * decision ("Peer A trusts Peer B to relay to this service"), orthogonal to
41
+ * the kernel-mesh capability that gates tenant-code network access.
42
+ *
43
+ * No browser-only imports at module level.
44
+ */
45
+
46
+ /** Default `envelope.type` used to route relay payloads on the shared `onIncomingData()` bus. */
47
+ const DEFAULT_ENVELOPE_TYPE = 'mesh-relay'
48
+
49
+ // ---------------------------------------------------------------------------
50
+ // Base64 helpers (mirrors peer-encrypted-store.mjs's Buffer-first, btoa/atob
51
+ // fallback -- PeerNode.sendTo() JSON-serializes envelopes, so raw byte
52
+ // payloads must travel as base64 strings, not Uint8Array).
53
+ // ---------------------------------------------------------------------------
54
+
55
+ /** @param {Uint8Array} bytes @returns {string} */
56
+ function toBase64(bytes) {
57
+ if (typeof Buffer !== 'undefined') {
58
+ return Buffer.from(bytes).toString('base64')
59
+ }
60
+ return btoa(String.fromCharCode(...bytes))
61
+ }
62
+
63
+ /** @param {string} str @returns {Uint8Array} */
64
+ function fromBase64(str) {
65
+ if (typeof Buffer !== 'undefined') {
66
+ return new Uint8Array(Buffer.from(str, 'base64'))
67
+ }
68
+ const bin = atob(str)
69
+ const bytes = new Uint8Array(bin.length)
70
+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
71
+ return bytes
72
+ }
73
+
74
+ // ---------------------------------------------------------------------------
75
+ // MeshRelayHost
76
+ // ---------------------------------------------------------------------------
77
+
78
+ /**
79
+ * Binds Peer A's `VirtualNetwork` to its `PeerNode`'s dispatch bus, exposing
80
+ * named services to specific, authorized mesh peers.
81
+ */
82
+ export class MeshRelayHost {
83
+ /** @type {import('./peer-node.mjs').PeerNode} */
84
+ #node
85
+
86
+ /** @type {import('@johnhenry/browsermesh-netway').VirtualNetwork} */
87
+ #network
88
+
89
+ /** @type {import('./peer-registry.mjs').PeerRegistry} */
90
+ #registry
91
+
92
+ /** @type {string} */
93
+ #envelopeType
94
+
95
+ /** @type {Function} */
96
+ #onLog
97
+
98
+ /** @type {Map<string, string>} service name -> target address (e.g. `'mem://localhost:8080'`) */
99
+ #services = new Map()
100
+
101
+ /** @type {Map<string, {socket: object, fromPubKey: string, connId: string, service: string}>}
102
+ * key: `${fromPubKey}::${connId}` */
103
+ #connections = new Map()
104
+
105
+ /** @type {(() => void)|null} */
106
+ #unsubscribeIncoming = null
107
+
108
+ /**
109
+ * @param {object} opts
110
+ * @param {import('./peer-node.mjs').PeerNode} opts.node
111
+ * @param {import('@johnhenry/browsermesh-netway').VirtualNetwork} opts.network
112
+ * Peer A's own, already-configured `VirtualNetwork` (e.g. with a
113
+ * `GatewayBackend` registered for real TCP via wsh).
114
+ * @param {import('./peer-registry.mjs').PeerRegistry} opts.registry
115
+ * @param {string} [opts.envelopeType='mesh-relay']
116
+ * @param {Function} [opts.onLog]
117
+ */
118
+ constructor({ node, network, registry, envelopeType, onLog } = {}) {
119
+ if (!node) throw new Error('node is required')
120
+ if (!network) throw new Error('network is required')
121
+ if (!registry) throw new Error('registry is required')
122
+
123
+ this.#node = node
124
+ this.#network = network
125
+ this.#registry = registry
126
+ this.#envelopeType = envelopeType || DEFAULT_ENVELOPE_TYPE
127
+ this.#onLog = onLog || (() => {})
128
+
129
+ this.#unsubscribeIncoming = this.#node.onIncomingData((pubKey, data) => {
130
+ this.#handleIncoming(pubKey, data).catch((err) => {
131
+ this.#onLog('mesh-relay-host:handle-incoming-error', { error: err?.message || String(err) })
132
+ })
133
+ })
134
+ }
135
+
136
+ /** The `envelope.type` this host routes on the shared dispatch bus. */
137
+ get envelopeType() {
138
+ return this.#envelopeType
139
+ }
140
+
141
+ // -----------------------------------------------------------------------
142
+ // Service exposure
143
+ // -----------------------------------------------------------------------
144
+
145
+ /**
146
+ * Expose a named service to authorized mesh peers. `targetAddress` is any
147
+ * address `network.connect()` understands (e.g. `'mem://localhost:8080'`,
148
+ * or a `tcp://` address routed through a `GatewayBackend`).
149
+ *
150
+ * @param {string} name
151
+ * @param {string} targetAddress
152
+ */
153
+ exposeService(name, targetAddress) {
154
+ if (!name || typeof name !== 'string') {
155
+ throw new Error('MeshRelayHost.exposeService: name is required')
156
+ }
157
+ if (!targetAddress || typeof targetAddress !== 'string') {
158
+ throw new Error('MeshRelayHost.exposeService: targetAddress is required')
159
+ }
160
+ this.#services.set(name, targetAddress)
161
+ this.#onLog('mesh-relay-host:service:exposed', { name, targetAddress })
162
+ }
163
+
164
+ /**
165
+ * Stop exposing a previously-exposed service. Already-open connections to
166
+ * it are left alone; only new `connect` attempts are affected.
167
+ *
168
+ * @param {string} name
169
+ * @returns {boolean} true if the service was exposed
170
+ */
171
+ hideService(name) {
172
+ const had = this.#services.delete(name)
173
+ if (had) this.#onLog('mesh-relay-host:service:hidden', { name })
174
+ return had
175
+ }
176
+
177
+ /** @returns {string[]} Names of currently exposed services. */
178
+ listServices() {
179
+ return [...this.#services.keys()]
180
+ }
181
+
182
+ // -----------------------------------------------------------------------
183
+ // Inbound envelope handling
184
+ // -----------------------------------------------------------------------
185
+
186
+ /** @param {string} fromPubKey @param {string} connId @returns {string} */
187
+ #key(fromPubKey, connId) {
188
+ return `${fromPubKey}::${connId}`
189
+ }
190
+
191
+ /**
192
+ * @param {string} fromPubKey
193
+ * @param {*} data
194
+ */
195
+ async #handleIncoming(fromPubKey, data) {
196
+ if (!data || typeof data !== 'object' || data.type !== this.#envelopeType) return
197
+ const { op, connId } = data
198
+ if (!connId || typeof connId !== 'string') return
199
+
200
+ if (op === 'connect') {
201
+ await this.#handleConnect(fromPubKey, connId, data.service)
202
+ return
203
+ }
204
+
205
+ // 'data' / 'close' only act on connections this host itself accepted
206
+ // for this exact (fromPubKey, connId) pair -- unknown/foreign connIds
207
+ // are silently ignored rather than acted on, so a peer can't spoof-close
208
+ // or inject data into another peer's session.
209
+ const key = this.#key(fromPubKey, connId)
210
+ const conn = this.#connections.get(key)
211
+ if (!conn) return
212
+
213
+ if (op === 'data') {
214
+ await this.#handleData(conn, data.data)
215
+ } else if (op === 'close') {
216
+ await this.#closeConnection(key, conn, { notifyPeer: false })
217
+ }
218
+ }
219
+
220
+ /**
221
+ * @param {string} fromPubKey
222
+ * @param {string} connId
223
+ * @param {*} service
224
+ */
225
+ async #handleConnect(fromPubKey, connId, service) {
226
+ if (!service || typeof service !== 'string') {
227
+ await this.#refuse(fromPubKey, connId, 'invalid service')
228
+ return
229
+ }
230
+
231
+ const { allowed } = this.#registry.checkAccess(fromPubKey, `mesh-relay:${service}`, 'connect')
232
+ if (!allowed) {
233
+ this.#onLog('mesh-relay-host:connect:denied', { fromPubKey, service, connId })
234
+ await this.#refuse(fromPubKey, connId, 'access denied')
235
+ return
236
+ }
237
+
238
+ const targetAddress = this.#services.get(service)
239
+ if (!targetAddress) {
240
+ // Explicit refusal, never a silent no-op -- an unknown service must
241
+ // never be treated as "connect to nothing" / a dangling success.
242
+ this.#onLog('mesh-relay-host:connect:unknown-service', { fromPubKey, service, connId })
243
+ await this.#refuse(fromPubKey, connId, 'unknown service')
244
+ return
245
+ }
246
+
247
+ let socket
248
+ try {
249
+ socket = await this.#network.connect(targetAddress)
250
+ } catch (err) {
251
+ this.#onLog('mesh-relay-host:connect:failed', {
252
+ fromPubKey, service, connId, error: err?.message || String(err),
253
+ })
254
+ await this.#refuse(fromPubKey, connId, 'connect failed')
255
+ return
256
+ }
257
+
258
+ const key = this.#key(fromPubKey, connId)
259
+ const conn = { socket, fromPubKey, connId, service }
260
+ this.#connections.set(key, conn)
261
+ this.#pumpToRemote(key, conn)
262
+
263
+ await this.#send(fromPubKey, { op: 'ok', connId })
264
+ this.#onLog('mesh-relay-host:connect:ok', { fromPubKey, service, connId })
265
+ }
266
+
267
+ /**
268
+ * @param {{socket: object}} conn
269
+ * @param {*} base64Data
270
+ */
271
+ async #handleData(conn, base64Data) {
272
+ if (typeof base64Data !== 'string') return
273
+ try {
274
+ await conn.socket.write(fromBase64(base64Data))
275
+ } catch (err) {
276
+ this.#onLog('mesh-relay-host:data:write-failed', {
277
+ connId: conn.connId, error: err?.message || String(err),
278
+ })
279
+ }
280
+ }
281
+
282
+ /**
283
+ * Pump bytes read from the local service socket back to the remote peer as
284
+ * `data` envelopes. Runs until the local socket closes (natural EOF) or
285
+ * errors, at which point the remote peer is told via a `close` envelope.
286
+ *
287
+ * @param {string} key
288
+ * @param {{socket: object, fromPubKey: string, connId: string}} conn
289
+ */
290
+ #pumpToRemote(key, conn) {
291
+ (async () => {
292
+ try {
293
+ while (true) {
294
+ const chunk = await conn.socket.read()
295
+ if (chunk === null) break // local service closed the connection (EOF)
296
+ await this.#send(conn.fromPubKey, {
297
+ op: 'data',
298
+ connId: conn.connId,
299
+ data: toBase64(chunk),
300
+ })
301
+ }
302
+ } catch (err) {
303
+ this.#onLog('mesh-relay-host:pump:error', { connId: conn.connId, error: err?.message || String(err) })
304
+ }
305
+ await this.#closeConnection(key, conn, { notifyPeer: true })
306
+ })()
307
+ }
308
+
309
+ /**
310
+ * @param {string} key
311
+ * @param {{socket: object, fromPubKey: string, connId: string}} conn
312
+ * @param {{notifyPeer: boolean}} opts
313
+ */
314
+ async #closeConnection(key, conn, { notifyPeer }) {
315
+ if (!this.#connections.has(key)) return
316
+ this.#connections.delete(key)
317
+ try { await conn.socket.close() } catch { /* already closed */ }
318
+ if (notifyPeer) {
319
+ await this.#send(conn.fromPubKey, { op: 'close', connId: conn.connId }).catch(() => {})
320
+ }
321
+ this.#onLog('mesh-relay-host:connection:closed', { connId: conn.connId, fromPubKey: conn.fromPubKey })
322
+ }
323
+
324
+ /**
325
+ * @param {string} fromPubKey
326
+ * @param {string} connId
327
+ * @param {string} reason
328
+ */
329
+ async #refuse(fromPubKey, connId, reason) {
330
+ await this.#send(fromPubKey, { op: 'refused', connId, reason }).catch(() => {})
331
+ }
332
+
333
+ /**
334
+ * @param {string} pubKey
335
+ * @param {object} payload
336
+ */
337
+ async #send(pubKey, payload) {
338
+ await this.#node.sendTo(pubKey, { type: this.#envelopeType, ...payload })
339
+ }
340
+
341
+ // -----------------------------------------------------------------------
342
+ // Teardown
343
+ // -----------------------------------------------------------------------
344
+
345
+ /**
346
+ * Detach from the `PeerNode` dispatch bus and close every currently
347
+ * relayed connection. Does not close `network` itself (the host doesn't
348
+ * own its lifecycle).
349
+ */
350
+ async detach() {
351
+ if (this.#unsubscribeIncoming) {
352
+ this.#unsubscribeIncoming()
353
+ this.#unsubscribeIncoming = null
354
+ }
355
+ for (const [key, conn] of [...this.#connections]) {
356
+ this.#connections.delete(key)
357
+ try { await conn.socket.close() } catch { /* already closed */ }
358
+ }
359
+ }
360
+ }
361
+
362
+ export { DEFAULT_ENVELOPE_TYPE }