@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,917 @@
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
+ // Set timeout for pong response
447
+ if (this.#heartbeatTimer) clearTimeout(this.#heartbeatTimer)
448
+ this.#heartbeatTimer = setTimeout(() => {
449
+ if (this.#state === 'active') {
450
+ this.#onLog(1, `Heartbeat timeout for session ${this.#sessionId}, suspending`)
451
+ this.suspend()
452
+ }
453
+ }, this.#heartbeatTimeoutMs)
454
+ }, intervalMs)
455
+ }
456
+
457
+ /**
458
+ * Stop heartbeat pinging and clear timers.
459
+ */
460
+ stopHeartbeat() {
461
+ if (this.#heartbeatInterval) {
462
+ clearInterval(this.#heartbeatInterval)
463
+ this.#heartbeatInterval = null
464
+ }
465
+ if (this.#heartbeatTimer) {
466
+ clearTimeout(this.#heartbeatTimer)
467
+ this.#heartbeatTimer = null
468
+ }
469
+ }
470
+
471
+ // -- Lifecycle ------------------------------------------------------------
472
+
473
+ /**
474
+ * Suspend the session. Can be resumed later.
475
+ */
476
+ suspend() {
477
+ if (this.#state === 'closed') return
478
+ this.#state = 'suspended'
479
+ this.stopHeartbeat()
480
+ this.#onLog(2, `Session ${this.#sessionId} suspended`)
481
+ }
482
+
483
+ /**
484
+ * Resume a suspended session.
485
+ */
486
+ resume() {
487
+ if (this.#state !== 'suspended') {
488
+ throw new Error(`Cannot resume session in state "${this.#state}"`)
489
+ }
490
+ this.#state = 'active'
491
+ this.#lastActivity = Date.now()
492
+ this.#onLog(2, `Session ${this.#sessionId} resumed`)
493
+ }
494
+
495
+ /**
496
+ * Close the session permanently. Stops heartbeat and cleans up.
497
+ */
498
+ close() {
499
+ if (this.#state === 'closed') return
500
+ this.stopHeartbeat()
501
+ this.#state = 'closed'
502
+ this.#handlers.clear()
503
+ this.#onLog(2, `Session ${this.#sessionId} closed`)
504
+ }
505
+
506
+ // -- Serialization --------------------------------------------------------
507
+
508
+ /**
509
+ * Serialize to a JSON-safe object.
510
+ * @returns {object}
511
+ */
512
+ toJSON() {
513
+ return {
514
+ sessionId: this.#sessionId,
515
+ localPodId: this.#localIdentity.podId,
516
+ remotePodId: this.#remoteIdentity.podId,
517
+ remotePublicKey: this.#remoteIdentity.publicKey || null,
518
+ capabilities: [...this.#capabilities],
519
+ state: this.#state,
520
+ createdAt: this.#createdAt,
521
+ lastActivity: this.#lastActivity,
522
+ stats: { ...this.#stats },
523
+ }
524
+ }
525
+ }
526
+
527
+ // ---------------------------------------------------------------------------
528
+ // SessionManager
529
+ // ---------------------------------------------------------------------------
530
+
531
+ /**
532
+ * Manages lifecycle for all active peer sessions.
533
+ *
534
+ * Provides session creation with rate limiting, access control via ACL,
535
+ * audit logging, and periodic pruning of inactive sessions.
536
+ */
537
+ export class SessionManager {
538
+ /** @type {Map<string, PeerSession>} sessionId -> PeerSession */
539
+ #sessions = new Map()
540
+
541
+ /** @type {Map<string, Set<string>>} remotePodId -> Set<sessionId> */
542
+ #peerSessions = new Map()
543
+
544
+ /** @type {object|null} MeshACL or duck-typed */
545
+ #acl
546
+
547
+ /** @type {object|null} AuditChain or duck-typed */
548
+ #auditLog
549
+
550
+ /** @type {string} */
551
+ #localPodId
552
+
553
+ /** @type {{ maxSessionsPerPeer: number, maxMessagesPerMinute: number }} */
554
+ #rateLimits
555
+
556
+ /** @type {Map<string, { count: number, resetAt: number }>} sessionId -> counter */
557
+ #messageCounters = new Map()
558
+
559
+ /** @type {Function} */
560
+ #onLog
561
+
562
+ /** @type {Map<string, Set<Function>>} event -> listeners */
563
+ #listeners = new Map()
564
+
565
+ /**
566
+ * @param {object} opts
567
+ * @param {string} opts.localPodId - Local pod identifier
568
+ * @param {object} [opts.acl] - MeshACL instance or duck-typed { check(identity, resource, action) }
569
+ * @param {object} [opts.auditLog] - AuditChain instance or duck-typed { append(author, op, data, signFn) }
570
+ * @param {{ maxSessionsPerPeer?: number, maxMessagesPerMinute?: number }} [opts.rateLimits]
571
+ * @param {Function} [opts.onLog] - Logging callback
572
+ */
573
+ constructor({ localPodId, acl, auditLog, rateLimits, onLog }) {
574
+ if (!localPodId || typeof localPodId !== 'string') {
575
+ throw new Error('localPodId is required and must be a non-empty string')
576
+ }
577
+ this.#localPodId = localPodId
578
+ this.#acl = acl || null
579
+ this.#auditLog = auditLog || null
580
+ this.#rateLimits = {
581
+ maxSessionsPerPeer: rateLimits?.maxSessionsPerPeer ?? 5,
582
+ maxMessagesPerMinute: rateLimits?.maxMessagesPerMinute ?? 120,
583
+ }
584
+ this.#onLog = onLog || (() => {})
585
+ }
586
+
587
+ // -- Session lifecycle ----------------------------------------------------
588
+
589
+ /**
590
+ * Create a new session with a remote peer.
591
+ *
592
+ * Checks per-peer session limits, creates a PeerSession, starts
593
+ * heartbeat, logs to audit, and emits 'session:create'.
594
+ *
595
+ * @param {string} peerId - Remote peer pod ID
596
+ * @param {object} transport - Transport with send(data) and onMessage(cb)
597
+ * @param {string[]} capabilities - Capabilities granted to the remote peer
598
+ * @returns {PeerSession}
599
+ */
600
+ createSession(peerId, transport, capabilities) {
601
+ // Check per-peer session limit
602
+ const existing = this.#peerSessions.get(peerId)
603
+ const currentCount = existing ? existing.size : 0
604
+ if (currentCount >= this.#rateLimits.maxSessionsPerPeer) {
605
+ throw new Error(
606
+ `Session limit reached for peer ${peerId}: ${currentCount}/${this.#rateLimits.maxSessionsPerPeer}`,
607
+ )
608
+ }
609
+
610
+ const sessionId = generateSessionId()
611
+ const session = new PeerSession({
612
+ sessionId,
613
+ localIdentity: { podId: this.#localPodId },
614
+ remoteIdentity: { podId: peerId },
615
+ capabilities,
616
+ transport,
617
+ onLog: this.#onLog,
618
+ })
619
+
620
+ // Register in maps
621
+ this.#sessions.set(sessionId, session)
622
+ if (!this.#peerSessions.has(peerId)) {
623
+ this.#peerSessions.set(peerId, new Set())
624
+ }
625
+ this.#peerSessions.get(peerId).add(sessionId)
626
+
627
+ // Initialize rate limit counter
628
+ this.#messageCounters.set(sessionId, {
629
+ count: 0,
630
+ resetAt: Date.now() + 60000,
631
+ })
632
+
633
+ // Start heartbeat
634
+ session.startHeartbeat()
635
+
636
+ // Audit log
637
+ this.logSessionAction(sessionId, 'session:create', {
638
+ peerId,
639
+ capabilities,
640
+ })
641
+
642
+ // Emit event
643
+ this.#fire('session:create', session)
644
+
645
+ this.#onLog(2, `Session ${sessionId} created with peer ${peerId}`)
646
+ return session
647
+ }
648
+
649
+ /**
650
+ * End a session by ID. Closes the PeerSession, removes from all maps,
651
+ * logs to audit, and emits 'session:end'.
652
+ *
653
+ * @param {string} sessionId - Session to end
654
+ */
655
+ endSession(sessionId) {
656
+ const session = this.#sessions.get(sessionId)
657
+ if (!session) return
658
+
659
+ const peerId = session.remotePodId
660
+ session.close()
661
+
662
+ // Remove from maps
663
+ this.#sessions.delete(sessionId)
664
+ const peerSet = this.#peerSessions.get(peerId)
665
+ if (peerSet) {
666
+ peerSet.delete(sessionId)
667
+ if (peerSet.size === 0) this.#peerSessions.delete(peerId)
668
+ }
669
+ this.#messageCounters.delete(sessionId)
670
+
671
+ // Audit log
672
+ this.logSessionAction(sessionId, 'session:end', { peerId })
673
+
674
+ // Emit event
675
+ this.#fire('session:end', session)
676
+
677
+ this.#onLog(2, `Session ${sessionId} ended with peer ${peerId}`)
678
+ }
679
+
680
+ // -- Session queries ------------------------------------------------------
681
+
682
+ /**
683
+ * Get a session by its ID.
684
+ *
685
+ * @param {string} sessionId
686
+ * @returns {PeerSession|null}
687
+ */
688
+ getSession(sessionId) {
689
+ return this.#sessions.get(sessionId) || null
690
+ }
691
+
692
+ /**
693
+ * Get all sessions for a given remote peer.
694
+ *
695
+ * @param {string} remotePodId
696
+ * @returns {PeerSession[]}
697
+ */
698
+ getSessionsForPeer(remotePodId) {
699
+ const ids = this.#peerSessions.get(remotePodId)
700
+ if (!ids) return []
701
+ return [...ids]
702
+ .map((id) => this.#sessions.get(id))
703
+ .filter(Boolean)
704
+ }
705
+
706
+ /**
707
+ * List all active sessions.
708
+ *
709
+ * @returns {PeerSession[]}
710
+ */
711
+ listSessions() {
712
+ return [...this.#sessions.values()]
713
+ }
714
+
715
+ /**
716
+ * Number of active sessions.
717
+ * @returns {number}
718
+ */
719
+ get size() {
720
+ return this.#sessions.size
721
+ }
722
+
723
+ // -- Access control -------------------------------------------------------
724
+
725
+ /**
726
+ * Check whether a remote peer is allowed to perform an action on a resource.
727
+ * Delegates to the ACL if available; otherwise allows all.
728
+ *
729
+ * @param {string} remotePodId - Remote peer pod ID
730
+ * @param {string} resource - Resource identifier
731
+ * @param {string} action - Action to check
732
+ * @returns {{ allowed: boolean, reason?: string }}
733
+ */
734
+ checkAccess(remotePodId, resource, action) {
735
+ if (!this.#acl) {
736
+ return { allowed: true }
737
+ }
738
+ return this.#acl.check(remotePodId, resource, action)
739
+ }
740
+
741
+ // -- Rate limiting --------------------------------------------------------
742
+
743
+ /**
744
+ * Check whether a session is within its message rate limit.
745
+ *
746
+ * @param {string} sessionId
747
+ * @returns {{ allowed: boolean, remaining: number }}
748
+ */
749
+ checkRateLimit(sessionId) {
750
+ const counter = this.#messageCounters.get(sessionId)
751
+ if (!counter) {
752
+ return { allowed: false, remaining: 0 }
753
+ }
754
+
755
+ const now = Date.now()
756
+ // Reset window if expired
757
+ if (now >= counter.resetAt) {
758
+ counter.count = 0
759
+ counter.resetAt = now + 60000
760
+ }
761
+
762
+ const remaining = this.#rateLimits.maxMessagesPerMinute - counter.count
763
+ return {
764
+ allowed: remaining > 0,
765
+ remaining: Math.max(0, remaining),
766
+ }
767
+ }
768
+
769
+ /**
770
+ * Record a message sent/received on a session for rate limiting.
771
+ *
772
+ * @param {string} sessionId
773
+ */
774
+ recordMessage(sessionId) {
775
+ const counter = this.#messageCounters.get(sessionId)
776
+ if (!counter) return
777
+
778
+ const now = Date.now()
779
+ // Reset window if expired
780
+ if (now >= counter.resetAt) {
781
+ counter.count = 0
782
+ counter.resetAt = now + 60000
783
+ }
784
+
785
+ counter.count++
786
+ }
787
+
788
+ // -- Events ---------------------------------------------------------------
789
+
790
+ /**
791
+ * Register a listener for session events.
792
+ * Events: 'session:create', 'session:end', 'session:error'
793
+ *
794
+ * @param {string} event
795
+ * @param {Function} cb
796
+ */
797
+ on(event, cb) {
798
+ if (!this.#listeners.has(event)) {
799
+ this.#listeners.set(event, new Set())
800
+ }
801
+ this.#listeners.get(event).add(cb)
802
+ }
803
+
804
+ /**
805
+ * Remove a listener for a session event.
806
+ *
807
+ * @param {string} event
808
+ * @param {Function} cb
809
+ */
810
+ off(event, cb) {
811
+ const set = this.#listeners.get(event)
812
+ if (set) set.delete(cb)
813
+ }
814
+
815
+ // -- Audit ----------------------------------------------------------------
816
+
817
+ /**
818
+ * Log a session action to the audit chain (if available).
819
+ * Silently no-ops if no audit log is configured.
820
+ *
821
+ * @param {string} sessionId - Session identifier
822
+ * @param {string} action - Action name
823
+ * @param {object} [details] - Additional details
824
+ * @param {*} [result] - Action result
825
+ */
826
+ async logSessionAction(sessionId, action, details, result) {
827
+ if (!this.#auditLog) return
828
+
829
+ const data = {
830
+ sessionId,
831
+ action,
832
+ details: details || {},
833
+ result: result || null,
834
+ timestamp: Date.now(),
835
+ }
836
+
837
+ try {
838
+ // AuditChain.append(authorPodId, operation, data, signFn)
839
+ // Use a no-op sign function if audit log is duck-typed
840
+ await this.#auditLog.append(
841
+ this.#localPodId,
842
+ action,
843
+ data,
844
+ async (bytes) => bytes, // placeholder signFn
845
+ )
846
+ } catch (err) {
847
+ this.#onLog(0, `Audit log error: ${err.message}`)
848
+ }
849
+ }
850
+
851
+ // -- Cleanup --------------------------------------------------------------
852
+
853
+ /**
854
+ * Close all active sessions.
855
+ */
856
+ closeAll() {
857
+ for (const sessionId of [...this.#sessions.keys()]) {
858
+ this.endSession(sessionId)
859
+ }
860
+ }
861
+
862
+ /**
863
+ * Prune sessions that have been idle longer than the threshold.
864
+ *
865
+ * @param {number} [maxIdleMs=300000] - Maximum idle time in ms (default 5 min)
866
+ * @returns {number} Number of sessions pruned
867
+ */
868
+ pruneInactive(maxIdleMs = 300000) {
869
+ const now = Date.now()
870
+ let pruned = 0
871
+
872
+ for (const [sessionId, session] of this.#sessions) {
873
+ if (now - session.lastActivity >= maxIdleMs) {
874
+ this.endSession(sessionId)
875
+ pruned++
876
+ }
877
+ }
878
+
879
+ if (pruned > 0) {
880
+ this.#onLog(2, `Pruned ${pruned} inactive session(s)`)
881
+ }
882
+ return pruned
883
+ }
884
+
885
+ // -- Serialization --------------------------------------------------------
886
+
887
+ /**
888
+ * Serialize the session manager state.
889
+ * @returns {object}
890
+ */
891
+ toJSON() {
892
+ return {
893
+ localPodId: this.#localPodId,
894
+ sessions: [...this.#sessions.values()].map((s) => s.toJSON()),
895
+ rateLimits: { ...this.#rateLimits },
896
+ }
897
+ }
898
+
899
+ // -- Internal -------------------------------------------------------------
900
+
901
+ /**
902
+ * Fire all listeners for a given event, swallowing listener errors.
903
+ * @param {string} event
904
+ * @param {*} data
905
+ */
906
+ #fire(event, data) {
907
+ const set = this.#listeners.get(event)
908
+ if (!set) return
909
+ for (const cb of [...set]) {
910
+ try {
911
+ cb(data)
912
+ } catch {
913
+ /* listener errors do not propagate */
914
+ }
915
+ }
916
+ }
917
+ }