peerpigeon 0.1.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +141 -1365
  2. package/cli.js +1382 -0
  3. package/dist/peerpigeon-browser.js +12290 -0
  4. package/dist/peerpigeon-browser.js.map +7 -0
  5. package/docs/API_DOCUMENTATION.md +1945 -0
  6. package/docs/BOOTSTRAP_HUBS.md +319 -0
  7. package/docs/CLI_README.md +371 -0
  8. package/docs/DOCUMENTATION_REORGANIZATION.md +172 -0
  9. package/docs/HUB_QUICK_REF.md +107 -0
  10. package/docs/HUB_SCRIPTS.md +331 -0
  11. package/docs/HUB_SYSTEM.md +552 -0
  12. package/docs/MIGRATION_COMPLETE.md +93 -0
  13. package/docs/NETWORK_NAMESPACES.md +212 -0
  14. package/docs/README.md +107 -0
  15. package/docs/SELECTIVE_STREAMING_GUIDE.md +427 -0
  16. package/docs/TEST_CLEANUP_COMPLETE.md +80 -0
  17. package/examples/bootstrap-hub-example.js +292 -0
  18. package/examples/browser/README.md +278 -0
  19. package/examples/browser/app.js +2426 -49
  20. package/examples/browser/index.html +482 -543
  21. package/examples/browser/minimal/README.md +55 -0
  22. package/examples/browser/minimal/index.html +75 -0
  23. package/examples/browser/minimal/minimal.js +234 -0
  24. package/examples/browser/styles.css +687 -1425
  25. package/examples/browser/test-bundle.html +35 -0
  26. package/examples/browser-2/index.html +30 -0
  27. package/examples/browser-2/package.json +21 -0
  28. package/examples/browser-2/src/App-simple.vue +21 -0
  29. package/examples/browser-2/src/App.vue +420 -0
  30. package/examples/browser-2/src/components/CryptoView.vue +1661 -0
  31. package/examples/browser-2/src/components/DHTView.vue +1281 -0
  32. package/examples/browser-2/src/components/DebugView.vue +1773 -0
  33. package/examples/browser-2/src/components/MediaView.vue +1048 -0
  34. package/examples/browser-2/src/components/MessagingView.vue +775 -0
  35. package/examples/browser-2/src/components/NetworkView.vue +930 -0
  36. package/examples/browser-2/src/components/StorageView.vue +1376 -0
  37. package/examples/browser-2/src/main.js +5 -0
  38. package/examples/browser-2/src/stores/peerpigeon.js +895 -0
  39. package/examples/browser-2/vite.config.js +6 -0
  40. package/examples/hub-example.js +186 -0
  41. package/examples/multi-hub-test.js +186 -0
  42. package/examples/node/README.md +2 -2
  43. package/examples/node/storage-test.js +141 -6
  44. package/examples/selective-streaming-demo.html +698 -0
  45. package/examples/standard-events-demo.js +126 -0
  46. package/package.json +33 -16
  47. package/server/index.js +1032 -98
  48. package/server/start.js +49 -0
  49. package/src/ConnectionManager.js +239 -225
  50. package/src/CryptoManager.js +147 -18
  51. package/src/DebugLogger.js +0 -7
  52. package/src/DistributedStorageManager.js +245 -205
  53. package/src/EnvironmentDetector.js +109 -2
  54. package/src/EventEmitter.js +79 -1
  55. package/src/EvictionManager.js +10 -9
  56. package/src/GossipManager.js +163 -11
  57. package/src/LexicalStorageInterface.js +332 -0
  58. package/src/PeerConnection.js +333 -310
  59. package/src/PeerPigeonMesh.js +577 -135
  60. package/src/SignalingClient.js +14 -243
  61. package/src/SignalingHandler.js +31 -10
  62. package/src/StorageManager.js +0 -39
  63. package/src/WebDHT-Simple.js +389 -0
  64. package/src/WebDHT.js +363 -1165
  65. package/src/browser-entry.js +40 -0
  66. package/examples/browser/assets/images/favicon.png +0 -0
  67. package/examples/browser/assets/images/pigeon.png +0 -0
  68. package/examples/browser/crypto-test.html +0 -427
  69. package/examples/browser/ui-old.js +0 -1926
  70. package/examples/browser/ui.js +0 -3010
  71. package/websocket-server/README.md +0 -247
  72. package/websocket-server/server.js +0 -391
@@ -2,7 +2,6 @@
2
2
  * EnvironmentDetector - Utility for detecting runtime environment and capabilities
3
3
  * Provides comprehensive environment detection for browser, Node.js, Worker contexts
4
4
  */
5
- import DebugLogger from './DebugLogger.js';
6
5
 
7
6
  export class EnvironmentDetector {
8
7
  constructor() {
@@ -21,6 +20,62 @@ export class EnvironmentDetector {
21
20
  this._cache.set('isDeno', this._detectDeno());
22
21
  this._cache.set('isBun', this._detectBun());
23
22
  this._cache.set('isNativeScript', this._detectNativeScript());
23
+
24
+ // Initialize WebRTC polyfill for Node.js if available
25
+ if (this._cache.get('isNodeJS')) {
26
+ this._initNodeWebRTC();
27
+ }
28
+ }
29
+
30
+ /**
31
+ * Initialize WebRTC polyfill for Node.js environment
32
+ * Attempts to load @koush/wrtc and set up WebRTC globals
33
+ * @private
34
+ */
35
+ _initNodeWebRTC() {
36
+ try {
37
+ // Check if WebRTC is already available globally
38
+ if (typeof global !== 'undefined' && typeof global.RTCPeerConnection !== 'undefined') {
39
+ return; // WebRTC already available
40
+ }
41
+
42
+ // Try to import @koush/wrtc package
43
+ let wrtc;
44
+ if (typeof require !== 'undefined') {
45
+ // CommonJS require
46
+ try {
47
+ wrtc = require('@koush/wrtc');
48
+ } catch (e) {
49
+ // @koush/wrtc not available, try node-webrtc as fallback
50
+ try {
51
+ wrtc = require('node-webrtc');
52
+ } catch (e2) {
53
+ // No WebRTC package available
54
+ return;
55
+ }
56
+ }
57
+ } else {
58
+ // ES modules - dynamic import would be needed
59
+ // Since we can't do synchronous dynamic imports, we'll skip this
60
+ // The async method initWebRTCAsync() should be used instead
61
+ return;
62
+ }
63
+
64
+ // Set up WebRTC globals if we successfully loaded a package
65
+ if (wrtc && typeof global !== 'undefined') {
66
+ global.RTCPeerConnection = wrtc.RTCPeerConnection;
67
+ global.RTCSessionDescription = wrtc.RTCSessionDescription;
68
+ global.RTCIceCandidate = wrtc.RTCIceCandidate;
69
+ global.MediaStream = wrtc.MediaStream || global.MediaStream;
70
+ global.MediaStreamTrack = wrtc.MediaStreamTrack || global.MediaStreamTrack;
71
+
72
+ // Update cache to reflect that WebRTC is now available
73
+ this._webrtcPolyfilled = true;
74
+ }
75
+ } catch (error) {
76
+ // Silently fail - WebRTC polyfill is optional
77
+ // The application will handle missing WebRTC through normal capability detection
78
+ }
24
79
  }
25
80
 
26
81
  // Primary environment detection
@@ -132,9 +187,11 @@ export class EnvironmentDetector {
132
187
  }
133
188
  if (this.isNodeJS) {
134
189
  // Check for Node.js WebRTC implementations or globally injected WebRTC
190
+ // This includes polyfills loaded by _initNodeWebRTC()
135
191
  return (typeof global !== 'undefined' &&
136
192
  typeof global.RTCPeerConnection !== 'undefined') ||
137
- typeof RTCPeerConnection !== 'undefined';
193
+ typeof RTCPeerConnection !== 'undefined' ||
194
+ this._webrtcPolyfilled === true;
138
195
  }
139
196
  if (this.isNativeScript) {
140
197
  // NativeScript can access native WebRTC implementations through native modules
@@ -491,6 +548,55 @@ export class EnvironmentDetector {
491
548
  };
492
549
  }
493
550
 
551
+ /**
552
+ * Asynchronously initialize WebRTC polyfill for Node.js environment
553
+ * This method is useful for ES module environments where dynamic imports are preferred
554
+ * @returns {Promise<boolean>} True if WebRTC was successfully initialized
555
+ */
556
+ async initWebRTCAsync() {
557
+ if (!this.isNodeJS) {
558
+ return false; // Only works in Node.js
559
+ }
560
+
561
+ try {
562
+ // Check if WebRTC is already available globally
563
+ if (typeof global !== 'undefined' && typeof global.RTCPeerConnection !== 'undefined') {
564
+ return true; // WebRTC already available
565
+ }
566
+
567
+ let wrtc;
568
+ try {
569
+ // Try to import @koush/wrtc first
570
+ wrtc = await import('@koush/wrtc');
571
+ } catch (e) {
572
+ try {
573
+ // Fallback to node-webrtc
574
+ wrtc = await import('node-webrtc');
575
+ } catch (e2) {
576
+ // No WebRTC package available
577
+ return false;
578
+ }
579
+ }
580
+
581
+ // Set up WebRTC globals if we successfully loaded a package
582
+ if (wrtc && typeof global !== 'undefined') {
583
+ global.RTCPeerConnection = wrtc.RTCPeerConnection || wrtc.default?.RTCPeerConnection;
584
+ global.RTCSessionDescription = wrtc.RTCSessionDescription || wrtc.default?.RTCSessionDescription;
585
+ global.RTCIceCandidate = wrtc.RTCIceCandidate || wrtc.default?.RTCIceCandidate;
586
+ global.MediaStream = wrtc.MediaStream || wrtc.default?.MediaStream || global.MediaStream;
587
+ global.MediaStreamTrack = wrtc.MediaStreamTrack || wrtc.default?.MediaStreamTrack || global.MediaStreamTrack;
588
+
589
+ // Update cache to reflect that WebRTC is now available
590
+ this._webrtcPolyfilled = true;
591
+ return true;
592
+ }
593
+ } catch (error) {
594
+ // Silently fail - WebRTC polyfill is optional
595
+ }
596
+
597
+ return false;
598
+ }
599
+
494
600
  // Static method for quick environment check
495
601
  static detect() {
496
602
  return new EnvironmentDetector();
@@ -514,3 +620,4 @@ export const isNativeScript = () => environmentDetector.isNativeScript;
514
620
  export const hasWebRTC = () => environmentDetector.hasWebRTC;
515
621
  export const hasWebSocket = () => environmentDetector.hasWebSocket;
516
622
  export const getEnvironmentReport = () => environmentDetector.getEnvironmentReport();
623
+ export const initWebRTCAsync = () => environmentDetector.initWebRTCAsync();
@@ -1,4 +1,3 @@
1
- import DebugLogger from './DebugLogger.js';
2
1
  export class EventEmitter {
3
2
  constructor() {
4
3
  this.eventListeners = {};
@@ -25,4 +24,83 @@ export class EventEmitter {
25
24
  this.eventListeners[event].forEach(callback => callback(data));
26
25
  }
27
26
  }
27
+
28
+ // Standard Node.js EventEmitter compatible methods
29
+
30
+ /**
31
+ * Add event listener (alias for addEventListener)
32
+ * @param {string} event - Event name
33
+ * @param {Function} callback - Event handler
34
+ * @returns {EventEmitter} Returns this for chaining
35
+ */
36
+ on(event, callback) {
37
+ this.addEventListener(event, callback);
38
+ return this;
39
+ }
40
+
41
+ /**
42
+ * Remove event listener (alias for removeEventListener)
43
+ * @param {string} event - Event name
44
+ * @param {Function} callback - Event handler to remove
45
+ * @returns {EventEmitter} Returns this for chaining
46
+ */
47
+ off(event, callback) {
48
+ this.removeEventListener(event, callback);
49
+ return this;
50
+ }
51
+
52
+ /**
53
+ * Add one-time event listener
54
+ * @param {string} event - Event name
55
+ * @param {Function} callback - Event handler
56
+ * @returns {EventEmitter} Returns this for chaining
57
+ */
58
+ once(event, callback) {
59
+ const onceWrapper = (data) => {
60
+ callback(data);
61
+ this.removeEventListener(event, onceWrapper);
62
+ };
63
+ this.addEventListener(event, onceWrapper);
64
+ return this;
65
+ }
66
+
67
+ /**
68
+ * Remove all listeners for an event, or all listeners if no event specified
69
+ * @param {string} [event] - Event name (optional)
70
+ * @returns {EventEmitter} Returns this for chaining
71
+ */
72
+ removeAllListeners(event) {
73
+ if (event) {
74
+ delete this.eventListeners[event];
75
+ } else {
76
+ this.eventListeners = {};
77
+ }
78
+ return this;
79
+ }
80
+
81
+ /**
82
+ * Get array of listeners for an event
83
+ * @param {string} event - Event name
84
+ * @returns {Function[]} Array of listeners
85
+ */
86
+ listeners(event) {
87
+ return this.eventListeners[event] ? [...this.eventListeners[event]] : [];
88
+ }
89
+
90
+ /**
91
+ * Get count of listeners for an event
92
+ * @param {string} event - Event name
93
+ * @returns {number} Number of listeners
94
+ */
95
+ listenerCount(event) {
96
+ return this.eventListeners[event] ? this.eventListeners[event].length : 0;
97
+ }
98
+
99
+ /**
100
+ * Get array of event names that have listeners
101
+ * @returns {string[]} Array of event names
102
+ */
103
+ eventNames() {
104
+ return Object.keys(this.eventListeners);
105
+ }
28
106
  }
@@ -22,13 +22,15 @@ export class EvictionManager extends EventEmitter {
22
22
 
23
23
  // Check total peer count (including connecting peers) to prevent race conditions
24
24
  const totalPeerCount = this.connectionManager.peers.size;
25
+ const connectedCount = this.connectionManager.getConnectedPeerCount();
26
+
27
+ // STRICT RULE: Never evict if we're under max capacity, unless we're completely isolated
25
28
  if (totalPeerCount < this.mesh.maxPeers) {
26
- this.debug.log(`No eviction needed: ${totalPeerCount}/${this.mesh.maxPeers} peers`);
29
+ this.debug.log(`No eviction needed: ${totalPeerCount}/${this.mesh.maxPeers} peers (connected: ${connectedCount})`);
27
30
  return null;
28
31
  }
29
32
 
30
- // Special case: if we have 0 connected peers (isolated), be very aggressive about making room
31
- const connectedCount = this.connectionManager.getConnectedPeerCount();
33
+ // Special case: if we have 0 connected peers (isolated), be aggressive about making room
32
34
  if (connectedCount === 0) {
33
35
  this.debug.log(`Isolated peer scenario: finding any peer to evict for ${newPeerId.substring(0, 8)}...`);
34
36
  // Find any peer to evict (even connecting ones) to make room for this connection
@@ -53,17 +55,16 @@ export class EvictionManager extends EventEmitter {
53
55
 
54
56
  this.debug.log(`Eviction check: new peer ${newPeerId.substring(0, 8)}... (distance: ${newPeerDistance.toString(16).substring(0, 8)}) vs farthest ${farthestPeerId.substring(0, 8)}... (distance: ${farthestDistance.toString(16).substring(0, 8)})`);
55
57
 
56
- // LOOSENED RULE: If we're at max capacity, always try to evict the farthest peer
57
- // even if the new peer isn't strictly closer (helps with network connectivity)
58
- const shouldEvict = newPeerDistance < farthestDistance ||
59
- (totalPeerCount >= this.mesh.maxPeers && connectedCount < this.mesh.minPeers);
58
+ // STRICT RULE: Only evict if we're at max capacity AND the new peer is closer
59
+ // Removed the aggressive eviction condition that could evict when under capacity
60
+ const shouldEvict = newPeerDistance < farthestDistance;
60
61
 
61
62
  if (shouldEvict) {
62
- this.debug.log(`Will evict ${farthestPeerId.substring(0, 8)}... for ${newPeerDistance < farthestDistance ? 'closer' : 'network connectivity'} peer ${newPeerId.substring(0, 8)}... (${totalPeerCount}/${this.mesh.maxPeers} peers)`);
63
+ this.debug.log(`Will evict ${farthestPeerId.substring(0, 8)}... for closer peer ${newPeerId.substring(0, 8)}... (${totalPeerCount}/${this.mesh.maxPeers} peers)`);
63
64
  return farthestPeerId;
64
65
  }
65
66
 
66
- this.debug.log(`Not evicting for ${newPeerId.substring(0, 8)}... - criteria not met (${totalPeerCount}/${this.mesh.maxPeers} peers)`);
67
+ this.debug.log(`Not evicting for ${newPeerId.substring(0, 8)}... - new peer is not closer (${totalPeerCount}/${this.mesh.maxPeers} peers)`);
67
68
  return null;
68
69
  } else {
69
70
  // If XOR routing is disabled, use simple FIFO eviction - evict oldest peer
@@ -17,6 +17,9 @@ export class GossipManager extends EventEmitter {
17
17
  this.seenMessages = new Map(); // messageId -> { timestamp, ttl }
18
18
  this.messageHistory = new Map(); // messageId -> message content
19
19
 
20
+ // Track key exchanges to prevent duplicates (separate from general message deduplication)
21
+ this.processedKeyExchanges = new Map(); // "peerId:keyType" -> timestamp
22
+
20
23
  // Configuration
21
24
  this.maxTTL = 10; // Maximum hops before message expires
22
25
  this.messageExpiryTime = 5 * 60 * 1000; // 5 minutes
@@ -29,7 +32,7 @@ export class GossipManager extends EventEmitter {
29
32
  /**
30
33
  * Broadcast a message to all peers in the network using gossip protocol
31
34
  */
32
- broadcastMessage(content, messageType = 'chat') {
35
+ async broadcastMessage(content, messageType = 'chat') {
33
36
  // Validate content
34
37
  if (content === undefined || content === null) {
35
38
  this.debug.error('Cannot broadcast message with undefined/null content');
@@ -46,13 +49,14 @@ export class GossipManager extends EventEmitter {
46
49
  return null;
47
50
  }
48
51
 
49
- const messageId = this.generateMessageId();
52
+ const messageId = await this.generateMessageId();
50
53
  const message = {
51
54
  id: messageId,
52
55
  type: 'gossip',
53
56
  subtype: messageType,
54
57
  content,
55
58
  from: this.mesh.peerId,
59
+ networkName: this.mesh.networkName, // Include network namespace
56
60
  timestamp: Date.now(),
57
61
  ttl: this.maxTTL,
58
62
  path: [this.mesh.peerId] // Track propagation path
@@ -91,7 +95,7 @@ export class GossipManager extends EventEmitter {
91
95
  * @param {string} subtype - Message subtype (default: 'dm')
92
96
  * @returns {string|null} The message ID if sent, or null on error
93
97
  */
94
- sendDirectMessage(targetPeerId, content, subtype = 'dm') {
98
+ async sendDirectMessage(targetPeerId, content, subtype = 'dm') {
95
99
  if (!targetPeerId || typeof targetPeerId !== 'string') {
96
100
  this.debug.error('Invalid targetPeerId for direct message');
97
101
  return null;
@@ -103,7 +107,7 @@ export class GossipManager extends EventEmitter {
103
107
  return null;
104
108
  }
105
109
 
106
- const messageId = this.generateMessageId();
110
+ const messageId = await this.generateMessageId();
107
111
  const message = {
108
112
  id: messageId,
109
113
  type: 'gossip',
@@ -111,6 +115,7 @@ export class GossipManager extends EventEmitter {
111
115
  content,
112
116
  from: this.mesh.peerId,
113
117
  to: targetPeerId,
118
+ networkName: this.mesh.networkName, // Include network namespace
114
119
  timestamp: Date.now(),
115
120
  ttl: this.maxTTL,
116
121
  path: [this.mesh.peerId]
@@ -133,7 +138,7 @@ export class GossipManager extends EventEmitter {
133
138
  this.debug.log(`🔥🔥🔥 GOSSIP MESSAGE RECEIVED! From: ${fromPeerId?.substring(0, 8)}...`);
134
139
  this.debug.log('🔥🔥🔥 Message:', message);
135
140
 
136
- const { id: messageId, ttl, from: originPeerId, subtype, content, timestamp, path, to } = message;
141
+ const { id: messageId, ttl, from: originPeerId, subtype, content, timestamp, path, to, networkName } = message;
137
142
 
138
143
  // Validate message structure
139
144
  if (!messageId || !originPeerId || !subtype || content === undefined) {
@@ -141,6 +146,15 @@ export class GossipManager extends EventEmitter {
141
146
  return;
142
147
  }
143
148
 
149
+ // Filter messages by network namespace
150
+ const messageNetwork = networkName || 'global';
151
+ const currentNetwork = this.mesh.networkName;
152
+
153
+ if (messageNetwork !== currentNetwork) {
154
+ this.debug.log(`Filtering gossip message from different network: ${messageNetwork} (current: ${currentNetwork})`);
155
+ return;
156
+ }
157
+
144
158
  // Check if we've already seen this message
145
159
  if (this.seenMessages.has(messageId)) {
146
160
  this.debug.log(`Ignoring duplicate message: ${messageId.substring(0, 8)}...`);
@@ -229,7 +243,78 @@ export class GossipManager extends EventEmitter {
229
243
  } else if (subtype === 'dm') {
230
244
  // Direct message logic
231
245
  if (typeof to === 'string' && typeof this.mesh.peerId === 'string' && to.trim().toLowerCase() === this.mesh.peerId.trim().toLowerCase()) {
232
- // This peer is the target, emit to UI
246
+ // This peer is the target - check if this message type should be filtered
247
+
248
+ this.debug.log(`🔍 DM DEBUG: Received DM from ${originPeerId?.substring(0, 8)}, content type: ${typeof processedContent}`);
249
+ if (typeof processedContent === 'object' && processedContent) {
250
+ this.debug.log(`🔍 DM DEBUG: Content object has type: ${processedContent.type}`);
251
+ }
252
+
253
+ // Define message types that should be filtered from peer-readable messages
254
+ // These messages are processed but not emitted as regular messages to UI/applications
255
+ const filteredMessageTypes = new Set([
256
+ 'signaling-relay',
257
+ 'peer-announce-relay',
258
+ 'bootstrap-keepalive'
259
+ ]);
260
+
261
+ // Parse the content to check message type
262
+ let messageType = null;
263
+ let shouldFilter = false;
264
+
265
+ // Check if content is already an object with type property
266
+ if (typeof processedContent === 'object' && processedContent && processedContent.type) {
267
+ messageType = processedContent.type;
268
+ shouldFilter = filteredMessageTypes.has(messageType);
269
+ } else if (typeof processedContent === 'string') {
270
+ // Try to parse as JSON if it's a string
271
+ try {
272
+ const parsedContent = JSON.parse(processedContent);
273
+ messageType = parsedContent.type;
274
+ shouldFilter = filteredMessageTypes.has(messageType);
275
+ } catch (e) {
276
+ // Not JSON or doesn't have type - treat as regular message
277
+ }
278
+ }
279
+
280
+ this.debug.log(`🔍 DM DEBUG: messageType=${messageType}, shouldFilter=${shouldFilter}`);
281
+
282
+ if (shouldFilter) {
283
+ this.debug.log(`🔇 FILTER: Processing filtered DM type '${messageType}' from ${originPeerId?.substring(0, 8)} (not emitted to UI)`);
284
+
285
+ // Process the filtered message internally but don't emit to UI
286
+ if (messageType === 'signaling-relay' && typeof processedContent === 'object') {
287
+ // Handle signaling relay
288
+ if (processedContent.signalingMessage && this.mesh.signalingHandler) {
289
+ this.mesh.signalingHandler.handleSignalingMessage({
290
+ type: processedContent.signalingMessage.type,
291
+ data: processedContent.signalingMessage.data,
292
+ fromPeerId: processedContent.signalingMessage.fromPeerId || originPeerId,
293
+ targetPeerId: processedContent.targetPeerId,
294
+ timestamp: processedContent.timestamp
295
+ });
296
+ }
297
+ } else if (messageType === 'peer-announce-relay' && typeof processedContent === 'object') {
298
+ // Handle peer announce relay
299
+ if (processedContent.data && this.mesh.signalingHandler) {
300
+ this.mesh.signalingHandler.handlePeerAnnouncement(processedContent.data, originPeerId);
301
+ }
302
+ } else if (messageType === 'bootstrap-keepalive') {
303
+ // Handle bootstrap keepalive - content can be object or string
304
+ if (this.mesh.peerDiscovery) {
305
+ // For bootstrap keepalive from a specific source, use the 'from' field as the peer ID
306
+ const keepalivePeerId = (typeof processedContent === 'object' && processedContent.from)
307
+ ? processedContent.from
308
+ : originPeerId;
309
+ this.mesh.peerDiscovery.updateDiscoveryTimestamp(keepalivePeerId);
310
+ }
311
+ }
312
+
313
+ // Do NOT emit to UI and do NOT relay further
314
+ return;
315
+ }
316
+
317
+ // This is a regular (non-filtered) direct message - emit to UI
233
318
  this.emit('messageReceived', {
234
319
  from: originPeerId,
235
320
  content: processedContent,
@@ -324,14 +409,14 @@ export class GossipManager extends EventEmitter {
324
409
  /**
325
410
  * Broadcast peer announcement via gossip when we connect
326
411
  */
327
- announcePeer(peerId = this.mesh.peerId) {
412
+ async announcePeer(peerId = this.mesh.peerId) {
328
413
  const announcementData = {
329
414
  peerId,
330
415
  timestamp: Date.now()
331
416
  };
332
417
 
333
418
  this.debug.log(`Gossiping peer announcement for: ${peerId.substring(0, 8)}...`);
334
- this.broadcastMessage(announcementData, 'peer-announcement');
419
+ await this.broadcastMessage(announcementData, 'peer-announcement');
335
420
  }
336
421
 
337
422
  /**
@@ -454,9 +539,33 @@ export class GossipManager extends EventEmitter {
454
539
  /**
455
540
  * Generate unique message ID
456
541
  */
457
- generateMessageId() {
542
+ async generateMessageId() {
458
543
  const array = new Uint8Array(16);
459
- crypto.getRandomValues(array);
544
+
545
+ // Environment-aware random value generation
546
+ if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
547
+ // Browser environment
548
+ crypto.getRandomValues(array);
549
+ } else if (typeof process !== 'undefined' && process.versions && process.versions.node) {
550
+ // Node.js environment
551
+ try {
552
+ const crypto = await import('crypto');
553
+ const randomBytes = crypto.randomBytes(16);
554
+ array.set(randomBytes);
555
+ } catch (e) {
556
+ console.warn('Could not use Node.js crypto, falling back to Math.random');
557
+ // Fallback to Math.random
558
+ for (let i = 0; i < array.length; i++) {
559
+ array[i] = Math.floor(Math.random() * 256);
560
+ }
561
+ }
562
+ } else {
563
+ // Fallback to Math.random for other environments
564
+ for (let i = 0; i < array.length; i++) {
565
+ array[i] = Math.floor(Math.random() * 256);
566
+ }
567
+ }
568
+
460
569
  return Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('');
461
570
  }
462
571
 
@@ -492,6 +601,7 @@ export class GossipManager extends EventEmitter {
492
601
  cleanupExpiredMessages() {
493
602
  const now = Date.now();
494
603
  let cleaned = 0;
604
+ let keyExchangesCleaned = 0;
495
605
 
496
606
  // Clean up seen messages
497
607
  this.seenMessages.forEach((data, messageId) => {
@@ -502,9 +612,20 @@ export class GossipManager extends EventEmitter {
502
612
  }
503
613
  });
504
614
 
615
+ // Clean up old key exchange tracking (keep for shorter time - 1 minute)
616
+ this.processedKeyExchanges.forEach((timestamp, keyExchangeId) => {
617
+ if (now - timestamp > 60000) { // 1 minute
618
+ this.processedKeyExchanges.delete(keyExchangeId);
619
+ keyExchangesCleaned++;
620
+ }
621
+ });
622
+
505
623
  if (cleaned > 0) {
506
624
  this.debug.log(`Cleaned up ${cleaned} expired gossip messages`);
507
625
  }
626
+ if (keyExchangesCleaned > 0) {
627
+ this.debug.log(`Cleaned up ${keyExchangesCleaned} old key exchange tracking entries`);
628
+ }
508
629
  }
509
630
 
510
631
  /**
@@ -514,6 +635,7 @@ export class GossipManager extends EventEmitter {
514
635
  this.stopCleanupTimer();
515
636
  this.seenMessages.clear();
516
637
  this.messageHistory.clear();
638
+ this.processedKeyExchanges.clear();
517
639
  }
518
640
 
519
641
  /**
@@ -526,7 +648,37 @@ export class GossipManager extends EventEmitter {
526
648
  // Handle key exchange messages
527
649
  if (subtype === 'key_exchange' || subtype === 'key_exchange_response') {
528
650
  if (content && (content.type === 'key_exchange' || content.type === 'key_exchange_response') && content.publicKey) {
529
- this.debug.log(`🔐 Received ${content.type} from peer ${originPeerId.substring(0, 8)}...`);
651
+
652
+ // Create a unique identifier for this key exchange to prevent duplicates
653
+ const keyExchangeId = `${originPeerId}:${content.type}:${content.timestamp || Date.now()}`;
654
+
655
+ // Check if we've already processed this key exchange
656
+ if (this.processedKeyExchanges.has(keyExchangeId)) {
657
+ this.debug.log(`🔐 Ignoring duplicate ${content.type} from peer ${originPeerId.substring(0, 8)}... (already processed)`);
658
+ return true; // Mark as handled to prevent further propagation
659
+ }
660
+
661
+ // Also check for recent key exchanges from the same peer (within last 5 seconds)
662
+ const recentKeyExchangePattern = `${originPeerId}:${content.type}:`;
663
+ const now = Date.now();
664
+ let foundRecent = false;
665
+
666
+ for (const [existingId, timestamp] of this.processedKeyExchanges.entries()) {
667
+ if (existingId.startsWith(recentKeyExchangePattern) && (now - timestamp) < 5000) {
668
+ foundRecent = true;
669
+ break;
670
+ }
671
+ }
672
+
673
+ if (foundRecent) {
674
+ this.debug.log(`🔐 Ignoring recent duplicate ${content.type} from peer ${originPeerId.substring(0, 8)}... (processed recently)`);
675
+ return true;
676
+ }
677
+
678
+ this.debug.log(`🔐 Processing ${content.type} from peer ${originPeerId.substring(0, 8)}...`);
679
+
680
+ // Mark this key exchange as processed
681
+ this.processedKeyExchanges.set(keyExchangeId, now);
530
682
 
531
683
  // Use the mesh's key exchange handler which properly handles both pub and epub keys
532
684
  this.mesh._handleKeyExchange(content, originPeerId);