@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
@@ -1,937 +0,0 @@
1
- import { silentCatch } from './silent-catch.mjs'
2
- /**
3
- // STATUS: INTEGRATED — wired into ClawserPod lifecycle, proven via E2E testing
4
- * clawser-peer-session.js -- Authenticated peer session management.
5
- *
6
- * Manages authenticated sessions between mesh peers, providing message
7
- * routing to service handlers, heartbeat detection, rate limiting, and
8
- * audit logging.
9
- *
10
- * - PeerSession: single authenticated connection to a remote peer
11
- * - SessionManager: lifecycle management for all active sessions
12
- * - SessionProtocol: constants and envelope helpers
13
- *
14
- * Dependencies are injected (MeshACL, AuditChain, transport).
15
- * No browser-only imports at module level.
16
- *
17
- * Run tests:
18
- * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-session.test.mjs
19
- */
20
-
21
- // ---------------------------------------------------------------------------
22
- // SessionProtocol — constants and envelope helpers
23
- // ---------------------------------------------------------------------------
24
-
25
- /** Standard message types for peer sessions. */
26
- export const SESSION_MSG_TYPES = Object.freeze({
27
- CHAT: 'chat',
28
- TERMINAL: 'terminal',
29
- FILES: 'files',
30
- AGENT: 'agent',
31
- PING: 'ping',
32
- PONG: 'pong',
33
- ERROR: 'error',
34
- })
35
-
36
- /**
37
- * Create a message envelope for sending over a session transport.
38
- *
39
- * @param {string} type - One of SESSION_MSG_TYPES or custom service type
40
- * @param {*} payload - Message payload
41
- * @param {string} sessionId - Session identifier
42
- * @param {string} fromPodId - Sender pod ID
43
- * @returns {{ type: string, payload: *, sessionId: string, from: string, timestamp: number }}
44
- */
45
- export function createEnvelope(type, payload, sessionId, fromPodId) {
46
- return {
47
- type,
48
- payload,
49
- sessionId,
50
- from: fromPodId,
51
- timestamp: Date.now(),
52
- }
53
- }
54
-
55
- /**
56
- * Parse and validate an incoming message envelope.
57
- *
58
- * @param {*} data - Raw data from transport (object or JSON string)
59
- * @returns {{ type: string, payload: *, sessionId: string, from: string, timestamp: number }|null}
60
- */
61
- export function parseEnvelope(data) {
62
- try {
63
- const envelope = typeof data === 'string' ? JSON.parse(data) : data
64
- if (
65
- !envelope ||
66
- typeof envelope !== 'object' ||
67
- typeof envelope.type !== 'string' ||
68
- typeof envelope.sessionId !== 'string' ||
69
- typeof envelope.from !== 'string' ||
70
- typeof envelope.timestamp !== 'number'
71
- ) {
72
- return null
73
- }
74
- return {
75
- type: envelope.type,
76
- payload: envelope.payload,
77
- sessionId: envelope.sessionId,
78
- from: envelope.from,
79
- timestamp: envelope.timestamp,
80
- }
81
- } catch {
82
- return null
83
- }
84
- }
85
-
86
- /**
87
- * Create an error envelope for reporting errors to a remote peer.
88
- *
89
- * @param {string} sessionId - Session identifier
90
- * @param {string} fromPodId - Sender pod ID
91
- * @param {string} error - Error message
92
- * @param {string} [code='UNKNOWN'] - Error code
93
- * @returns {object}
94
- */
95
- export function createErrorEnvelope(sessionId, fromPodId, error, code = 'UNKNOWN') {
96
- return createEnvelope(SESSION_MSG_TYPES.ERROR, { error, code }, sessionId, fromPodId)
97
- }
98
-
99
- // ---------------------------------------------------------------------------
100
- // Session ID generator
101
- // ---------------------------------------------------------------------------
102
-
103
- let _sessionSeq = 0
104
-
105
- /**
106
- * Generate a unique session identifier.
107
- * @returns {string}
108
- */
109
- function generateSessionId() {
110
- return `sess_${Date.now().toString(36)}_${(++_sessionSeq).toString(36)}`
111
- }
112
-
113
- // ---------------------------------------------------------------------------
114
- // PeerSession
115
- // ---------------------------------------------------------------------------
116
-
117
- /**
118
- * Represents an authenticated connection to a single remote peer.
119
- *
120
- * Provides message routing to registered service handlers, heartbeat
121
- * keep-alive, capability checking, and per-session statistics.
122
- */
123
- export class PeerSession {
124
- /** @type {string} */
125
- #sessionId
126
-
127
- /** @type {{ podId: string }} */
128
- #localIdentity
129
-
130
- /** @type {{ podId: string, publicKey?: string }} */
131
- #remoteIdentity
132
-
133
- /** @type {string[]} */
134
- #capabilities
135
-
136
- /** @type {object} transport with send(data) and onMessage(cb) */
137
- #transport
138
-
139
- /** @type {Map<string, Function>} service type -> async handler(message, session) */
140
- #handlers = new Map()
141
-
142
- /** @type {'active'|'suspended'|'closed'} */
143
- #state = 'active'
144
-
145
- /** @type {number} */
146
- #createdAt
147
-
148
- /** @type {number} */
149
- #lastActivity
150
-
151
- /** @type {*} timer ID */
152
- #heartbeatInterval = null
153
-
154
- /** @type {number} ms before declaring peer dead */
155
- #heartbeatTimeoutMs
156
-
157
- /** @type {*} timer ID for heartbeat timeout */
158
- #heartbeatTimer = null
159
-
160
- /** @type {Function} */
161
- #onLog
162
-
163
- /** @type {{ messagesSent: number, messagesReceived: number, errors: number }} */
164
- #stats = { messagesSent: 0, messagesReceived: 0, errors: 0 }
165
-
166
- /** @type {Function} bound message handler reference for cleanup */
167
- #boundMessageHandler
168
-
169
- /**
170
- * @param {object} opts
171
- * @param {string} opts.sessionId - Unique session identifier
172
- * @param {{ podId: string }} opts.localIdentity - Local identity
173
- * @param {{ podId: string, publicKey?: string }} opts.remoteIdentity - Remote identity
174
- * @param {string[]} opts.capabilities - What the remote peer is allowed to do
175
- * @param {object} opts.transport - Transport with send(data) and onMessage(cb)
176
- * @param {number} [opts.heartbeatTimeoutMs=60000] - Heartbeat timeout
177
- * @param {Function} [opts.onLog] - Logging callback
178
- */
179
- constructor({
180
- sessionId,
181
- localIdentity,
182
- remoteIdentity,
183
- capabilities,
184
- transport,
185
- heartbeatTimeoutMs = 60000,
186
- onLog,
187
- }) {
188
- if (!sessionId || typeof sessionId !== 'string') {
189
- throw new Error('sessionId is required and must be a non-empty string')
190
- }
191
- if (!localIdentity || !localIdentity.podId) {
192
- throw new Error('localIdentity with podId is required')
193
- }
194
- if (!remoteIdentity || !remoteIdentity.podId) {
195
- throw new Error('remoteIdentity with podId is required')
196
- }
197
- if (!transport || typeof transport.send !== 'function') {
198
- throw new Error('transport with send() method is required')
199
- }
200
-
201
- this.#sessionId = sessionId
202
- this.#localIdentity = localIdentity
203
- this.#remoteIdentity = remoteIdentity
204
- this.#capabilities = Array.isArray(capabilities) ? [...capabilities] : []
205
- this.#transport = transport
206
- this.#heartbeatTimeoutMs = heartbeatTimeoutMs
207
- this.#onLog = onLog || (() => {})
208
- this.#createdAt = Date.now()
209
- this.#lastActivity = Date.now()
210
-
211
- // Wire up transport message handler
212
- this.#boundMessageHandler = (data) => this.#handleMessage(data)
213
- if (typeof transport.onMessage === 'function') {
214
- transport.onMessage(this.#boundMessageHandler)
215
- }
216
- }
217
-
218
- // -- Properties -----------------------------------------------------------
219
-
220
- /** @returns {string} */
221
- get sessionId() { return this.#sessionId }
222
-
223
- /** @returns {string} */
224
- get localPodId() { return this.#localIdentity.podId }
225
-
226
- /** @returns {string} */
227
- get remotePodId() { return this.#remoteIdentity.podId }
228
-
229
- /** @returns {string[]} Copy of capabilities array. */
230
- get capabilities() { return [...this.#capabilities] }
231
-
232
- /** @returns {'active'|'suspended'|'closed'} */
233
- get state() { return this.#state }
234
-
235
- /** @returns {number} */
236
- get createdAt() { return this.#createdAt }
237
-
238
- /** @returns {number} */
239
- get lastActivity() { return this.#lastActivity }
240
-
241
- /** @returns {{ messagesSent: number, messagesReceived: number, errors: number }} */
242
- get stats() { return { ...this.#stats } }
243
-
244
- // -- Capability checking --------------------------------------------------
245
-
246
- /**
247
- * Check whether the remote peer has a given capability scope.
248
- *
249
- * @param {string} scope - Capability scope string
250
- * @returns {boolean}
251
- */
252
- hasCapability(scope) {
253
- return this.#capabilities.includes(scope) || this.#capabilities.includes('*')
254
- }
255
-
256
- /**
257
- * Require a capability, throwing if the remote peer does not have it.
258
- *
259
- * @param {string} scope - Capability scope string
260
- * @throws {Error} If capability is not granted
261
- */
262
- requireCapability(scope) {
263
- if (!this.hasCapability(scope)) {
264
- throw new Error(`Capability "${scope}" not granted for session ${this.#sessionId}`)
265
- }
266
- }
267
-
268
- // -- Message handling -----------------------------------------------------
269
-
270
- /**
271
- * Register a handler for a service type.
272
- * Handler signature: async (message, session) => response
273
- *
274
- * @param {string} serviceType - Service type string
275
- * @param {Function} handler - Async handler function
276
- */
277
- registerHandler(serviceType, handler) {
278
- if (typeof handler !== 'function') {
279
- throw new Error('handler must be a function')
280
- }
281
- this.#handlers.set(serviceType, handler)
282
- }
283
-
284
- /**
285
- * Remove a handler for a service type.
286
- *
287
- * @param {string} serviceType - Service type string
288
- */
289
- removeHandler(serviceType) {
290
- this.#handlers.delete(serviceType)
291
- }
292
-
293
- /**
294
- * Send a message to the remote peer.
295
- * Wraps the payload in a session envelope and transmits via transport.
296
- *
297
- * @param {string} serviceType - Message type / service type
298
- * @param {*} payload - Message payload
299
- */
300
- send(serviceType, payload) {
301
- if (this.#state === 'closed') {
302
- throw new Error('Cannot send on a closed session')
303
- }
304
- if (this.#state === 'suspended') {
305
- throw new Error('Cannot send on a suspended session')
306
- }
307
-
308
- const envelope = createEnvelope(
309
- serviceType,
310
- payload,
311
- this.#sessionId,
312
- this.#localIdentity.podId,
313
- )
314
-
315
- this.#transport.send(envelope)
316
- this.#stats.messagesSent++
317
- this.#lastActivity = Date.now()
318
- }
319
-
320
- /**
321
- * Handle an incoming message from the transport.
322
- * Validates the envelope, routes to the appropriate handler, and
323
- * tracks statistics.
324
- *
325
- * @param {*} data - Raw message data
326
- */
327
- #handleMessage(data) {
328
- if (this.#state === 'closed') return
329
-
330
- const envelope = parseEnvelope(data)
331
- if (!envelope) {
332
- this.#stats.errors++
333
- this.#onLog(1, `Invalid envelope on session ${this.#sessionId}`)
334
- return
335
- }
336
-
337
- // Validate session ID matches
338
- if (envelope.sessionId !== this.#sessionId) {
339
- this.#stats.errors++
340
- return
341
- }
342
-
343
- // Validate sender matches expected remote identity
344
- if (envelope.from && this.#remoteIdentity?.podId &&
345
- envelope.from !== this.#remoteIdentity.podId) {
346
- this.#stats.errors++
347
- this.#onLog(1, `Sender mismatch on session ${this.#sessionId}: expected ${this.#remoteIdentity.podId}, got ${envelope.from}`)
348
- return
349
- }
350
-
351
- this.#lastActivity = Date.now()
352
- this.#stats.messagesReceived++
353
-
354
- // Handle built-in ping/pong
355
- if (envelope.type === SESSION_MSG_TYPES.PING) {
356
- this.#handlePing(envelope)
357
- return
358
- }
359
- if (envelope.type === SESSION_MSG_TYPES.PONG) {
360
- this.#handlePong()
361
- return
362
- }
363
-
364
- // Route to registered handler
365
- const handler = this.#handlers.get(envelope.type)
366
- if (!handler) {
367
- this.#onLog(1, `No handler for type "${envelope.type}" on session ${this.#sessionId}`)
368
- return
369
- }
370
-
371
- try {
372
- const result = handler(envelope, this)
373
- // If handler returns a promise, catch rejections
374
- if (result && typeof result.catch === 'function') {
375
- result.catch((err) => {
376
- this.#stats.errors++
377
- this.#onLog(0, `Handler error for "${envelope.type}": ${err.message}`)
378
- })
379
- }
380
- } catch (err) {
381
- this.#stats.errors++
382
- this.#onLog(0, `Handler error for "${envelope.type}": ${err.message}`)
383
- }
384
- }
385
-
386
- /**
387
- * Respond to a ping with a pong.
388
- * @param {object} envelope - Incoming ping envelope
389
- */
390
- #handlePing(envelope) {
391
- if (this.#state !== 'active') return
392
- const pong = createEnvelope(
393
- SESSION_MSG_TYPES.PONG,
394
- { replyTo: envelope.timestamp },
395
- this.#sessionId,
396
- this.#localIdentity.podId,
397
- )
398
- try {
399
- this.#transport.send(pong)
400
- } catch (e) { silentCatch('clawser-peer-session', 'swallow-send-errors-on-pong', e) }
401
- }
402
-
403
- /**
404
- * Handle an incoming pong — reset the heartbeat timeout timer.
405
- */
406
- #handlePong() {
407
- // Reset heartbeat timeout since we got a response
408
- if (this.#heartbeatTimer) {
409
- clearTimeout(this.#heartbeatTimer)
410
- this.#heartbeatTimer = null
411
- }
412
- }
413
-
414
- // -- Heartbeat ------------------------------------------------------------
415
-
416
- /**
417
- * Start sending periodic heartbeat pings.
418
- * If no pong is received within heartbeatTimeoutMs, the session is suspended.
419
- *
420
- * @param {number} [intervalMs=15000] - Interval between pings
421
- */
422
- startHeartbeat(intervalMs = 15000) {
423
- this.stopHeartbeat()
424
- if (this.#state !== 'active') return
425
-
426
- this.#heartbeatInterval = setInterval(() => {
427
- if (this.#state !== 'active') {
428
- this.stopHeartbeat()
429
- return
430
- }
431
-
432
- // Send ping
433
- const ping = createEnvelope(
434
- SESSION_MSG_TYPES.PING,
435
- null,
436
- this.#sessionId,
437
- this.#localIdentity.podId,
438
- )
439
- try {
440
- this.#transport.send(ping)
441
- } catch {
442
- this.suspend()
443
- return
444
- }
445
-
446
- /*
447
- * Arm a pong deadline, and DO NOT disturb one already outstanding.
448
- *
449
- * This used to `clearTimeout` unconditionally before re-arming, which
450
- * made the detector incapable of firing under its own defaults: the
451
- * interval is 15s and the timeout 60s, so each ping cancelled the
452
- * deadline three times over before it could elapse. `#handlePong()`
453
- * already clears it on a reply -- that is the only thing that should.
454
- *
455
- * Measured against a transport that accepts sends and never pongs, at
456
- * the shipped 1:4 ratio scaled down: 21 pings, state still `active`.
457
- * The only configuration in which it worked was the inverted one,
458
- * interval longer than timeout.
459
- *
460
- * The surviving escape was `send()` throwing, which a buffering or
461
- * half-open transport will not do -- so a peer whose tab closed kept a
462
- * session `active` forever, `send()` kept succeeding into a dead pipe,
463
- * and no 'session:suspend' ever fired.
464
- */
465
- if (this.#heartbeatTimer === null) {
466
- this.#heartbeatTimer = setTimeout(() => {
467
- this.#heartbeatTimer = null
468
- if (this.#state === 'active') {
469
- this.#onLog(1, `Heartbeat timeout for session ${this.#sessionId}, suspending`)
470
- this.suspend()
471
- }
472
- }, this.#heartbeatTimeoutMs)
473
- }
474
- }, intervalMs)
475
- }
476
-
477
- /**
478
- * Stop heartbeat pinging and clear timers.
479
- */
480
- stopHeartbeat() {
481
- if (this.#heartbeatInterval) {
482
- clearInterval(this.#heartbeatInterval)
483
- this.#heartbeatInterval = null
484
- }
485
- if (this.#heartbeatTimer) {
486
- clearTimeout(this.#heartbeatTimer)
487
- this.#heartbeatTimer = null
488
- }
489
- }
490
-
491
- // -- Lifecycle ------------------------------------------------------------
492
-
493
- /**
494
- * Suspend the session. Can be resumed later.
495
- */
496
- suspend() {
497
- if (this.#state === 'closed') return
498
- this.#state = 'suspended'
499
- this.stopHeartbeat()
500
- this.#onLog(2, `Session ${this.#sessionId} suspended`)
501
- }
502
-
503
- /**
504
- * Resume a suspended session.
505
- */
506
- resume() {
507
- if (this.#state !== 'suspended') {
508
- throw new Error(`Cannot resume session in state "${this.#state}"`)
509
- }
510
- this.#state = 'active'
511
- this.#lastActivity = Date.now()
512
- this.#onLog(2, `Session ${this.#sessionId} resumed`)
513
- }
514
-
515
- /**
516
- * Close the session permanently. Stops heartbeat and cleans up.
517
- */
518
- close() {
519
- if (this.#state === 'closed') return
520
- this.stopHeartbeat()
521
- this.#state = 'closed'
522
- this.#handlers.clear()
523
- this.#onLog(2, `Session ${this.#sessionId} closed`)
524
- }
525
-
526
- // -- Serialization --------------------------------------------------------
527
-
528
- /**
529
- * Serialize to a JSON-safe object.
530
- * @returns {object}
531
- */
532
- toJSON() {
533
- return {
534
- sessionId: this.#sessionId,
535
- localPodId: this.#localIdentity.podId,
536
- remotePodId: this.#remoteIdentity.podId,
537
- remotePublicKey: this.#remoteIdentity.publicKey || null,
538
- capabilities: [...this.#capabilities],
539
- state: this.#state,
540
- createdAt: this.#createdAt,
541
- lastActivity: this.#lastActivity,
542
- stats: { ...this.#stats },
543
- }
544
- }
545
- }
546
-
547
- // ---------------------------------------------------------------------------
548
- // SessionManager
549
- // ---------------------------------------------------------------------------
550
-
551
- /**
552
- * Manages lifecycle for all active peer sessions.
553
- *
554
- * Provides session creation with rate limiting, access control via ACL,
555
- * audit logging, and periodic pruning of inactive sessions.
556
- */
557
- export class SessionManager {
558
- /** @type {Map<string, PeerSession>} sessionId -> PeerSession */
559
- #sessions = new Map()
560
-
561
- /** @type {Map<string, Set<string>>} remotePodId -> Set<sessionId> */
562
- #peerSessions = new Map()
563
-
564
- /** @type {object|null} MeshACL or duck-typed */
565
- #acl
566
-
567
- /** @type {object|null} AuditChain or duck-typed */
568
- #auditLog
569
-
570
- /** @type {string} */
571
- #localPodId
572
-
573
- /** @type {{ maxSessionsPerPeer: number, maxMessagesPerMinute: number }} */
574
- #rateLimits
575
-
576
- /** @type {Map<string, { count: number, resetAt: number }>} sessionId -> counter */
577
- #messageCounters = new Map()
578
-
579
- /** @type {Function} */
580
- #onLog
581
-
582
- /** @type {Map<string, Set<Function>>} event -> listeners */
583
- #listeners = new Map()
584
-
585
- /**
586
- * @param {object} opts
587
- * @param {string} opts.localPodId - Local pod identifier
588
- * @param {object} [opts.acl] - MeshACL instance or duck-typed { check(identity, resource, action) }
589
- * @param {object} [opts.auditLog] - AuditChain instance or duck-typed { append(author, op, data, signFn) }
590
- * @param {{ maxSessionsPerPeer?: number, maxMessagesPerMinute?: number }} [opts.rateLimits]
591
- * @param {Function} [opts.onLog] - Logging callback
592
- */
593
- constructor({ localPodId, acl, auditLog, rateLimits, onLog }) {
594
- if (!localPodId || typeof localPodId !== 'string') {
595
- throw new Error('localPodId is required and must be a non-empty string')
596
- }
597
- this.#localPodId = localPodId
598
- this.#acl = acl || null
599
- this.#auditLog = auditLog || null
600
- this.#rateLimits = {
601
- maxSessionsPerPeer: rateLimits?.maxSessionsPerPeer ?? 5,
602
- maxMessagesPerMinute: rateLimits?.maxMessagesPerMinute ?? 120,
603
- }
604
- this.#onLog = onLog || (() => {})
605
- }
606
-
607
- // -- Session lifecycle ----------------------------------------------------
608
-
609
- /**
610
- * Create a new session with a remote peer.
611
- *
612
- * Checks per-peer session limits, creates a PeerSession, starts
613
- * heartbeat, logs to audit, and emits 'session:create'.
614
- *
615
- * @param {string} peerId - Remote peer pod ID
616
- * @param {object} transport - Transport with send(data) and onMessage(cb)
617
- * @param {string[]} capabilities - Capabilities granted to the remote peer
618
- * @returns {PeerSession}
619
- */
620
- createSession(peerId, transport, capabilities) {
621
- // Check per-peer session limit
622
- const existing = this.#peerSessions.get(peerId)
623
- const currentCount = existing ? existing.size : 0
624
- if (currentCount >= this.#rateLimits.maxSessionsPerPeer) {
625
- throw new Error(
626
- `Session limit reached for peer ${peerId}: ${currentCount}/${this.#rateLimits.maxSessionsPerPeer}`,
627
- )
628
- }
629
-
630
- const sessionId = generateSessionId()
631
- const session = new PeerSession({
632
- sessionId,
633
- localIdentity: { podId: this.#localPodId },
634
- remoteIdentity: { podId: peerId },
635
- capabilities,
636
- transport,
637
- onLog: this.#onLog,
638
- })
639
-
640
- // Register in maps
641
- this.#sessions.set(sessionId, session)
642
- if (!this.#peerSessions.has(peerId)) {
643
- this.#peerSessions.set(peerId, new Set())
644
- }
645
- this.#peerSessions.get(peerId).add(sessionId)
646
-
647
- // Initialize rate limit counter
648
- this.#messageCounters.set(sessionId, {
649
- count: 0,
650
- resetAt: Date.now() + 60000,
651
- })
652
-
653
- // Start heartbeat
654
- session.startHeartbeat()
655
-
656
- // Audit log
657
- this.logSessionAction(sessionId, 'session:create', {
658
- peerId,
659
- capabilities,
660
- })
661
-
662
- // Emit event
663
- this.#fire('session:create', session)
664
-
665
- this.#onLog(2, `Session ${sessionId} created with peer ${peerId}`)
666
- return session
667
- }
668
-
669
- /**
670
- * End a session by ID. Closes the PeerSession, removes from all maps,
671
- * logs to audit, and emits 'session:end'.
672
- *
673
- * @param {string} sessionId - Session to end
674
- */
675
- endSession(sessionId) {
676
- const session = this.#sessions.get(sessionId)
677
- if (!session) return
678
-
679
- const peerId = session.remotePodId
680
- session.close()
681
-
682
- // Remove from maps
683
- this.#sessions.delete(sessionId)
684
- const peerSet = this.#peerSessions.get(peerId)
685
- if (peerSet) {
686
- peerSet.delete(sessionId)
687
- if (peerSet.size === 0) this.#peerSessions.delete(peerId)
688
- }
689
- this.#messageCounters.delete(sessionId)
690
-
691
- // Audit log
692
- this.logSessionAction(sessionId, 'session:end', { peerId })
693
-
694
- // Emit event
695
- this.#fire('session:end', session)
696
-
697
- this.#onLog(2, `Session ${sessionId} ended with peer ${peerId}`)
698
- }
699
-
700
- // -- Session queries ------------------------------------------------------
701
-
702
- /**
703
- * Get a session by its ID.
704
- *
705
- * @param {string} sessionId
706
- * @returns {PeerSession|null}
707
- */
708
- getSession(sessionId) {
709
- return this.#sessions.get(sessionId) || null
710
- }
711
-
712
- /**
713
- * Get all sessions for a given remote peer.
714
- *
715
- * @param {string} remotePodId
716
- * @returns {PeerSession[]}
717
- */
718
- getSessionsForPeer(remotePodId) {
719
- const ids = this.#peerSessions.get(remotePodId)
720
- if (!ids) return []
721
- return [...ids]
722
- .map((id) => this.#sessions.get(id))
723
- .filter(Boolean)
724
- }
725
-
726
- /**
727
- * List all active sessions.
728
- *
729
- * @returns {PeerSession[]}
730
- */
731
- listSessions() {
732
- return [...this.#sessions.values()]
733
- }
734
-
735
- /**
736
- * Number of active sessions.
737
- * @returns {number}
738
- */
739
- get size() {
740
- return this.#sessions.size
741
- }
742
-
743
- // -- Access control -------------------------------------------------------
744
-
745
- /**
746
- * Check whether a remote peer is allowed to perform an action on a resource.
747
- * Delegates to the ACL if available; otherwise allows all.
748
- *
749
- * @param {string} remotePodId - Remote peer pod ID
750
- * @param {string} resource - Resource identifier
751
- * @param {string} action - Action to check
752
- * @returns {{ allowed: boolean, reason?: string }}
753
- */
754
- checkAccess(remotePodId, resource, action) {
755
- if (!this.#acl) {
756
- return { allowed: true }
757
- }
758
- return this.#acl.check(remotePodId, resource, action)
759
- }
760
-
761
- // -- Rate limiting --------------------------------------------------------
762
-
763
- /**
764
- * Check whether a session is within its message rate limit.
765
- *
766
- * @param {string} sessionId
767
- * @returns {{ allowed: boolean, remaining: number }}
768
- */
769
- checkRateLimit(sessionId) {
770
- const counter = this.#messageCounters.get(sessionId)
771
- if (!counter) {
772
- return { allowed: false, remaining: 0 }
773
- }
774
-
775
- const now = Date.now()
776
- // Reset window if expired
777
- if (now >= counter.resetAt) {
778
- counter.count = 0
779
- counter.resetAt = now + 60000
780
- }
781
-
782
- const remaining = this.#rateLimits.maxMessagesPerMinute - counter.count
783
- return {
784
- allowed: remaining > 0,
785
- remaining: Math.max(0, remaining),
786
- }
787
- }
788
-
789
- /**
790
- * Record a message sent/received on a session for rate limiting.
791
- *
792
- * @param {string} sessionId
793
- */
794
- recordMessage(sessionId) {
795
- const counter = this.#messageCounters.get(sessionId)
796
- if (!counter) return
797
-
798
- const now = Date.now()
799
- // Reset window if expired
800
- if (now >= counter.resetAt) {
801
- counter.count = 0
802
- counter.resetAt = now + 60000
803
- }
804
-
805
- counter.count++
806
- }
807
-
808
- // -- Events ---------------------------------------------------------------
809
-
810
- /**
811
- * Register a listener for session events.
812
- * Events: 'session:create', 'session:end', 'session:error'
813
- *
814
- * @param {string} event
815
- * @param {Function} cb
816
- */
817
- on(event, cb) {
818
- if (!this.#listeners.has(event)) {
819
- this.#listeners.set(event, new Set())
820
- }
821
- this.#listeners.get(event).add(cb)
822
- }
823
-
824
- /**
825
- * Remove a listener for a session event.
826
- *
827
- * @param {string} event
828
- * @param {Function} cb
829
- */
830
- off(event, cb) {
831
- const set = this.#listeners.get(event)
832
- if (set) set.delete(cb)
833
- }
834
-
835
- // -- Audit ----------------------------------------------------------------
836
-
837
- /**
838
- * Log a session action to the audit chain (if available).
839
- * Silently no-ops if no audit log is configured.
840
- *
841
- * @param {string} sessionId - Session identifier
842
- * @param {string} action - Action name
843
- * @param {object} [details] - Additional details
844
- * @param {*} [result] - Action result
845
- */
846
- async logSessionAction(sessionId, action, details, result) {
847
- if (!this.#auditLog) return
848
-
849
- const data = {
850
- sessionId,
851
- action,
852
- details: details || {},
853
- result: result || null,
854
- timestamp: Date.now(),
855
- }
856
-
857
- try {
858
- // AuditChain.append(authorPodId, operation, data, signFn)
859
- // Use a no-op sign function if audit log is duck-typed
860
- await this.#auditLog.append(
861
- this.#localPodId,
862
- action,
863
- data,
864
- async (bytes) => bytes, // placeholder signFn
865
- )
866
- } catch (err) {
867
- this.#onLog(0, `Audit log error: ${err.message}`)
868
- }
869
- }
870
-
871
- // -- Cleanup --------------------------------------------------------------
872
-
873
- /**
874
- * Close all active sessions.
875
- */
876
- closeAll() {
877
- for (const sessionId of [...this.#sessions.keys()]) {
878
- this.endSession(sessionId)
879
- }
880
- }
881
-
882
- /**
883
- * Prune sessions that have been idle longer than the threshold.
884
- *
885
- * @param {number} [maxIdleMs=300000] - Maximum idle time in ms (default 5 min)
886
- * @returns {number} Number of sessions pruned
887
- */
888
- pruneInactive(maxIdleMs = 300000) {
889
- const now = Date.now()
890
- let pruned = 0
891
-
892
- for (const [sessionId, session] of this.#sessions) {
893
- if (now - session.lastActivity >= maxIdleMs) {
894
- this.endSession(sessionId)
895
- pruned++
896
- }
897
- }
898
-
899
- if (pruned > 0) {
900
- this.#onLog(2, `Pruned ${pruned} inactive session(s)`)
901
- }
902
- return pruned
903
- }
904
-
905
- // -- Serialization --------------------------------------------------------
906
-
907
- /**
908
- * Serialize the session manager state.
909
- * @returns {object}
910
- */
911
- toJSON() {
912
- return {
913
- localPodId: this.#localPodId,
914
- sessions: [...this.#sessions.values()].map((s) => s.toJSON()),
915
- rateLimits: { ...this.#rateLimits },
916
- }
917
- }
918
-
919
- // -- Internal -------------------------------------------------------------
920
-
921
- /**
922
- * Fire all listeners for a given event, swallowing listener errors.
923
- * @param {string} event
924
- * @param {*} data
925
- */
926
- #fire(event, data) {
927
- const set = this.#listeners.get(event)
928
- if (!set) return
929
- for (const cb of [...set]) {
930
- try {
931
- cb(data)
932
- } catch {
933
- /* listener errors do not propagate */
934
- }
935
- }
936
- }
937
- }