peerpigeon 0.0.5 → 0.0.7

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