peerpigeon 0.1.1 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/README.md +141 -1365
  2. package/cli.js +1382 -0
  3. package/dist/peerpigeon-browser.js +12450 -0
  4. package/dist/peerpigeon-browser.js.map +7 -0
  5. package/docs/API_DOCUMENTATION.md +1976 -0
  6. package/docs/BOOTSTRAP_HUBS.md +319 -0
  7. package/docs/CLI_README.md +371 -0
  8. package/docs/CUSTOM_HUB_NAMESPACES.md +182 -0
  9. package/docs/CUSTOM_NAMESPACE_IMPLEMENTATION.md +187 -0
  10. package/docs/DOCUMENTATION_REORGANIZATION.md +172 -0
  11. package/docs/HUB_QUICK_REF.md +108 -0
  12. package/docs/HUB_SCRIPTS.md +341 -0
  13. package/docs/HUB_SYSTEM.md +599 -0
  14. package/docs/MIGRATION_COMPLETE.md +93 -0
  15. package/docs/NETWORK_NAMESPACES.md +212 -0
  16. package/docs/PIGEONRTC_MIGRATION.md +280 -0
  17. package/docs/README.md +108 -0
  18. package/docs/SELECTIVE_STREAMING_GUIDE.md +427 -0
  19. package/docs/TEST_CLEANUP_COMPLETE.md +80 -0
  20. package/examples/bootstrap-hub-example.js +292 -0
  21. package/examples/browser/README.md +278 -0
  22. package/examples/browser/app.js +2426 -49
  23. package/examples/browser/index.html +481 -630
  24. package/examples/browser/minimal/README.md +55 -0
  25. package/examples/browser/minimal/index.html +75 -0
  26. package/examples/browser/minimal/minimal.js +234 -0
  27. package/examples/browser/styles.css +687 -1425
  28. package/examples/browser/test-bundle.html +35 -0
  29. package/examples/browser-2/index.html +30 -0
  30. package/examples/browser-2/package.json +21 -0
  31. package/examples/browser-2/src/App-simple.vue +21 -0
  32. package/examples/browser-2/src/App.vue +420 -0
  33. package/examples/browser-2/src/components/CryptoView.vue +1661 -0
  34. package/examples/browser-2/src/components/DHTView.vue +1281 -0
  35. package/examples/browser-2/src/components/DebugView.vue +1773 -0
  36. package/examples/browser-2/src/components/MediaView.vue +1048 -0
  37. package/examples/browser-2/src/components/MessagingView.vue +775 -0
  38. package/examples/browser-2/src/components/NetworkView.vue +930 -0
  39. package/examples/browser-2/src/components/StorageView.vue +1376 -0
  40. package/examples/browser-2/src/main.js +5 -0
  41. package/examples/browser-2/src/stores/peerpigeon.js +895 -0
  42. package/examples/browser-2/vite.config.js +6 -0
  43. package/examples/hub-example.js +189 -0
  44. package/examples/multi-hub-test.js +186 -0
  45. package/examples/node/README.md +2 -2
  46. package/examples/programmatic-namespace-example.js +108 -0
  47. package/examples/selective-streaming-demo.html +698 -0
  48. package/examples/standard-events-demo.js +126 -0
  49. package/index.js +7 -1
  50. package/package.json +34 -16
  51. package/server/index.js +1058 -98
  52. package/server/start.js +52 -0
  53. package/src/ConnectionManager.js +239 -225
  54. package/src/CryptoManager.js +147 -18
  55. package/src/DebugLogger.js +0 -7
  56. package/src/DistributedStorageManager.js +224 -205
  57. package/src/EnvironmentDetector.js +88 -4
  58. package/src/EventEmitter.js +79 -1
  59. package/src/EvictionManager.js +10 -9
  60. package/src/GossipManager.js +163 -11
  61. package/src/MediaManager.js +12 -2
  62. package/src/PeerConnection.js +343 -311
  63. package/src/PeerPigeonMesh.js +576 -135
  64. package/src/PigeonRTC-browser.js +247 -0
  65. package/src/SignalingClient.js +14 -243
  66. package/src/SignalingHandler.js +31 -10
  67. package/src/StorageManager.js +0 -39
  68. package/src/WebDHT-Simple.js +389 -0
  69. package/src/WebDHT.js +363 -1165
  70. package/src/browser-entry.js +58 -0
  71. package/examples/browser/assets/images/favicon.png +0 -0
  72. package/examples/browser/assets/images/pigeon.png +0 -0
  73. package/examples/browser/crypto-test.html +0 -427
  74. package/examples/browser/ui-old.js +0 -1926
  75. package/examples/browser/ui.js +0 -3391
  76. package/websocket-server/README.md +0 -247
  77. package/websocket-server/server.js +0 -391
@@ -28,21 +28,33 @@ export class PeerPigeonMesh extends EventEmitter {
28
28
  this.signalingClient = null;
29
29
  this.peerDiscovery = null;
30
30
 
31
- // Configuration
32
- this.maxPeers = 3;
33
- this.minPeers = 2;
34
- this.autoDiscovery = true;
35
- this.evictionStrategy = true;
36
- this.xorRouting = true;
31
+ // Network namespace configuration
32
+ this.networkName = options.networkName || 'global';
33
+ this.allowGlobalFallback = options.allowGlobalFallback !== false; // Default to true
34
+ this.isInFallbackMode = false;
35
+ this.originalNetworkName = this.networkName;
36
+
37
+ // Configuration - Optional features enabled by default (opt-out)
38
+ this.maxPeers = options.maxPeers !== undefined ? options.maxPeers : 3;
39
+ this.minPeers = options.minPeers !== undefined ? options.minPeers : 2;
40
+ this.autoConnect = options.autoConnect !== false; // Default to true, can be disabled by setting to false
41
+ this.autoDiscovery = options.autoDiscovery !== false;
42
+ this.evictionStrategy = options.evictionStrategy !== false;
43
+ this.xorRouting = options.xorRouting !== false;
37
44
  this.enableWebDHT = options.enableWebDHT !== false; // Default to true, can be disabled by setting to false
38
- this.enableCrypto = options.enableCrypto === true; // Default to false, must be explicitly enabled
45
+ this.enableCrypto = options.enableCrypto !== false; // Default to true, can be disabled by setting to false
39
46
 
40
47
  // State
41
48
  this.connected = false;
42
49
  this.polling = false; // Only WebSocket is supported
43
50
  this.signalingUrl = null;
44
51
  this.discoveredPeers = new Map();
45
- this.connectionMonitorInterval = null;
52
+
53
+ // Track ongoing key exchange attempts to prevent duplicates across all channels
54
+ this.ongoingKeyExchanges = new Set();
55
+
56
+ // Track peers for which we've already emitted peerKeyAdded events to prevent UI spam
57
+ this.emittedPeerKeyEvents = new Set();
46
58
 
47
59
  // Initialize managers
48
60
  this.storageManager = new StorageManager(this);
@@ -78,15 +90,13 @@ export class PeerPigeonMesh extends EventEmitter {
78
90
  this.emit('peersUpdated');
79
91
  });
80
92
 
81
- // Handle peer disconnections and trigger keep-alive ping coordination
93
+ // Handle peer disconnections
82
94
  this.addEventListener('peerDisconnected', (data) => {
83
95
  this.debug.log(`Peer ${data.peerId.substring(0, 8)}... disconnected: ${data.reason}`);
84
- // Trigger immediate keep-alive ping check in case the disconnected peer was the designated sender
85
- if (this.signalingClient && this.signalingClient.connected) {
86
- setTimeout(() => {
87
- this.signalingClient.triggerKeepAlivePingCheck();
88
- }, 1000); // Small delay to let peer lists update
89
- }
96
+
97
+ // Clear tracking for this peer to allow fresh key exchange if they reconnect
98
+ this.emittedPeerKeyEvents.delete(data.peerId);
99
+ this.ongoingKeyExchanges.delete(data.peerId);
90
100
  });
91
101
 
92
102
  // Handle gossip messages and intercept mesh signaling
@@ -99,10 +109,33 @@ export class PeerPigeonMesh extends EventEmitter {
99
109
 
100
110
  // Handle crypto key exchange messages
101
111
  if (data.message && (data.message.type === 'key_exchange' || data.message.type === 'key_exchange_response')) {
102
- this._handleKeyExchange(data.message, data.from);
112
+ this._handleKeyExchange(data.message, data.from).catch(err => {
113
+ this.debug.error('Key exchange handling failed:', err);
114
+ });
115
+ return; // Don't emit as regular message
116
+ }
117
+
118
+ // Handle DHT messages - route to WebDHT
119
+ if (data.message && data.message.type === 'dht' && this.webDHT) {
120
+ this.webDHT.handleMessage(data.message, data.from);
103
121
  return; // Don't emit as regular message
104
122
  }
105
123
 
124
+ // Additional safety filter for message types that should not be emitted to UI
125
+ // These should already be filtered at the GossipManager level, but this provides defense in depth
126
+ if (data.content && typeof data.content === 'string') {
127
+ try {
128
+ const parsedContent = JSON.parse(data.content);
129
+ const filteredTypes = ['signaling-relay', 'peer-announce-relay', 'bootstrap-keepalive', 'client-peer-announcement', 'cross-bootstrap-signaling'];
130
+ if (filteredTypes.includes(parsedContent.type)) {
131
+ console.debug(`🔇 MESH FILTER: Blocked filtered message type '${parsedContent.type}' from UI emission`);
132
+ return; // Don't emit to UI
133
+ }
134
+ } catch (e) {
135
+ // Not JSON, continue normally
136
+ }
137
+ }
138
+
106
139
  this.emit('messageReceived', data);
107
140
  });
108
141
 
@@ -123,7 +156,9 @@ export class PeerPigeonMesh extends EventEmitter {
123
156
  hasVideo: data.hasVideo,
124
157
  hasAudio: data.hasAudio,
125
158
  timestamp: Date.now()
126
- }, 'mediaEvent');
159
+ }, 'mediaEvent').catch(err => {
160
+ this.debug.error('Failed to broadcast stream started event:', err);
161
+ });
127
162
  });
128
163
 
129
164
  this.mediaManager.addEventListener('localStreamStopped', () => {
@@ -133,7 +168,9 @@ export class PeerPigeonMesh extends EventEmitter {
133
168
  event: 'streamStopped',
134
169
  peerId: this.peerId,
135
170
  timestamp: Date.now()
136
- }, 'mediaEvent');
171
+ }, 'mediaEvent').catch(err => {
172
+ this.debug.error('Failed to broadcast stream stopped event:', err);
173
+ });
137
174
  });
138
175
 
139
176
  this.mediaManager.addEventListener('error', (data) => {
@@ -156,7 +193,11 @@ export class PeerPigeonMesh extends EventEmitter {
156
193
  });
157
194
 
158
195
  this.cryptoManager.addEventListener('peerKeyAdded', (data) => {
159
- this.emit('peerKeyAdded', data);
196
+ // Only emit peerKeyAdded event once per peer to prevent UI spam from duplicate key exchanges
197
+ if (!this.emittedPeerKeyEvents.has(data.peerId)) {
198
+ this.emittedPeerKeyEvents.add(data.peerId);
199
+ this.emit('peerKeyAdded', data);
200
+ }
160
201
  });
161
202
 
162
203
  this.cryptoManager.addEventListener('userAuthenticated', (data) => {
@@ -184,7 +225,7 @@ export class PeerPigeonMesh extends EventEmitter {
184
225
  if (report.runtime.isBrowser) {
185
226
  errors.push('WebRTC is not supported in this browser. PeerPigeon requires WebRTC for peer-to-peer connections.');
186
227
  } else if (report.runtime.isNodeJS) {
187
- warnings.push('WebRTC support not detected in Node.js environment. Consider using a WebRTC library like node-webrtc.');
228
+ warnings.push('WebRTC support not detected in Node.js environment. PeerPigeon includes @koush/wrtc for automatic WebRTC support - ensure it is properly installed.');
188
229
  } else if (report.runtime.isNativeScript) {
189
230
  warnings.push('WebRTC support not detected in NativeScript environment. Consider using a native WebRTC plugin.');
190
231
  }
@@ -267,30 +308,43 @@ export class PeerPigeonMesh extends EventEmitter {
267
308
 
268
309
  async init() {
269
310
  try {
311
+ // Initialize PigeonRTC for cross-platform WebRTC support
312
+ try {
313
+ const webrtcInitialized = await environmentDetector.initWebRTCAsync();
314
+ if (webrtcInitialized) {
315
+ const adapterName = environmentDetector.getPigeonRTC()?.getAdapterName();
316
+ this.debug.log(`🌐 PigeonRTC initialized successfully (${adapterName})`);
317
+ }
318
+ } catch (error) {
319
+ this.debug.warn('PigeonRTC initialization failed:', error.message);
320
+ }
321
+
270
322
  // Use provided peer ID if valid, otherwise generate one
271
323
  if (this.providedPeerId) {
272
- if (this.storageManager.validatePeerId(this.providedPeerId)) {
324
+ if (PeerPigeonMesh.validatePeerId(this.providedPeerId)) {
273
325
  this.peerId = this.providedPeerId;
274
326
  this.debug.log(`Using provided peer ID: ${this.peerId}`);
275
327
  } else {
276
328
  this.debug.warn(`Invalid peer ID provided: ${this.providedPeerId}. Must be 40-character SHA-1 hex string. Generating new one.`);
277
- this.peerId = await this.storageManager.generatePeerId();
329
+ this.peerId = await PeerPigeonMesh.generatePeerId();
278
330
  }
279
331
  } else {
280
- this.peerId = await this.storageManager.generatePeerId();
332
+ this.peerId = await PeerPigeonMesh.generatePeerId();
281
333
  }
282
334
 
283
335
  // Initialize WebDHT now that we have a peerId (if enabled)
284
336
  if (this.enableWebDHT) {
337
+ // Initialize WebDHT - Low-level distributed hash table for raw key-value storage
285
338
  this.webDHT = new WebDHT(this);
286
- this.debug.log('WebDHT initialized and enabled');
339
+ this.debug.log('WebDHT (low-level DHT) initialized and enabled');
287
340
 
288
341
  // Setup WebDHT event handlers now that it's initialized
289
342
  this.setupWebDHTEventHandlers();
290
343
 
291
- // Initialize DistributedStorageManager if WebDHT is enabled
344
+ // Initialize DistributedStorageManager - High-level storage with encryption/access control
345
+ // Note: This uses WebDHT as its storage backend but provides a separate high-level API
292
346
  this.distributedStorage = new DistributedStorageManager(this);
293
- this.debug.log('DistributedStorageManager initialized');
347
+ this.debug.log('DistributedStorageManager (high-level encrypted storage) initialized');
294
348
 
295
349
  // Setup DistributedStorageManager event handlers
296
350
  this.setupDistributedStorageEventHandlers();
@@ -319,9 +373,16 @@ export class PeerPigeonMesh extends EventEmitter {
319
373
  // Initialize crypto manager if enabled
320
374
  if (this.cryptoManager) {
321
375
  try {
322
- this.debug.log('🔐 Initializing crypto manager...');
323
- await this.cryptoManager.init({ generateKeypair: true });
324
- this.debug.log('🔐 Crypto manager initialized successfully');
376
+ this.debug.log('🔐 Initializing crypto manager with automatic key persistence...');
377
+
378
+ // Add timeout to prevent hanging
379
+ const cryptoInitPromise = this.cryptoManager.initWithPeerId(this.peerId);
380
+ const timeoutPromise = new Promise((resolve, reject) => {
381
+ setTimeout(() => reject(new Error('Crypto initialization timeout')), 10000);
382
+ });
383
+
384
+ await Promise.race([cryptoInitPromise, timeoutPromise]);
385
+ this.debug.log('🔐 Crypto manager initialized successfully with persistent keys');
325
386
  } catch (error) {
326
387
  this.debug.error('Failed to initialize crypto manager:', error);
327
388
  // Continue without crypto - don't fail the entire init
@@ -344,9 +405,6 @@ export class PeerPigeonMesh extends EventEmitter {
344
405
  this.polling = false;
345
406
  this.peerDiscovery.start();
346
407
 
347
- // Start periodic health monitoring
348
- this.startConnectionMonitoring();
349
-
350
408
  this.emit('statusChanged', { type: 'connected' });
351
409
  });
352
410
 
@@ -355,7 +413,6 @@ export class PeerPigeonMesh extends EventEmitter {
355
413
  this.polling = false;
356
414
  this.peerDiscovery.stop();
357
415
  this.connectionManager.disconnectAllPeers();
358
- this.stopConnectionMonitoring();
359
416
  this.emit('statusChanged', { type: 'disconnected' });
360
417
  });
361
418
 
@@ -371,6 +428,11 @@ export class PeerPigeonMesh extends EventEmitter {
371
428
  setupDiscoveryHandlers() {
372
429
  this.peerDiscovery.addEventListener('peerDiscovered', (data) => {
373
430
  this.emit('peerDiscovered', data);
431
+
432
+ // Check if we should return from global fallback to original network
433
+ if (this.isInFallbackMode && this.originalNetworkName !== 'global') {
434
+ this._tryReturnToOriginalNetwork();
435
+ }
374
436
  });
375
437
 
376
438
  this.peerDiscovery.addEventListener('connectToPeer', (data) => {
@@ -390,6 +452,11 @@ export class PeerPigeonMesh extends EventEmitter {
390
452
  this.meshOptimizer.handleOptimizeConnections(data.unconnectedPeers);
391
453
  });
392
454
 
455
+ // Monitor network health and activate fallback if needed
456
+ this.addEventListener('peersUpdated', () => {
457
+ this._checkNetworkHealth();
458
+ });
459
+
393
460
  this.peerDiscovery.addEventListener('peersUpdated', (data) => {
394
461
  this.emit('statusChanged', { type: 'info', message: `Cleaned up ${data.removedCount} stale peer(s)` });
395
462
  this.emit('peersUpdated');
@@ -436,9 +503,6 @@ export class PeerPigeonMesh extends EventEmitter {
436
503
  this.connected = false;
437
504
  this.polling = false;
438
505
 
439
- // Stop connection monitoring
440
- this.stopConnectionMonitoring();
441
-
442
506
  if (this.signalingClient) {
443
507
  this.signalingClient.disconnect();
444
508
  }
@@ -450,10 +514,7 @@ export class PeerPigeonMesh extends EventEmitter {
450
514
  this.connectionManager.disconnectAllPeers();
451
515
  this.connectionManager.cleanup();
452
516
 
453
- // Cleanup WebDHT
454
- if (this.webDHT) {
455
- this.webDHT.cleanup();
456
- }
517
+ // WebDHT persists in the mesh - no cleanup needed on disconnect
457
518
  this.evictionManager.cleanup();
458
519
  this.cleanupManager.cleanup();
459
520
  this.gossipManager.cleanup();
@@ -498,11 +559,149 @@ export class PeerPigeonMesh extends EventEmitter {
498
559
  this.emit('statusChanged', { type: 'setting', setting: 'autoDiscovery', value: enabled });
499
560
  }
500
561
 
562
+ setAutoConnect(enabled) {
563
+ this.autoConnect = enabled;
564
+ this.emit('statusChanged', { type: 'setting', setting: 'autoConnect', value: enabled });
565
+ }
566
+
501
567
  setEvictionStrategy(enabled) {
502
568
  this.evictionStrategy = enabled;
503
569
  this.emit('statusChanged', { type: 'setting', setting: 'evictionStrategy', value: enabled });
504
570
  }
505
571
 
572
+ // Network namespace management methods
573
+ setNetworkName(networkName) {
574
+ if (this.connected) {
575
+ throw new Error('Cannot change network name while connected. Disconnect first.');
576
+ }
577
+
578
+ this.networkName = networkName || 'global';
579
+ this.originalNetworkName = this.networkName;
580
+ this.isInFallbackMode = false;
581
+
582
+ this.emit('statusChanged', {
583
+ type: 'setting',
584
+ setting: 'networkName',
585
+ value: this.networkName
586
+ });
587
+
588
+ return this.networkName;
589
+ }
590
+
591
+ getNetworkName() {
592
+ return this.networkName;
593
+ }
594
+
595
+ getOriginalNetworkName() {
596
+ return this.originalNetworkName;
597
+ }
598
+
599
+ isUsingGlobalFallback() {
600
+ return this.isInFallbackMode;
601
+ }
602
+
603
+ setAllowGlobalFallback(allow) {
604
+ this.allowGlobalFallback = allow;
605
+ this.emit('statusChanged', {
606
+ type: 'setting',
607
+ setting: 'allowGlobalFallback',
608
+ value: allow
609
+ });
610
+
611
+ // If we're currently in fallback mode and fallback is disabled, try to return to original network
612
+ if (!allow && this.isInFallbackMode) {
613
+ this._tryReturnToOriginalNetwork();
614
+ }
615
+
616
+ return this.allowGlobalFallback;
617
+ }
618
+
619
+ async _tryReturnToOriginalNetwork() {
620
+ if (!this.isInFallbackMode || this.originalNetworkName === 'global') {
621
+ return;
622
+ }
623
+
624
+ // Check if there are now peers in the original network
625
+ const originalNetworkPeerCount = await this._getNetworkPeerCount(this.originalNetworkName);
626
+
627
+ if (originalNetworkPeerCount > 0) {
628
+ this.debug.log(`Returning from global fallback to original network: ${this.originalNetworkName}`);
629
+ this.networkName = this.originalNetworkName;
630
+ this.isInFallbackMode = false;
631
+
632
+ this.emit('statusChanged', {
633
+ type: 'network',
634
+ message: `Returned to network: ${this.networkName}`,
635
+ networkName: this.networkName,
636
+ fallbackMode: false
637
+ });
638
+
639
+ // Trigger reconnection to rebuild mesh in correct network
640
+ if (this.connected) {
641
+ this.disconnect();
642
+ setTimeout(() => {
643
+ if (this.signalingUrl) {
644
+ this.connect(this.signalingUrl);
645
+ }
646
+ }, 1000);
647
+ }
648
+ }
649
+ }
650
+
651
+ async _activateGlobalFallback() {
652
+ if (this.originalNetworkName === 'global' || this.isInFallbackMode || !this.allowGlobalFallback) {
653
+ return false;
654
+ }
655
+
656
+ this.debug.log(`Activating global fallback from network: ${this.originalNetworkName}`);
657
+ this.networkName = 'global';
658
+ this.isInFallbackMode = true;
659
+
660
+ this.emit('statusChanged', {
661
+ type: 'network',
662
+ message: `Fallback to global network from: ${this.originalNetworkName}`,
663
+ networkName: this.networkName,
664
+ originalNetwork: this.originalNetworkName,
665
+ fallbackMode: true
666
+ });
667
+
668
+ return true;
669
+ }
670
+
671
+ async _getNetworkPeerCount(networkName) {
672
+ // This would need to be implemented with signaling server support
673
+ // For now, return 0 to indicate we can't determine peer count
674
+ return 0;
675
+ }
676
+
677
+ _checkNetworkHealth() {
678
+ // TEMPORARILY DISABLED - aggressive fallback for debugging
679
+ return;
680
+
681
+ if (this.originalNetworkName === 'global' || !this.allowGlobalFallback) {
682
+ return;
683
+ }
684
+
685
+ const connectedCount = this.connectionManager.getConnectedPeerCount();
686
+ const discoveredCount = this.discoveredPeers.size;
687
+
688
+ // If we're in the original network but have insufficient peers, activate fallback
689
+ if (!this.isInFallbackMode && this.networkName === this.originalNetworkName) {
690
+ if (connectedCount === 0 && discoveredCount === 0) {
691
+ this.debug.log(`Network ${this.originalNetworkName} appears empty, activating global fallback`);
692
+ this._activateGlobalFallback().then(activated => {
693
+ if (activated && this.connected && this.signalingUrl) {
694
+ // Reconnect to signaling server with global network
695
+ this.disconnect();
696
+ setTimeout(() => {
697
+ this.connect(this.signalingUrl);
698
+ }, 1000);
699
+ }
700
+ });
701
+ }
702
+ }
703
+ }
704
+
506
705
  // Status and information methods
507
706
  getStatus() {
508
707
  const connectedCount = this.connectionManager.getConnectedPeerCount();
@@ -511,11 +710,17 @@ export class PeerPigeonMesh extends EventEmitter {
511
710
  peerId: this.peerId,
512
711
  connected: this.connected,
513
712
  polling: false, // Only WebSocket is supported
713
+ signalingUrl: this.signalingUrl,
714
+ networkName: this.networkName,
715
+ originalNetworkName: this.originalNetworkName,
716
+ isInFallbackMode: this.isInFallbackMode,
717
+ allowGlobalFallback: this.allowGlobalFallback,
514
718
  connectedCount,
515
719
  totalPeerCount: totalCount, // Include total count for debugging
516
720
  minPeers: this.minPeers,
517
721
  maxPeers: this.maxPeers,
518
722
  discoveredCount: this.discoveredPeers.size,
723
+ autoConnect: this.autoConnect,
519
724
  autoDiscovery: this.autoDiscovery,
520
725
  evictionStrategy: this.evictionStrategy,
521
726
  xorRouting: this.xorRouting
@@ -560,12 +765,12 @@ export class PeerPigeonMesh extends EventEmitter {
560
765
  * @param {string|object} content - The message content
561
766
  * @returns {string|null} The message ID if sent, or null on error
562
767
  */
563
- sendDirectMessage(targetPeerId, content) {
768
+ async sendDirectMessage(targetPeerId, content) {
564
769
  if (!targetPeerId || typeof targetPeerId !== 'string') {
565
770
  this.debug.error('Invalid targetPeerId for direct message');
566
771
  return null;
567
772
  }
568
- return this.gossipManager.sendDirectMessage(targetPeerId, content);
773
+ return await this.gossipManager.sendDirectMessage(targetPeerId, content);
569
774
  }
570
775
 
571
776
  /**
@@ -573,9 +778,9 @@ export class PeerPigeonMesh extends EventEmitter {
573
778
  * @param {string|object} content - The message content
574
779
  * @returns {string|null} The message ID if sent, or null on error
575
780
  */
576
- sendMessage(content) {
781
+ async sendMessage(content) {
577
782
  // For clarity, this is a broadcast/gossip message
578
- return this.gossipManager.broadcastMessage(content, 'chat');
783
+ return await this.gossipManager.broadcastMessage(content, 'chat');
579
784
  }
580
785
 
581
786
  // Helper methods for backward compatibility
@@ -633,50 +838,6 @@ export class PeerPigeonMesh extends EventEmitter {
633
838
  return this.meshOptimizer.debugConnectivity();
634
839
  }
635
840
 
636
- // Connection monitoring methods
637
- startConnectionMonitoring() {
638
- // Monitor connection health every 2 minutes
639
- if (this.connectionMonitorInterval) {
640
- clearInterval(this.connectionMonitorInterval);
641
- }
642
-
643
- // Environment-aware timer
644
- const intervalCallback = () => {
645
- if (this.signalingClient) {
646
- const stats = this.signalingClient.getConnectionStats();
647
- this.debug.log('Connection monitoring:', stats);
648
-
649
- // Force health check if connection seems problematic
650
- if (stats.connected && stats.lastPingTime && stats.lastPongTime) {
651
- const timeSinceLastPong = Date.now() - stats.lastPongTime;
652
- if (timeSinceLastPong > 60000) { // 1 minute without pong
653
- this.debug.warn('Connection may be unhealthy, forcing health check');
654
- this.signalingClient.forceHealthCheck();
655
- }
656
- }
657
-
658
- // Emit connection status for UI
659
- this.emit('connectionStats', stats);
660
- }
661
- };
662
-
663
- if (environmentDetector.isBrowser) {
664
- this.connectionMonitorInterval = window.setInterval(intervalCallback, 120000);
665
- } else {
666
- this.connectionMonitorInterval = setInterval(intervalCallback, 120000);
667
- }
668
-
669
- this.debug.log('Started connection monitoring');
670
- }
671
-
672
- stopConnectionMonitoring() {
673
- if (this.connectionMonitorInterval) {
674
- clearInterval(this.connectionMonitorInterval);
675
- this.connectionMonitorInterval = null;
676
- this.debug.log('Stopped connection monitoring');
677
- }
678
- }
679
-
680
841
  // Media management methods
681
842
  async initializeMedia() {
682
843
  return await this.mediaManager.init();
@@ -688,34 +849,33 @@ export class PeerPigeonMesh extends EventEmitter {
688
849
  try {
689
850
  const stream = await this.mediaManager.startLocalStream({ video, audio, deviceIds });
690
851
 
691
- // Update all existing peer connections with the new stream
852
+ // Update all existing peer connections with the new stream - but only if crypto allows it
692
853
  const connections = this.connectionManager.getAllConnections();
693
- this.debug.log(`📡 MEDIA START: Applying stream to ${connections.length} connections`);
854
+ this.debug.log(`📡 MEDIA START: Applying stream to ${connections.length} connections (with crypto verification)`);
694
855
 
695
856
  for (const connection of connections) {
696
- this.debug.log(`📡 MEDIA START: Setting stream for peer ${connection.peerId.substring(0, 8)}...`);
697
- await connection.setLocalStream(stream);
698
-
699
- // FORCE IMMEDIATE RENEGOTIATION: Don't wait for the automatic trigger
700
- this.debug.log(`📡 MEDIA START: Forcing immediate renegotiation for peer ${connection.peerId.substring(0, 8)}...`);
701
- setTimeout(async () => {
702
- try {
703
- if (connection.connection && connection.connection.signalingState === 'stable') {
704
- // Create and send a renegotiation offer immediately
705
- const offer = await connection.createOffer();
706
- await this.sendSignalingMessage({
707
- type: 'renegotiation-offer',
708
- data: offer,
709
- timestamp: Date.now(),
710
- forced: true // Mark as forced renegotiation
711
- }, connection.peerId);
712
- this.debug.log(`✅ MEDIA START: Forced renegotiation offer sent to ${connection.peerId.substring(0, 8)}...`);
713
- }
714
- } catch (error) {
715
- this.debug.error(`❌ MEDIA START: Failed to force renegotiation for ${connection.peerId.substring(0, 8)}...`, error);
857
+ // SECURITY: Only share media if crypto keys are established or crypto is disabled
858
+ let shouldShareMedia = true;
859
+
860
+ if (this.enableCrypto && this.cryptoManager) {
861
+ const hasKeys = this.cryptoManager.peerKeys && this.cryptoManager.peerKeys.has(connection.peerId);
862
+ if (!hasKeys) {
863
+ this.debug.log(`� MEDIA START: Skipping media share with ${connection.peerId.substring(0, 8)}... - no crypto keys established`);
864
+ shouldShareMedia = false;
865
+ } else {
866
+ this.debug.log(`🔒 MEDIA START: Crypto keys verified for ${connection.peerId.substring(0, 8)}... - sharing media`);
716
867
  }
717
- }, 500); // Small delay to ensure setLocalStream completes
718
- }
868
+ }
869
+
870
+ if (shouldShareMedia) {
871
+ this.debug.log(`📡 MEDIA START: Setting stream for peer ${connection.peerId.substring(0, 8)}...`);
872
+ await connection.setLocalStream(stream);
873
+ this.debug.log(`✅ MEDIA START: Stream applied to ${connection.peerId.substring(0, 8)}...`);
874
+
875
+ // REMOVED: No forced immediate renegotiation - let natural renegotiation handle it
876
+ // This prevents cascade renegotiation conflicts when multiple peers join
877
+ } // End of shouldShareMedia block
878
+ } // End of connections loop
719
879
 
720
880
  return stream;
721
881
  } catch (error) {
@@ -773,6 +933,218 @@ export class PeerPigeonMesh extends EventEmitter {
773
933
  return streams;
774
934
  }
775
935
 
936
+ // === SELECTIVE STREAMING CONTROL METHODS ===
937
+
938
+ /**
939
+ * Enable streaming to specific peers only (1:1 or 1:many patterns)
940
+ * @param {string|string[]} peerIds - Single peer ID or array of peer IDs to stream to
941
+ * @param {Object} options - Stream options (video, audio, deviceIds)
942
+ * @returns {Promise<MediaStream>} The local stream
943
+ */
944
+ async startSelectiveStream(peerIds, options = {}) {
945
+ // Normalize to array
946
+ const targetPeerIds = Array.isArray(peerIds) ? peerIds : [peerIds];
947
+
948
+ this.debug.log(`🎯 SELECTIVE STREAM: Starting stream to ${targetPeerIds.length} specific peer(s)`);
949
+
950
+ // Start local media stream
951
+ const stream = await this.mediaManager.startLocalStream(options);
952
+
953
+ // Get all connections
954
+ const connections = this.connectionManager.getAllConnections();
955
+
956
+ // Apply stream only to target peers
957
+ for (const connection of connections) {
958
+ if (targetPeerIds.includes(connection.peerId)) {
959
+ this.debug.log(`📡 SELECTIVE STREAM: Enabling stream for target peer ${connection.peerId.substring(0, 8)}...`);
960
+
961
+ // Enable remote stream reception on target peer
962
+ if (connection.allowRemoteStreamEmission) {
963
+ connection.allowRemoteStreamEmission();
964
+ }
965
+
966
+ // Set local stream for this connection
967
+ await connection.setLocalStream(stream);
968
+ } else {
969
+ this.debug.log(`🚫 SELECTIVE STREAM: Blocking stream for non-target peer ${connection.peerId.substring(0, 8)}...`);
970
+
971
+ // Ensure no stream is set for non-target peers
972
+ await connection.setLocalStream(null);
973
+
974
+ // Block remote stream reception from non-target peers if desired
975
+ if (connection.blockRemoteStreamEmission) {
976
+ connection.blockRemoteStreamEmission();
977
+ }
978
+ }
979
+ }
980
+
981
+ // Emit event for UI updates
982
+ this.emit('selectiveStreamStarted', {
983
+ targetPeerIds,
984
+ stream,
985
+ streamType: targetPeerIds.length === 1 ? '1:1' : '1:many'
986
+ });
987
+
988
+ return stream;
989
+ }
990
+
991
+ /**
992
+ * Stop selective streaming and return to broadcast mode or stop entirely
993
+ * @param {boolean} returnToBroadcast - If true, switch to broadcast mode; if false, stop streaming entirely
994
+ */
995
+ async stopSelectiveStream(returnToBroadcast = false) {
996
+ this.debug.log(`🛑 SELECTIVE STREAM: Stopping selective streaming (broadcast mode: ${returnToBroadcast})`);
997
+
998
+ if (returnToBroadcast) {
999
+ // Switch to broadcast mode - enable streams for all connected peers
1000
+ await this.enableStreamingForAllPeers();
1001
+ } else {
1002
+ // Stop streaming entirely
1003
+ await this.stopMedia();
1004
+ }
1005
+
1006
+ this.emit('selectiveStreamStopped', { returnToBroadcast });
1007
+ }
1008
+
1009
+ /**
1010
+ * Enable streaming for all connected peers (broadcast mode)
1011
+ */
1012
+ async enableStreamingForAllPeers() {
1013
+ this.debug.log('📡 BROADCAST STREAM: Enabling streaming for ALL connected peers');
1014
+
1015
+ const connections = this.connectionManager.getAllConnections();
1016
+ const currentStream = this.mediaManager.localStream;
1017
+
1018
+ for (const connection of connections) {
1019
+ this.debug.log(`📡 BROADCAST STREAM: Enabling stream for peer ${connection.peerId.substring(0, 8)}...`);
1020
+
1021
+ // Enable remote stream reception
1022
+ if (connection.allowRemoteStreamEmission) {
1023
+ connection.allowRemoteStreamEmission();
1024
+ }
1025
+
1026
+ // Set local stream if we have one
1027
+ if (currentStream) {
1028
+ await connection.setLocalStream(currentStream);
1029
+ }
1030
+ }
1031
+
1032
+ this.emit('broadcastStreamEnabled');
1033
+ }
1034
+
1035
+ /**
1036
+ * Block streaming to specific peers while maintaining streams to others
1037
+ * @param {string|string[]} peerIds - Peer ID(s) to block streaming to
1038
+ */
1039
+ async blockStreamingToPeers(peerIds) {
1040
+ const targetPeerIds = Array.isArray(peerIds) ? peerIds : [peerIds];
1041
+
1042
+ this.debug.log(`🚫 BLOCK STREAM: Blocking streaming to ${targetPeerIds.length} peer(s)`);
1043
+
1044
+ for (const peerId of targetPeerIds) {
1045
+ const connection = this.connectionManager.getPeer(peerId);
1046
+ if (connection) {
1047
+ this.debug.log(`🚫 BLOCK STREAM: Blocking stream to peer ${peerId.substring(0, 8)}...`);
1048
+
1049
+ // Remove local stream from this connection
1050
+ await connection.setLocalStream(null);
1051
+
1052
+ // Block remote stream reception
1053
+ if (connection.blockRemoteStreamEmission) {
1054
+ connection.blockRemoteStreamEmission();
1055
+ }
1056
+ }
1057
+ }
1058
+
1059
+ this.emit('streamingBlockedToPeers', { blockedPeerIds: targetPeerIds });
1060
+ }
1061
+
1062
+ /**
1063
+ * Allow streaming to specific peers (unblock them)
1064
+ * @param {string|string[]} peerIds - Peer ID(s) to allow streaming to
1065
+ */
1066
+ async allowStreamingToPeers(peerIds) {
1067
+ const targetPeerIds = Array.isArray(peerIds) ? peerIds : [peerIds];
1068
+
1069
+ this.debug.log(`✅ ALLOW STREAM: Allowing streaming to ${targetPeerIds.length} peer(s)`);
1070
+
1071
+ const currentStream = this.mediaManager.localStream;
1072
+
1073
+ for (const peerId of targetPeerIds) {
1074
+ const connection = this.connectionManager.getPeer(peerId);
1075
+ if (connection) {
1076
+ this.debug.log(`✅ ALLOW STREAM: Allowing stream to peer ${peerId.substring(0, 8)}...`);
1077
+
1078
+ // Enable remote stream reception
1079
+ if (connection.allowRemoteStreamEmission) {
1080
+ connection.allowRemoteStreamEmission();
1081
+ }
1082
+
1083
+ // Set local stream if we have one
1084
+ if (currentStream) {
1085
+ await connection.setLocalStream(currentStream);
1086
+ }
1087
+ }
1088
+ }
1089
+
1090
+ this.emit('streamingAllowedToPeers', { allowedPeerIds: targetPeerIds });
1091
+ }
1092
+
1093
+ /**
1094
+ * Get current streaming status for all connected peers
1095
+ * @returns {Map} Map of peer IDs to streaming status
1096
+ */
1097
+ getStreamingStatus() {
1098
+ const status = new Map();
1099
+ const connections = this.connectionManager.getAllConnections();
1100
+
1101
+ for (const connection of connections) {
1102
+ const hasLocalStream = connection.getLocalStream() !== null;
1103
+ const allowsRemoteStreams = connection.allowRemoteStreams;
1104
+
1105
+ status.set(connection.peerId, {
1106
+ sendingStream: hasLocalStream,
1107
+ receivingStreams: allowsRemoteStreams,
1108
+ streamType: hasLocalStream ? (this.isStreamingToAll() ? 'broadcast' : 'selective') : 'none'
1109
+ });
1110
+ }
1111
+
1112
+ return status;
1113
+ }
1114
+
1115
+ /**
1116
+ * Check if currently streaming to all connected peers
1117
+ * @returns {boolean} True if streaming to all peers
1118
+ */
1119
+ isStreamingToAll() {
1120
+ const connections = this.connectionManager.getAllConnections();
1121
+ if (connections.length === 0) return false;
1122
+
1123
+ return connections.every(connection => connection.getLocalStream() !== null);
1124
+ }
1125
+
1126
+ /**
1127
+ * Get list of peers currently receiving streams
1128
+ * @returns {string[]} Array of peer IDs receiving streams
1129
+ */
1130
+ getStreamingPeers() {
1131
+ const connections = this.connectionManager.getAllConnections();
1132
+ return connections
1133
+ .filter(connection => connection.getLocalStream() !== null)
1134
+ .map(connection => connection.peerId);
1135
+ }
1136
+
1137
+ /**
1138
+ * Get list of peers currently blocked from streaming
1139
+ * @returns {string[]} Array of peer IDs blocked from streaming
1140
+ */
1141
+ getBlockedStreamingPeers() {
1142
+ const connections = this.connectionManager.getAllConnections();
1143
+ return connections
1144
+ .filter(connection => connection.getLocalStream() === null && this.mediaManager.localStream !== null)
1145
+ .map(connection => connection.peerId);
1146
+ }
1147
+
776
1148
  // Static utility methods
777
1149
  static validatePeerId(peerId) {
778
1150
  return typeof peerId === 'string' && /^[a-fA-F0-9]{40}$/.test(peerId);
@@ -780,13 +1152,39 @@ export class PeerPigeonMesh extends EventEmitter {
780
1152
 
781
1153
  static async generatePeerId() {
782
1154
  const array = new Uint8Array(20);
783
- crypto.getRandomValues(array);
1155
+
1156
+ // Environment-aware random value generation
1157
+ if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
1158
+ // Browser environment
1159
+ crypto.getRandomValues(array);
1160
+ } else if (typeof process !== 'undefined' && process.versions && process.versions.node) {
1161
+ // Node.js environment
1162
+ try {
1163
+ const crypto = await import('crypto');
1164
+ const randomBytes = crypto.randomBytes(20);
1165
+ array.set(randomBytes);
1166
+ } catch (e) {
1167
+ console.warn('Could not use Node.js crypto, falling back to Math.random');
1168
+ // Fallback to Math.random
1169
+ for (let i = 0; i < array.length; i++) {
1170
+ array[i] = Math.floor(Math.random() * 256);
1171
+ }
1172
+ }
1173
+ } else {
1174
+ // Fallback for unknown environments
1175
+ console.warn('Secure random values not available, using fallback method');
1176
+ for (let i = 0; i < array.length; i++) {
1177
+ array[i] = Math.floor(Math.random() * 256);
1178
+ }
1179
+ }
1180
+
784
1181
  return Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('');
785
1182
  }
786
1183
 
787
- // WebDHT methods - Distributed Hash Table
1184
+ // WebDHT methods - Low-level Distributed Hash Table for raw key-value storage
1185
+ // Note: For encrypted storage with access control, use this.distributedStorage instead
788
1186
  /**
789
- * Store a key-value pair in the distributed hash table
1187
+ * Store a key-value pair in the distributed hash table (low-level, no encryption)
790
1188
  * @param {string} key - The key to store
791
1189
  * @param {any} value - The value to store
792
1190
  * @param {object} options - Storage options (ttl, etc.)
@@ -803,7 +1201,7 @@ export class PeerPigeonMesh extends EventEmitter {
803
1201
  }
804
1202
 
805
1203
  /**
806
- * Retrieve a value from the distributed hash table
1204
+ * Retrieve a value from the distributed hash table (low-level, no encryption)
807
1205
  * @param {string} key - The key to retrieve
808
1206
  * @param {object} options - Retrieval options (subscribe, etc.)
809
1207
  * @returns {Promise<any>} The stored value or null if not found
@@ -1161,7 +1559,7 @@ export class PeerPigeonMesh extends EventEmitter {
1161
1559
  try {
1162
1560
  if (targetPeerId) {
1163
1561
  // Send directly to target peer
1164
- return this.sendDirectMessage(targetPeerId, signalingMessage);
1562
+ return await this.sendDirectMessage(targetPeerId, signalingMessage);
1165
1563
  } else {
1166
1564
  // Broadcast to all connected peers
1167
1565
  return this.broadcast(signalingMessage);
@@ -1276,7 +1674,7 @@ export class PeerPigeonMesh extends EventEmitter {
1276
1674
 
1277
1675
  try {
1278
1676
  const encryptedContent = await this.cryptoManager.encryptForPeer(content, peerId);
1279
- return this.sendDirectMessage(peerId, encryptedContent);
1677
+ return await this.sendDirectMessage(peerId, encryptedContent);
1280
1678
  } catch (error) {
1281
1679
  this.debug.error('Failed to send encrypted message:', error);
1282
1680
  throw error;
@@ -1310,7 +1708,7 @@ export class PeerPigeonMesh extends EventEmitter {
1310
1708
  };
1311
1709
  }
1312
1710
  // Use 'encrypted' message type instead of 'chat' for encrypted broadcasts
1313
- return this.gossipManager.broadcastMessage(encryptedContent, 'encrypted');
1711
+ return await this.gossipManager.broadcastMessage(encryptedContent, 'encrypted');
1314
1712
  } catch (error) {
1315
1713
  this.debug.error('Failed to send encrypted broadcast:', error);
1316
1714
  throw error;
@@ -1348,20 +1746,51 @@ export class PeerPigeonMesh extends EventEmitter {
1348
1746
  throw new Error('Crypto not enabled or initialized');
1349
1747
  }
1350
1748
 
1749
+ // Check if we're already in the process of exchanging keys with this peer
1750
+ if (this.ongoingKeyExchanges.has(peerId)) {
1751
+ this.debug.log(`🔐 Skipping key exchange with ${peerId.substring(0, 8)}... - exchange already in progress`);
1752
+ return;
1753
+ }
1754
+
1755
+ // Check if we already have this peer's key to avoid duplicate exchanges
1756
+ const hasExistingKey = this.cryptoManager.peerKeys.has(peerId);
1757
+ if (hasExistingKey) {
1758
+ this.debug.log(`🔐 Skipping key exchange with ${peerId.substring(0, 8)}... - key already exists`);
1759
+ return;
1760
+ }
1761
+
1351
1762
  const keypair = this.cryptoManager.keypair;
1352
1763
  if (!keypair || !keypair.pub || !keypair.epub) {
1353
1764
  throw new Error('No complete keypair available (need both pub and epub)');
1354
1765
  }
1355
1766
 
1356
- // Send both our public key (pub) and encryption public key (epub) to the peer
1357
- return this.gossipManager.sendDirectMessage(peerId, {
1358
- type: 'key_exchange',
1359
- publicKey: {
1360
- pub: keypair.pub,
1361
- epub: keypair.epub
1362
- },
1363
- timestamp: Date.now()
1364
- }, 'key_exchange');
1767
+ this.debug.log(`🔐 Initiating key exchange with ${peerId.substring(0, 8)}...`);
1768
+
1769
+ // Mark this peer as having an ongoing key exchange
1770
+ this.ongoingKeyExchanges.add(peerId);
1771
+
1772
+ try {
1773
+ // Send both our public key (pub) and encryption public key (epub) to the peer
1774
+ const result = await this.gossipManager.sendDirectMessage(peerId, {
1775
+ type: 'key_exchange',
1776
+ publicKey: {
1777
+ pub: keypair.pub,
1778
+ epub: keypair.epub
1779
+ },
1780
+ timestamp: Date.now()
1781
+ }, 'key_exchange');
1782
+
1783
+ // Clear the ongoing exchange after a short delay (allow time for response)
1784
+ setTimeout(() => {
1785
+ this.ongoingKeyExchanges.delete(peerId);
1786
+ }, 5000); // 5 second timeout
1787
+
1788
+ return result;
1789
+ } catch (error) {
1790
+ // Clear the ongoing exchange on error
1791
+ this.ongoingKeyExchanges.delete(peerId);
1792
+ throw error;
1793
+ }
1365
1794
  }
1366
1795
 
1367
1796
  /**
@@ -1463,6 +1892,10 @@ export class PeerPigeonMesh extends EventEmitter {
1463
1892
  if (this.cryptoManager) {
1464
1893
  this.cryptoManager.reset();
1465
1894
  }
1895
+ // Clear ongoing key exchange tracking
1896
+ this.ongoingKeyExchanges.clear();
1897
+ // Clear emitted key event tracking
1898
+ this.emittedPeerKeyEvents.clear();
1466
1899
  }
1467
1900
 
1468
1901
  /**
@@ -1471,16 +1904,24 @@ export class PeerPigeonMesh extends EventEmitter {
1471
1904
  * @param {string} from - Sender's peer ID
1472
1905
  * @private
1473
1906
  */
1474
- _handleKeyExchange(data, from) {
1907
+ async _handleKeyExchange(data, from) {
1475
1908
  if ((data.type === 'key_exchange' || data.type === 'key_exchange_response') && data.publicKey && this.cryptoManager) {
1476
- this.cryptoManager.addPeerKey(from, data.publicKey);
1477
- this.debug.log(`🔐 Stored public key for peer ${from.substring(0, 8)}...`);
1909
+ // Try to add the peer key - will return false if it's a duplicate
1910
+ const keyAdded = this.cryptoManager.addPeerKey(from, data.publicKey);
1911
+
1912
+ if (keyAdded) {
1913
+ this.debug.log(`🔐 Stored public key for peer ${from.substring(0, 8)}...`);
1914
+ // Clear any ongoing key exchange tracking for this peer since we now have their key
1915
+ this.ongoingKeyExchanges.delete(from);
1916
+ } else {
1917
+ this.debug.log(`🔐 Key exchange ignored for peer ${from.substring(0, 8)}... - duplicate key`);
1918
+ }
1478
1919
 
1479
- // Send our public key back if this was an initial exchange (not a response)
1480
- if (data.type === 'key_exchange') {
1920
+ // Send our public key back if this was an initial exchange (not a response) and the key was actually new
1921
+ if (data.type === 'key_exchange' && keyAdded) {
1481
1922
  const keypair = this.cryptoManager.keypair;
1482
1923
  if (keypair && keypair.pub && keypair.epub) {
1483
- this.gossipManager.sendDirectMessage(from, {
1924
+ await this.gossipManager.sendDirectMessage(from, {
1484
1925
  type: 'key_exchange_response',
1485
1926
  publicKey: {
1486
1927
  pub: keypair.pub,
@@ -1511,6 +1952,6 @@ export class PeerPigeonMesh extends EventEmitter {
1511
1952
 
1512
1953
  // Stream forwarding is now handled automatically by ConnectionManager
1513
1954
  // when remoteStream events are received, so we just emit for UI handling
1514
- this.emit('remoteStreamAnnouncement', data);
1955
+ this.emit('remoteStreamAnnouncementReceived', data);
1515
1956
  }
1516
1957
  }