peerpigeon 0.0.4 → 0.0.6

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.
@@ -10,879 +10,1238 @@ import { StorageManager } from './StorageManager.js';
10
10
  import { GossipManager } from './GossipManager.js';
11
11
  import { MediaManager } from './MediaManager.js';
12
12
  import { WebDHT } from './WebDHT.js';
13
+ import { CryptoManager } from './CryptoManager.js';
13
14
  import { environmentDetector } from './EnvironmentDetector.js';
14
15
 
15
16
  export class PeerPigeonMesh extends EventEmitter {
16
- constructor(options = {}) {
17
- super();
18
-
19
- // Validate environment capabilities
20
- this.environmentReport = this.validateEnvironment(options);
21
-
22
- this.peerId = null;
23
- this.providedPeerId = options.peerId || null;
24
- this.signalingClient = null;
25
- this.peerDiscovery = null;
26
-
27
- // Configuration
28
- this.maxPeers = 3;
29
- this.minPeers = 2;
30
- this.autoDiscovery = true;
31
- this.evictionStrategy = true;
32
- this.xorRouting = true;
33
- this.enableWebDHT = options.enableWebDHT !== false; // Default to true, can be disabled by setting to false
34
-
35
- // State
36
- this.connected = false;
37
- this.polling = false; // Only WebSocket is supported
38
- this.signalingUrl = null;
39
- this.discoveredPeers = new Map();
40
- this.connectionMonitorInterval = null;
41
-
42
- // Initialize managers
43
- this.storageManager = new StorageManager(this);
44
- this.mediaManager = new MediaManager();
45
- this.connectionManager = new ConnectionManager(this);
46
- this.evictionManager = new EvictionManager(this, this.connectionManager);
47
- this.meshOptimizer = new MeshOptimizer(this, this.connectionManager, this.evictionManager);
48
- this.cleanupManager = new CleanupManager(this);
49
- this.signalingHandler = new SignalingHandler(this, this.connectionManager);
50
- this.gossipManager = new GossipManager(this, this.connectionManager);
51
- this.webDHT = null; // Will be initialized after peerId is set
52
-
53
- // Set up inter-module event forwarding
54
- this.setupManagerEventHandlers();
55
-
56
- // Set up unload handlers
57
- this.cleanupManager.setupUnloadHandlers();
58
-
59
- // Load saved signaling URL immediately
60
- this.storageManager.loadSignalingUrlFromStorage();
61
- }
62
-
63
- setupManagerEventHandlers() {
64
- // Forward events from managers to main mesh
65
- this.connectionManager.addEventListener('peersUpdated', () => {
66
- this.emit('peersUpdated');
67
- });
68
-
69
- // Track successful connections to reset isolation timer
70
- this.connectionManager.addEventListener('peerConnected', (data) => {
71
- if (this.peerDiscovery) {
72
- this.peerDiscovery.onConnectionEstablished();
73
- }
74
- this.emit('peerConnected', data);
75
- });
76
-
77
- // Handle peer disconnections and trigger keep-alive ping coordination
78
- this.addEventListener('peerDisconnected', (data) => {
79
- console.log(`Peer ${data.peerId.substring(0, 8)}... disconnected: ${data.reason}`);
80
- // Trigger immediate keep-alive ping check in case the disconnected peer was the designated sender
81
- if (this.signalingClient && this.signalingClient.connected) {
82
- setTimeout(() => {
83
- this.signalingClient.triggerKeepAlivePingCheck();
84
- }, 1000); // Small delay to let peer lists update
85
- }
86
- });
87
-
88
- // Handle gossip messages
89
- this.gossipManager.addEventListener('messageReceived', (data) => {
90
- this.emit('messageReceived', data);
91
- });
92
-
93
- // Forward media events
94
- this.mediaManager.addEventListener('localStreamStarted', (data) => {
95
- this.emit('localStreamStarted', data);
96
- });
97
-
98
- this.mediaManager.addEventListener('localStreamStopped', () => {
99
- this.emit('localStreamStopped');
100
- });
101
-
102
- this.mediaManager.addEventListener('error', (data) => {
103
- this.emit('mediaError', data);
104
- });
17
+ constructor(options = {}) {
18
+ super();
19
+
20
+ // Validate environment capabilities
21
+ this.environmentReport = this.validateEnvironment(options);
22
+
23
+ this.peerId = null;
24
+ this.providedPeerId = options.peerId || null;
25
+ this.signalingClient = null;
26
+ this.peerDiscovery = null;
27
+
28
+ // Configuration
29
+ this.maxPeers = 3;
30
+ this.minPeers = 2;
31
+ this.autoDiscovery = true;
32
+ this.evictionStrategy = true;
33
+ this.xorRouting = true;
34
+ this.enableWebDHT = options.enableWebDHT !== false; // Default to true, can be disabled by setting to false
35
+ this.enableCrypto = options.enableCrypto === true; // Default to false, must be explicitly enabled
36
+
37
+ // State
38
+ this.connected = false;
39
+ this.polling = false; // Only WebSocket is supported
40
+ this.signalingUrl = null;
41
+ this.discoveredPeers = new Map();
42
+ this.connectionMonitorInterval = null;
43
+
44
+ // Initialize managers
45
+ this.storageManager = new StorageManager(this);
46
+ this.mediaManager = new MediaManager();
47
+ this.connectionManager = new ConnectionManager(this);
48
+ this.evictionManager = new EvictionManager(this, this.connectionManager);
49
+ this.meshOptimizer = new MeshOptimizer(this, this.connectionManager, this.evictionManager);
50
+ this.cleanupManager = new CleanupManager(this);
51
+ this.signalingHandler = new SignalingHandler(this, this.connectionManager);
52
+ this.gossipManager = new GossipManager(this, this.connectionManager);
53
+ this.webDHT = null; // Will be initialized after peerId is set
54
+
55
+ // Initialize crypto manager if enabled
56
+ this.cryptoManager = null;
57
+ if (this.enableCrypto) {
58
+ this.cryptoManager = new CryptoManager();
59
+ }
105
60
 
106
- // Forward remote stream events from ConnectionManager
107
- this.connectionManager.addEventListener('remoteStream', (data) => {
108
- this.emit('remoteStream', data);
109
- });
61
+ // Set up inter-module event forwarding
62
+ this.setupManagerEventHandlers();
63
+
64
+ // Set up unload handlers
65
+ this.cleanupManager.setupUnloadHandlers();
66
+
67
+ // Load saved signaling URL immediately
68
+ this.storageManager.loadSignalingUrlFromStorage();
69
+ }
70
+
71
+ setupManagerEventHandlers() {
72
+ // Forward events from managers to main mesh
73
+ this.connectionManager.addEventListener('peersUpdated', () => {
74
+ this.emit('peersUpdated');
75
+ });
76
+
77
+ // Handle peer disconnections and trigger keep-alive ping coordination
78
+ this.addEventListener('peerDisconnected', (data) => {
79
+ console.log(`Peer ${data.peerId.substring(0, 8)}... disconnected: ${data.reason}`);
80
+ // Trigger immediate keep-alive ping check in case the disconnected peer was the designated sender
81
+ if (this.signalingClient && this.signalingClient.connected) {
82
+ setTimeout(() => {
83
+ this.signalingClient.triggerKeepAlivePingCheck();
84
+ }, 1000); // Small delay to let peer lists update
85
+ }
86
+ });
87
+
88
+ // Handle gossip messages
89
+ this.gossipManager.addEventListener('messageReceived', (data) => {
90
+ this.emit('messageReceived', data);
91
+ });
92
+
93
+ // Forward media events
94
+ this.mediaManager.addEventListener('localStreamStarted', (data) => {
95
+ this.emit('localStreamStarted', data);
96
+ });
97
+
98
+ this.mediaManager.addEventListener('localStreamStopped', () => {
99
+ this.emit('localStreamStopped');
100
+ });
101
+
102
+ this.mediaManager.addEventListener('error', (data) => {
103
+ this.emit('mediaError', data);
104
+ });
105
+
106
+ // Forward remote stream events from ConnectionManager
107
+ this.connectionManager.addEventListener('remoteStream', (data) => {
108
+ this.emit('remoteStream', data);
109
+ });
110
+
111
+ // Handle crypto events if crypto is enabled
112
+ if (this.cryptoManager) {
113
+ this.cryptoManager.addEventListener('cryptoReady', (data) => {
114
+ this.emit('cryptoReady', data);
115
+ });
116
+
117
+ this.cryptoManager.addEventListener('cryptoError', (data) => {
118
+ this.emit('cryptoError', data);
119
+ });
120
+
121
+ this.cryptoManager.addEventListener('peerKeyAdded', (data) => {
122
+ this.emit('peerKeyAdded', data);
123
+ });
124
+
125
+ this.cryptoManager.addEventListener('userAuthenticated', (data) => {
126
+ this.emit('userAuthenticated', data);
127
+ });
128
+ }
129
+ }
130
+
131
+ validateEnvironment(options = {}) {
132
+ const report = environmentDetector.getEnvironmentReport();
133
+ const warnings = [];
134
+ const errors = [];
135
+
136
+ // Log environment info
137
+ console.log('🔍 PeerPigeon Environment Detection:', {
138
+ runtime: `${report.runtime.isBrowser ? 'Browser' : ''}${report.runtime.isNodeJS ? 'Node.js' : ''}${report.runtime.isWorker ? 'Worker' : ''}`,
139
+ webrtc: report.capabilities.webrtc,
140
+ websocket: report.capabilities.webSocket,
141
+ browser: report.browser?.name || 'N/A'
142
+ });
143
+
144
+ // Check WebRTC support (required for peer connections)
145
+ if (!report.capabilities.webrtc) {
146
+ if (report.runtime.isBrowser) {
147
+ errors.push('WebRTC is not supported in this browser. PeerPigeon requires WebRTC for peer-to-peer connections.');
148
+ } else if (report.runtime.isNodeJS) {
149
+ warnings.push('WebRTC support not detected in Node.js environment. Consider using a WebRTC library like node-webrtc.');
150
+ }
110
151
  }
111
152
 
112
- validateEnvironment(options = {}) {
113
- const report = environmentDetector.getEnvironmentReport();
114
- const warnings = [];
115
- const errors = [];
153
+ // Check WebSocket support (required for signaling)
154
+ if (!report.capabilities.webSocket) {
155
+ if (report.runtime.isBrowser) {
156
+ errors.push('WebSocket is not supported in this browser. PeerPigeon requires WebSocket for signaling.');
157
+ } else if (report.runtime.isNodeJS) {
158
+ warnings.push('WebSocket support not detected. Install the "ws" package for WebSocket support in Node.js.');
159
+ }
160
+ }
116
161
 
117
- // Log environment info
118
- console.log('🔍 PeerPigeon Environment Detection:', {
119
- runtime: `${report.runtime.isBrowser ? 'Browser' : ''}${report.runtime.isNodeJS ? 'Node.js' : ''}${report.runtime.isWorker ? 'Worker' : ''}`,
120
- webrtc: report.capabilities.webrtc,
121
- websocket: report.capabilities.webSocket,
122
- browser: report.browser?.name || 'N/A'
123
- });
162
+ // Check storage capabilities for persistent peer ID
163
+ if (report.runtime.isBrowser && !report.capabilities.localStorage && !report.capabilities.sessionStorage) {
164
+ warnings.push('No storage mechanism available. Peer ID will not persist between sessions.');
165
+ }
124
166
 
125
- // Check WebRTC support (required for peer connections)
126
- if (!report.capabilities.webrtc) {
127
- if (report.runtime.isBrowser) {
128
- errors.push('WebRTC is not supported in this browser. PeerPigeon requires WebRTC for peer-to-peer connections.');
129
- } else if (report.runtime.isNodeJS) {
130
- warnings.push('WebRTC support not detected in Node.js environment. Consider using a WebRTC library like node-webrtc.');
131
- }
132
- }
167
+ // Check crypto support for secure peer ID generation
168
+ if (!report.capabilities.randomValues) {
169
+ warnings.push('Crypto random values not available. Peer ID generation may be less secure.');
170
+ }
133
171
 
134
- // Check WebSocket support (required for signaling)
135
- if (!report.capabilities.webSocket) {
136
- if (report.runtime.isBrowser) {
137
- errors.push('WebSocket is not supported in this browser. PeerPigeon requires WebSocket for signaling.');
138
- } else if (report.runtime.isNodeJS) {
139
- warnings.push('WebSocket support not detected. Install the "ws" package for WebSocket support in Node.js.');
140
- }
141
- }
172
+ // Network connectivity checks
173
+ if (report.runtime.isBrowser && !report.network.online) {
174
+ warnings.push('Browser reports offline status. Mesh networking may not function properly.');
175
+ }
142
176
 
143
- // Check storage capabilities for persistent peer ID
144
- if (report.runtime.isBrowser && !report.capabilities.localStorage && !report.capabilities.sessionStorage) {
145
- warnings.push('No storage mechanism available. Peer ID will not persist between sessions.');
146
- }
177
+ // Environment-specific warnings
178
+ if (report.runtime.isBrowser) {
179
+ // Browser-specific checks
180
+ const browser = report.browser;
181
+ if (browser && browser.name === 'ie') {
182
+ errors.push('Internet Explorer is not supported. Please use a modern browser.');
183
+ }
184
+
185
+ // Check for secure context in production
186
+ if (typeof location !== 'undefined' && location.protocol === 'http:' && location.hostname !== 'localhost') {
187
+ warnings.push('Running on HTTP in production. Some WebRTC features may be limited. Consider using HTTPS.');
188
+ }
189
+ }
147
190
 
148
- // Check crypto support for secure peer ID generation
149
- if (!report.capabilities.randomValues) {
150
- warnings.push('Crypto random values not available. Peer ID generation may be less secure.');
151
- }
191
+ // Handle errors and warnings
192
+ if (errors.length > 0) {
193
+ const errorMessage = 'PeerPigeon environment validation failed:\n' + errors.join('\n');
194
+ console.error(errorMessage);
195
+ if (!options.ignoreEnvironmentErrors) {
196
+ throw new Error(errorMessage);
197
+ }
198
+ }
152
199
 
153
- // Network connectivity checks
154
- if (report.runtime.isBrowser && !report.network.online) {
155
- warnings.push('Browser reports offline status. Mesh networking may not function properly.');
156
- }
200
+ if (warnings.length > 0) {
201
+ console.warn('PeerPigeon environment warnings:\n' + warnings.join('\n'));
202
+ }
157
203
 
158
- // Environment-specific warnings
159
- if (report.runtime.isBrowser) {
160
- // Browser-specific checks
161
- const browser = report.browser;
162
- if (browser && browser.name === 'ie') {
163
- errors.push('Internet Explorer is not supported. Please use a modern browser.');
164
- }
165
-
166
- // Check for secure context in production
167
- if (typeof location !== 'undefined' && location.protocol === 'http:' && location.hostname !== 'localhost') {
168
- warnings.push('Running on HTTP in production. Some WebRTC features may be limited. Consider using HTTPS.');
169
- }
170
- }
204
+ // Store capabilities for runtime checks
205
+ this.capabilities = report.capabilities;
206
+ this.runtimeInfo = report.runtime;
171
207
 
172
- // Handle errors and warnings
173
- if (errors.length > 0) {
174
- const errorMessage = 'PeerPigeon environment validation failed:\n' + errors.join('\n');
175
- console.error(errorMessage);
176
- if (!options.ignoreEnvironmentErrors) {
177
- throw new Error(errorMessage);
178
- }
179
- }
208
+ return report;
209
+ }
180
210
 
181
- if (warnings.length > 0) {
182
- console.warn('PeerPigeon environment warnings:\n' + warnings.join('\n'));
211
+ async init() {
212
+ try {
213
+ // Use provided peer ID if valid, otherwise generate one
214
+ if (this.providedPeerId) {
215
+ if (this.storageManager.validatePeerId(this.providedPeerId)) {
216
+ this.peerId = this.providedPeerId;
217
+ console.log(`Using provided peer ID: ${this.peerId}`);
218
+ } else {
219
+ console.warn(`Invalid peer ID provided: ${this.providedPeerId}. Must be 40-character SHA-1 hex string. Generating new one.`);
220
+ this.peerId = await this.storageManager.generatePeerId();
183
221
  }
184
-
185
- // Store capabilities for runtime checks
186
- this.capabilities = report.capabilities;
187
- this.runtimeInfo = report.runtime;
188
-
189
- return report;
190
- }
191
-
192
- async init() {
222
+ } else {
223
+ this.peerId = await this.storageManager.generatePeerId();
224
+ }
225
+
226
+ // Initialize WebDHT now that we have a peerId (if enabled)
227
+ if (this.enableWebDHT) {
228
+ this.webDHT = new WebDHT(this);
229
+ console.log('WebDHT initialized and enabled');
230
+
231
+ // Setup WebDHT event handlers now that it's initialized
232
+ this.setupWebDHTEventHandlers();
233
+ } else {
234
+ console.log('WebDHT disabled by configuration');
235
+ }
236
+
237
+ // Load signaling URL from query params or storage
238
+ const savedUrl = this.storageManager.loadSignalingUrlFromQuery();
239
+ if (savedUrl) {
240
+ this.signalingUrl = savedUrl;
241
+ }
242
+
243
+ this.signalingClient = new SignalingClient(this.peerId, this.maxPeers, this);
244
+ this.setupSignalingHandlers();
245
+
246
+ this.peerDiscovery = new PeerDiscovery(this.peerId, {
247
+ autoDiscovery: this.autoDiscovery,
248
+ evictionStrategy: this.evictionStrategy,
249
+ xorRouting: this.xorRouting,
250
+ minPeers: this.minPeers,
251
+ maxPeers: this.maxPeers
252
+ });
253
+ this.setupDiscoveryHandlers();
254
+
255
+ // Initialize crypto manager if enabled
256
+ if (this.cryptoManager) {
193
257
  try {
194
- // Use provided peer ID if valid, otherwise generate one
195
- if (this.providedPeerId) {
196
- if (this.storageManager.validatePeerId(this.providedPeerId)) {
197
- this.peerId = this.providedPeerId;
198
- console.log(`Using provided peer ID: ${this.peerId}`);
199
- } else {
200
- console.warn(`Invalid peer ID provided: ${this.providedPeerId}. Must be 40-character SHA-1 hex string. Generating new one.`);
201
- this.peerId = await this.storageManager.generatePeerId();
202
- }
203
- } else {
204
- this.peerId = await this.storageManager.generatePeerId();
205
- }
206
-
207
- // Initialize WebDHT now that we have a peerId (if enabled)
208
- if (this.enableWebDHT) {
209
- this.webDHT = new WebDHT(this);
210
- console.log('WebDHT initialized and enabled');
211
-
212
- // Setup WebDHT event handlers now that it's initialized
213
- this.setupWebDHTEventHandlers();
214
- } else {
215
- console.log('WebDHT disabled by configuration');
216
- }
217
-
218
- // Load signaling URL from query params or storage
219
- const savedUrl = this.storageManager.loadSignalingUrlFromQuery();
220
- if (savedUrl) {
221
- this.signalingUrl = savedUrl;
222
- }
223
-
224
- this.signalingClient = new SignalingClient(this.peerId, this.maxPeers, this);
225
- this.setupSignalingHandlers();
226
-
227
- this.peerDiscovery = new PeerDiscovery(this.peerId, {
228
- autoDiscovery: this.autoDiscovery,
229
- evictionStrategy: this.evictionStrategy,
230
- xorRouting: this.xorRouting,
231
- minPeers: this.minPeers,
232
- maxPeers: this.maxPeers
233
- });
234
- this.setupDiscoveryHandlers();
235
-
236
- this.emit('statusChanged', { type: 'initialized', peerId: this.peerId });
258
+ console.log('🔐 Initializing crypto manager...');
259
+ await this.cryptoManager.init({ generateKeypair: true });
260
+ console.log('🔐 Crypto manager initialized successfully');
237
261
  } catch (error) {
238
- console.error('Failed to initialize mesh:', error);
239
- this.emit('statusChanged', { type: 'error', message: `Initialization failed: ${error.message}` });
240
- throw error;
262
+ console.error('Failed to initialize crypto manager:', error);
263
+ // Continue without crypto - don't fail the entire init
264
+ this.enableCrypto = false;
265
+ this.cryptoManager = null;
241
266
  }
242
- }
243
-
244
- setupSignalingHandlers() {
245
- this.signalingClient.addEventListener('connected', () => {
246
- this.connected = true;
247
- this.polling = false;
248
- this.peerDiscovery.start();
249
-
250
- // Start periodic health monitoring
251
- this.startConnectionMonitoring();
252
-
253
- this.emit('statusChanged', { type: 'connected' });
254
- });
267
+ }
255
268
 
256
- this.signalingClient.addEventListener('disconnected', () => {
257
- this.connected = false;
258
- this.polling = false;
259
- this.peerDiscovery.stop();
260
- this.connectionManager.disconnectAllPeers();
261
- this.stopConnectionMonitoring();
262
- this.emit('statusChanged', { type: 'disconnected' });
263
- });
264
-
265
- this.signalingClient.addEventListener('signalingMessage', (message) => {
266
- this.signalingHandler.handleSignalingMessage(message);
267
- });
268
-
269
- this.signalingClient.addEventListener('statusChanged', (data) => {
270
- this.emit('statusChanged', data);
271
- });
269
+ this.emit('statusChanged', { type: 'initialized', peerId: this.peerId });
270
+ } catch (error) {
271
+ console.error('Failed to initialize mesh:', error);
272
+ this.emit('statusChanged', { type: 'error', message: `Initialization failed: ${error.message}` });
273
+ throw error;
272
274
  }
275
+ }
276
+
277
+ setupSignalingHandlers() {
278
+ this.signalingClient.addEventListener('connected', () => {
279
+ this.connected = true;
280
+ this.polling = false;
281
+ this.peerDiscovery.start();
282
+
283
+ // Start periodic health monitoring
284
+ this.startConnectionMonitoring();
285
+
286
+ this.emit('statusChanged', { type: 'connected' });
287
+ });
288
+
289
+ this.signalingClient.addEventListener('disconnected', () => {
290
+ this.connected = false;
291
+ this.polling = false;
292
+ this.peerDiscovery.stop();
293
+ this.connectionManager.disconnectAllPeers();
294
+ this.stopConnectionMonitoring();
295
+ this.emit('statusChanged', { type: 'disconnected' });
296
+ });
297
+
298
+ this.signalingClient.addEventListener('signalingMessage', (message) => {
299
+ this.signalingHandler.handleSignalingMessage(message);
300
+ });
301
+
302
+ this.signalingClient.addEventListener('statusChanged', (data) => {
303
+ this.emit('statusChanged', data);
304
+ });
305
+ }
306
+
307
+ setupDiscoveryHandlers() {
308
+ this.peerDiscovery.addEventListener('peerDiscovered', (data) => {
309
+ this.emit('peerDiscovered', data);
310
+ });
311
+
312
+ this.peerDiscovery.addEventListener('connectToPeer', (data) => {
313
+ console.log(`PeerDiscovery requested connection to: ${data.peerId.substring(0, 8)}...`);
314
+ this.connectionManager.connectToPeer(data.peerId);
315
+ });
316
+
317
+ this.peerDiscovery.addEventListener('evictPeer', (data) => {
318
+ this.evictionManager.evictPeer(data.peerId, data.reason);
319
+ });
320
+
321
+ this.peerDiscovery.addEventListener('optimizeMesh', () => {
322
+ this.peerDiscovery.optimizeMeshConnections(this.connectionManager.peers);
323
+ });
324
+
325
+ this.peerDiscovery.addEventListener('optimizeConnections', (data) => {
326
+ this.meshOptimizer.handleOptimizeConnections(data.unconnectedPeers);
327
+ });
328
+
329
+ this.peerDiscovery.addEventListener('peersUpdated', (data) => {
330
+ this.emit('statusChanged', { type: 'info', message: `Cleaned up ${data.removedCount} stale peer(s)` });
331
+ this.emit('peersUpdated');
332
+ });
333
+
334
+ // Handle capacity checks
335
+ this.peerDiscovery.addEventListener('checkCapacity', () => {
336
+ const canAccept = this.connectionManager.canAcceptMorePeers();
337
+ const currentConnectionCount = this.connectionManager.getConnectedPeerCount();
338
+ console.log(`Capacity check: ${canAccept} (${currentConnectionCount}/${this.maxPeers} peers)`);
339
+ this.peerDiscovery._canAcceptMorePeers = canAccept;
340
+ this.peerDiscovery._currentConnectionCount = currentConnectionCount;
341
+ });
342
+
343
+ // Handle eviction checks
344
+ this.peerDiscovery.addEventListener('checkEviction', (data) => {
345
+ const evictPeerId = this.evictionManager.shouldEvictForPeer(data.newPeerId);
346
+ console.log(`Eviction check for ${data.newPeerId.substring(0, 8)}...: ${evictPeerId ? evictPeerId.substring(0, 8) + '...' : 'none'}`);
347
+ this.peerDiscovery._shouldEvictForPeer = evictPeerId;
348
+ });
349
+ }
350
+
351
+ async connect(signalingUrl) {
352
+ this.signalingUrl = signalingUrl;
353
+ this.storageManager.saveSignalingUrlToStorage(signalingUrl);
354
+ this.polling = false; // Only WebSocket is supported
355
+ // Don't emit connecting here - SignalingClient will handle it with more detail
356
+
357
+ try {
358
+ await this.signalingClient.connect(signalingUrl);
359
+ } catch (error) {
360
+ console.error('Connection failed:', error);
361
+ this.polling = false;
362
+ this.emit('statusChanged', { type: 'error', message: `Connection failed: ${error.message}` });
363
+ throw error;
364
+ }
365
+ }
273
366
 
274
- setupDiscoveryHandlers() {
275
- this.peerDiscovery.addEventListener('peerDiscovered', (data) => {
276
- this.emit('peerDiscovered', data);
277
- });
278
-
279
- this.peerDiscovery.addEventListener('connectToPeer', (data) => {
280
- console.log(`PeerDiscovery requested connection to: ${data.peerId.substring(0, 8)}...`);
281
- this.connectionManager.connectToPeer(data.peerId);
282
- });
283
-
284
- this.peerDiscovery.addEventListener('evictPeer', (data) => {
285
- this.evictionManager.evictPeer(data.peerId, data.reason);
286
- });
287
-
288
- this.peerDiscovery.addEventListener('optimizeMesh', () => {
289
- this.peerDiscovery.optimizeMeshConnections(this.connectionManager.peers);
290
- });
367
+ disconnect() {
368
+ if (this.connected) {
369
+ this.cleanupManager.sendGoodbyeMessage();
370
+ }
291
371
 
292
- this.peerDiscovery.addEventListener('optimizeConnections', (data) => {
293
- this.meshOptimizer.handleOptimizeConnections(data.unconnectedPeers);
294
- });
372
+ this.connected = false;
373
+ this.polling = false;
295
374
 
296
- this.peerDiscovery.addEventListener('peersUpdated', (data) => {
297
- this.emit('statusChanged', { type: 'info', message: `Cleaned up ${data.removedCount} stale peer(s)` });
298
- this.emit('peersUpdated');
299
- });
375
+ // Stop connection monitoring
376
+ this.stopConnectionMonitoring();
300
377
 
301
- // Handle capacity checks
302
- this.peerDiscovery.addEventListener('checkCapacity', () => {
303
- const canAccept = this.connectionManager.canAcceptMorePeers();
304
- const currentConnectionCount = this.connectionManager.getConnectedPeerCount();
305
- console.log(`Capacity check: ${canAccept} (${currentConnectionCount}/${this.maxPeers} peers)`);
306
- this.peerDiscovery._canAcceptMorePeers = canAccept;
307
- this.peerDiscovery._currentConnectionCount = currentConnectionCount;
308
- });
378
+ if (this.signalingClient) {
379
+ this.signalingClient.disconnect();
380
+ }
309
381
 
310
- // Handle eviction checks
311
- this.peerDiscovery.addEventListener('checkEviction', (data) => {
312
- const evictPeerId = this.evictionManager.shouldEvictForPeer(data.newPeerId);
313
- console.log(`Eviction check for ${data.newPeerId.substring(0, 8)}...: ${evictPeerId ? evictPeerId.substring(0, 8) + '...' : 'none'}`);
314
- this.peerDiscovery._shouldEvictForPeer = evictPeerId;
315
- });
382
+ if (this.peerDiscovery) {
383
+ this.peerDiscovery.stop();
316
384
  }
317
385
 
318
- async connect(signalingUrl) {
319
- this.signalingUrl = signalingUrl;
320
- this.storageManager.saveSignalingUrlToStorage(signalingUrl);
321
- this.polling = false; // Only WebSocket is supported
322
- // Don't emit connecting here - SignalingClient will handle it with more detail
386
+ this.connectionManager.disconnectAllPeers();
387
+ this.connectionManager.cleanup();
323
388
 
324
- try {
325
- await this.signalingClient.connect(signalingUrl);
326
- } catch (error) {
327
- console.error('Connection failed:', error);
328
- this.polling = false;
329
- this.emit('statusChanged', { type: 'error', message: `Connection failed: ${error.message}` });
330
- throw error;
331
- }
389
+ // Cleanup WebDHT
390
+ if (this.webDHT) {
391
+ this.webDHT.cleanup();
332
392
  }
393
+ this.evictionManager.cleanup();
394
+ this.cleanupManager.cleanup();
395
+ this.gossipManager.cleanup();
333
396
 
334
- disconnect() {
335
- if (this.connected) {
336
- this.cleanupManager.sendGoodbyeMessage();
337
- }
338
-
339
- this.connected = false;
340
- this.polling = false;
341
-
342
- // Stop connection monitoring
343
- this.stopConnectionMonitoring();
344
-
345
- if (this.signalingClient) {
346
- this.signalingClient.disconnect();
347
- }
348
-
349
- if (this.peerDiscovery) {
350
- this.peerDiscovery.stop();
351
- }
397
+ this.emit('statusChanged', { type: 'disconnected' });
398
+ }
352
399
 
353
- this.connectionManager.disconnectAllPeers();
354
- this.connectionManager.cleanup();
355
-
356
- // Cleanup WebDHT
357
- if (this.webDHT) {
358
- this.webDHT.cleanup();
359
- }
360
- this.evictionManager.cleanup();
361
- this.cleanupManager.cleanup();
362
- this.gossipManager.cleanup();
400
+ // Configuration methods
401
+ setMaxPeers(maxPeers) {
402
+ this.maxPeers = Math.max(1, Math.min(50, maxPeers));
363
403
 
364
- this.emit('statusChanged', { type: 'disconnected' });
404
+ if (this.connectionManager.peers.size > this.maxPeers) {
405
+ this.evictionManager.disconnectExcessPeers();
365
406
  }
366
407
 
367
- // Configuration methods
368
- setMaxPeers(maxPeers) {
369
- this.maxPeers = Math.max(1, Math.min(50, maxPeers));
370
-
371
- if (this.connectionManager.peers.size > this.maxPeers) {
372
- this.evictionManager.disconnectExcessPeers();
373
- }
374
-
375
- return this.maxPeers;
376
- }
408
+ return this.maxPeers;
409
+ }
377
410
 
378
- setMinPeers(minPeers) {
379
- this.minPeers = Math.max(0, Math.min(49, minPeers));
380
-
381
- // If we're below minimum and auto-discovery is enabled, trigger optimization
382
- if (this.connectionManager.getConnectedPeerCount() < this.minPeers && this.autoDiscovery && this.connected) {
383
- this.peerDiscovery.optimizeMeshConnections(this.connectionManager.peers);
384
- }
385
-
386
- return this.minPeers;
387
- }
411
+ setMinPeers(minPeers) {
412
+ this.minPeers = Math.max(0, Math.min(49, minPeers));
388
413
 
389
- setXorRouting(enabled) {
390
- this.xorRouting = enabled;
391
- this.emit('statusChanged', { type: 'setting', setting: 'xorRouting', value: enabled });
392
-
393
- // If XOR routing is disabled, we might need to adjust our connection strategy
394
- if (!enabled && this.evictionStrategy) {
395
- this.emit('statusChanged', { type: 'warning', message: 'XOR routing disabled - eviction strategy effectiveness reduced' });
396
- }
414
+ // If we're below minimum and auto-discovery is enabled, trigger optimization
415
+ if (this.connectionManager.getConnectedPeerCount() < this.minPeers && this.autoDiscovery && this.connected) {
416
+ this.peerDiscovery.optimizeMeshConnections(this.connectionManager.peers);
397
417
  }
398
418
 
399
- setAutoDiscovery(enabled) {
400
- this.autoDiscovery = enabled;
401
- this.emit('statusChanged', { type: 'setting', setting: 'autoDiscovery', value: enabled });
402
- }
403
-
404
- setEvictionStrategy(enabled) {
405
- this.evictionStrategy = enabled;
406
- this.emit('statusChanged', { type: 'setting', setting: 'evictionStrategy', value: enabled });
407
- }
408
-
409
- // Status and information methods
410
- getStatus() {
411
- const connectedCount = this.connectionManager.getConnectedPeerCount();
412
- const totalCount = this.connectionManager.peers.size;
413
- return {
414
- peerId: this.peerId,
415
- connected: this.connected,
416
- polling: false, // Only WebSocket is supported
417
- connectedCount: connectedCount,
418
- totalPeerCount: totalCount, // Include total count for debugging
419
- minPeers: this.minPeers,
420
- maxPeers: this.maxPeers,
421
- discoveredCount: this.discoveredPeers.size,
422
- autoDiscovery: this.autoDiscovery,
423
- evictionStrategy: this.evictionStrategy,
424
- xorRouting: this.xorRouting
425
- };
426
- }
419
+ return this.minPeers;
420
+ }
427
421
 
428
- getPeers() {
429
- return this.connectionManager.getPeers();
430
- }
422
+ setXorRouting(enabled) {
423
+ this.xorRouting = enabled;
424
+ this.emit('statusChanged', { type: 'setting', setting: 'xorRouting', value: enabled });
431
425
 
432
- getPeerStatus(peerConnection) {
433
- return peerConnection.getStatus();
426
+ // If XOR routing is disabled, we might need to adjust our connection strategy
427
+ if (!enabled && this.evictionStrategy) {
428
+ this.emit('statusChanged', { type: 'warning', message: 'XOR routing disabled - eviction strategy effectiveness reduced' });
434
429
  }
435
-
436
- getDiscoveredPeers() {
437
- if (!this.peerDiscovery) {
438
- return [];
439
- }
440
- const discoveredPeers = this.peerDiscovery.getDiscoveredPeers();
441
-
442
- // Enrich with connection state from the actual peer connections
443
- return discoveredPeers.map(peer => {
444
- const peerConnection = this.connectionManager.getPeer(peer.peerId);
445
- let isConnected = false;
446
-
447
- if (peerConnection) {
448
- const status = peerConnection.getStatus();
449
- // Consider peer connected if WebRTC connection is established
450
- isConnected = status === 'connected' || status === 'channel-connecting';
451
- }
452
-
453
- return {
454
- ...peer,
455
- isConnected
456
- };
457
- });
430
+ }
431
+
432
+ setAutoDiscovery(enabled) {
433
+ this.autoDiscovery = enabled;
434
+ this.emit('statusChanged', { type: 'setting', setting: 'autoDiscovery', value: enabled });
435
+ }
436
+
437
+ setEvictionStrategy(enabled) {
438
+ this.evictionStrategy = enabled;
439
+ this.emit('statusChanged', { type: 'setting', setting: 'evictionStrategy', value: enabled });
440
+ }
441
+
442
+ // Status and information methods
443
+ getStatus() {
444
+ const connectedCount = this.connectionManager.getConnectedPeerCount();
445
+ const totalCount = this.connectionManager.peers.size;
446
+ return {
447
+ peerId: this.peerId,
448
+ connected: this.connected,
449
+ polling: false, // Only WebSocket is supported
450
+ connectedCount,
451
+ totalPeerCount: totalCount, // Include total count for debugging
452
+ minPeers: this.minPeers,
453
+ maxPeers: this.maxPeers,
454
+ discoveredCount: this.discoveredPeers.size,
455
+ autoDiscovery: this.autoDiscovery,
456
+ evictionStrategy: this.evictionStrategy,
457
+ xorRouting: this.xorRouting
458
+ };
459
+ }
460
+
461
+ getPeers() {
462
+ return this.connectionManager.getPeers();
463
+ }
464
+
465
+ getPeerStatus(peerConnection) {
466
+ return peerConnection.getStatus();
467
+ }
468
+
469
+ getDiscoveredPeers() {
470
+ if (!this.peerDiscovery) {
471
+ return [];
458
472
  }
459
-
460
- /**
473
+ const discoveredPeers = this.peerDiscovery.getDiscoveredPeers();
474
+
475
+ // Enrich with connection state from the actual peer connections
476
+ return discoveredPeers.map(peer => {
477
+ const peerConnection = this.connectionManager.getPeer(peer.peerId);
478
+ let isConnected = false;
479
+
480
+ if (peerConnection) {
481
+ const status = peerConnection.getStatus();
482
+ // Consider peer connected if WebRTC connection is established
483
+ isConnected = status === 'connected' || status === 'channel-connecting';
484
+ }
485
+
486
+ return {
487
+ ...peer,
488
+ isConnected
489
+ };
490
+ });
491
+ }
492
+
493
+ /**
461
494
  * Send a direct message to a specific peer via gossip routing
462
495
  * @param {string} targetPeerId - The destination peer's ID
463
496
  * @param {string|object} content - The message content
464
497
  * @returns {string|null} The message ID if sent, or null on error
465
498
  */
466
- sendDirectMessage(targetPeerId, content) {
467
- if (!targetPeerId || typeof targetPeerId !== 'string') {
468
- console.error('Invalid targetPeerId for direct message');
469
- return null;
470
- }
471
- return this.gossipManager.sendDirectMessage(targetPeerId, content);
499
+ sendDirectMessage(targetPeerId, content) {
500
+ if (!targetPeerId || typeof targetPeerId !== 'string') {
501
+ console.error('Invalid targetPeerId for direct message');
502
+ return null;
472
503
  }
504
+ return this.gossipManager.sendDirectMessage(targetPeerId, content);
505
+ }
473
506
 
474
- /**
507
+ /**
475
508
  * Send a broadcast (gossip) message to all peers
476
509
  * @param {string|object} content - The message content
477
510
  * @returns {string|null} The message ID if sent, or null on error
478
511
  */
479
- sendMessage(content) {
480
- // For clarity, this is a broadcast/gossip message
481
- return this.gossipManager.broadcastMessage(content, 'chat');
482
- }
483
-
484
- // Helper methods for backward compatibility
485
- canAcceptMorePeers() {
486
- return this.connectionManager.canAcceptMorePeers();
487
- }
488
-
489
- getConnectedPeerCount() {
490
- return this.connectionManager.getConnectedPeerCount();
491
- }
492
-
493
- // Expose peers Map for backward compatibility
494
- get peers() {
495
- return this.connectionManager.peers;
496
- }
497
-
498
- // Get peer status method for UI compatibility
499
- getPeerStatus(peer) {
500
- if (!peer) return 'unknown';
501
- return peer.getStatus ? peer.getStatus() : 'unknown';
502
- }
503
-
504
- // Get connected peer IDs as array for UI compatibility
505
- getConnectedPeerIds() {
506
- return this.connectionManager.getPeers()
507
- .filter(peer => peer.status === 'connected')
508
- .map(peer => peer.peerId);
512
+ sendMessage(content) {
513
+ // For clarity, this is a broadcast/gossip message
514
+ return this.gossipManager.broadcastMessage(content, 'chat');
515
+ }
516
+
517
+ // Helper methods for backward compatibility
518
+ canAcceptMorePeers() {
519
+ return this.connectionManager.canAcceptMorePeers();
520
+ }
521
+
522
+ getConnectedPeerCount() {
523
+ return this.connectionManager.getConnectedPeerCount();
524
+ }
525
+
526
+ // Expose peers Map for backward compatibility
527
+ get peers() {
528
+ return this.connectionManager.peers;
529
+ }
530
+
531
+ // Get peer status method for UI compatibility
532
+ getPeerUIStatus(peer) {
533
+ if (!peer) return 'unknown';
534
+ return peer.getStatus ? peer.getStatus() : 'unknown';
535
+ }
536
+
537
+ // Get connected peer IDs as array for UI compatibility
538
+ getConnectedPeerIds() {
539
+ return this.connectionManager.getPeers()
540
+ .filter(peer => peer.status === 'connected')
541
+ .map(peer => peer.peerId);
542
+ }
543
+
544
+ // Advanced methods
545
+ async cleanupStaleSignalingData() {
546
+ return this.cleanupManager.cleanupStaleSignalingData();
547
+ }
548
+
549
+ forceConnectToAllPeers() {
550
+ return this.meshOptimizer.forceConnectToAllPeers();
551
+ }
552
+
553
+ // Debugging and maintenance methods
554
+ forceCleanupInvalidPeers() {
555
+ console.log('Force cleaning up peers not in connected state...');
556
+ return this.connectionManager.forceCleanupInvalidPeers();
557
+ }
558
+
559
+ cleanupStalePeers() {
560
+ console.log('Manually cleaning up stale peers...');
561
+ return this.connectionManager.cleanupStalePeers();
562
+ }
563
+
564
+ getPeerStateSummary() {
565
+ return this.connectionManager.getPeerStateSummary();
566
+ }
567
+
568
+ debugConnectivity() {
569
+ return this.meshOptimizer.debugConnectivity();
570
+ }
571
+
572
+ // Connection monitoring methods
573
+ startConnectionMonitoring() {
574
+ // Monitor connection health every 2 minutes
575
+ if (this.connectionMonitorInterval) {
576
+ clearInterval(this.connectionMonitorInterval);
509
577
  }
510
578
 
511
- // Advanced methods
512
- async cleanupStaleSignalingData() {
513
- return this.cleanupManager.cleanupStaleSignalingData();
514
- }
515
-
516
- forceConnectToAllPeers() {
517
- return this.meshOptimizer.forceConnectToAllPeers();
518
- }
519
-
520
- // Debugging and maintenance methods
521
- forceCleanupInvalidPeers() {
522
- console.log('Force cleaning up peers not in connected state...');
523
- return this.connectionManager.forceCleanupInvalidPeers();
524
- }
525
-
526
- cleanupStalePeers() {
527
- console.log('Manually cleaning up stale peers...');
528
- return this.connectionManager.cleanupStalePeers();
529
- }
530
-
531
- getPeerStateSummary() {
532
- return this.connectionManager.getPeerStateSummary();
533
- }
534
-
535
- debugConnectivity() {
536
- return this.meshOptimizer.debugConnectivity();
537
- }
538
-
539
- // Connection monitoring methods
540
- startConnectionMonitoring() {
541
- // Monitor connection health every 2 minutes
542
- if (this.connectionMonitorInterval) {
543
- clearInterval(this.connectionMonitorInterval);
579
+ // Environment-aware timer
580
+ const intervalCallback = () => {
581
+ if (this.signalingClient) {
582
+ const stats = this.signalingClient.getConnectionStats();
583
+ console.log('Connection monitoring:', stats);
584
+
585
+ // Force health check if connection seems problematic
586
+ if (stats.connected && stats.lastPingTime && stats.lastPongTime) {
587
+ const timeSinceLastPong = Date.now() - stats.lastPongTime;
588
+ if (timeSinceLastPong > 60000) { // 1 minute without pong
589
+ console.warn('Connection may be unhealthy, forcing health check');
590
+ this.signalingClient.forceHealthCheck();
591
+ }
544
592
  }
545
-
546
- // Environment-aware timer
547
- const intervalCallback = () => {
548
- if (this.signalingClient) {
549
- const stats = this.signalingClient.getConnectionStats();
550
- console.log('Connection monitoring:', stats);
551
-
552
- // Force health check if connection seems problematic
553
- if (stats.connected && stats.lastPingTime && stats.lastPongTime) {
554
- const timeSinceLastPong = Date.now() - stats.lastPongTime;
555
- if (timeSinceLastPong > 60000) { // 1 minute without pong
556
- console.warn('Connection may be unhealthy, forcing health check');
557
- this.signalingClient.forceHealthCheck();
558
- }
559
- }
560
-
561
- // Emit connection status for UI
562
- this.emit('connectionStats', stats);
563
- }
564
- };
565
593
 
566
- if (environmentDetector.isBrowser) {
567
- this.connectionMonitorInterval = window.setInterval(intervalCallback, 120000);
568
- } else {
569
- this.connectionMonitorInterval = setInterval(intervalCallback, 120000);
570
- }
571
-
572
- console.log('Started connection monitoring');
573
- }
594
+ // Emit connection status for UI
595
+ this.emit('connectionStats', stats);
596
+ }
597
+ };
574
598
 
575
- stopConnectionMonitoring() {
576
- if (this.connectionMonitorInterval) {
577
- clearInterval(this.connectionMonitorInterval);
578
- this.connectionMonitorInterval = null;
579
- console.log('Stopped connection monitoring');
580
- }
599
+ if (environmentDetector.isBrowser) {
600
+ this.connectionMonitorInterval = window.setInterval(intervalCallback, 120000);
601
+ } else {
602
+ this.connectionMonitorInterval = setInterval(intervalCallback, 120000);
581
603
  }
582
604
 
583
- // Media management methods
584
- async initializeMedia() {
585
- return await this.mediaManager.init();
586
- }
605
+ console.log('Started connection monitoring');
606
+ }
587
607
 
588
- async startMedia(options = {}) {
589
- const { video = false, audio = false, deviceIds = {} } = options;
590
-
591
- try {
592
- const stream = await this.mediaManager.startLocalStream({ video, audio, deviceIds });
593
-
594
- // Update all existing peer connections with the new stream
595
- const connections = this.connectionManager.getAllConnections();
596
- for (const connection of connections) {
597
- await connection.setLocalStream(stream);
598
- }
599
-
600
- return stream;
601
- } catch (error) {
602
- console.error('Failed to start media:', error);
603
- throw error;
604
- }
608
+ stopConnectionMonitoring() {
609
+ if (this.connectionMonitorInterval) {
610
+ clearInterval(this.connectionMonitorInterval);
611
+ this.connectionMonitorInterval = null;
612
+ console.log('Stopped connection monitoring');
605
613
  }
614
+ }
606
615
 
607
- async stopMedia() {
608
- this.mediaManager.stopLocalStream();
609
-
610
- // Update all existing peer connections to remove the stream
611
- const connections = this.connectionManager.getAllConnections();
612
- for (const connection of connections) {
613
- await connection.setLocalStream(null);
614
- }
615
- }
616
+ // Media management methods
617
+ async initializeMedia() {
618
+ return await this.mediaManager.init();
619
+ }
616
620
 
617
- toggleVideo() {
618
- return this.mediaManager.toggleVideo();
619
- }
621
+ async startMedia(options = {}) {
622
+ const { video = false, audio = false, deviceIds = {} } = options;
620
623
 
621
- toggleAudio() {
622
- return this.mediaManager.toggleAudio();
623
- }
624
+ try {
625
+ const stream = await this.mediaManager.startLocalStream({ video, audio, deviceIds });
624
626
 
625
- getMediaState() {
626
- return this.mediaManager.getMediaState();
627
- }
627
+ // Update all existing peer connections with the new stream
628
+ const connections = this.connectionManager.getAllConnections();
629
+ for (const connection of connections) {
630
+ await connection.setLocalStream(stream);
631
+ }
628
632
 
629
- getMediaDevices() {
630
- return this.mediaManager.devices;
633
+ return stream;
634
+ } catch (error) {
635
+ console.error('Failed to start media:', error);
636
+ throw error;
631
637
  }
638
+ }
632
639
 
633
- async enumerateMediaDevices() {
634
- return await this.mediaManager.enumerateDevices();
635
- }
640
+ async stopMedia() {
641
+ this.mediaManager.stopLocalStream();
636
642
 
637
- getLocalStream() {
638
- return this.mediaManager.localStream;
643
+ // Update all existing peer connections to remove the stream
644
+ const connections = this.connectionManager.getAllConnections();
645
+ for (const connection of connections) {
646
+ await connection.setLocalStream(null);
639
647
  }
640
-
641
- // Get remote streams from all connected peers
642
- getRemoteStreams() {
643
- const streams = new Map();
644
- const connections = this.connectionManager.getAllConnections();
645
-
646
- for (const connection of connections) {
647
- const remoteStream = connection.getRemoteStream();
648
- if (remoteStream) {
649
- streams.set(connection.peerId, remoteStream);
650
- }
651
- }
652
-
653
- return streams;
648
+ }
649
+
650
+ toggleVideo() {
651
+ return this.mediaManager.toggleVideo();
652
+ }
653
+
654
+ toggleAudio() {
655
+ return this.mediaManager.toggleAudio();
656
+ }
657
+
658
+ getMediaState() {
659
+ return this.mediaManager.getMediaState();
660
+ }
661
+
662
+ getMediaDevices() {
663
+ return this.mediaManager.devices;
664
+ }
665
+
666
+ async enumerateMediaDevices() {
667
+ return await this.mediaManager.enumerateDevices();
668
+ }
669
+
670
+ getLocalStream() {
671
+ return this.mediaManager.localStream;
672
+ }
673
+
674
+ // Get remote streams from all connected peers
675
+ getRemoteStreams() {
676
+ const streams = new Map();
677
+ const connections = this.connectionManager.getAllConnections();
678
+
679
+ for (const connection of connections) {
680
+ const remoteStream = connection.getRemoteStream();
681
+ if (remoteStream) {
682
+ streams.set(connection.peerId, remoteStream);
683
+ }
654
684
  }
655
685
 
656
- // Static utility methods
657
- static validatePeerId(peerId) {
658
- return typeof peerId === 'string' && /^[a-fA-F0-9]{40}$/.test(peerId);
659
- }
686
+ return streams;
687
+ }
660
688
 
661
- static async generatePeerId() {
662
- const array = new Uint8Array(20);
663
- crypto.getRandomValues(array);
664
- return Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('');
665
- }
689
+ // Static utility methods
690
+ static validatePeerId(peerId) {
691
+ return typeof peerId === 'string' && /^[a-fA-F0-9]{40}$/.test(peerId);
692
+ }
666
693
 
667
- // WebDHT methods - Distributed Hash Table
668
- /**
694
+ static async generatePeerId() {
695
+ const array = new Uint8Array(20);
696
+ crypto.getRandomValues(array);
697
+ return Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('');
698
+ }
699
+
700
+ // WebDHT methods - Distributed Hash Table
701
+ /**
669
702
  * Store a key-value pair in the distributed hash table
670
703
  * @param {string} key - The key to store
671
704
  * @param {any} value - The value to store
672
705
  * @param {object} options - Storage options (ttl, etc.)
673
706
  * @returns {Promise<boolean>} True if stored successfully
674
707
  */
675
- async dhtPut(key, value, options = {}) {
676
- if (!this.enableWebDHT) {
677
- throw new Error('WebDHT is disabled. Enable it by setting enableWebDHT: true in constructor options.');
678
- }
679
- if (!this.webDHT) {
680
- throw new Error('WebDHT not initialized');
681
- }
682
- return this.webDHT.put(key, value, options);
708
+ async dhtPut(key, value, options = {}) {
709
+ if (!this.enableWebDHT) {
710
+ throw new Error('WebDHT is disabled. Enable it by setting enableWebDHT: true in constructor options.');
711
+ }
712
+ if (!this.webDHT) {
713
+ throw new Error('WebDHT not initialized');
683
714
  }
715
+ return this.webDHT.put(key, value, options);
716
+ }
684
717
 
685
- /**
718
+ /**
686
719
  * Retrieve a value from the distributed hash table
687
720
  * @param {string} key - The key to retrieve
688
721
  * @param {object} options - Retrieval options (subscribe, etc.)
689
722
  * @returns {Promise<any>} The stored value or null if not found
690
723
  */
691
- async dhtGet(key, options = {}) {
692
- if (!this.enableWebDHT) {
693
- throw new Error('WebDHT is disabled. Enable it by setting enableWebDHT: true in constructor options.');
694
- }
695
- if (!this.webDHT) {
696
- throw new Error('WebDHT not initialized');
697
- }
698
- return this.webDHT.get(key, options);
724
+ async dhtGet(key, options = {}) {
725
+ if (!this.enableWebDHT) {
726
+ throw new Error('WebDHT is disabled. Enable it by setting enableWebDHT: true in constructor options.');
699
727
  }
728
+ if (!this.webDHT) {
729
+ throw new Error('WebDHT not initialized');
730
+ }
731
+ return this.webDHT.get(key, options);
732
+ }
700
733
 
701
- /**
734
+ /**
702
735
  * Subscribe to changes for a key in the DHT
703
736
  * @param {string} key - The key to subscribe to
704
737
  * @returns {Promise<any>} The current value
705
738
  */
706
- async dhtSubscribe(key) {
707
- if (!this.enableWebDHT) {
708
- throw new Error('WebDHT is disabled. Enable it by setting enableWebDHT: true in constructor options.');
709
- }
710
- if (!this.webDHT) {
711
- throw new Error('WebDHT not initialized');
712
- }
713
- return this.webDHT.subscribe(key);
739
+ async dhtSubscribe(key) {
740
+ if (!this.enableWebDHT) {
741
+ throw new Error('WebDHT is disabled. Enable it by setting enableWebDHT: true in constructor options.');
742
+ }
743
+ if (!this.webDHT) {
744
+ throw new Error('WebDHT not initialized');
714
745
  }
746
+ return this.webDHT.subscribe(key);
747
+ }
715
748
 
716
- /**
749
+ /**
717
750
  * Unsubscribe from changes for a key in the DHT
718
751
  * @param {string} key - The key to unsubscribe from
719
752
  */
720
- async dhtUnsubscribe(key) {
721
- if (!this.enableWebDHT) {
722
- throw new Error('WebDHT is disabled. Enable it by setting enableWebDHT: true in constructor options.');
723
- }
724
- if (!this.webDHT) {
725
- throw new Error('WebDHT not initialized');
726
- }
727
- return this.webDHT.unsubscribe(key);
753
+ async dhtUnsubscribe(key) {
754
+ if (!this.enableWebDHT) {
755
+ throw new Error('WebDHT is disabled. Enable it by setting enableWebDHT: true in constructor options.');
756
+ }
757
+ if (!this.webDHT) {
758
+ throw new Error('WebDHT not initialized');
728
759
  }
760
+ return this.webDHT.unsubscribe(key);
761
+ }
729
762
 
730
- /**
763
+ /**
731
764
  * Update a key's value and notify subscribers
732
765
  * @param {string} key - The key to update
733
766
  * @param {any} newValue - The new value
734
767
  * @param {object} options - Update options
735
768
  * @returns {Promise<boolean>} True if updated successfully
736
769
  */
737
- async dhtUpdate(key, newValue, options = {}) {
738
- if (!this.enableWebDHT) {
739
- throw new Error('WebDHT is disabled. Enable it by setting enableWebDHT: true in constructor options.');
740
- }
741
- if (!this.webDHT) {
742
- throw new Error('WebDHT not initialized');
743
- }
744
- return this.webDHT.update(key, newValue, options);
770
+ async dhtUpdate(key, newValue, options = {}) {
771
+ if (!this.enableWebDHT) {
772
+ throw new Error('WebDHT is disabled. Enable it by setting enableWebDHT: true in constructor options.');
745
773
  }
774
+ if (!this.webDHT) {
775
+ throw new Error('WebDHT not initialized');
776
+ }
777
+ return this.webDHT.update(key, newValue, options);
778
+ }
746
779
 
747
- /**
780
+ /**
748
781
  * Get DHT statistics
749
782
  * @returns {object} DHT statistics
750
783
  */
751
- getDHTStats() {
752
- if (!this.enableWebDHT) {
753
- return { error: 'WebDHT is disabled. Enable it by setting enableWebDHT: true in constructor options.' };
754
- }
755
- if (!this.webDHT) {
756
- return { error: 'WebDHT not initialized' };
757
- }
758
- return this.webDHT.getStats();
784
+ getDHTStats() {
785
+ if (!this.enableWebDHT) {
786
+ return { error: 'WebDHT is disabled. Enable it by setting enableWebDHT: true in constructor options.' };
787
+ }
788
+ if (!this.webDHT) {
789
+ return { error: 'WebDHT not initialized' };
759
790
  }
791
+ return this.webDHT.getStats();
792
+ }
760
793
 
761
- /**
794
+ /**
762
795
  * Check if WebDHT is enabled
763
796
  * @returns {boolean} True if WebDHT is enabled
764
797
  */
765
- isDHTEnabled() {
766
- return this.enableWebDHT;
767
- }
798
+ isDHTEnabled() {
799
+ return this.enableWebDHT;
800
+ }
768
801
 
769
- /**
802
+ /**
770
803
  * Setup WebDHT event handlers
771
804
  */
772
- setupWebDHTEventHandlers() {
773
- // Only set up if webDHT exists
774
- if (this.webDHT) {
775
- this.webDHT.addEventListener('valueChanged', (data) => {
776
- this.emit('dhtValueChanged', data);
777
- });
778
- }
805
+ setupWebDHTEventHandlers() {
806
+ // Only set up if webDHT exists
807
+ if (this.webDHT) {
808
+ this.webDHT.addEventListener('valueChanged', (data) => {
809
+ this.emit('dhtValueChanged', data);
810
+ });
779
811
  }
812
+ }
780
813
 
781
- /**
814
+ /**
782
815
  * Connect to a specific peer by ID
783
816
  */
784
- connectToPeer(peerId) {
785
- if (!peerId || typeof peerId !== 'string') {
786
- throw new Error('Valid peer ID is required');
787
- }
788
-
789
- if (peerId === this.peerId) {
790
- throw new Error('Cannot connect to yourself');
791
- }
792
-
793
- return this.connectionManager.connectToPeer(peerId);
817
+ connectToPeer(peerId) {
818
+ if (!peerId || typeof peerId !== 'string') {
819
+ throw new Error('Valid peer ID is required');
794
820
  }
795
821
 
796
- /**
822
+ if (peerId === this.peerId) {
823
+ throw new Error('Cannot connect to yourself');
824
+ }
825
+
826
+ return this.connectionManager.connectToPeer(peerId);
827
+ }
828
+
829
+ /**
797
830
  * Get the current environment report
798
831
  * @returns {object} Complete environment detection report
799
832
  */
800
- getEnvironmentReport() {
801
- return this.environmentReport;
802
- }
833
+ getEnvironmentReport() {
834
+ return this.environmentReport;
835
+ }
803
836
 
804
- /**
837
+ /**
805
838
  * Get runtime capabilities
806
839
  * @returns {object} Capabilities detected during initialization
807
840
  */
808
- getCapabilities() {
809
- return this.capabilities;
810
- }
841
+ getCapabilities() {
842
+ return this.capabilities;
843
+ }
811
844
 
812
- /**
845
+ /**
813
846
  * Get runtime information
814
847
  * @returns {object} Runtime environment information
815
848
  */
816
- getRuntimeInfo() {
817
- return this.runtimeInfo;
818
- }
849
+ getRuntimeInfo() {
850
+ return this.runtimeInfo;
851
+ }
819
852
 
820
- /**
853
+ /**
821
854
  * Check if a specific feature is supported
822
855
  * @param {string} feature - The feature to check (e.g., 'webrtc', 'websocket', 'localstorage')
823
856
  * @returns {boolean} True if the feature is supported
824
857
  */
825
- hasFeature(feature) {
826
- return environmentDetector.hasFeature(feature);
827
- }
858
+ hasFeature(feature) {
859
+ return environmentDetector.hasFeature(feature);
860
+ }
828
861
 
829
- /**
862
+ /**
830
863
  * Get environment-specific recommendations
831
864
  * @returns {object} Recommendations based on current environment
832
865
  */
833
- getEnvironmentRecommendations() {
834
- const recommendations = [];
835
- const report = this.environmentReport;
836
-
837
- if (report.runtime.isBrowser) {
838
- if (!report.network.online) {
839
- recommendations.push({
840
- type: 'warning',
841
- message: 'Browser is offline. Enable network connectivity for mesh functionality.'
842
- });
843
- }
844
-
845
- if (typeof location !== 'undefined' && location.protocol === 'http:' && location.hostname !== 'localhost') {
846
- recommendations.push({
847
- type: 'security',
848
- message: 'Consider using HTTPS for better WebRTC compatibility and security.'
849
- });
850
- }
851
-
852
- if (report.browser && report.browser.name === 'safari') {
853
- recommendations.push({
854
- type: 'compatibility',
855
- message: 'Safari has some WebRTC limitations. Test thoroughly for production use.'
856
- });
857
- }
858
- }
866
+ getEnvironmentRecommendations() {
867
+ const recommendations = [];
868
+ const report = this.environmentReport;
869
+
870
+ if (report.runtime.isBrowser) {
871
+ if (!report.network.online) {
872
+ recommendations.push({
873
+ type: 'warning',
874
+ message: 'Browser is offline. Enable network connectivity for mesh functionality.'
875
+ });
876
+ }
859
877
 
860
- if (report.runtime.isNodeJS) {
861
- if (!report.capabilities.webSocket) {
862
- recommendations.push({
863
- type: 'dependency',
864
- message: 'Install the "ws" package for WebSocket support: npm install ws'
865
- });
866
- }
867
-
868
- if (!report.capabilities.webrtc) {
869
- recommendations.push({
870
- type: 'dependency',
871
- message: 'Install "node-webrtc" or similar for WebRTC support in Node.js: npm install node-webrtc'
872
- });
873
- }
874
- }
878
+ if (typeof location !== 'undefined' && location.protocol === 'http:' && location.hostname !== 'localhost') {
879
+ recommendations.push({
880
+ type: 'security',
881
+ message: 'Consider using HTTPS for better WebRTC compatibility and security.'
882
+ });
883
+ }
884
+
885
+ if (report.browser && report.browser.name === 'safari') {
886
+ recommendations.push({
887
+ type: 'compatibility',
888
+ message: 'Safari has some WebRTC limitations. Test thoroughly for production use.'
889
+ });
890
+ }
891
+ }
892
+
893
+ if (report.runtime.isNodeJS) {
894
+ if (!report.capabilities.webSocket) {
895
+ recommendations.push({
896
+ type: 'dependency',
897
+ message: 'Install the "ws" package for WebSocket support: npm install ws'
898
+ });
899
+ }
900
+
901
+ if (!report.capabilities.webrtc) {
902
+ recommendations.push({
903
+ type: 'dependency',
904
+ message: 'Install "node-webrtc" or similar for WebRTC support in Node.js: npm install node-webrtc'
905
+ });
906
+ }
907
+ }
908
+
909
+ if (!report.capabilities.localStorage && !report.capabilities.sessionStorage) {
910
+ recommendations.push({
911
+ type: 'feature',
912
+ message: 'No persistent storage available. Peer ID will change on restart.'
913
+ });
914
+ }
915
+
916
+ return {
917
+ environment: report.runtime,
918
+ recommendations
919
+ };
920
+ }
921
+
922
+ // ============================================
923
+ // Cryptographic Methods (unsea integration)
924
+ // ============================================
925
+
926
+ /**
927
+ * Initialize crypto with user credentials
928
+ * @param {Object} options - Crypto initialization options
929
+ * @param {string} options.alias - User alias for persistent identity
930
+ * @param {string} options.password - User password
931
+ * @returns {Promise<boolean>} True if crypto was initialized successfully
932
+ */
933
+ async initCrypto(options = {}) {
934
+ if (!this.enableCrypto) {
935
+ this.enableCrypto = true;
936
+ this.cryptoManager = new CryptoManager();
937
+ }
938
+
939
+ if (!this.cryptoManager) {
940
+ throw new Error('Crypto manager not available');
941
+ }
942
+
943
+ try {
944
+ await this.cryptoManager.init(options);
945
+ return true;
946
+ } catch (error) {
947
+ console.error('Failed to initialize crypto:', error);
948
+ throw error;
949
+ }
950
+ }
951
+
952
+ /**
953
+ * Get crypto status and information
954
+ * @returns {Object} Crypto status information
955
+ */
956
+ getCryptoStatus() {
957
+ if (!this.cryptoManager) {
958
+ return {
959
+ enabled: false,
960
+ initialized: false,
961
+ error: 'Crypto not enabled. Enable with enableCrypto: true in constructor'
962
+ };
963
+ }
964
+
965
+ return this.cryptoManager.getStatus();
966
+ }
967
+
968
+ /**
969
+ * Enable/disable crypto functionality
970
+ * @param {boolean} enabled - Whether to enable crypto
971
+ */
972
+ setCrypto(enabled) {
973
+ if (enabled && !this.cryptoManager) {
974
+ this.cryptoManager = new CryptoManager();
975
+ }
976
+ this.enableCrypto = enabled;
977
+ }
978
+
979
+ /**
980
+ * Encrypt a message without sending it
981
+ * @param {any} content - Message content to encrypt
982
+ * @param {string} peerId - Optional target peer ID for peer-to-peer encryption
983
+ * @param {string} groupId - Optional group ID for group encryption
984
+ * @returns {Promise<Object>} Encrypted message object
985
+ */
986
+ async encryptMessage(content, peerId = null, groupId = null) {
987
+ if (!this.enableCrypto || !this.cryptoManager) {
988
+ throw new Error('Crypto not enabled or initialized');
989
+ }
875
990
 
876
- if (!report.capabilities.localStorage && !report.capabilities.sessionStorage) {
877
- recommendations.push({
878
- type: 'feature',
879
- message: 'No persistent storage available. Peer ID will change on restart.'
880
- });
991
+ try {
992
+ if (groupId) {
993
+ return await this.cryptoManager.encryptForGroup(content, groupId);
994
+ } else if (peerId) {
995
+ return await this.cryptoManager.encryptForPeer(content, peerId);
996
+ } else {
997
+ // For benchmark/testing purposes, encrypt with our own public key
998
+ const ourPeerId = this.peerId;
999
+ const ourKeypair = this.cryptoManager.keypair;
1000
+ if (ourKeypair && ourKeypair.pub && ourKeypair.epub) {
1001
+ // Add our own key temporarily for testing (include both pub and epub)
1002
+ this.cryptoManager.addPeerKey(ourPeerId, {
1003
+ pub: ourKeypair.pub,
1004
+ epub: ourKeypair.epub
1005
+ });
1006
+ return await this.cryptoManager.encryptForPeer(content, ourPeerId);
1007
+ } else {
1008
+ throw new Error('No complete keypair available for encryption (need both pub and epub)');
881
1009
  }
1010
+ }
1011
+ } catch (error) {
1012
+ console.error('Failed to encrypt message:', error);
1013
+ throw error;
1014
+ }
1015
+ }
1016
+
1017
+ /**
1018
+ * Send an encrypted message to a specific peer
1019
+ * @param {string} peerId - Target peer ID
1020
+ * @param {any} content - Message content
1021
+ * @param {Object} options - Message options
1022
+ * @returns {Promise<string|null>} Message ID if sent successfully
1023
+ */
1024
+ async sendEncryptedMessage(peerId, content, _options = {}) {
1025
+ if (!this.enableCrypto || !this.cryptoManager) {
1026
+ throw new Error('Crypto not enabled or initialized');
1027
+ }
882
1028
 
883
- return {
884
- environment: report.runtime,
885
- recommendations
1029
+ try {
1030
+ const encryptedContent = await this.cryptoManager.encryptForPeer(content, peerId);
1031
+ return this.sendDirectMessage(peerId, encryptedContent);
1032
+ } catch (error) {
1033
+ console.error('Failed to send encrypted message:', error);
1034
+ throw error;
1035
+ }
1036
+ }
1037
+
1038
+ /**
1039
+ * Send an encrypted broadcast message
1040
+ * @param {any} content - Message content
1041
+ * @param {string} groupId - Optional group ID for group encryption
1042
+ * @returns {Promise<string|null>} Message ID if sent successfully
1043
+ */
1044
+ async sendEncryptedBroadcast(content, groupId = null) {
1045
+ if (!this.enableCrypto || !this.cryptoManager) {
1046
+ throw new Error('Crypto not enabled or initialized');
1047
+ }
1048
+
1049
+ try {
1050
+ let encryptedContent;
1051
+ if (groupId) {
1052
+ encryptedContent = await this.cryptoManager.encryptForGroup(content, groupId);
1053
+ } else {
1054
+ // For broadcast without group, we'll need to encrypt for each peer individually
1055
+ // This is a simplified approach - in practice, you'd use group keys
1056
+ encryptedContent = {
1057
+ encrypted: true,
1058
+ broadcast: true,
1059
+ data: content,
1060
+ from: this.cryptoManager.getPublicKey(),
1061
+ timestamp: Date.now()
886
1062
  };
1063
+ }
1064
+ // Use 'encrypted' message type instead of 'chat' for encrypted broadcasts
1065
+ return this.gossipManager.broadcastMessage(encryptedContent, 'encrypted');
1066
+ } catch (error) {
1067
+ console.error('Failed to send encrypted broadcast:', error);
1068
+ throw error;
1069
+ }
1070
+ }
1071
+
1072
+ /**
1073
+ * Decrypt a received message
1074
+ * @param {Object} encryptedData - Encrypted message data
1075
+ * @returns {Promise<any>} Decrypted content
1076
+ */
1077
+ async decryptMessage(encryptedData) {
1078
+ if (!this.enableCrypto || !this.cryptoManager) {
1079
+ return encryptedData; // Return as-is if crypto not enabled
1080
+ }
1081
+
1082
+ try {
1083
+ if (encryptedData.group) {
1084
+ return await this.cryptoManager.decryptFromGroup(encryptedData);
1085
+ } else {
1086
+ return await this.cryptoManager.decryptFromPeer(encryptedData);
1087
+ }
1088
+ } catch (error) {
1089
+ console.error('Failed to decrypt message:', error);
1090
+ throw error;
1091
+ }
1092
+ }
1093
+
1094
+ /**
1095
+ * Exchange public keys with a peer
1096
+ * @param {string} peerId - Peer ID to exchange keys with
1097
+ */
1098
+ async exchangeKeysWithPeer(peerId) {
1099
+ if (!this.enableCrypto || !this.cryptoManager) {
1100
+ throw new Error('Crypto not enabled or initialized');
1101
+ }
1102
+
1103
+ const keypair = this.cryptoManager.keypair;
1104
+ if (!keypair || !keypair.pub || !keypair.epub) {
1105
+ throw new Error('No complete keypair available (need both pub and epub)');
1106
+ }
1107
+
1108
+ // Send both our public key (pub) and encryption public key (epub) to the peer
1109
+ return this.gossipManager.sendDirectMessage(peerId, {
1110
+ type: 'key_exchange',
1111
+ publicKey: {
1112
+ pub: keypair.pub,
1113
+ epub: keypair.epub
1114
+ },
1115
+ timestamp: Date.now()
1116
+ }, 'key_exchange');
1117
+ }
1118
+
1119
+ /**
1120
+ * Add a peer's public key
1121
+ * @param {string} peerId - Peer ID
1122
+ * @param {string} publicKey - Peer's public key
1123
+ * @returns {boolean} True if key was added successfully
1124
+ */
1125
+ addPeerPublicKey(peerId, publicKey) {
1126
+ if (!this.enableCrypto || !this.cryptoManager) {
1127
+ return false;
1128
+ }
1129
+
1130
+ return this.cryptoManager.addPeerKey(peerId, publicKey);
1131
+ }
1132
+
1133
+ /**
1134
+ * Generate a group key for encrypted group communications
1135
+ * @param {string} groupId - Group identifier
1136
+ * @returns {Promise<Object>} Generated group key
1137
+ */
1138
+ async generateGroupKey(groupId) {
1139
+ if (!this.enableCrypto || !this.cryptoManager) {
1140
+ throw new Error('Crypto not enabled or initialized');
1141
+ }
1142
+
1143
+ return await this.cryptoManager.generateGroupKey(groupId);
1144
+ }
1145
+
1146
+ /**
1147
+ * Add a group key for encrypted group communications
1148
+ * @param {string} groupId - Group identifier
1149
+ * @param {Object} groupKey - Group key object
1150
+ */
1151
+ addGroupKey(groupId, groupKey) {
1152
+ if (!this.enableCrypto || !this.cryptoManager) {
1153
+ throw new Error('Crypto not enabled or initialized');
1154
+ }
1155
+
1156
+ this.cryptoManager.addGroupKey(groupId, groupKey);
1157
+ }
1158
+
1159
+ /**
1160
+ * Sign data with our private key
1161
+ * @param {any} data - Data to sign
1162
+ * @returns {Promise<string>} Digital signature
1163
+ */
1164
+ async signData(data) {
1165
+ if (!this.enableCrypto || !this.cryptoManager) {
1166
+ throw new Error('Crypto not enabled or initialized');
1167
+ }
1168
+
1169
+ return await this.cryptoManager.sign(data);
1170
+ }
1171
+
1172
+ /**
1173
+ * Verify a signature
1174
+ * @param {string} signature - Signature to verify
1175
+ * @param {any} data - Original data
1176
+ * @param {string} publicKey - Signer's public key
1177
+ * @returns {Promise<boolean>} True if signature is valid
1178
+ */
1179
+ async verifySignature(signature, data, publicKey) {
1180
+ if (!this.enableCrypto || !this.cryptoManager) {
1181
+ return true; // If crypto disabled, assume valid
1182
+ }
1183
+
1184
+ return await this.cryptoManager.verify(signature, data, publicKey);
1185
+ }
1186
+
1187
+ /**
1188
+ * Export our public key for sharing
1189
+ * @returns {Object|null} Public key export data
1190
+ */
1191
+ exportPublicKey() {
1192
+ if (!this.enableCrypto || !this.cryptoManager) {
1193
+ return null;
1194
+ }
1195
+
1196
+ return this.cryptoManager.exportPublicKey();
1197
+ }
1198
+
1199
+ /**
1200
+ * Run crypto self-tests
1201
+ * @returns {Promise<Object>} Test results
1202
+ */
1203
+ async runCryptoTests() {
1204
+ if (!this.enableCrypto || !this.cryptoManager) {
1205
+ throw new Error('Crypto not enabled or initialized');
1206
+ }
1207
+
1208
+ return await this.cryptoManager.runSelfTest();
1209
+ }
1210
+
1211
+ /**
1212
+ * Reset crypto state and clear all keys
1213
+ */
1214
+ resetCrypto() {
1215
+ if (this.cryptoManager) {
1216
+ this.cryptoManager.reset();
1217
+ }
1218
+ }
1219
+
1220
+ /**
1221
+ * Handle incoming key exchange messages
1222
+ * @param {Object} data - Key exchange message data
1223
+ * @param {string} from - Sender's peer ID
1224
+ * @private
1225
+ */
1226
+ _handleKeyExchange(data, from) {
1227
+ if ((data.type === 'key_exchange' || data.type === 'key_exchange_response') && data.publicKey && this.cryptoManager) {
1228
+ this.cryptoManager.addPeerKey(from, data.publicKey);
1229
+ console.log(`🔐 Stored public key for peer ${from.substring(0, 8)}...`);
1230
+
1231
+ // Send our public key back if this was an initial exchange (not a response)
1232
+ if (data.type === 'key_exchange') {
1233
+ const keypair = this.cryptoManager.keypair;
1234
+ if (keypair && keypair.pub && keypair.epub) {
1235
+ this.gossipManager.sendDirectMessage(from, {
1236
+ type: 'key_exchange_response',
1237
+ publicKey: {
1238
+ pub: keypair.pub,
1239
+ epub: keypair.epub
1240
+ },
1241
+ timestamp: Date.now()
1242
+ }, 'key_exchange_response');
1243
+ }
1244
+ }
887
1245
  }
888
- }
1246
+ }
1247
+ }