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
@@ -2,11 +2,11 @@
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() {
9
8
  this._cache = new Map();
9
+ this._pigeonRTC = null;
10
10
  this._init();
11
11
  }
12
12
 
@@ -21,6 +21,33 @@ export class EnvironmentDetector {
21
21
  this._cache.set('isDeno', this._detectDeno());
22
22
  this._cache.set('isBun', this._detectBun());
23
23
  this._cache.set('isNativeScript', this._detectNativeScript());
24
+
25
+ // Initialize PigeonRTC for cross-platform WebRTC support
26
+ this._initPigeonRTC();
27
+ }
28
+
29
+ /**
30
+ * Initialize PigeonRTC for cross-platform WebRTC support
31
+ * PigeonRTC provides a unified WebRTC interface across browser and Node.js
32
+ * @private
33
+ */
34
+ _initPigeonRTC() {
35
+ try {
36
+ // PigeonRTC will be initialized asynchronously via initWebRTCAsync()
37
+ // This is a placeholder to mark that we're using PigeonRTC
38
+ this._webrtcPolyfilled = false;
39
+ } catch (error) {
40
+ // Silently fail - WebRTC polyfill is optional
41
+ // The application will handle missing WebRTC through normal capability detection
42
+ }
43
+ }
44
+
45
+ /**
46
+ * Get the PigeonRTC instance
47
+ * @returns {PigeonRTC|null} The PigeonRTC instance or null if not initialized
48
+ */
49
+ getPigeonRTC() {
50
+ return this._pigeonRTC;
24
51
  }
25
52
 
26
53
  // Primary environment detection
@@ -125,20 +152,26 @@ export class EnvironmentDetector {
125
152
 
126
153
  // WebRTC capability detection
127
154
  get hasWebRTC() {
155
+ // If PigeonRTC is initialized, use its support check
156
+ if (this._pigeonRTC) {
157
+ return this._pigeonRTC.isSupported();
158
+ }
159
+
160
+ // Fallback to native detection
128
161
  if (this.isBrowser) {
129
162
  return typeof RTCPeerConnection !== 'undefined' ||
130
163
  typeof webkitRTCPeerConnection !== 'undefined' ||
131
164
  typeof mozRTCPeerConnection !== 'undefined';
132
165
  }
133
166
  if (this.isNodeJS) {
134
- // Check for Node.js WebRTC implementations or globally injected WebRTC
167
+ // Check for globally injected WebRTC (from PigeonRTC or other sources)
135
168
  return (typeof global !== 'undefined' &&
136
169
  typeof global.RTCPeerConnection !== 'undefined') ||
137
- typeof RTCPeerConnection !== 'undefined';
170
+ typeof RTCPeerConnection !== 'undefined' ||
171
+ this._webrtcPolyfilled === true;
138
172
  }
139
173
  if (this.isNativeScript) {
140
174
  // NativeScript can access native WebRTC implementations through native modules
141
- // Check for globally injected WebRTC first
142
175
  return (typeof global !== 'undefined' &&
143
176
  typeof global.RTCPeerConnection !== 'undefined') ||
144
177
  typeof RTCPeerConnection !== 'undefined';
@@ -491,6 +524,56 @@ export class EnvironmentDetector {
491
524
  };
492
525
  }
493
526
 
527
+ /**
528
+ * Asynchronously initialize WebRTC using PigeonRTC
529
+ * This method initializes PigeonRTC for cross-platform WebRTC support
530
+ * @returns {Promise<boolean>} True if WebRTC was successfully initialized
531
+ */
532
+ async initWebRTCAsync() {
533
+ try {
534
+ // Check if already initialized
535
+ if (this._pigeonRTC) {
536
+ return true;
537
+ }
538
+
539
+ // Check for bundled PigeonRTC in browser builds
540
+ let createPigeonRTC;
541
+ if (typeof globalThis !== 'undefined' && globalThis.__PEERPIGEON_PIGEONRTC__) {
542
+ createPigeonRTC = globalThis.__PEERPIGEON_PIGEONRTC__.createPigeonRTC ||
543
+ globalThis.__PEERPIGEON_PIGEONRTC__.default;
544
+ } else if (typeof window !== 'undefined' && window.__PEERPIGEON_PIGEONRTC__) {
545
+ createPigeonRTC = window.__PEERPIGEON_PIGEONRTC__.createPigeonRTC ||
546
+ window.__PEERPIGEON_PIGEONRTC__.default;
547
+ }
548
+
549
+ // If not found in globals, try dynamic import (Node.js only)
550
+ if (!createPigeonRTC && this.isNodeJS) {
551
+ try {
552
+ // Import PigeonRTC dynamically (for non-bundled Node.js environments)
553
+ const pigeonRTCModule = await import('pigeonrtc');
554
+ createPigeonRTC = pigeonRTCModule.createPigeonRTC || pigeonRTCModule.default;
555
+ } catch (error) {
556
+ console.error('Failed to dynamically import PigeonRTC:', error);
557
+ }
558
+ }
559
+
560
+ if (!createPigeonRTC) {
561
+ throw new Error('PigeonRTC createPigeonRTC function not found');
562
+ }
563
+
564
+ // Initialize PigeonRTC (auto-detects environment)
565
+ this._pigeonRTC = await createPigeonRTC();
566
+
567
+ // Update cache to reflect that WebRTC is now available
568
+ this._webrtcPolyfilled = true;
569
+
570
+ return this._pigeonRTC.isSupported();
571
+ } catch (error) {
572
+ console.error('Failed to initialize PigeonRTC:', error);
573
+ return false;
574
+ }
575
+ }
576
+
494
577
  // Static method for quick environment check
495
578
  static detect() {
496
579
  return new EnvironmentDetector();
@@ -514,3 +597,4 @@ export const isNativeScript = () => environmentDetector.isNativeScript;
514
597
  export const hasWebRTC = () => environmentDetector.hasWebRTC;
515
598
  export const hasWebSocket = () => environmentDetector.hasWebSocket;
516
599
  export const getEnvironmentReport = () => environmentDetector.getEnvironmentReport();
600
+ 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);
@@ -111,7 +111,14 @@ export class MediaManager extends EventEmitter {
111
111
  throw new Error('At least one of video or audio must be enabled');
112
112
  }
113
113
 
114
- this.localStream = await navigator.mediaDevices.getUserMedia(constraints);
114
+ // Try to use PigeonRTC's getUserMedia if available, otherwise fall back to navigator
115
+ const pigeonRTC = environmentDetector.getPigeonRTC();
116
+ if (pigeonRTC) {
117
+ this.localStream = await pigeonRTC.getUserMedia(constraints);
118
+ } else {
119
+ this.localStream = await navigator.mediaDevices.getUserMedia(constraints);
120
+ }
121
+
115
122
  this.isVideoEnabled = video;
116
123
  this.isAudioEnabled = audio;
117
124
 
@@ -215,10 +222,13 @@ export class MediaManager extends EventEmitter {
215
222
  * Check if browser supports required APIs
216
223
  */
217
224
  static checkSupport() {
225
+ // Get PigeonRTC instance if available
226
+ const pigeonRTC = environmentDetector.getPigeonRTC();
227
+
218
228
  const support = {
219
229
  getUserMedia: !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia),
220
230
  enumerateDevices: !!(navigator.mediaDevices && navigator.mediaDevices.enumerateDevices),
221
- webRTC: !!(window.RTCPeerConnection)
231
+ webRTC: pigeonRTC ? pigeonRTC.isSupported() : !!(window.RTCPeerConnection)
222
232
  };
223
233
 
224
234
  support.fullSupport = support.getUserMedia && support.enumerateDevices && support.webRTC;