@johnhenry/browsermesh-apps 0.2.0 → 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 (41) hide show
  1. package/README.md +232 -1
  2. package/package.json +2 -2
  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/grant-log.mjs +840 -0
  9. package/src/index.mjs +25 -2
  10. package/src/key-distribution.mjs +525 -0
  11. package/src/manifest-sync.mjs +363 -0
  12. package/src/mesh-agent-swarm.mjs +376 -0
  13. package/src/mesh-bootstrap.mjs +1131 -12
  14. package/src/mesh-compute.mjs +397 -0
  15. package/src/mesh-dht.mjs +182 -0
  16. package/src/mesh-fetch.mjs +246 -0
  17. package/src/mesh-hardening.mjs +226 -0
  18. package/src/mesh-health.mjs +282 -0
  19. package/src/mesh-keepalive.mjs +353 -0
  20. package/src/mesh-kv.mjs +673 -0
  21. package/src/mesh-orchestrator-tools.mjs +251 -0
  22. package/src/mesh-orchestrator.mjs +343 -0
  23. package/src/mesh-rpc.mjs +300 -0
  24. package/src/mesh-service.mjs +403 -0
  25. package/src/mesh-swarm.mjs +677 -0
  26. package/src/mesh-timestamp.mjs +265 -0
  27. package/src/mesh-torrent.mjs +683 -0
  28. package/src/mesh-verification.mjs +367 -0
  29. package/src/mesh-websocket.mjs +722 -0
  30. package/src/observability-bridge.mjs +453 -0
  31. package/src/orchestrator.mjs +18 -5
  32. package/src/peer-agent-swarm.mjs +12 -1
  33. package/src/peer-chat.mjs +230 -61
  34. package/src/peer-compute.mjs +66 -3
  35. package/src/peer-escrow.mjs +350 -1
  36. package/src/peer-files.mjs +362 -168
  37. package/src/peer-ipfs.mjs +205 -10
  38. package/src/peer-node.mjs +33 -2
  39. package/src/peer-routing.mjs +369 -5
  40. package/src/peer-terminal.mjs +400 -130
  41. package/src/peer-session.mjs +0 -937
@@ -0,0 +1,722 @@
1
+ /**
2
+ * mesh-websocket.mjs -- Phase 3 of the BrowserMeshFetch/BrowserMeshWebSocket
3
+ * plan (`browsermesh-fetch-websocket.md`; independent of, and does not
4
+ * import, Phase 2's `mesh-fetch.mjs` -- both depend only on the same
5
+ * `MeshService` convention and `parseMeshRequest()`, not on each other).
6
+ *
7
+ * Provides `BrowserMeshWebSocket`, a class implementing the standard
8
+ * `WebSocket` INSTANCE surface (`readyState`, `url`, `onopen`/`onmessage`/
9
+ * `onerror`/`onclose`, `addEventListener`/`removeEventListener`, `send()`,
10
+ * `close()`) over a persistent envelope channel addressed by podId, using
11
+ * `mesh://podId/path`-shaped URLs parsed via
12
+ * `@johnhenry/browsermesh-discovery`'s `parseMeshRequest()` (the same parser
13
+ * `sw-routing.mjs`'s `MeshFetchRouter` and Phase 2's `browserMeshFetch()`
14
+ * both use), and `createMeshWebSocketService()`, a `MeshService` (Phase C,
15
+ * `mesh-service.mjs`) that lets a pod ACCEPT inbound connections.
16
+ *
17
+ * ---------------------------------------------------------------------------
18
+ * DEVIATION FROM THE REAL `WebSocket` CONSTRUCTOR (stated up front, per the
19
+ * plan's own framing -- "make the deviation as small and sensible as
20
+ * possible"): a real `new WebSocket(url, protocols)` needs no extra
21
+ * arguments because the browser's networking stack is a process-wide
22
+ * ambient resource. There is no equivalent ambient mesh connection here --
23
+ * `new BrowserMeshWebSocket(url, opts)` therefore requires
24
+ * `opts.peerNode`, a duck-typed object exposing `podId`, `sendTo(pubKey,
25
+ * data)`, and `onIncomingData(cb)` (exactly the subset of the real
26
+ * `PeerNode`'s API this family's other `MeshService`s/tests already rely on
27
+ * -- see `mesh-rpc.mjs`'s test fixtures). This is the ONE required
28
+ * deviation; everything else on the constructed instance matches the
29
+ * standard `WebSocket` instance shape as closely as this transport allows.
30
+ * `opts` also accepts:
31
+ * - `headers` (object, default `{}`) -- forwarded as connection metadata
32
+ * on the open handshake, mirroring `mesh-rpc.mjs`'s `headers` field.
33
+ * - `envelopeType` (string, default `'mesh-websocket'`) -- the shared
34
+ * `onIncomingData()` dispatch-bus `type`, matching every other
35
+ * `MeshService` in this family.
36
+ * - `openTimeoutMs` (number, default 10000) -- see "OPEN TIMEOUT" below.
37
+ * - `connectionId` (string, optional) -- override the generated
38
+ * correlation id; only useful for tests wanting deterministic ids.
39
+ *
40
+ * NOTE: unlike every OTHER `MeshService` in this family, a client-role
41
+ * `BrowserMeshWebSocket` does NOT need `createMeshWebSocketService()`
42
+ * attached on the CALLING peer at all -- it subscribes directly to
43
+ * `peerNode.onIncomingData()` and calls `peerNode.sendTo()` itself,
44
+ * filtering by its own `connectionId` (the same envelope-type + extra-field
45
+ * filtering `mesh-service.mjs`'s `ctx.onIncomingData()` does for `type`
46
+ * alone, just one field finer-grained). This keeps `new
47
+ * BrowserMeshWebSocket(url, {peerNode})` usable standalone, matching real
48
+ * `new WebSocket(url)` usage as closely as possible -- a caller should not
49
+ * have to separately construct and attach a `MeshService` just to originate
50
+ * an outbound connection. The RESPONDING side, in contrast, genuinely needs
51
+ * `createMeshWebSocketService({onConnection})` attached, because deciding
52
+ * whether to accept an INBOUND connection this peer didn't initiate is
53
+ * exactly the kind of policy decision every other `MeshService` in this
54
+ * family (`onRequest`, `onGrantChange`, etc.) also delegates to a
55
+ * caller-supplied hook rather than deciding unilaterally.
56
+ *
57
+ * ---------------------------------------------------------------------------
58
+ * WIRE PROTOCOL -- one envelope `type` (default `'mesh-websocket'`), five
59
+ * message `kind`s, every message carrying the `connectionId` that
60
+ * correlates it to one logical connection (generated by the connection's
61
+ * ORIGINATOR -- the client -- exactly like `mesh-rpc.mjs`'s `requestId`):
62
+ *
63
+ * Open handshake (client -> target podId), sent once at construction:
64
+ * `{ type, kind: 'ws-open', connectionId, path, headers }`
65
+ *
66
+ * Accept (target -> client), sent once the target's `onConnection` hook
67
+ * returns/resolves truthy:
68
+ * `{ type, kind: 'ws-open-ack', connectionId }`
69
+ *
70
+ * Reject (target -> client), sent once `onConnection` returns/resolves
71
+ * falsy, throws, or is not registered at all (see "NO onConnection
72
+ * HANDLER" below):
73
+ * `{ type, kind: 'ws-reject', connectionId, code, reason }`
74
+ *
75
+ * Message (either direction, free-form, any number of times once OPEN):
76
+ * `{ type, kind: 'ws-message', connectionId, encoding: 'text'|'binary', data }`
77
+ * -- see "BINARY ENCODING" below for what `data` holds under each
78
+ * `encoding`.
79
+ *
80
+ * Close (either direction, at most meaningfully once per side):
81
+ * `{ type, kind: 'ws-close', connectionId, code, reason }`
82
+ * -- ONE-DIRECTIONAL notification, not a two-phase closing handshake
83
+ * like real WebSocket's (client FIN / server FIN / TCP close). The
84
+ * side that calls `close()` sends this envelope best-effort (a send
85
+ * failure, e.g. the peer already disconnected, is swallowed -- there
86
+ * is nothing further to do) and transitions itself to `CLOSED`
87
+ * immediately afterward, without waiting for any acknowledgement.
88
+ * The receiving side transitions to `CLOSED` the moment this envelope
89
+ * arrives. This is the plan's own explicitly sanctioned "keep it
90
+ * minimal" choice (see the plan's Phase 3 section: "mirrors
91
+ * grant-log.mjs's [...] initial exchange only if a real security need
92
+ * is identified -- otherwise keep it minimal"): no real security
93
+ * property depends on a slower, acknowledged close, and a persistent
94
+ * mesh envelope channel has no TCP-level half-open state to model in
95
+ * the first place.
96
+ *
97
+ * ---------------------------------------------------------------------------
98
+ * ACCEPT/REJECT HANDSHAKE AND AUTHORIZATION (mirrors `mesh-rpc.mjs`'s own
99
+ * stance almost exactly): `createMeshWebSocketService({onConnection})`'s
100
+ * `onConnection(fromPubKey, path) -> boolean|Promise<boolean>` hook is the
101
+ * ONLY place accept/reject policy lives. This file does not check
102
+ * `registry.checkAccess()` against any fixed resource/scope -- like
103
+ * mesh-RPC, a persistent duplex channel has no fixed resource this
104
+ * transport could hardcode a scope for; deciding which `(fromPubKey, path)`
105
+ * combinations are acceptable is the RESPONDING POD's own concern, not this
106
+ * transport's, exactly mirroring `mesh-rpc.mjs`'s "authorization is
107
+ * explicitly out of scope for this transport" stance. A caller that needs
108
+ * ACL-gated WebSocket connections should implement that inside its own
109
+ * `onConnection` (e.g. calling `ctx.registry.checkAccess()` itself).
110
+ *
111
+ * NO onConnection HANDLER REGISTERED: every inbound `ws-open` is REJECTED
112
+ * (`ws-reject` with `reason: 'no onConnection handler registered'`),
113
+ * deliberately the OPPOSITE default from `mesh-rpc.mjs`'s missing-handler
114
+ * behavior (which answers `501`, i.e. "here, but nothing implemented") --
115
+ * a WebSocket service with no accept policy at all should not silently
116
+ * accept every inbound connection (an "open door" is a materially worse
117
+ * default than an RPC transport answering "not implemented" to plain
118
+ * request/response calls), so REJECT is the safe default here, still
119
+ * explicit/discoverable rather than a silent hang. `onConnection` THROWING
120
+ * is treated the same as returning falsy -- rejected, never an unhandled
121
+ * rejection, never a crash of the shared `ctx.onIncomingData()` dispatch
122
+ * loop (mirrors `mesh-rpc.mjs`'s `onRequest`-threw handling).
123
+ *
124
+ * ---------------------------------------------------------------------------
125
+ * BINARY ENCODING (the plan's explicit ask: "decide how you encode binary
126
+ * payloads over the JSON envelope, e.g. base64, matching
127
+ * chunk-replication.mjs's established convention"): `send(data)` accepts a
128
+ * `string`, an `ArrayBuffer`, or an `ArrayBuffer` view (any `TypedArray` or
129
+ * `DataView`) -- NOT a `Blob` (a deliberate, documented gap: `Blob` has no
130
+ * universal synchronous-encode story and this class is meant to run
131
+ * identically in Node test environments and browsers; a caller holding a
132
+ * `Blob` should `await blob.arrayBuffer()` first, exactly the same
133
+ * conversion a caller would need for `fetch()`'s body in a
134
+ * `Content-Length`-aware context anyway). A string is sent as
135
+ * `{encoding: 'text', data: theString}` verbatim; binary input is
136
+ * base64-encoded into `{encoding: 'binary', data: base64String}`, using the
137
+ * exact same `toBase64`/`fromBase64` helper shape `chunk-replication.mjs`
138
+ * duplicates per-file rather than sharing (this family's established
139
+ * convention for this one small helper -- see that file's own doc comment).
140
+ * On receipt, a `'text'` message's event `.data` is the string verbatim; a
141
+ * `'binary'` message's event `.data` is a freshly-allocated `ArrayBuffer`
142
+ * (this class's `binaryType` is always effectively `'arraybuffer'` -- there
143
+ * is no `Blob` reconstruction and no `binaryType` property to reconfigure
144
+ * that, another explicit, documented gap versus real `WebSocket`, which
145
+ * defaults to `'blob'`).
146
+ *
147
+ * ---------------------------------------------------------------------------
148
+ * `send()` BEFORE OPEN THROWS; `send()` AFTER CLOSE ALSO THROWS (both
149
+ * documented choices, not oversights):
150
+ *
151
+ * - Before OPEN (`readyState === CONNECTING`): throws a
152
+ * `DOMException`/`Error` named `'InvalidStateError'`, EXACTLY matching
153
+ * real `WebSocket.send()`'s actual behavior (the WHATWG spec mandates
154
+ * this).
155
+ * - After CLOSE (`readyState === CLOSING` or `CLOSED`): ALSO throws the
156
+ * same `InvalidStateError`. This is a DELIBERATE DEVIATION from the
157
+ * WHATWG spec, per this phase's own explicit brief ("matching real
158
+ * WebSocket's actual behavior of throwing InvalidStateError if called
159
+ * before OPEN, not silently dropping" for the before-OPEN case, and
160
+ * separately, "calling send() after CLOSE throws/rejects rather than
161
+ * silently doing nothing" for the after-CLOSE case) -- real browsers
162
+ * silently drop a post-close `send()` (per spec: "If this's ready state
163
+ * is CLOSING or CLOSED, then return"), which this phase's brief judged
164
+ * a worse default for mesh code than a loud, discoverable throw. Stated
165
+ * explicitly here so nobody mistakes this for a spec-compliance bug.
166
+ *
167
+ * ---------------------------------------------------------------------------
168
+ * OPEN TIMEOUT: if no `ws-open-ack`/`ws-reject` arrives within
169
+ * `openTimeoutMs` (default 10000ms, matching `mesh-rpc.mjs`'s
170
+ * `DEFAULT_REQUEST_TIMEOUT_MS` reasoning exactly -- generous enough for a
171
+ * legitimately slow `onConnection` hook, short enough not to hang a caller
172
+ * indefinitely), the connection fires `onerror` then `onclose` with code
173
+ * `1006` (`CLOSE_ABNORMAL`, the same code real `WebSocket` uses for a
174
+ * connection that never completed its opening handshake) and `reason: 'open
175
+ * handshake timed out'`, and transitions straight from `CONNECTING` to
176
+ * `CLOSED` (there is no meaningful `CLOSING` state for a connection that
177
+ * never opened).
178
+ *
179
+ * A `ws-reject` response instead fires `onerror` then `onclose` with code
180
+ * `4403` (a private-use code in RFC 6455's `4000-4999` application-reserved
181
+ * range -- chosen to loosely echo HTTP 403 Forbidden without claiming an
182
+ * IANA-registered meaning it doesn't have) and whatever `reason` the
183
+ * responder's `ws-reject` carried.
184
+ *
185
+ * ---------------------------------------------------------------------------
186
+ * Observability events (`ctx.emit()`, Phase 1 of the mesh-KV-and-
187
+ * observability plan -- see `mesh-service.mjs`'s module doc comment for the
188
+ * full convention this follows). Only meaningful on the ACCEPTING side
189
+ * (`createMeshWebSocketService()`'s `attach()`) -- a standalone,
190
+ * client-originated `BrowserMeshWebSocket` has no `ctx` of its own (see
191
+ * "NOTE" above: it deliberately doesn't need `createMeshWebSocketService`
192
+ * attached at all), so it cannot emit anything through this convention.
193
+ * Three curated events:
194
+ *
195
+ * - `mesh-websocket:connection-opened` `{from, path, connectionId}` -- an
196
+ * inbound `ws-open` was accepted and the session handle was handed to
197
+ * `onIncomingConnection` (before the ack is even sent -- see that
198
+ * handler's own ordering comment).
199
+ * - `mesh-websocket:connection-rejected` `{from, path, connectionId, reason}`
200
+ * -- an inbound `ws-open` was rejected, whether by a real `onConnection`
201
+ * decision, a thrown `onConnection`, or the "no handler registered"
202
+ * default.
203
+ * - `mesh-websocket:connection-closed` `{from, path, connectionId, code,
204
+ * reason}` -- an accepted session transitioned to `CLOSED`, from either
205
+ * side (this peer's own `close()` or a received `ws-close`).
206
+ *
207
+ * No browser-only imports at module level.
208
+ */
209
+
210
+ import { parseMeshRequest } from '@johnhenry/browsermesh-discovery'
211
+
212
+ /** Default `envelope.type` used to route mesh-websocket payloads on the shared `onIncomingData()` bus. */
213
+ const DEFAULT_ENVELOPE_TYPE = 'mesh-websocket'
214
+
215
+ /** See this file's module doc comment's "OPEN TIMEOUT" section. */
216
+ const DEFAULT_OPEN_TIMEOUT_MS = 10000
217
+
218
+ /** Standard `WebSocket.readyState` numeric values. */
219
+ const CONNECTING = 0
220
+ const OPEN = 1
221
+ const CLOSING = 2
222
+ const CLOSED = 3
223
+
224
+ /**
225
+ * Internal-only construction flag, used by `createMeshWebSocketService()`'s
226
+ * `attach()` to build an already-`OPEN` session handle for an ACCEPTED
227
+ * inbound connection, without duplicating this class's send/close/event
228
+ * machinery in a second class. Not exported -- external callers cannot
229
+ * pass this key, so `new BrowserMeshWebSocket(url, opts)` always goes
230
+ * through the normal client-originates-a-connection path documented above.
231
+ */
232
+ const ACCEPTED_SESSION = Symbol('mesh-websocket:accepted-session')
233
+
234
+ // ---------------------------------------------------------------------------
235
+ // Base64 helpers -- deliberately duplicated rather than shared, matching
236
+ // this family's established convention of small, self-contained per-file
237
+ // helpers (see chunk-replication.mjs's / cloud-storage-backend.mjs's own
238
+ // identical duplication).
239
+ // ---------------------------------------------------------------------------
240
+
241
+ /** @param {Uint8Array} bytes @returns {string} */
242
+ function toBase64(bytes) {
243
+ if (typeof Buffer !== 'undefined') return Buffer.from(bytes).toString('base64')
244
+ let bin = ''
245
+ for (const b of bytes) bin += String.fromCharCode(b)
246
+ return btoa(bin)
247
+ }
248
+
249
+ /** @param {string} str @returns {Uint8Array} */
250
+ function fromBase64(str) {
251
+ if (typeof Buffer !== 'undefined') return new Uint8Array(Buffer.from(str, 'base64'))
252
+ const bin = atob(str)
253
+ const bytes = new Uint8Array(bin.length)
254
+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
255
+ return bytes
256
+ }
257
+
258
+ /** @param {Uint8Array} bytes @returns {ArrayBuffer} A fresh, tightly-sized ArrayBuffer (never a view into a larger/pooled buffer). */
259
+ function toFreshArrayBuffer(bytes) {
260
+ return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength)
261
+ }
262
+
263
+ /**
264
+ * @param {string} message
265
+ * @returns {Error} A `DOMException`-shaped `'InvalidStateError'`, matching
266
+ * what real `WebSocket.send()` throws, with a plain-`Error` fallback for
267
+ * environments with no global `DOMException` (older Node).
268
+ */
269
+ function invalidStateError(message) {
270
+ if (typeof DOMException !== 'undefined') return new DOMException(message, 'InvalidStateError')
271
+ const err = new Error(message)
272
+ err.name = 'InvalidStateError'
273
+ return err
274
+ }
275
+
276
+ /** Monotonic-ish unique id for correlating a connection's envelopes, matching mesh-rpc.mjs's nextRequestId() shape. */
277
+ function nextConnectionId(podId) {
278
+ return `${podId || 'local'}:${Date.now()}:${Math.random().toString(36).slice(2, 10)}`
279
+ }
280
+
281
+ // ---------------------------------------------------------------------------
282
+ // BrowserMeshWebSocket
283
+ // ---------------------------------------------------------------------------
284
+
285
+ /**
286
+ * A standard-`WebSocket`-instance-shaped class over a persistent mesh
287
+ * envelope channel. See this file's module doc comment for the full
288
+ * wire-protocol/binary-encoding/send-semantics writeup.
289
+ */
290
+ export class BrowserMeshWebSocket {
291
+ static CONNECTING = CONNECTING
292
+ static OPEN = OPEN
293
+ static CLOSING = CLOSING
294
+ static CLOSED = CLOSED
295
+
296
+ /** @type {{podId?: string, sendTo: Function, onIncomingData: Function}} */
297
+ #peerNode
298
+ /** @type {string} */
299
+ #envelopeType
300
+ /** @type {string} */
301
+ #connectionId
302
+ /** @type {string} Target/remote podId this connection is with. */
303
+ #remotePodId
304
+ /** @type {string} */
305
+ #path
306
+ /** @type {(() => void)|null} */
307
+ #unsubscribe = null
308
+ /** @type {number} */
309
+ #readyState = CONNECTING
310
+ /** @type {ReturnType<typeof setTimeout>|null} */
311
+ #openTimer = null
312
+ /** @type {Record<string, Set<Function>>} */
313
+ #listeners = { open: new Set(), message: new Set(), error: new Set(), close: new Set() }
314
+
315
+ /** Settable standard event-handler properties, matching real `WebSocket`. */
316
+ onopen = null
317
+ onmessage = null
318
+ onerror = null
319
+ onclose = null
320
+
321
+ /**
322
+ * @param {string} url - `mesh://podId/path`-shaped (or `https://podId.mesh.local/path`),
323
+ * parsed via `parseMeshRequest()`. Ignored on the internal accepted-session path.
324
+ * @param {object} opts
325
+ * @param {{podId?: string, sendTo: (pubKey: string, data: object) => Promise<void>,
326
+ * onIncomingData: (cb: (pubKey: string, data: object) => void) => (() => void)}} opts.peerNode
327
+ * Required (unless constructing via the internal accepted-session path).
328
+ * @param {object} [opts.headers]
329
+ * @param {string} [opts.envelopeType='mesh-websocket']
330
+ * @param {number} [opts.openTimeoutMs=10000]
331
+ * @param {string} [opts.connectionId]
332
+ */
333
+ constructor(url, opts = {}) {
334
+ if (opts[ACCEPTED_SESSION]) {
335
+ const { peerNode, envelopeType, connectionId, remotePodId, path } = opts[ACCEPTED_SESSION]
336
+ this.url = url
337
+ this.#peerNode = peerNode
338
+ this.#envelopeType = envelopeType
339
+ this.#connectionId = connectionId
340
+ this.#remotePodId = remotePodId
341
+ this.#path = path
342
+ this.#readyState = OPEN
343
+ this.#subscribe()
344
+ return
345
+ }
346
+
347
+ const {
348
+ peerNode,
349
+ headers = {},
350
+ envelopeType = DEFAULT_ENVELOPE_TYPE,
351
+ openTimeoutMs = DEFAULT_OPEN_TIMEOUT_MS,
352
+ connectionId,
353
+ } = opts
354
+
355
+ if (!peerNode || typeof peerNode.sendTo !== 'function' || typeof peerNode.onIncomingData !== 'function') {
356
+ throw new Error('BrowserMeshWebSocket: opts.peerNode is required and must provide sendTo()/onIncomingData()')
357
+ }
358
+ const parsed = parseMeshRequest(url)
359
+ if (!parsed) {
360
+ throw new Error(`BrowserMeshWebSocket: invalid mesh URL '${url}' (expected mesh://podId/path or https://podId.mesh.local/path)`)
361
+ }
362
+
363
+ this.url = url
364
+ this.#peerNode = peerNode
365
+ this.#envelopeType = envelopeType
366
+ this.#remotePodId = parsed.podId
367
+ this.#path = parsed.path
368
+ this.#connectionId = connectionId || nextConnectionId(peerNode.podId)
369
+ this.#readyState = CONNECTING
370
+
371
+ this.#subscribe()
372
+
373
+ this.#openTimer = setTimeout(() => {
374
+ if (this.#readyState !== CONNECTING) return
375
+ this.#dispatch('error', { type: 'error', message: `BrowserMeshWebSocket: open handshake to ${this.#remotePodId} timed out after ${openTimeoutMs}ms` })
376
+ this.#finalizeClose(1006, 'open handshake timed out')
377
+ }, openTimeoutMs)
378
+
379
+ Promise.resolve(this.#peerNode.sendTo(this.#remotePodId, {
380
+ type: this.#envelopeType,
381
+ kind: 'ws-open',
382
+ connectionId: this.#connectionId,
383
+ path: this.#path,
384
+ headers,
385
+ })).catch((err) => {
386
+ if (this.#readyState !== CONNECTING) return
387
+ this.#dispatch('error', { type: 'error', message: err?.message || String(err) })
388
+ this.#finalizeClose(1006, 'failed to send open handshake')
389
+ })
390
+ }
391
+
392
+ /** @returns {number} One of `CONNECTING`/`OPEN`/`CLOSING`/`CLOSED` (0/1/2/3). */
393
+ get readyState() {
394
+ return this.#readyState
395
+ }
396
+
397
+ /** @returns {string} The connection's path, as parsed from the URL (or supplied by the accepting service) -- additive metadata beyond the standard `WebSocket` surface, not a removal of anything standard. */
398
+ get path() {
399
+ return this.#path
400
+ }
401
+
402
+ /** @returns {string} The remote peer's podId this connection is with -- additive metadata, see `path`'s doc comment. */
403
+ get remotePodId() {
404
+ return this.#remotePodId
405
+ }
406
+
407
+ // -----------------------------------------------------------------------
408
+ // Inbound dispatch
409
+ // -----------------------------------------------------------------------
410
+
411
+ #subscribe() {
412
+ this.#unsubscribe = this.#peerNode.onIncomingData((fromPubKey, data) => {
413
+ if (!data || typeof data !== 'object') return
414
+ if (data.type !== this.#envelopeType || data.connectionId !== this.#connectionId) return
415
+ this.#handleEnvelope(fromPubKey, data)
416
+ })
417
+ }
418
+
419
+ /** @param {string} fromPubKey @param {object} data */
420
+ #handleEnvelope(fromPubKey, data) {
421
+ switch (data.kind) {
422
+ case 'ws-open-ack': {
423
+ if (this.#readyState !== CONNECTING) return
424
+ if (this.#openTimer) clearTimeout(this.#openTimer)
425
+ this.#readyState = OPEN
426
+ this.#dispatch('open', { type: 'open' })
427
+ return
428
+ }
429
+ case 'ws-reject': {
430
+ if (this.#readyState !== CONNECTING) return
431
+ if (this.#openTimer) clearTimeout(this.#openTimer)
432
+ this.#dispatch('error', { type: 'error', message: data.reason || 'connection rejected' })
433
+ this.#finalizeClose(typeof data.code === 'number' ? data.code : 4403, data.reason || 'rejected')
434
+ return
435
+ }
436
+ case 'ws-message': {
437
+ if (this.#readyState !== OPEN) return
438
+ let payload
439
+ if (data.encoding === 'binary') {
440
+ if (typeof data.data !== 'string') return
441
+ payload = toFreshArrayBuffer(fromBase64(data.data))
442
+ } else {
443
+ payload = data.data
444
+ }
445
+ this.#dispatch('message', { type: 'message', data: payload })
446
+ return
447
+ }
448
+ case 'ws-close': {
449
+ if (this.#readyState === CLOSED) return
450
+ this.#finalizeClose(typeof data.code === 'number' ? data.code : 1000, data.reason || '')
451
+ return
452
+ }
453
+ default:
454
+ return
455
+ }
456
+ }
457
+
458
+ // -----------------------------------------------------------------------
459
+ // Standard methods
460
+ // -----------------------------------------------------------------------
461
+
462
+ /**
463
+ * @param {string|ArrayBuffer|ArrayBufferView} data
464
+ * @throws {DOMException} `InvalidStateError` if `readyState` is not `OPEN`
465
+ * (see module doc comment's send-semantics section for why this is true
466
+ * both before open AND after close, the latter a deliberate deviation
467
+ * from the WHATWG spec).
468
+ */
469
+ send(data) {
470
+ if (this.#readyState !== OPEN) {
471
+ throw invalidStateError(`BrowserMeshWebSocket.send() called while readyState is ${this.#readyState} (must be OPEN)`)
472
+ }
473
+
474
+ let payload
475
+ if (typeof data === 'string') {
476
+ payload = { encoding: 'text', data }
477
+ } else if (data instanceof ArrayBuffer) {
478
+ payload = { encoding: 'binary', data: toBase64(new Uint8Array(data)) }
479
+ } else if (ArrayBuffer.isView(data)) {
480
+ payload = { encoding: 'binary', data: toBase64(new Uint8Array(data.buffer, data.byteOffset, data.byteLength)) }
481
+ } else {
482
+ throw new TypeError('BrowserMeshWebSocket.send(): data must be a string, ArrayBuffer, or ArrayBuffer view (Blob is not supported -- see module doc comment)')
483
+ }
484
+
485
+ Promise.resolve(this.#peerNode.sendTo(this.#remotePodId, {
486
+ type: this.#envelopeType,
487
+ kind: 'ws-message',
488
+ connectionId: this.#connectionId,
489
+ ...payload,
490
+ })).catch((err) => {
491
+ this.#dispatch('error', { type: 'error', message: err?.message || String(err) })
492
+ })
493
+ }
494
+
495
+ /**
496
+ * @param {number} [code=1000]
497
+ * @param {string} [reason='']
498
+ */
499
+ close(code = 1000, reason = '') {
500
+ if (this.#readyState === CLOSING || this.#readyState === CLOSED) return
501
+ this.#readyState = CLOSING
502
+ Promise.resolve(this.#peerNode.sendTo(this.#remotePodId, {
503
+ type: this.#envelopeType,
504
+ kind: 'ws-close',
505
+ connectionId: this.#connectionId,
506
+ code,
507
+ reason,
508
+ })).catch(() => {
509
+ // Best-effort notification -- see module doc comment's "one-directional,
510
+ // not a two-phase closing handshake" reasoning. Nothing further to do
511
+ // if the peer is already unreachable; we still finalize our own side.
512
+ }).finally(() => {
513
+ this.#finalizeClose(code, reason)
514
+ })
515
+ }
516
+
517
+ /** @param {number} code @param {string} reason */
518
+ #finalizeClose(code, reason) {
519
+ if (this.#readyState === CLOSED) return
520
+ this.#readyState = CLOSED
521
+ if (this.#openTimer) {
522
+ clearTimeout(this.#openTimer)
523
+ this.#openTimer = null
524
+ }
525
+ if (this.#unsubscribe) {
526
+ this.#unsubscribe()
527
+ this.#unsubscribe = null
528
+ }
529
+ this.#dispatch('close', { type: 'close', code, reason, wasClean: true })
530
+ }
531
+
532
+ // -----------------------------------------------------------------------
533
+ // Event dispatch: onX properties AND addEventListener()-registered listeners
534
+ // -----------------------------------------------------------------------
535
+
536
+ /** @param {'open'|'message'|'error'|'close'} type @param {object} event */
537
+ #dispatch(type, event) {
538
+ const handler = this[`on${type}`]
539
+ if (typeof handler === 'function') {
540
+ try {
541
+ handler.call(this, event)
542
+ } catch {
543
+ // A throwing handler must never break this class's own internal
544
+ // state machine -- matches real EventTarget dispatch semantics
545
+ // (a listener throwing does not stop other listeners/handlers).
546
+ }
547
+ }
548
+ const set = this.#listeners[type]
549
+ if (!set) return
550
+ for (const cb of [...set]) {
551
+ try {
552
+ cb.call(this, event)
553
+ } catch {
554
+ // Same reasoning as above.
555
+ }
556
+ }
557
+ }
558
+
559
+ /** @param {'open'|'message'|'error'|'close'} type @param {Function} listener */
560
+ addEventListener(type, listener) {
561
+ const set = this.#listeners[type]
562
+ if (!set || typeof listener !== 'function') return
563
+ set.add(listener)
564
+ }
565
+
566
+ /** @param {'open'|'message'|'error'|'close'} type @param {Function} listener */
567
+ removeEventListener(type, listener) {
568
+ const set = this.#listeners[type]
569
+ if (!set) return
570
+ set.delete(listener)
571
+ }
572
+ }
573
+
574
+ // ---------------------------------------------------------------------------
575
+ // createMeshWebSocketService -- the responding-pod-side MeshService
576
+ // ---------------------------------------------------------------------------
577
+
578
+ /**
579
+ * Build an already-`OPEN` `BrowserMeshWebSocket`-shaped handle for an
580
+ * ACCEPTED inbound connection, via the internal-only construction path (see
581
+ * `ACCEPTED_SESSION` above). Not exported.
582
+ *
583
+ * @param {object} opts
584
+ * @param {object} opts.peerNode - The raw `peerNode` (not `ctx`) -- needed
585
+ * because `BrowserMeshWebSocket` subscribes via the single-callback
586
+ * `peerNode.onIncomingData(cb)` shape, not `ctx`'s type-filtered
587
+ * `onIncomingData(types, cb)` shape.
588
+ * @param {string} opts.envelopeType
589
+ * @param {string} opts.connectionId
590
+ * @param {string} opts.remotePodId
591
+ * @param {string} opts.path
592
+ * @returns {BrowserMeshWebSocket}
593
+ */
594
+ function createAcceptedSession({ peerNode, envelopeType, connectionId, remotePodId, path }) {
595
+ const url = `mesh://${remotePodId}${path}`
596
+ return new BrowserMeshWebSocket(url, {
597
+ [ACCEPTED_SESSION]: { peerNode, envelopeType, connectionId, remotePodId, path },
598
+ })
599
+ }
600
+
601
+ /**
602
+ * Build a `MeshService` descriptor (`mesh-service.mjs`, Phase C) that lets a
603
+ * pod ACCEPT inbound `BrowserMeshWebSocket` connections and originate
604
+ * outbound ones via its `api`. See this file's module doc comment for the
605
+ * full protocol/authorization writeup.
606
+ *
607
+ * @param {object} [opts]
608
+ * @param {(fromPubKey: string, path: string) => boolean|Promise<boolean>} [opts.onConnection]
609
+ * Accept/reject hook for inbound connections. If omitted, EVERY inbound
610
+ * connection is rejected -- see module doc comment's "NO onConnection
611
+ * HANDLER REGISTERED" section. A thrown/rejected hook is treated as a
612
+ * rejection, never an unhandled rejection.
613
+ * @param {(session: BrowserMeshWebSocket, info: {fromPubKey: string, path: string}) => void} [opts.onIncomingConnection]
614
+ * Called once per ACCEPTED inbound connection, with an already-`OPEN`
615
+ * `BrowserMeshWebSocket`-shaped handle for that session (same
616
+ * send/close/onmessage/addEventListener surface).
617
+ * @param {string} [opts.envelopeType='mesh-websocket']
618
+ * @param {Function} [opts.onLog]
619
+ * @returns {import('./mesh-service.mjs').MeshService}
620
+ */
621
+ export function createMeshWebSocketService({
622
+ onConnection,
623
+ onIncomingConnection,
624
+ envelopeType = DEFAULT_ENVELOPE_TYPE,
625
+ onLog,
626
+ } = {}) {
627
+ const log = onLog || (() => {})
628
+
629
+ return {
630
+ name: 'mesh-websocket',
631
+
632
+ attach(peerNode, ctx) {
633
+ const unsubscribe = ctx.onIncomingData(envelopeType, (fromPubKey, msg) => {
634
+ if (!msg || msg.kind !== 'ws-open') return
635
+ handleOpen(fromPubKey, msg).catch((err) => {
636
+ log('mesh-websocket:open-handling-failed', { from: fromPubKey, connectionId: msg.connectionId, error: err?.message || String(err) })
637
+ })
638
+ })
639
+
640
+ /** @param {string} fromPubKey @param {object} msg */
641
+ async function handleOpen(fromPubKey, msg) {
642
+ const { connectionId, path } = msg
643
+ let accepted = false
644
+ let rejectReason = 'no onConnection handler registered'
645
+
646
+ if (typeof onConnection === 'function') {
647
+ try {
648
+ accepted = await onConnection(fromPubKey, path)
649
+ rejectReason = 'connection rejected'
650
+ } catch (err) {
651
+ log('mesh-websocket:onConnection-threw', { from: fromPubKey, connectionId, error: err?.message || String(err) })
652
+ accepted = false
653
+ rejectReason = err?.message || 'onConnection threw'
654
+ }
655
+ }
656
+
657
+ if (!accepted) {
658
+ ctx.emit('mesh-websocket:connection-rejected', { from: fromPubKey, path, connectionId, reason: rejectReason })
659
+ await ctx.sendTo(fromPubKey, envelopeType, { kind: 'ws-reject', connectionId, code: 4403, reason: rejectReason }).catch((err) => {
660
+ log('mesh-websocket:reject-send-failed', { to: fromPubKey, connectionId, error: err?.message || String(err) })
661
+ })
662
+ return
663
+ }
664
+
665
+ const session = createAcceptedSession({ peerNode, envelopeType, connectionId, remotePodId: fromPubKey, path })
666
+ session.addEventListener('close', (event) => {
667
+ ctx.emit('mesh-websocket:connection-closed', { from: fromPubKey, path, connectionId, code: event.code, reason: event.reason })
668
+ })
669
+ ctx.emit('mesh-websocket:connection-opened', { from: fromPubKey, path, connectionId })
670
+
671
+ // `onIncomingConnection` is called BEFORE the ack is sent (not
672
+ // after), and synchronously -- deliberately. Sending the ack first
673
+ // yields to the event loop (`await ctx.sendTo()`), and a fast
674
+ // remote peer can react to its own `onopen` and send a message
675
+ // before this continuation resumes; if the application hadn't
676
+ // attached its `onmessage`/etc. handlers to `session` yet at that
677
+ // point, the message is lost. Calling this synchronously, before
678
+ // any `await`, guarantees the application has had a chance to wire
679
+ // up handlers before the ack (and therefore before any reply) can
680
+ // possibly reach the other side. If the ack send below fails, the
681
+ // application already has `session` and will observe the failure
682
+ // via `onclose` (1011) rather than silently never learning the
683
+ // connection was attempted.
684
+ if (typeof onIncomingConnection === 'function') {
685
+ onIncomingConnection(session, { fromPubKey, path })
686
+ }
687
+
688
+ try {
689
+ await ctx.sendTo(fromPubKey, envelopeType, { kind: 'ws-open-ack', connectionId })
690
+ } catch (err) {
691
+ log('mesh-websocket:ack-send-failed', { to: fromPubKey, connectionId, error: err?.message || String(err) })
692
+ session.close(1011, 'failed to acknowledge open')
693
+ }
694
+ }
695
+
696
+ const api = {
697
+ /**
698
+ * Originate an outbound connection from this peer, equivalent to
699
+ * `new BrowserMeshWebSocket(url, {peerNode, envelopeType, ...connectOpts})`.
700
+ * A thin convenience so a caller that already attached this service
701
+ * (e.g. to also accept inbound connections) doesn't need to
702
+ * separately import the class and re-pass `peerNode`.
703
+ * @param {string} url
704
+ * @param {object} [connectOpts]
705
+ * @returns {BrowserMeshWebSocket}
706
+ */
707
+ connect(url, connectOpts = {}) {
708
+ return new BrowserMeshWebSocket(url, { peerNode, envelopeType, ...connectOpts })
709
+ },
710
+ }
711
+
712
+ return {
713
+ api,
714
+ teardown() {
715
+ unsubscribe()
716
+ },
717
+ }
718
+ },
719
+ }
720
+ }
721
+
722
+ export { DEFAULT_ENVELOPE_TYPE, DEFAULT_OPEN_TIMEOUT_MS, CONNECTING, OPEN, CLOSING, CLOSED }