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