@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,793 @@
1
+ /**
2
+ * clawser-peer-node.js -- Top-level P2P mesh orchestrator.
3
+ *
4
+ * Wires together IdentityWallet, PeerRegistry, DiscoveryManager,
5
+ * MeshTransportNegotiator, and AuditChain into a unified PeerNode
6
+ * lifecycle. All subsystems are accepted via dependency injection --
7
+ * no imports at module level.
8
+ *
9
+ * No browser-only imports at module level.
10
+ *
11
+ * Run tests:
12
+ * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-peer-node.test.mjs
13
+ */
14
+
15
+ // ---------------------------------------------------------------------------
16
+ // Valid lifecycle states
17
+ // ---------------------------------------------------------------------------
18
+
19
+ const PEER_NODE_STATES = Object.freeze([
20
+ 'stopped',
21
+ 'booting',
22
+ 'running',
23
+ 'shutting_down',
24
+ ])
25
+
26
+ // ---------------------------------------------------------------------------
27
+ // PeerNode
28
+ // ---------------------------------------------------------------------------
29
+
30
+ /**
31
+ * Top-level orchestrator for a mesh peer. Manages the full lifecycle
32
+ * from identity bootstrap through discovery, connection, and shutdown.
33
+ *
34
+ * All subsystems are injected via the constructor. Only `wallet` and
35
+ * `registry` are required; discovery, transport negotiation, and audit
36
+ * are optional and gracefully degrade when absent.
37
+ */
38
+ export class PeerNode {
39
+ /** @type {import('@johnhenry/browsermesh-core').IdentityWallet} */
40
+ #wallet
41
+
42
+ /** @type {import('./peer-registry.mjs').PeerRegistry} */
43
+ #registry
44
+
45
+ /** @type {import('@johnhenry/browsermesh-discovery').DiscoveryManager|null} */
46
+ #discovery
47
+
48
+ /** @type {import('@johnhenry/browsermesh-transport').MeshTransportNegotiator|null} */
49
+ #transportNeg
50
+
51
+ /** @type {import('./audit.mjs').AuditChain|null} */
52
+ #auditChain
53
+
54
+ /** @type {Map<string, object>} sessionId -> session info */
55
+ #sessions = new Map()
56
+
57
+ /** @type {'stopped'|'booting'|'running'|'shutting_down'} */
58
+ #state = 'stopped'
59
+
60
+ /** @type {Function} */
61
+ #onLog
62
+
63
+ /** @type {Map<string, Set<Function>>} event -> callbacks */
64
+ #listeners = new Map()
65
+
66
+ /** @type {Set<Function>} listeners for raw incoming session data
67
+ * (cb(pubKey, data, {sessionId, transport})). Used by ClawserPod
68
+ * to surface a pod-level message bus on top of per-transport
69
+ * inbound bytes. */
70
+ #dataListeners = new Set()
71
+
72
+ /** @type {Function|null} bound peer connect listener for cleanup */
73
+ #boundPeerConnect = null
74
+
75
+ /** @type {Function|null} bound peer disconnect listener for cleanup */
76
+ #boundPeerDisconnect = null
77
+
78
+ /**
79
+ * @param {object} opts
80
+ * @param {import('@johnhenry/browsermesh-core').IdentityWallet} opts.wallet
81
+ * @param {import('./peer-registry.mjs').PeerRegistry} opts.registry
82
+ * @param {import('@johnhenry/browsermesh-discovery').DiscoveryManager} [opts.discovery]
83
+ * @param {import('@johnhenry/browsermesh-transport').MeshTransportNegotiator} [opts.transportNegotiator]
84
+ * @param {import('./audit.mjs').AuditChain} [opts.auditChain]
85
+ * @param {Function} [opts.onLog]
86
+ */
87
+ constructor({ wallet, registry, discovery, transportNegotiator, auditChain, onLog }) {
88
+ if (!wallet) {
89
+ throw new Error('wallet is required')
90
+ }
91
+ if (!registry) {
92
+ throw new Error('registry is required')
93
+ }
94
+
95
+ this.#wallet = wallet
96
+ this.#registry = registry
97
+ this.#discovery = discovery || null
98
+ this.#transportNeg = transportNegotiator || null
99
+ this.#auditChain = auditChain || null
100
+ this.#onLog = onLog || (() => {})
101
+ }
102
+
103
+ // -----------------------------------------------------------------------
104
+ // Lifecycle
105
+ // -----------------------------------------------------------------------
106
+
107
+ /**
108
+ * Boot the peer node. Creates a default identity if none exist,
109
+ * starts discovery, and transitions to 'running'.
110
+ *
111
+ * @param {object} [opts]
112
+ * @param {string} [opts.label='default'] - Label for auto-created identity
113
+ * @param {boolean} [opts.skipDiscovery=false] - Skip starting discovery
114
+ * @returns {Promise<void>}
115
+ */
116
+ async boot(opts = {}) {
117
+ if (this.#state === 'running') {
118
+ throw new Error('PeerNode is already running')
119
+ }
120
+ if (this.#state === 'booting') {
121
+ throw new Error('PeerNode is already booting')
122
+ }
123
+ if (this.#state === 'shutting_down') {
124
+ throw new Error('PeerNode is shutting down')
125
+ }
126
+
127
+ this.#state = 'booting'
128
+ this.#onLog('peer-node:boot:start', { state: this.#state })
129
+
130
+ try {
131
+ // Ensure at least one identity exists
132
+ const identities = this.#wallet.listIdentities()
133
+ if (identities.length === 0) {
134
+ const label = opts.label || 'default'
135
+ await this.#wallet.createIdentity(label)
136
+ this.#onLog('peer-node:identity:auto-created', { label })
137
+ }
138
+
139
+ // Start discovery if available and not skipped
140
+ if (this.#discovery && !opts.skipDiscovery) {
141
+ await this.#discovery.start()
142
+ this.#onLog('peer-node:discovery:started', {})
143
+ }
144
+
145
+ // Wire registry events to our event bus (store refs for cleanup)
146
+ this.#boundPeerConnect = (peer) => { this.#emit('peer:connect', peer) } // emitted for future extension hooks
147
+ this.#boundPeerDisconnect = (peer) => { this.#emit('peer:disconnect', peer) } // emitted for future extension hooks
148
+ this.#registry.onPeerConnect(this.#boundPeerConnect)
149
+ this.#registry.onPeerDisconnect(this.#boundPeerDisconnect)
150
+
151
+ // Transition to running
152
+ this.#state = 'running'
153
+ this.#onLog('peer-node:boot:complete', { podId: this.podId })
154
+
155
+ // Log boot to audit chain
156
+ await this.#audit('peer-node:boot', {
157
+ podId: this.podId,
158
+ timestamp: Date.now(),
159
+ })
160
+
161
+ this.#emit('boot', { podId: this.podId })
162
+ } catch (err) {
163
+ this.#state = 'stopped'
164
+ this.#onLog('peer-node:boot:failed', { error: err.message })
165
+ throw err
166
+ }
167
+ }
168
+
169
+ /**
170
+ * Shut down the peer node. Stops discovery, disconnects all peers,
171
+ * cleans up sessions, and transitions to 'stopped'.
172
+ *
173
+ * @returns {Promise<void>}
174
+ */
175
+ async shutdown() {
176
+ if (this.#state === 'stopped') {
177
+ return
178
+ }
179
+ if (this.#state === 'shutting_down') {
180
+ throw new Error('PeerNode is already shutting down')
181
+ }
182
+
183
+ const previousState = this.#state
184
+ this.#state = 'shutting_down'
185
+ this.#onLog('peer-node:shutdown:start', { previousState })
186
+
187
+ try {
188
+ // Stop discovery
189
+ if (this.#discovery) {
190
+ await this.#discovery.stop()
191
+ this.#onLog('peer-node:discovery:stopped', {})
192
+ }
193
+
194
+ // Remove registry event listeners to prevent accumulation on re-boot
195
+ if (this.#boundPeerConnect && this.#registry.offPeerConnect) {
196
+ this.#registry.offPeerConnect(this.#boundPeerConnect)
197
+ }
198
+ if (this.#boundPeerDisconnect && this.#registry.offPeerDisconnect) {
199
+ this.#registry.offPeerDisconnect(this.#boundPeerDisconnect)
200
+ }
201
+ this.#boundPeerConnect = null
202
+ this.#boundPeerDisconnect = null
203
+
204
+ // Disconnect all peers
205
+ this.#registry.disconnectAll()
206
+
207
+ // Clear all sessions
208
+ this.#sessions.clear()
209
+
210
+ // Log shutdown to audit chain
211
+ await this.#audit('peer-node:shutdown', {
212
+ podId: this.podId,
213
+ timestamp: Date.now(),
214
+ })
215
+
216
+ this.#state = 'stopped'
217
+ this.#onLog('peer-node:shutdown:complete', {})
218
+ this.#emit('shutdown', { podId: this.podId })
219
+ } catch (err) {
220
+ // Force stopped even on error
221
+ this.#state = 'stopped'
222
+ this.#onLog('peer-node:shutdown:error', { error: err.message })
223
+ throw err
224
+ }
225
+ }
226
+
227
+ /**
228
+ * Current lifecycle state.
229
+ *
230
+ * @returns {'stopped'|'booting'|'running'|'shutting_down'}
231
+ */
232
+ get state() {
233
+ return this.#state
234
+ }
235
+
236
+ // -----------------------------------------------------------------------
237
+ // Identity shortcuts
238
+ // -----------------------------------------------------------------------
239
+
240
+ /**
241
+ * The default identity's podId, or null if no identities exist.
242
+ *
243
+ * @returns {string|null}
244
+ */
245
+ get podId() {
246
+ const def = this.#wallet.getDefault()
247
+ return def ? def.podId : null
248
+ }
249
+
250
+ /**
251
+ * The identity wallet.
252
+ *
253
+ * @returns {import('@johnhenry/browsermesh-core').IdentityWallet}
254
+ */
255
+ get wallet() {
256
+ return this.#wallet
257
+ }
258
+
259
+ // -----------------------------------------------------------------------
260
+ // Registry shortcuts
261
+ // -----------------------------------------------------------------------
262
+
263
+ /**
264
+ * The peer registry.
265
+ *
266
+ * @returns {import('./peer-registry.mjs').PeerRegistry}
267
+ */
268
+ get registry() {
269
+ return this.#registry
270
+ }
271
+
272
+ /**
273
+ * Add a peer to the registry.
274
+ *
275
+ * @param {string} pubKey - Peer fingerprint / public key hash
276
+ * @param {string} [label] - Human-readable name
277
+ * @param {string[]} [caps] - Initial capability scopes
278
+ * @returns {import('@johnhenry/browsermesh-core').PeerState}
279
+ */
280
+ addPeer(pubKey, label, caps) {
281
+ this.#ensureRunning('addPeer')
282
+ const peer = this.#registry.addPeer(pubKey, label, caps)
283
+ this.#onLog('peer-node:peer:add', { pubKey, label })
284
+ return peer
285
+ }
286
+
287
+ /**
288
+ * Remove a peer from the registry and clean up its sessions.
289
+ *
290
+ * @param {string} pubKey
291
+ * @returns {boolean} true if the peer existed
292
+ */
293
+ removePeer(pubKey) {
294
+ this.#ensureRunning('removePeer')
295
+
296
+ // Remove any sessions associated with this peer
297
+ for (const [sessionId, session] of this.#sessions) {
298
+ if (session.pubKey === pubKey) {
299
+ this.#sessions.delete(sessionId)
300
+ }
301
+ }
302
+
303
+ const removed = this.#registry.removePeer(pubKey)
304
+ if (removed) {
305
+ this.#onLog('peer-node:peer:remove', { pubKey })
306
+ }
307
+ return removed
308
+ }
309
+
310
+ /**
311
+ * List peers, optionally filtered.
312
+ *
313
+ * @param {object} [filter]
314
+ * @param {string} [filter.status]
315
+ * @param {number} [filter.minTrust]
316
+ * @returns {import('@johnhenry/browsermesh-core').PeerState[]}
317
+ */
318
+ listPeers(filter) {
319
+ return this.#registry.listPeers(filter)
320
+ }
321
+
322
+ // -----------------------------------------------------------------------
323
+ // Connection management
324
+ // -----------------------------------------------------------------------
325
+
326
+ /**
327
+ * Connect to a peer using the transport negotiator (if available)
328
+ * or falling back to direct registry connection.
329
+ *
330
+ * Creates a session entry and logs the connection to the audit chain.
331
+ *
332
+ * @param {string} pubKey - Peer fingerprint / public key hash
333
+ * @param {object} [endpoints] - Map of transport type -> endpoint string
334
+ * @param {object} [auth] - Auth credentials for transport negotiation
335
+ * @returns {Promise<object>} Session info
336
+ */
337
+ async connectToPeer(pubKey, endpoints, auth) {
338
+ this.#ensureRunning('connectToPeer')
339
+
340
+ let transport = null
341
+ let transportType = null
342
+
343
+ // Try transport negotiation if we have a negotiator and endpoints
344
+ if (this.#transportNeg && endpoints && Object.keys(endpoints).length > 0) {
345
+ try {
346
+ transport = await this.#transportNeg.negotiate(endpoints, auth)
347
+ transportType = transport.type
348
+ this.#onLog('peer-node:transport:negotiated', { pubKey, type: transportType })
349
+ } catch (err) {
350
+ this.#onLog('peer-node:transport:negotiation-failed', {
351
+ pubKey,
352
+ error: err.message,
353
+ })
354
+ // Fall through to direct registry connection
355
+ }
356
+ }
357
+
358
+ // Connect through the registry
359
+ const connectOpts = {}
360
+ if (transportType) connectOpts.transport = transportType
361
+ if (endpoints) {
362
+ // Use the first available endpoint as a fallback
363
+ const firstEndpoint = Object.values(endpoints)[0]
364
+ if (firstEndpoint) connectOpts.endpoint = firstEndpoint
365
+ }
366
+
367
+ this.#registry.connect(pubKey, connectOpts)
368
+
369
+ // Create session
370
+ const sessionId = crypto.randomUUID()
371
+ const session = {
372
+ sessionId,
373
+ pubKey,
374
+ transport: transportType,
375
+ transportInstance: transport,
376
+ connectedAt: Date.now(),
377
+ state: 'active',
378
+ }
379
+ this.#sessions.set(sessionId, session)
380
+
381
+ // Wire inbound data fan-out — every connected transport pushes
382
+ // received bytes to subscribers registered via `onIncomingData`.
383
+ // This is what backs `ClawserPod.onMessage` so workspace consumers
384
+ // can route incoming sync/deploy envelopes by `envelope.type`.
385
+ if (transport && typeof transport.onMessage === 'function') {
386
+ transport.onMessage((data) => {
387
+ for (const cb of this.#dataListeners) {
388
+ try { cb(pubKey, data, { sessionId, transport: transportType }) }
389
+ catch (err) { this.#onLog('peer-node:data-listener-error', { error: err?.message || String(err) }) }
390
+ }
391
+ })
392
+ }
393
+
394
+ this.#onLog('peer-node:session:created', { sessionId, pubKey, transport: transportType })
395
+
396
+ // Log to audit chain
397
+ await this.#audit('peer-node:connect', {
398
+ sessionId,
399
+ pubKey,
400
+ transport: transportType,
401
+ })
402
+
403
+ return { ...session, transportInstance: undefined }
404
+ }
405
+
406
+ /**
407
+ * Send raw bytes/data to a connected peer via its current transport
408
+ * session. Looks up the most recently-created active session for the
409
+ * given pubKey and calls `transport.send(data)`.
410
+ *
411
+ * Throws when no active session exists for the peer (caller should
412
+ * either connect first or surface the error to the user).
413
+ *
414
+ * @param {string} pubKey - Peer fingerprint / public key hash
415
+ * @param {*} data - Wire payload to send. Format is transport-defined;
416
+ * typical callers stringify a JSON envelope first.
417
+ * @returns {Promise<void>} Resolves when the underlying transport
418
+ * has accepted the send (transport-defined; some are fire-and-
419
+ * forget, others await an ack).
420
+ *
421
+ * @example
422
+ * await peerNode.sendTo('podid_abc', JSON.stringify({ type: 'ping' }));
423
+ */
424
+ async sendTo(pubKey, data) {
425
+ this.#ensureRunning('sendTo');
426
+ let session = null;
427
+ for (const [, s] of this.#sessions) {
428
+ if (s.pubKey === pubKey && s.state === 'active') {
429
+ // Prefer the most recently-created active session
430
+ if (!session || (s.connectedAt || 0) > (session.connectedAt || 0)) session = s;
431
+ }
432
+ }
433
+ if (!session) {
434
+ throw new Error(`PeerNode.sendTo: no active session for pubKey ${pubKey}`);
435
+ }
436
+ if (!session.transportInstance || typeof session.transportInstance.send !== 'function') {
437
+ throw new Error(`PeerNode.sendTo: session for ${pubKey} has no transport.send`);
438
+ }
439
+ return session.transportInstance.send(data);
440
+ }
441
+
442
+ /**
443
+ * Subscribe to raw incoming data from any session. The callback
444
+ * receives `(pubKey, data, {sessionId, transport})`. Used by
445
+ * `ClawserPod.onMessage` to fan an envelope-level dispatch on
446
+ * top of per-transport bytes. Returns an unsubscribe function.
447
+ *
448
+ * @param {(pubKey:string, data:any, meta:{sessionId:string, transport:string}) => void} cb
449
+ * @returns {() => void}
450
+ */
451
+ onIncomingData(cb) {
452
+ if (typeof cb !== 'function') return () => {}
453
+ this.#dataListeners.add(cb)
454
+ return () => this.#dataListeners.delete(cb)
455
+ }
456
+
457
+ /**
458
+ * Whether the peer has an active session ready for `sendTo`.
459
+ *
460
+ * @param {string} pubKey
461
+ * @returns {boolean}
462
+ */
463
+ hasActiveSession(pubKey) {
464
+ for (const [, s] of this.#sessions) {
465
+ if (s.pubKey === pubKey && s.state === 'active') return true;
466
+ }
467
+ return false;
468
+ }
469
+
470
+ /**
471
+ * Disconnect a peer and clean up its sessions.
472
+ *
473
+ * @param {string} pubKey
474
+ */
475
+ disconnectPeer(pubKey) {
476
+ this.#ensureRunning('disconnectPeer')
477
+
478
+ // Close transport instances and remove sessions for this peer
479
+ for (const [sessionId, session] of this.#sessions) {
480
+ if (session.pubKey === pubKey) {
481
+ if (session.transportInstance && typeof session.transportInstance.close === 'function') {
482
+ try {
483
+ session.transportInstance.close()
484
+ } catch {
485
+ // Swallow close errors
486
+ }
487
+ }
488
+ session.state = 'closed'
489
+ this.#sessions.delete(sessionId)
490
+ this.#onLog('peer-node:session:closed', { sessionId, pubKey })
491
+ }
492
+ }
493
+
494
+ this.#registry.disconnect(pubKey)
495
+ this.#onLog('peer-node:peer:disconnect', { pubKey })
496
+ }
497
+
498
+ // -----------------------------------------------------------------------
499
+ // Session tracking
500
+ // -----------------------------------------------------------------------
501
+
502
+ /**
503
+ * Get a session by ID.
504
+ *
505
+ * @param {string} sessionId
506
+ * @returns {object|null} Session info (without transport instance)
507
+ */
508
+ getSession(sessionId) {
509
+ const session = this.#sessions.get(sessionId)
510
+ if (!session) return null
511
+ return { ...session, transportInstance: undefined }
512
+ }
513
+
514
+ /**
515
+ * List all active sessions.
516
+ *
517
+ * @returns {object[]} Session info array (without transport instances)
518
+ */
519
+ listSessions() {
520
+ const result = []
521
+ for (const session of this.#sessions.values()) {
522
+ result.push({ ...session, transportInstance: undefined })
523
+ }
524
+ return result
525
+ }
526
+
527
+ // -----------------------------------------------------------------------
528
+ // Discovery
529
+ // -----------------------------------------------------------------------
530
+
531
+ /**
532
+ * Announce this node to the mesh network via discovery.
533
+ * No-op if discovery is not configured.
534
+ *
535
+ * @returns {Promise<void>}
536
+ */
537
+ async announce() {
538
+ this.#ensureRunning('announce')
539
+
540
+ if (!this.#discovery) {
541
+ this.#onLog('peer-node:announce:skip', { reason: 'no discovery manager' })
542
+ return
543
+ }
544
+
545
+ await this.#discovery.announce()
546
+ this.#onLog('peer-node:announce:complete', { podId: this.podId })
547
+ }
548
+
549
+ /**
550
+ * Discover peers on the mesh network.
551
+ * Returns an empty array if discovery is not configured.
552
+ *
553
+ * @param {object} [filter]
554
+ * @param {string[]} [filter.capabilities] - Required capabilities
555
+ * @returns {Promise<import('@johnhenry/browsermesh-discovery').DiscoveryRecord[]>}
556
+ */
557
+ async discover(filter) {
558
+ this.#ensureRunning('discover')
559
+
560
+ if (!this.#discovery) {
561
+ this.#onLog('peer-node:discover:skip', { reason: 'no discovery manager' })
562
+ return []
563
+ }
564
+
565
+ const records = await this.#discovery.discover(filter)
566
+ this.#onLog('peer-node:discover:complete', { count: records.length })
567
+ return records
568
+ }
569
+
570
+ // -----------------------------------------------------------------------
571
+ // Audit
572
+ // -----------------------------------------------------------------------
573
+
574
+ /**
575
+ * Log an action to the audit chain.
576
+ * No-op if audit chain is not configured.
577
+ *
578
+ * @param {string} operation - Operation name
579
+ * @param {*} data - Arbitrary payload
580
+ * @returns {Promise<void>}
581
+ */
582
+ async logAction(operation, data) {
583
+ await this.#audit(operation, data)
584
+ }
585
+
586
+ /**
587
+ * Get all audit entries.
588
+ * Returns an empty array if audit chain is not configured.
589
+ *
590
+ * @returns {import('./audit.mjs').AuditEntry[]}
591
+ */
592
+ getAuditEntries() {
593
+ if (!this.#auditChain) return []
594
+ return [...this.#auditChain.entries()]
595
+ }
596
+
597
+ // -----------------------------------------------------------------------
598
+ // Events
599
+ // -----------------------------------------------------------------------
600
+
601
+ /**
602
+ * Register a callback for a node event.
603
+ *
604
+ * Supported events:
605
+ * - 'peer:connect' — fired when a peer connects
606
+ * - 'peer:disconnect' — fired when a peer disconnects
607
+ * - 'boot' — fired after successful boot
608
+ * - 'shutdown' — fired after shutdown
609
+ *
610
+ * @param {string} event
611
+ * @param {Function} cb
612
+ */
613
+ on(event, cb) {
614
+ if (typeof cb !== 'function') {
615
+ throw new Error('Callback must be a function')
616
+ }
617
+ if (!this.#listeners.has(event)) {
618
+ this.#listeners.set(event, new Set())
619
+ }
620
+ this.#listeners.get(event).add(cb)
621
+ }
622
+
623
+ /**
624
+ * Remove a callback for a node event.
625
+ *
626
+ * @param {string} event
627
+ * @param {Function} cb
628
+ */
629
+ off(event, cb) {
630
+ const cbs = this.#listeners.get(event)
631
+ if (cbs) {
632
+ cbs.delete(cb)
633
+ if (cbs.size === 0) {
634
+ this.#listeners.delete(event)
635
+ }
636
+ }
637
+ }
638
+
639
+ // -----------------------------------------------------------------------
640
+ // Persistence
641
+ // -----------------------------------------------------------------------
642
+
643
+ /**
644
+ * Serialize the PeerNode state to a JSON-safe object.
645
+ * Includes wallet, registry, discovery, audit, and session data.
646
+ *
647
+ * @returns {object}
648
+ */
649
+ toJSON() {
650
+ const sessions = []
651
+ for (const session of this.#sessions.values()) {
652
+ sessions.push({
653
+ sessionId: session.sessionId,
654
+ pubKey: session.pubKey,
655
+ transport: session.transport,
656
+ connectedAt: session.connectedAt,
657
+ state: session.state,
658
+ })
659
+ }
660
+
661
+ return {
662
+ state: this.#state,
663
+ wallet: this.#wallet.toJSON(),
664
+ registry: this.#registry.toJSON(),
665
+ discovery: this.#discovery && typeof this.#discovery.toJSON === 'function'
666
+ ? this.#discovery.toJSON()
667
+ : null,
668
+ auditChain: this.#auditChain && typeof this.#auditChain.toJSON === 'function'
669
+ ? this.#auditChain.toJSON()
670
+ : null,
671
+ sessions,
672
+ }
673
+ }
674
+
675
+ /**
676
+ * Restore a PeerNode from serialized data.
677
+ *
678
+ * Subsystem instances must be provided via deps since they cannot be
679
+ * reconstructed from JSON alone (they require their own constructors
680
+ * and injected dependencies).
681
+ *
682
+ * @param {object} data - Output of toJSON()
683
+ * @param {object} deps - Pre-constructed subsystem instances
684
+ * @param {import('@johnhenry/browsermesh-core').IdentityWallet} deps.wallet
685
+ * @param {import('./peer-registry.mjs').PeerRegistry} deps.registry
686
+ * @param {import('@johnhenry/browsermesh-discovery').DiscoveryManager} [deps.discovery]
687
+ * @param {import('@johnhenry/browsermesh-transport').MeshTransportNegotiator} [deps.transportNegotiator]
688
+ * @param {import('./audit.mjs').AuditChain} [deps.auditChain]
689
+ * @param {Function} [deps.onLog]
690
+ * @returns {PeerNode}
691
+ */
692
+ static fromJSON(data, deps) {
693
+ if (!deps || !deps.wallet || !deps.registry) {
694
+ throw new Error('deps.wallet and deps.registry are required')
695
+ }
696
+
697
+ const node = new PeerNode({
698
+ wallet: deps.wallet,
699
+ registry: deps.registry,
700
+ discovery: deps.discovery || null,
701
+ transportNegotiator: deps.transportNegotiator || null,
702
+ auditChain: deps.auditChain || null,
703
+ onLog: deps.onLog,
704
+ })
705
+
706
+ // Restore sessions
707
+ if (Array.isArray(data?.sessions)) {
708
+ for (const s of data.sessions) {
709
+ if (s.sessionId) {
710
+ node.#sessions.set(s.sessionId, {
711
+ sessionId: s.sessionId,
712
+ pubKey: s.pubKey,
713
+ transport: s.transport || null,
714
+ transportInstance: null,
715
+ connectedAt: s.connectedAt || 0,
716
+ state: s.state || 'closed',
717
+ })
718
+ }
719
+ }
720
+ }
721
+
722
+ // Restore lifecycle state — always restore as 'stopped'. A restored
723
+ // node must call boot() to re-wire event listeners and discovery.
724
+ // Restoring as 'running' would skip the boot sequence, leaving event
725
+ // bridging unwired.
726
+ node.#state = 'stopped'
727
+
728
+ return node
729
+ }
730
+
731
+ // -----------------------------------------------------------------------
732
+ // Internal helpers
733
+ // -----------------------------------------------------------------------
734
+
735
+ /**
736
+ * Emit an event to all registered listeners. Swallows listener errors.
737
+ *
738
+ * @param {string} event
739
+ * @param {*} data
740
+ */
741
+ #emit(event, data) {
742
+ const cbs = this.#listeners.get(event)
743
+ if (!cbs || cbs.size === 0) return
744
+ for (const cb of [...cbs]) {
745
+ try {
746
+ cb(data)
747
+ } catch {
748
+ // Listener errors do not propagate
749
+ }
750
+ }
751
+ }
752
+
753
+ /**
754
+ * Append an entry to the audit chain if available.
755
+ * Uses the default identity's podId as the author, and the wallet's
756
+ * sign method for the signature.
757
+ *
758
+ * @param {string} operation
759
+ * @param {*} data
760
+ * @returns {Promise<void>}
761
+ */
762
+ async #audit(operation, data) {
763
+ if (!this.#auditChain) return
764
+
765
+ const podId = this.podId
766
+ if (!podId) return
767
+
768
+ try {
769
+ await this.#auditChain.append(
770
+ podId,
771
+ operation,
772
+ data,
773
+ (payload) => this.#wallet.sign(podId, payload),
774
+ )
775
+ } catch (err) {
776
+ // Audit failures are logged but do not break operations
777
+ this.#onLog('peer-node:audit:error', { operation, error: err.message })
778
+ }
779
+ }
780
+
781
+ /**
782
+ * Guard that throws if the node is not in the 'running' state.
783
+ *
784
+ * @param {string} method - Name of the calling method, for the error message
785
+ */
786
+ #ensureRunning(method) {
787
+ if (this.#state !== 'running') {
788
+ throw new Error(`PeerNode must be running to call ${method}() (current state: ${this.#state})`)
789
+ }
790
+ }
791
+ }
792
+
793
+ export { PEER_NODE_STATES }