@johnhenry/browsermesh-apps 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,555 @@
1
+ /**
2
+ // STATUS: INTEGRATED — wired into ClawserPod lifecycle, proven via E2E testing
3
+ * clawser-peer-routing.js -- Multi-hop message routing and server sharing.
4
+ *
5
+ * Routes messages across the mesh via intermediary peers when direct
6
+ * connections are unavailable. Also enables HTTP server sharing via mesh.
7
+ *
8
+ * MeshRouter manages a route table and forwards messages through multi-hop
9
+ * paths with TTL enforcement.
10
+ * ServerSharing exposes local HTTP servers to the mesh and proxies incoming
11
+ * requests from peers.
12
+ *
13
+ * No browser-only imports at module level. All dependencies injected.
14
+ *
15
+ * Run tests:
16
+ * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-routing.test.mjs
17
+ */
18
+
19
+ // ---------------------------------------------------------------------------
20
+ // Constants
21
+ // ---------------------------------------------------------------------------
22
+
23
+ /**
24
+ * Default configuration for the mesh router.
25
+ */
26
+ export const ROUTING_DEFAULTS = Object.freeze({
27
+ maxTTL: 8,
28
+ routeCacheMs: 60_000, // 1 minute
29
+ maxRouteEntries: 1000,
30
+ })
31
+
32
+ // ---------------------------------------------------------------------------
33
+ // RouteEntry (plain object factory)
34
+ // ---------------------------------------------------------------------------
35
+
36
+ /**
37
+ * Create a RouteEntry describing a path to a target pod.
38
+ *
39
+ * @param {object} opts
40
+ * @param {string} opts.target - Target pod ID
41
+ * @param {string} opts.nextHop - Next hop pod ID to reach target
42
+ * @param {number} [opts.hops] - Number of hops along the route
43
+ * @param {number} [opts.addedAt]
44
+ * @param {number} [opts.expiresAt]
45
+ * @returns {object}
46
+ */
47
+ function createRouteEntry({ target, nextHop, hops = 1, addedAt, expiresAt }) {
48
+ const now = Date.now()
49
+ return {
50
+ target,
51
+ nextHop,
52
+ hops,
53
+ addedAt: addedAt ?? now,
54
+ expiresAt: expiresAt ?? (now + ROUTING_DEFAULTS.routeCacheMs),
55
+ }
56
+ }
57
+
58
+ // ---------------------------------------------------------------------------
59
+ // MeshRouter
60
+ // ---------------------------------------------------------------------------
61
+
62
+ /**
63
+ * Multi-hop message router for the mesh network.
64
+ *
65
+ * Maintains a route table mapping target pod IDs to next-hop peers,
66
+ * forwards messages with TTL enforcement, and emits events for
67
+ * delivered and forwarded messages.
68
+ */
69
+ export class MeshRouter {
70
+ /** @type {string} */
71
+ #localPodId
72
+
73
+ /** @type {Map<string, object>} targetPodId -> RouteEntry */
74
+ #routeTable = new Map()
75
+
76
+ /** @type {Set<string>} directly connected peer pod IDs */
77
+ #directPeers = new Set()
78
+
79
+ /** @type {Function|null} (nextHop, envelope) => void */
80
+ #forwardFn
81
+
82
+ /** @type {number} */
83
+ #maxTTL
84
+
85
+ /** @type {number} */
86
+ #routeCacheMs
87
+
88
+ /** @type {Function} */
89
+ #onLog
90
+
91
+ /** @type {Map<string, Function[]>} */
92
+ #listeners = new Map()
93
+
94
+ /**
95
+ * @param {object} opts
96
+ * @param {string} opts.localPodId - This pod's identifier
97
+ * @param {Function} [opts.forwardFn] - (nextHop, envelope) => void
98
+ * @param {number} [opts.maxTTL] - Maximum time-to-live for routed messages
99
+ * @param {number} [opts.routeCacheMs] - How long routes remain valid
100
+ * @param {Function} [opts.onLog] - Logging callback
101
+ */
102
+ constructor({ localPodId, forwardFn, maxTTL, routeCacheMs, onLog }) {
103
+ if (!localPodId || typeof localPodId !== 'string') {
104
+ throw new Error('localPodId is required and must be a non-empty string')
105
+ }
106
+ this.#localPodId = localPodId
107
+ this.#forwardFn = forwardFn ?? null
108
+ this.#maxTTL = maxTTL ?? ROUTING_DEFAULTS.maxTTL
109
+ this.#routeCacheMs = routeCacheMs ?? ROUTING_DEFAULTS.routeCacheMs
110
+ this.#onLog = onLog ?? (() => {})
111
+ }
112
+
113
+ // ── Routing ───────────────────────────────────────────────────────
114
+
115
+ /**
116
+ * Route a message to a target pod.
117
+ *
118
+ * 1. If targetPodId is a direct peer, send directly (via forwardFn).
119
+ * 2. If a known route exists, forward to the next hop.
120
+ * 3. Otherwise, return { success: false }.
121
+ *
122
+ * @param {string} targetPodId
123
+ * @param {*} message
124
+ * @returns {{ success: boolean, hops?: number, path?: string[] }}
125
+ */
126
+ route(targetPodId, message) {
127
+ // Build envelope with TTL
128
+ const envelope = {
129
+ from: this.#localPodId,
130
+ to: targetPodId,
131
+ ttl: this.#maxTTL,
132
+ message,
133
+ path: [this.#localPodId],
134
+ }
135
+
136
+ // 1. Direct peer?
137
+ if (this.#directPeers.has(targetPodId)) {
138
+ if (this.#forwardFn) {
139
+ this.#forwardFn(targetPodId, envelope)
140
+ }
141
+ return { success: true, hops: 1, path: [this.#localPodId, targetPodId] }
142
+ }
143
+
144
+ // 2. Known route? (check expiry)
145
+ const route = this.#routeTable.get(targetPodId)
146
+ if (route && route.expiresAt > Date.now()) {
147
+ if (this.#forwardFn) {
148
+ this.#forwardFn(route.nextHop, envelope)
149
+ }
150
+ this.#emit('forward', envelope)
151
+ return { success: true, hops: route.hops, path: [this.#localPodId, route.nextHop] }
152
+ }
153
+ // Clean up expired route
154
+ if (route && route.expiresAt <= Date.now()) {
155
+ this.#routeTable.delete(targetPodId)
156
+ }
157
+
158
+ // 3. No route
159
+ return { success: false }
160
+ }
161
+
162
+ // ── Route Table Management ────────────────────────────────────────
163
+
164
+ /**
165
+ * Add or update a route to a target pod.
166
+ *
167
+ * @param {string} targetPodId
168
+ * @param {string} nextHop
169
+ * @param {number} [hops=1]
170
+ * @param {number} [ttl] - Override route TTL (ms)
171
+ */
172
+ addRoute(targetPodId, nextHop, hops, ttl) {
173
+ if (this.#routeTable.size >= ROUTING_DEFAULTS.maxRouteEntries && !this.#routeTable.has(targetPodId)) {
174
+ // Evict oldest entry
175
+ const oldestKey = this.#routeTable.keys().next().value
176
+ this.#routeTable.delete(oldestKey)
177
+ }
178
+ const now = Date.now()
179
+ const entry = createRouteEntry({
180
+ target: targetPodId,
181
+ nextHop,
182
+ hops: hops ?? 1,
183
+ addedAt: now,
184
+ expiresAt: now + (ttl ?? this.#routeCacheMs),
185
+ })
186
+ this.#routeTable.set(targetPodId, entry)
187
+ this.#emit('route:add', entry)
188
+ }
189
+
190
+ /**
191
+ * Remove a route to a target pod.
192
+ * @param {string} targetPodId
193
+ * @returns {boolean}
194
+ */
195
+ removeRoute(targetPodId) {
196
+ const existed = this.#routeTable.delete(targetPodId)
197
+ if (existed) {
198
+ this.#emit('route:remove', targetPodId)
199
+ }
200
+ return existed
201
+ }
202
+
203
+ /**
204
+ * Get the route entry for a target pod.
205
+ * @param {string} targetPodId
206
+ * @returns {object|null} RouteEntry or null
207
+ */
208
+ getRoute(targetPodId) {
209
+ return this.#routeTable.get(targetPodId) ?? null
210
+ }
211
+
212
+ // ── Incoming Routed Messages ──────────────────────────────────────
213
+
214
+ /**
215
+ * Handle an incoming routed message (envelope).
216
+ *
217
+ * If the message is addressed to this pod, emit 'message'.
218
+ * Otherwise, decrement TTL and forward to the next hop.
219
+ *
220
+ * @param {object} envelope - { from, to, ttl, message, path }
221
+ */
222
+ handleRoutedMessage(envelope) {
223
+ if (!envelope || typeof envelope !== 'object') return
224
+
225
+ // Message is for us
226
+ if (envelope.to === this.#localPodId) {
227
+ this.#emit('message', envelope)
228
+ return
229
+ }
230
+
231
+ // TTL enforcement
232
+ const newTTL = (envelope.ttl ?? 0) - 1
233
+ if (newTTL <= 0) {
234
+ this.#onLog(`Dropping message from ${envelope.from} to ${envelope.to}: TTL expired`)
235
+ return
236
+ }
237
+
238
+ // Build forwarded envelope
239
+ const forwarded = {
240
+ ...envelope,
241
+ ttl: newTTL,
242
+ path: [...(envelope.path || []), this.#localPodId],
243
+ }
244
+
245
+ // Try to forward
246
+ const targetPodId = envelope.to
247
+
248
+ // Direct peer?
249
+ if (this.#directPeers.has(targetPodId)) {
250
+ if (this.#forwardFn) {
251
+ this.#forwardFn(targetPodId, forwarded)
252
+ }
253
+ this.#emit('forward', forwarded)
254
+ return
255
+ }
256
+
257
+ // Known route? (check expiry)
258
+ const route = this.#routeTable.get(targetPodId)
259
+ if (route && route.expiresAt > Date.now() && this.#forwardFn) {
260
+ this.#forwardFn(route.nextHop, forwarded)
261
+ this.#emit('forward', forwarded)
262
+ }
263
+ }
264
+
265
+ // ── Direct Peer Management ────────────────────────────────────────
266
+
267
+ /**
268
+ * Register a directly connected peer.
269
+ * @param {string} podId
270
+ */
271
+ addDirectPeer(podId) {
272
+ this.#directPeers.add(podId)
273
+ }
274
+
275
+ /**
276
+ * Remove a directly connected peer.
277
+ * @param {string} podId
278
+ */
279
+ removeDirectPeer(podId) {
280
+ this.#directPeers.delete(podId)
281
+ }
282
+
283
+ /**
284
+ * List all directly connected peers.
285
+ * @returns {string[]}
286
+ */
287
+ listDirectPeers() {
288
+ return [...this.#directPeers]
289
+ }
290
+
291
+ // ── Route Discovery ───────────────────────────────────────────────
292
+
293
+ /**
294
+ * List all route entries.
295
+ * @returns {object[]} Array of RouteEntry
296
+ */
297
+ listRoutes() {
298
+ return [...this.#routeTable.values()]
299
+ }
300
+
301
+ /**
302
+ * Remove expired route entries.
303
+ * @param {number} [now=Date.now()]
304
+ * @returns {number} Number of routes pruned
305
+ */
306
+ pruneExpired(now = Date.now()) {
307
+ let count = 0
308
+ for (const [target, entry] of this.#routeTable) {
309
+ if (now >= entry.expiresAt) {
310
+ this.#routeTable.delete(target)
311
+ this.#emit('route:remove', target)
312
+ count++
313
+ }
314
+ }
315
+ return count
316
+ }
317
+
318
+ // ── Events ────────────────────────────────────────────────────────
319
+
320
+ /**
321
+ * Subscribe to an event.
322
+ * @param {string} event - 'message' | 'forward' | 'route:add' | 'route:remove'
323
+ * @param {Function} cb
324
+ */
325
+ on(event, cb) {
326
+ if (!this.#listeners.has(event)) {
327
+ this.#listeners.set(event, [])
328
+ }
329
+ this.#listeners.get(event).push(cb)
330
+ }
331
+
332
+ /**
333
+ * Unsubscribe from an event.
334
+ * @param {string} event
335
+ * @param {Function} cb
336
+ */
337
+ off(event, cb) {
338
+ const cbs = this.#listeners.get(event)
339
+ if (!cbs) return
340
+ const idx = cbs.indexOf(cb)
341
+ if (idx !== -1) cbs.splice(idx, 1)
342
+ }
343
+
344
+ /**
345
+ * Emit an event to all listeners.
346
+ * @param {string} event
347
+ * @param {...any} args
348
+ */
349
+ #emit(event, ...args) {
350
+ const cbs = this.#listeners.get(event)
351
+ if (!cbs) return
352
+ for (const cb of [...cbs]) {
353
+ try { cb(...args) } catch { /* listener errors do not propagate */ }
354
+ }
355
+ }
356
+
357
+ // ── Serialization ─────────────────────────────────────────────────
358
+
359
+ /**
360
+ * Serialize to a JSON-safe object.
361
+ * @returns {object}
362
+ */
363
+ toJSON() {
364
+ return {
365
+ localPodId: this.#localPodId,
366
+ maxTTL: this.#maxTTL,
367
+ routeCacheMs: this.#routeCacheMs,
368
+ directPeers: [...this.#directPeers],
369
+ routes: [...this.#routeTable.values()],
370
+ }
371
+ }
372
+ }
373
+
374
+ // ---------------------------------------------------------------------------
375
+ // ServerSharing
376
+ // ---------------------------------------------------------------------------
377
+
378
+ /**
379
+ * Exposes local HTTP servers to the mesh network and handles incoming
380
+ * proxy requests from remote peers.
381
+ */
382
+ export class ServerSharing {
383
+ /** @type {string} */
384
+ #localPodId
385
+
386
+ /** @type {Map<string, object>} name -> ServerConfig */
387
+ #exposedServers = new Map()
388
+
389
+ /** @type {Function} */
390
+ #fetchFn
391
+
392
+ /** @type {Function} */
393
+ #onLog
394
+
395
+ /**
396
+ * @param {object} opts
397
+ * @param {string} opts.localPodId - This pod's identifier
398
+ * @param {Function} [opts.fetchFn] - (url, init?) => Response, defaults to globalThis.fetch
399
+ * @param {Function} [opts.onLog] - Logging callback
400
+ */
401
+ constructor(opts) {
402
+ const { localPodId, fetchFn, onLog } = opts
403
+ if (!localPodId || typeof localPodId !== 'string') {
404
+ throw new Error('localPodId is required and must be a non-empty string')
405
+ }
406
+ this.#localPodId = localPodId
407
+ this.#fetchFn = 'fetchFn' in opts
408
+ ? fetchFn
409
+ : (typeof globalThis.fetch === 'function' ? globalThis.fetch : null)
410
+ this.#onLog = onLog ?? (() => {})
411
+ }
412
+
413
+ // ── Expose / Unexpose ─────────────────────────────────────────────
414
+
415
+ /**
416
+ * Expose a local HTTP server on the mesh.
417
+ *
418
+ * @param {number} port - Local port number
419
+ * @param {string} name - Service name for the exposed server
420
+ * @param {object} [opts]
421
+ * @param {string} [opts.hostname='localhost'] - Local hostname
422
+ * @param {string} [opts.protocol='http'] - Protocol (http or https)
423
+ * @returns {object} ServerConfig
424
+ */
425
+ expose(port, name, opts = {}) {
426
+ if (typeof port !== 'number' || port <= 0) {
427
+ throw new Error('port must be a positive number')
428
+ }
429
+ if (!name || typeof name !== 'string') {
430
+ throw new Error('name is required and must be a non-empty string')
431
+ }
432
+
433
+ const hostname = opts.hostname ?? 'localhost'
434
+ const protocol = opts.protocol ?? 'http'
435
+ const address = `mesh://${this.#localPodId}/http/${name}`
436
+
437
+ const config = {
438
+ name,
439
+ port,
440
+ hostname,
441
+ protocol,
442
+ address,
443
+ exposedAt: Date.now(),
444
+ }
445
+
446
+ this.#exposedServers.set(name, config)
447
+ this.#onLog(`Exposed server "${name}" at port ${port} → ${address}`)
448
+
449
+ return config
450
+ }
451
+
452
+ /**
453
+ * Remove an exposed server.
454
+ * @param {string} name
455
+ * @returns {boolean} true if the server existed
456
+ */
457
+ unexpose(name) {
458
+ const existed = this.#exposedServers.delete(name)
459
+ if (existed) {
460
+ this.#onLog(`Unexposed server "${name}"`)
461
+ }
462
+ return existed
463
+ }
464
+
465
+ // ── Proxy Handling ────────────────────────────────────────────────
466
+
467
+ /**
468
+ * Handle an incoming HTTP proxy request from a remote peer.
469
+ *
470
+ * @param {object} request
471
+ * @param {string} request.name - Name of the exposed server
472
+ * @param {string} request.method - HTTP method
473
+ * @param {string} request.path - Request path
474
+ * @param {object} [request.headers] - Request headers
475
+ * @param {*} [request.body] - Request body
476
+ * @returns {Promise<{ status: number, headers: object, body: * }>}
477
+ */
478
+ async handleRequest(request) {
479
+ if (!request || typeof request !== 'object') {
480
+ return { status: 400, headers: {}, body: 'Invalid request' }
481
+ }
482
+
483
+ const config = this.#exposedServers.get(request.name)
484
+ if (!config) {
485
+ return { status: 404, headers: {}, body: `Server "${request.name}" not found` }
486
+ }
487
+
488
+ const url = `${config.protocol}://${config.hostname}:${config.port}${request.path || '/'}`
489
+
490
+ if (!this.#fetchFn) {
491
+ return { status: 503, headers: {}, body: 'Fetch not available' }
492
+ }
493
+
494
+ try {
495
+ const response = await this.#fetchFn(url, {
496
+ method: request.method || 'GET',
497
+ headers: request.headers || {},
498
+ body: request.body,
499
+ })
500
+
501
+ const responseHeaders = {}
502
+ if (response.headers && typeof response.headers.forEach === 'function') {
503
+ response.headers.forEach((value, key) => {
504
+ responseHeaders[key] = value
505
+ })
506
+ }
507
+
508
+ const body = await (typeof response.text === 'function' ? response.text() : response.body)
509
+
510
+ return {
511
+ status: response.status,
512
+ headers: responseHeaders,
513
+ body,
514
+ }
515
+ } catch (err) {
516
+ return {
517
+ status: 502,
518
+ headers: {},
519
+ body: `Proxy error: ${err.message || err}`,
520
+ }
521
+ }
522
+ }
523
+
524
+ // ── Queries ───────────────────────────────────────────────────────
525
+
526
+ /**
527
+ * List all exposed servers.
528
+ * @returns {object[]} Array of ServerConfig
529
+ */
530
+ listExposed() {
531
+ return [...this.#exposedServers.values()]
532
+ }
533
+
534
+ /**
535
+ * Get a specific exposed server by name.
536
+ * @param {string} name
537
+ * @returns {object|null} ServerConfig or null
538
+ */
539
+ getExposed(name) {
540
+ return this.#exposedServers.get(name) ?? null
541
+ }
542
+
543
+ // ── Serialization ─────────────────────────────────────────────────
544
+
545
+ /**
546
+ * Serialize to a JSON-safe object.
547
+ * @returns {object}
548
+ */
549
+ toJSON() {
550
+ return {
551
+ localPodId: this.#localPodId,
552
+ servers: [...this.#exposedServers.values()],
553
+ }
554
+ }
555
+ }