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
@@ -1,53 +1,2430 @@
1
- import { PeerPigeonMesh } from '../../src/PeerPigeonMesh.js';
2
- import { PeerPigeonUI } from './ui.js';
3
-
4
- class PeerPigeonApp {
5
- constructor() {
6
- // Initialize mesh with crypto, WebDHT, and distributed storage enabled
7
- this.mesh = new PeerPigeonMesh({
8
- enableWebDHT: true,
9
- enableCrypto: true,
10
- enableDistributedStorage: true
11
- });
12
-
13
- this.ui = new PeerPigeonUI(this.mesh);
14
- this.init();
15
- }
16
-
17
- async init() {
18
- try {
19
- await this.mesh.init();
20
- this.ui.updateUI();
21
- this.setupUnloadHandler();
22
- } catch (error) {
23
- console.error('Failed to initialize app:', error);
24
- }
25
- }
26
-
27
- setupUnloadHandler() {
28
- const handleUnload = () => {
29
- if (this.mesh.connected) {
30
- this.mesh.sendGoodbyeMessage();
31
- }
32
- };
33
-
34
- window.addEventListener('beforeunload', handleUnload);
35
- window.addEventListener('unload', handleUnload);
36
- }
37
- }
1
+ /**
2
+ * PeerPigeon Complete API Testing Suite
3
+ * Browser-3 Example - Comprehensive feature testing interface
4
+ */
5
+
6
+ /* global PeerPigeon */
7
+
8
+ class PeerPigeonTestSuite {
9
+ constructor() {
10
+ this.mesh = null;
11
+ this.activeSubscriptions = new Set();
12
+ this.messageHistory = [];
13
+ this.testResults = [];
14
+ this.isMonitoring = false;
15
+ this.performanceMetrics = {
16
+ messagesSent: 0,
17
+ messagesReceived: 0,
18
+ startTime: null,
19
+ endTime: null
20
+ };
21
+
22
+ this.init();
23
+ }
24
+
25
+ async init() {
26
+ this.log('๐Ÿš€ Initializing PeerPigeon Test Suite...');
27
+
28
+ try {
29
+ // Detect video test mode to disable crypto blocking
30
+ const isVideoTest = window.location.search.includes('test=video') ||
31
+ document.title.includes('Video Test') ||
32
+ window.testMode === 'video';
33
+
34
+ if (isVideoTest) {
35
+ this.log('๐Ÿ”“ Video test mode detected: Disabling crypto stream blocking');
36
+ window.DISABLE_CRYPTO_BLOCKING = true;
37
+ }
38
+
39
+ // Initialize PeerPigeon mesh with all features enabled
40
+ this.mesh = new PeerPigeon.PeerPigeonMesh({
41
+ enableWebDHT: true,
42
+ enableCrypto: true,
43
+ enableDistributedStorage: true, // Enable distributed storage
44
+ networkName: 'global', // Default network
45
+ allowGlobalFallback: true, // Allow fallback to global network
46
+ maxPeers: 3,
47
+ minPeers: 2,
48
+ autoConnect: true,
49
+ autoDiscovery: true,
50
+ evictionStrategy: true,
51
+ xorRouting: true
52
+ });
53
+
54
+ await this.mesh.init();
55
+ this.setupEventListeners();
56
+ this.setupUI();
57
+ this.updatePeerInfo();
58
+ this.initializeMediaDevices();
59
+
60
+ this.log('โœ… PeerPigeon Test Suite initialized successfully');
61
+
62
+ // Update status displays
63
+ this.updateNetworkInfo();
64
+ this.updateCryptoStatus();
65
+
66
+ // Add delayed crypto status update to catch async crypto initialization
67
+ setTimeout(() => {
68
+ this.log('๐Ÿ”„ Delayed crypto status update...');
69
+ this.updateCryptoStatus();
70
+ }, 1000);
71
+
72
+ // Another update after a longer delay to catch slow initialization
73
+ setTimeout(() => {
74
+ this.updateCryptoStatus();
75
+ }, 3000);
76
+ } catch (error) {
77
+ this.log(`โŒ Initialization failed: ${error.message}`, 'error');
78
+ }
79
+ }
80
+
81
+ setupEventListeners() {
82
+ // Connection events
83
+ this.mesh.addEventListener('statusChanged', (data) => {
84
+ this.handleStatusChange(data);
85
+ });
86
+
87
+ this.mesh.addEventListener('peerConnected', (data) => {
88
+ this.log(`๐Ÿค Peer connected: ${data.peerId.substring(0, 8)}...`);
89
+
90
+ // CRITICAL FIX: Enable remote stream reception from this newly connected peer
91
+ // This ensures ALL peers can receive streams whether they're senders or not
92
+ if (this.mesh.connectionManager) {
93
+ const connection = this.mesh.connectionManager.peers.get(data.peerId);
94
+ if (connection && connection.allowRemoteStreamEmission) {
95
+ connection.allowRemoteStreamEmission();
96
+ this.log(`๐Ÿ”“ Enabled remote stream reception from ${data.peerId.substring(0, 8)}...`);
97
+ }
98
+ }
99
+
100
+ this.updateNetworkInfo();
101
+ this.updatePeersList();
102
+ });
103
+
104
+ this.mesh.addEventListener('peerDisconnected', (data) => {
105
+ this.log(`๐Ÿ‘‹ Peer disconnected: ${data.peerId.substring(0, 8)}... (${data.reason})`);
106
+ this.updateNetworkInfo();
107
+ this.updatePeersList();
108
+ });
109
+
110
+ this.mesh.addEventListener('peerDiscovered', (data) => {
111
+ this.log(`๐Ÿ” Peer discovered: ${data.peerId.substring(0, 8)}...`);
112
+ this.updateDiscoveredPeers();
113
+ });
114
+
115
+ // Message events
116
+ this.mesh.addEventListener('messageReceived', (data) => {
117
+ this.handleMessageReceived(data);
118
+ });
119
+
120
+ // WebDHT events (low-level, raw key-value operations)
121
+ this.mesh.addEventListener('dhtValueChanged', (data) => {
122
+ this.handleDHTValueChanged(data);
123
+ });
124
+
125
+ // Media events
126
+ this.mesh.addEventListener('localStreamStarted', (data) => {
127
+ this.handleLocalStreamStarted(data);
128
+ });
129
+
130
+ this.mesh.addEventListener('localStreamStopped', () => {
131
+ this.handleLocalStreamStopped();
132
+ });
133
+
134
+ this.mesh.addEventListener('remoteStream', (data) => {
135
+ this.handleRemoteStream(data);
136
+ });
137
+
138
+ this.mesh.addEventListener('mediaError', (data) => {
139
+ this.log(`๐ŸŽฅ Media error: ${data.error.message}`, 'error');
140
+ });
141
+
142
+ // Crypto events
143
+ this.mesh.addEventListener('cryptoReady', () => {
144
+ this.log('๐Ÿ” Encryption system ready');
145
+ this.updateCryptoStatus();
146
+ });
147
+
148
+ this.mesh.addEventListener('cryptoError', (data) => {
149
+ this.log(`๐Ÿ” Crypto error: ${data.error}`, 'error');
150
+ });
151
+
152
+ this.mesh.addEventListener('peerKeyAdded', (data) => {
153
+ this.log(`๐Ÿ” Key exchange completed with ${data.peerId.substring(0, 8)}...`);
154
+ this.updateCryptoStatus();
155
+
156
+ // Check if all connected peers are now ready for media
157
+ this.checkAndNotifyMediaReadiness();
158
+ });
159
+
160
+ // === NEW SELECTIVE STREAMING EVENTS ===
161
+
162
+ this.mesh.addEventListener('selectiveStreamStarted', (data) => {
163
+ this.log(`๐ŸŽฏ Selective ${data.streamType} streaming started to ${data.targetPeerIds.length} peer(s)`);
164
+ });
165
+
166
+ this.mesh.addEventListener('selectiveStreamStopped', (data) => {
167
+ this.log(`๐Ÿ›‘ Selective streaming stopped${data.returnToBroadcast ? ' (switched to broadcast)' : ''}`);
168
+ });
169
+
170
+ this.mesh.addEventListener('broadcastStreamEnabled', () => {
171
+ this.log('๐Ÿ“ก Broadcast streaming enabled for all peers');
172
+ });
173
+
174
+ this.mesh.addEventListener('streamingBlockedToPeers', (data) => {
175
+ this.log(`๐Ÿšซ Streaming blocked to ${data.blockedPeerIds.length} peer(s)`);
176
+ });
177
+
178
+ this.mesh.addEventListener('streamingAllowedToPeers', (data) => {
179
+ this.log(`โœ… Streaming allowed to ${data.allowedPeerIds.length} peer(s)`);
180
+ });
181
+
182
+ // Connection monitoring
183
+ this.mesh.addEventListener('connectionStats', (stats) => {
184
+ this.updateConnectionStats(stats);
185
+ });
186
+ }
187
+
188
+ setupUI() {
189
+ this.setupTabNavigation();
190
+ this.setupConnectionControls();
191
+ this.setupMessagingControls();
192
+ this.setupMediaControls();
193
+ this.setupDHTControls();
194
+ this.setupStorageControls();
195
+ this.setupCryptoControls();
196
+ this.setupNetworkControls();
197
+ this.setupTestingControls();
198
+ }
199
+
200
+ setupTabNavigation() {
201
+ const tabBtns = document.querySelectorAll('.tab-btn');
202
+ const tabContents = document.querySelectorAll('.tab-content');
203
+
204
+ tabBtns.forEach(btn => {
205
+ btn.addEventListener('click', () => {
206
+ const targetTab = btn.dataset.tab;
207
+
208
+ // Update active states
209
+ tabBtns.forEach(b => b.classList.remove('active'));
210
+ tabContents.forEach(c => c.classList.remove('active'));
211
+
212
+ btn.classList.add('active');
213
+ document.getElementById(`${targetTab}-tab`).classList.add('active');
214
+ });
215
+ });
216
+ }
217
+
218
+ setupConnectionControls() {
219
+ document.getElementById('connect-btn').addEventListener('click', () => {
220
+ this.connect();
221
+ });
222
+
223
+ document.getElementById('disconnect-btn').addEventListener('click', () => {
224
+ this.disconnect();
225
+ });
226
+
227
+ document.getElementById('cleanup-btn').addEventListener('click', () => {
228
+ this.cleanupStaleData();
229
+ });
230
+
231
+ document.getElementById('apply-config-btn').addEventListener('click', () => {
232
+ this.applyConfiguration();
233
+ });
234
+
235
+ document.getElementById('connect-peer-btn').addEventListener('click', () => {
236
+ this.connectToPeer();
237
+ });
238
+
239
+ document.getElementById('force-connect-all-btn').addEventListener('click', () => {
240
+ this.forceConnectAll();
241
+ });
242
+
243
+ // Network name controls
244
+ document.getElementById('network-name').addEventListener('change', (e) => {
245
+ this.setNetworkName(e.target.value);
246
+ });
247
+
248
+ document.getElementById('allow-global-fallback').addEventListener('change', (e) => {
249
+ this.setAllowGlobalFallback(e.checked);
250
+ });
251
+
252
+ // Quick network buttons
253
+ document.querySelectorAll('.network-btn').forEach(btn => {
254
+ btn.addEventListener('click', (e) => {
255
+ const networkName = e.target.dataset.network;
256
+ this.setNetworkName(networkName);
257
+ });
258
+ });
259
+ }
260
+
261
+ setupMessagingControls() {
262
+ document.getElementById('send-broadcast-btn').addEventListener('click', () => {
263
+ this.sendBroadcastMessage();
264
+ });
265
+
266
+ document.getElementById('send-direct-btn').addEventListener('click', () => {
267
+ this.sendDirectMessage();
268
+ });
269
+
270
+ document.getElementById('clear-messages-btn').addEventListener('click', () => {
271
+ this.clearMessageHistory();
272
+ });
273
+
274
+ // Enter key handlers
275
+ document.getElementById('broadcast-message').addEventListener('keypress', (e) => {
276
+ if (e.key === 'Enter' && !e.shiftKey) {
277
+ e.preventDefault();
278
+ this.sendBroadcastMessage();
279
+ }
280
+ });
281
+
282
+ document.getElementById('direct-message').addEventListener('keypress', (e) => {
283
+ if (e.key === 'Enter' && !e.shiftKey) {
284
+ e.preventDefault();
285
+ this.sendDirectMessage();
286
+ }
287
+ });
288
+ }
289
+
290
+ setupMediaControls() {
291
+ document.getElementById('start-media-btn').addEventListener('click', () => {
292
+ this.startMedia();
293
+ });
294
+
295
+ document.getElementById('stop-media-btn').addEventListener('click', () => {
296
+ this.stopMedia();
297
+ });
298
+
299
+ document.getElementById('toggle-video-btn').addEventListener('click', () => {
300
+ this.toggleVideo();
301
+ });
302
+
303
+ document.getElementById('toggle-audio-btn').addEventListener('click', () => {
304
+ this.toggleAudio();
305
+ });
306
+
307
+ document.getElementById('enumerate-devices-btn').addEventListener('click', () => {
308
+ this.enumerateDevices();
309
+ });
310
+
311
+ // === NEW SELECTIVE STREAMING CONTROLS ===
312
+
313
+ // Make peer selector multiple for selective streaming
314
+ const targetPeerSelect = document.getElementById('target-peer-select');
315
+ if (targetPeerSelect) {
316
+ targetPeerSelect.multiple = true;
317
+ targetPeerSelect.size = 3; // Show 3 options at once
318
+ }
319
+
320
+ // Add selective streaming buttons
321
+ this.addSelectiveStreamingButtons();
322
+ }
323
+
324
+ addSelectiveStreamingButtons() {
325
+ const mediaControlsDiv = document.querySelector('#media-tab .controls');
326
+ if (mediaControlsDiv) {
327
+ // Create selective streaming section
328
+ const selectiveStreamingSection = document.createElement('div');
329
+ selectiveStreamingSection.className = 'control-section';
330
+ selectiveStreamingSection.innerHTML = `
331
+ <h4>๐ŸŽฏ Selective Streaming</h4>
332
+ <div class="control-group">
333
+ <button id="start-selective-btn" class="btn">Start Selective Stream</button>
334
+ <button id="stop-selective-btn" class="btn">Stop Selective</button>
335
+ <button id="switch-broadcast-btn" class="btn">Switch to Broadcast</button>
336
+ </div>
337
+ <div class="control-group">
338
+ <button id="block-peers-btn" class="btn secondary">Block Selected Peers</button>
339
+ <button id="allow-peers-btn" class="btn secondary">Allow Selected Peers</button>
340
+ <button id="show-streaming-status-btn" class="btn secondary">Show Status</button>
341
+ </div>
342
+ <div id="streaming-status" class="status-display"></div>
343
+ <p class="info-text">๐Ÿ’ก Select multiple peers from the dropdown above to control streaming patterns</p>
344
+ `;
345
+
346
+ mediaControlsDiv.appendChild(selectiveStreamingSection);
347
+
348
+ // Add event listeners for new buttons
349
+ document.getElementById('start-selective-btn').addEventListener('click', () => {
350
+ this.startSelectiveStreaming();
351
+ });
352
+
353
+ document.getElementById('stop-selective-btn').addEventListener('click', () => {
354
+ this.stopSelectiveStreaming();
355
+ });
356
+
357
+ document.getElementById('switch-broadcast-btn').addEventListener('click', () => {
358
+ this.switchToBroadcastMode();
359
+ });
360
+
361
+ document.getElementById('block-peers-btn').addEventListener('click', () => {
362
+ this.blockStreamingToPeer();
363
+ });
364
+
365
+ document.getElementById('allow-peers-btn').addEventListener('click', () => {
366
+ this.allowStreamingToPeer();
367
+ });
368
+
369
+ document.getElementById('show-streaming-status-btn').addEventListener('click', () => {
370
+ this.showStreamingStatus();
371
+ });
372
+ }
373
+ }
374
+
375
+ setupDHTControls() {
376
+ document.getElementById('dht-put-btn').addEventListener('click', () => {
377
+ this.dhtPut();
378
+ });
379
+
380
+ document.getElementById('dht-update-btn').addEventListener('click', () => {
381
+ this.dhtUpdate();
382
+ });
383
+
384
+ document.getElementById('dht-get-btn').addEventListener('click', () => {
385
+ this.dhtGet();
386
+ });
387
+
388
+ document.getElementById('dht-delete-btn').addEventListener('click', () => {
389
+ this.dhtDelete();
390
+ });
391
+
392
+ document.getElementById('dht-subscribe-btn').addEventListener('click', () => {
393
+ this.dhtSubscribe();
394
+ });
395
+
396
+ document.getElementById('dht-unsubscribe-btn').addEventListener('click', () => {
397
+ this.dhtUnsubscribe();
398
+ });
399
+
400
+ document.getElementById('clear-dht-log-btn').addEventListener('click', () => {
401
+ this.clearDHTLog();
402
+ });
403
+ }
404
+
405
+ setupStorageControls() {
406
+ document.getElementById('storage-enable-btn')?.addEventListener('click', () => {
407
+ this.enableDistributedStorage();
408
+ });
409
+
410
+ document.getElementById('storage-disable-btn')?.addEventListener('click', () => {
411
+ this.disableDistributedStorage();
412
+ });
413
+
414
+ document.getElementById('storage-status-btn')?.addEventListener('click', () => {
415
+ this.getStorageStatus();
416
+ });
417
+
418
+ document.getElementById('storage-put-btn')?.addEventListener('click', () => {
419
+ this.putStorageData();
420
+ });
421
+
422
+ document.getElementById('storage-get-btn')?.addEventListener('click', () => {
423
+ this.getStorageData();
424
+ });
425
+
426
+ document.getElementById('storage-delete-btn')?.addEventListener('click', () => {
427
+ this.deleteStorageData();
428
+ });
429
+
430
+ document.getElementById('storage-list-btn')?.addEventListener('click', () => {
431
+ this.listStorageKeys();
432
+ });
433
+
434
+ document.getElementById('storage-stats-btn')?.addEventListener('click', () => {
435
+ this.getStorageStats();
436
+ });
437
+
438
+ document.getElementById('storage-clear-btn')?.addEventListener('click', () => {
439
+ this.clearAllStorage();
440
+ });
441
+
442
+ document.getElementById('clear-storage-log-btn')?.addEventListener('click', () => {
443
+ this.clearStorageLog();
444
+ });
445
+ }
446
+
447
+ setupCryptoControls() {
448
+ document.getElementById('send-encrypted-btn').addEventListener('click', () => {
449
+ this.sendEncryptedMessage();
450
+ });
451
+
452
+ document.getElementById('exchange-keys-btn').addEventListener('click', () => {
453
+ this.exchangeKeys();
454
+ });
455
+
456
+ document.getElementById('add-peer-key-btn').addEventListener('click', () => {
457
+ this.addPeerKey();
458
+ });
459
+
460
+ document.getElementById('clear-crypto-log-btn').addEventListener('click', () => {
461
+ this.clearCryptoLog();
462
+ });
463
+
464
+ document.getElementById('refresh-crypto-status-btn')?.addEventListener('click', () => {
465
+ this.log('๐Ÿ”„ Manually refreshing crypto status...');
466
+ this.updateCryptoStatus();
467
+ });
468
+
469
+ document.getElementById('force-crypto-init-btn')?.addEventListener('click', () => {
470
+ this.forceCryptoInit();
471
+ });
472
+
473
+ document.getElementById('exchange-keys-btn')?.addEventListener('click', () => {
474
+ this.exchangeKeysWithConnectedPeers();
475
+ });
476
+ }
477
+
478
+ setupNetworkControls() {
479
+ document.getElementById('refresh-status-btn').addEventListener('click', () => {
480
+ this.updateNetworkInfo();
481
+ });
482
+
483
+ document.getElementById('get-peer-states-btn').addEventListener('click', () => {
484
+ this.getPeerStates();
485
+ });
486
+
487
+ document.getElementById('start-monitoring-btn').addEventListener('click', () => {
488
+ this.startConnectionMonitoring();
489
+ });
490
+
491
+ document.getElementById('stop-monitoring-btn').addEventListener('click', () => {
492
+ this.stopConnectionMonitoring();
493
+ });
494
+
495
+ document.getElementById('debug-connectivity-btn').addEventListener('click', () => {
496
+ this.debugConnectivity();
497
+ });
498
+ }
499
+
500
+ setupTestingControls() {
501
+ document.getElementById('validate-peer-id-btn').addEventListener('click', () => {
502
+ this.validatePeerId();
503
+ });
504
+
505
+ document.getElementById('force-connect-all-api-btn').addEventListener('click', () => {
506
+ this.forceConnectAll();
507
+ });
508
+
509
+ document.getElementById('cleanup-stale-btn').addEventListener('click', () => {
510
+ this.cleanupStaleData();
511
+ });
512
+
513
+ document.getElementById('performance-test-btn').addEventListener('click', () => {
514
+ this.runPerformanceTest();
515
+ });
516
+
517
+ document.getElementById('stress-test-btn').addEventListener('click', () => {
518
+ this.runStressTest();
519
+ });
520
+
521
+ document.getElementById('export-logs-btn').addEventListener('click', () => {
522
+ this.exportLogs();
523
+ });
524
+
525
+ document.getElementById('clear-test-log-btn').addEventListener('click', () => {
526
+ this.clearTestLog();
527
+ });
528
+
529
+ document.getElementById('clear-log-btn').addEventListener('click', () => {
530
+ this.clearSystemLog();
531
+ });
532
+
533
+ // Error testing buttons
534
+ document.getElementById('test-invalid-peer-btn').addEventListener('click', () => {
535
+ this.testInvalidPeerConnection();
536
+ });
537
+
538
+ document.getElementById('test-malformed-message-btn').addEventListener('click', () => {
539
+ this.testMalformedMessage();
540
+ });
541
+
542
+ document.getElementById('test-dht-limits-btn').addEventListener('click', () => {
543
+ this.testDHTLimits();
544
+ });
545
+ }
546
+
547
+ // Connection Management
548
+ async connect() {
549
+ const url = document.getElementById('signaling-url').value.trim();
550
+ if (!url) {
551
+ this.log('โŒ Please enter a signaling server URL', 'error');
552
+ return;
553
+ }
554
+
555
+ // Set network name before connecting
556
+ const networkName = document.getElementById('network-name').value.trim() || 'global';
557
+ const allowFallback = document.getElementById('allow-global-fallback').checked;
558
+
559
+ try {
560
+ // Apply network settings before connecting
561
+ if (this.mesh.setNetworkName) {
562
+ this.mesh.setNetworkName(networkName);
563
+ this.log(`๐ŸŒ Network set to: ${networkName}`);
564
+ }
565
+
566
+ if (this.mesh.setAllowGlobalFallback) {
567
+ this.mesh.setAllowGlobalFallback(allowFallback);
568
+ this.log(`๐Ÿ”„ Global fallback ${allowFallback ? 'enabled' : 'disabled'}`);
569
+ }
570
+
571
+ this.log(`๐Ÿ”Œ Connecting to ${url} on network "${networkName}"...`);
572
+ await this.mesh.connect(url);
573
+ this.updateConnectionButtons(true);
574
+ this.updateNetworkStatus();
575
+ } catch (error) {
576
+ this.log(`โŒ Connection failed: ${error.message}`, 'error');
577
+ }
578
+ }
579
+
580
+ disconnect() {
581
+ try {
582
+ this.mesh.disconnect();
583
+ this.updateConnectionButtons(false);
584
+ this.updateNetworkStatus();
585
+ this.log('๐Ÿ”Œ Disconnected from signaling server');
586
+ } catch (error) {
587
+ this.log(`โŒ Disconnect error: ${error.message}`, 'error');
588
+ }
589
+ }
590
+
591
+ // Network Management
592
+ setNetworkName(networkName) {
593
+ if (!networkName || networkName.trim() === '') {
594
+ networkName = 'global';
595
+ }
596
+
597
+ const trimmedName = networkName.trim();
598
+
599
+ // Update the input field
600
+ document.getElementById('network-name').value = trimmedName;
601
+
602
+ // Update network buttons active state
603
+ document.querySelectorAll('.network-btn').forEach(btn => {
604
+ btn.classList.toggle('active', btn.dataset.network === trimmedName);
605
+ });
606
+
607
+ // If disconnected, can change network name immediately
608
+ if (!this.mesh.connected) {
609
+ if (this.mesh.setNetworkName) {
610
+ this.mesh.setNetworkName(trimmedName);
611
+ this.log(`๐ŸŒ Network name set to: ${trimmedName}`);
612
+ }
613
+ this.updateNetworkStatus();
614
+ } else {
615
+ this.log(`โš ๏ธ Disconnect first to change network from current network`, 'warning');
616
+ }
617
+ }
618
+
619
+ setAllowGlobalFallback(allow) {
620
+ if (this.mesh.setAllowGlobalFallback) {
621
+ this.mesh.setAllowGlobalFallback(allow);
622
+ this.log(`๐Ÿ”„ Global fallback ${allow ? 'enabled' : 'disabled'}`);
623
+ }
624
+ document.getElementById('allow-global-fallback').checked = allow;
625
+ }
626
+
627
+ updateNetworkStatus() {
628
+ const networkStatus = document.getElementById('network-status');
629
+ const currentNetworkEl = document.getElementById('current-network');
630
+ const fallbackIndicator = document.getElementById('fallback-indicator');
631
+ const originalNetworkInfo = document.getElementById('original-network-info');
632
+ const originalNetworkEl = document.getElementById('original-network');
633
+
634
+ if (this.mesh && this.mesh.getNetworkName) {
635
+ const currentNetwork = this.mesh.getNetworkName();
636
+ const originalNetwork = this.mesh.getOriginalNetworkName ? this.mesh.getOriginalNetworkName() : currentNetwork;
637
+ const isInFallback = this.mesh.isUsingGlobalFallback ? this.mesh.isUsingGlobalFallback() : false;
638
+
639
+ currentNetworkEl.textContent = currentNetwork;
640
+ fallbackIndicator.style.display = isInFallback ? 'inline' : 'none';
641
+
642
+ if (isInFallback && originalNetwork !== currentNetwork) {
643
+ originalNetworkEl.textContent = originalNetwork;
644
+ originalNetworkInfo.style.display = 'block';
645
+ } else {
646
+ originalNetworkInfo.style.display = 'none';
647
+ }
648
+
649
+ networkStatus.style.display = this.mesh.connected ? 'block' : 'none';
650
+ } else {
651
+ networkStatus.style.display = 'none';
652
+ }
653
+ }
654
+
655
+ async cleanupStaleData() {
656
+ try {
657
+ await this.mesh.cleanupStaleSignalingData();
658
+ this.log('๐Ÿงน Stale signaling data cleaned up');
659
+ } catch (error) {
660
+ this.log(`โŒ Cleanup error: ${error.message}`, 'error');
661
+ }
662
+ }
663
+
664
+ applyConfiguration() {
665
+ const maxPeers = parseInt(document.getElementById('max-peers').value);
666
+ const minPeers = parseInt(document.getElementById('min-peers').value);
667
+ const autoConnect = document.getElementById('auto-connect').checked;
668
+ const autoDiscovery = document.getElementById('auto-discovery').checked;
669
+ const evictionStrategy = document.getElementById('eviction-strategy').checked;
670
+ const xorRouting = document.getElementById('xor-routing').checked;
671
+
672
+ this.mesh.setMaxPeers(maxPeers);
673
+ this.mesh.setMinPeers(minPeers);
674
+ this.mesh.setAutoConnect(autoConnect);
675
+ this.mesh.setAutoDiscovery(autoDiscovery);
676
+ this.mesh.setEvictionStrategy(evictionStrategy);
677
+ this.mesh.setXorRouting(xorRouting);
678
+
679
+ this.log('โš™๏ธ Configuration applied successfully');
680
+ }
681
+
682
+ connectToPeer() {
683
+ const peerId = document.getElementById('manual-peer-id').value.trim();
684
+ if (!peerId) {
685
+ this.log('โŒ Please enter a peer ID', 'error');
686
+ return;
687
+ }
688
+
689
+ // PeerPigeon handles peer connections automatically through the mesh
690
+ this.log(`๐Ÿ” Attempting to connect to peer: ${peerId.substring(0, 8)}...`);
691
+ document.getElementById('manual-peer-id').value = '';
692
+ }
693
+
694
+ forceConnectAll() {
695
+ const attempts = this.mesh.forceConnectToAllPeers();
696
+ this.log(`๐Ÿš€ Forced ${attempts} connection attempts`);
697
+ }
698
+
699
+ // Messaging
700
+ sendBroadcastMessage() {
701
+ const message = document.getElementById('broadcast-message').value.trim();
702
+ if (!message) {
703
+ this.log('โŒ Please enter a message', 'error');
704
+ return;
705
+ }
706
+
707
+ try {
708
+ const messageId = this.mesh.sendMessage(message);
709
+ if (messageId) {
710
+ this.addMessageToHistory('broadcast', 'You', message);
711
+ this.log(`๐Ÿ“ข Broadcast message sent (ID: ${messageId.substring(0, 8)}...)`);
712
+ this.performanceMetrics.messagesSent++;
713
+ } else {
714
+ this.log('โŒ Failed to send broadcast message', 'error');
715
+ }
716
+ } catch (error) {
717
+ this.log(`โŒ Broadcast error: ${error.message}`, 'error');
718
+ }
719
+
720
+ document.getElementById('broadcast-message').value = '';
721
+ }
722
+
723
+ sendDirectMessage() {
724
+ // Try dropdown first, then manual input
725
+ const targetPeerSelect = document.getElementById('target-peer-select');
726
+ const targetPeerManual = document.getElementById('target-peer');
727
+ const targetPeer = (targetPeerSelect?.value || targetPeerManual?.value || '').trim();
728
+ const message = document.getElementById('direct-message').value.trim();
729
+
730
+ if (!targetPeer || !message) {
731
+ this.log('โŒ Please select/enter a target peer ID and message', 'error');
732
+ return;
733
+ }
734
+
735
+ try {
736
+ // Check encryption option
737
+ const shouldEncrypt = document.getElementById('encrypt-direct')?.checked || false;
738
+
739
+ let messageId;
740
+ if (shouldEncrypt && this.mesh.cryptoManager) {
741
+ messageId = this.mesh.sendEncryptedMessage(targetPeer, message);
742
+ this.log(`๐Ÿ”’ Encrypted direct message sent to ${targetPeer.substring(0, 8)}...`);
743
+ } else {
744
+ messageId = this.mesh.sendDirectMessage(targetPeer, message);
745
+ this.log(`๐Ÿ“จ Direct message sent to ${targetPeer.substring(0, 8)}...`);
746
+ }
747
+
748
+ if (messageId) {
749
+ this.addMessageToHistory('direct', 'You', `To ${targetPeer.substring(0, 8)}...: ${message}`, shouldEncrypt);
750
+ this.performanceMetrics.messagesSent++;
751
+ } else {
752
+ this.log('โŒ Failed to send direct message', 'error');
753
+ }
754
+ } catch (error) {
755
+ this.log(`โŒ Direct message error: ${error.message}`, 'error');
756
+ }
757
+
758
+ document.getElementById('direct-message').value = '';
759
+
760
+ // Clear manual input if dropdown was used
761
+ if (targetPeerSelect?.value && targetPeerManual) {
762
+ targetPeerManual.value = '';
763
+ }
764
+ }
765
+
766
+ // Media Management
767
+ async startMedia() {
768
+ // CRITICAL: Media can only be started AFTER data channels are established and keys exchanged
769
+ const connectedPeers = this.getConnectedPeers();
770
+ if (connectedPeers.length === 0) {
771
+ this.log('โŒ Cannot start media: No connected peers. Connect to peers first!', 'error');
772
+ return;
773
+ }
774
+
775
+ // Check that ALL connected peers have data channels ready
776
+ const peersWithDataChannels = connectedPeers.filter(peer =>
777
+ this.mesh.connectionManager && this.mesh.connectionManager.peers && this.mesh.connectionManager.peers.get(peer.id)?.dataChannelReady === true
778
+ );
779
+
780
+ if (peersWithDataChannels.length < connectedPeers.length) {
781
+ this.log(`โŒ Cannot start media: Not all peers have data channels ready. ${peersWithDataChannels.length}/${connectedPeers.length} peers ready`, 'error');
782
+ this.log('Wait for all peers to establish data channels before starting media', 'error');
783
+ return;
784
+ }
785
+
786
+ // Check that crypto keys are exchanged with ALL connected peers
787
+ console.log('๐Ÿ” Debug: Checking crypto manager state:', {
788
+ hasCryptoManager: !!this.mesh.cryptoManager,
789
+ hasPeerKeys: !!(this.mesh.cryptoManager && this.mesh.cryptoManager.peerKeys),
790
+ peerKeysType: this.mesh.cryptoManager ? typeof this.mesh.cryptoManager.peerKeys : 'no cryptoManager'
791
+ });
792
+
793
+ const peersWithKeys = connectedPeers.filter(peer => {
794
+ try {
795
+ const hasCrypto = this.mesh.cryptoManager && this.mesh.cryptoManager.peerKeys && this.mesh.cryptoManager.peerKeys.get(peer.id);
796
+ console.log(`๐Ÿ” Debug: Peer ${peer.id.substring(0, 8)} has crypto:`, hasCrypto);
797
+ return hasCrypto;
798
+ } catch (error) {
799
+ console.error(`๐Ÿ” Debug: Error checking peer ${peer.id.substring(0, 8)} crypto:`, error);
800
+ return false;
801
+ }
802
+ });
803
+
804
+ if (peersWithKeys.length < connectedPeers.length) {
805
+ this.log(`โŒ Cannot start media: Not all peers have exchanged crypto keys. ${peersWithKeys.length}/${connectedPeers.length} peers ready`, 'error');
806
+ this.log('Wait for key exchange to complete with all peers before starting media', 'error');
807
+ return;
808
+ }
809
+
810
+ this.log(`โœ… All ${connectedPeers.length} peers ready for media (data channels + key exchange complete)`, 'success');
811
+
812
+ const enableVideo = document.getElementById('enable-video').checked;
813
+ const enableAudio = document.getElementById('enable-audio').checked;
814
+ const cameraSelect = document.getElementById('camera-select');
815
+ const micSelect = document.getElementById('microphone-select');
816
+
817
+ if (!enableVideo && !enableAudio) {
818
+ this.log('โŒ Please enable at least video or audio', 'error');
819
+ return;
820
+ }
821
+
822
+ const options = {
823
+ video: enableVideo,
824
+ audio: enableAudio,
825
+ deviceIds: {}
826
+ };
827
+
828
+ if (enableVideo && cameraSelect.value) {
829
+ options.deviceIds.camera = cameraSelect.value;
830
+ }
831
+ if (enableAudio && micSelect.value) {
832
+ options.deviceIds.microphone = micSelect.value;
833
+ }
834
+
835
+ try {
836
+ // Check if crypto is ready before starting media
837
+ if (!this.mesh.cryptoManager || !this.mesh.cryptoManager.keypair) {
838
+ this.log('โš ๏ธ Warning: Crypto not ready. Generating keypair before starting media...', 'warning');
839
+
840
+ // Try to initialize crypto
841
+ if (this.mesh.cryptoManager) {
842
+ await this.mesh.cryptoManager.generateKeypair();
843
+ this.log('๐Ÿ” Keypair generated for secure media transmission');
844
+ } else {
845
+ this.log('โŒ Crypto manager not available. Media streams will not be encrypted!', 'error');
846
+ }
847
+ }
848
+
849
+ // Check for connected peers with exchanged keys
850
+ const connectedPeers = this.getConnectedPeers();
851
+ if (connectedPeers.length > 0) {
852
+ const peersWithKeys = connectedPeers.filter(peer =>
853
+ this.mesh.cryptoManager && this.mesh.cryptoManager.peerKeys && this.mesh.cryptoManager.peerKeys.get(peer.id)
854
+ );
855
+
856
+ if (peersWithKeys.length < connectedPeers.length) {
857
+ this.log(`โš ๏ธ Warning: Not all peers have exchanged keys. ${peersWithKeys.length}/${connectedPeers.length} peers ready for encrypted media`, 'warning');
858
+ }
859
+ }
860
+
861
+ await this.mesh.initializeMedia();
862
+
863
+ // CRITICAL: Enable remote stream reception from all peers BEFORE starting media
864
+ // This ensures we can receive streams from peers who start media before us
865
+ if (this.mesh.connectionManager) {
866
+ const connections = this.mesh.connectionManager.getAllConnections();
867
+ for (const connection of connections) {
868
+ if (connection.allowRemoteStreamEmission) {
869
+ connection.allowRemoteStreamEmission();
870
+ this.log(`๐Ÿ”“ Enabled remote streams from ${connection.peerId.substring(0, 8)}...`);
871
+ }
872
+ }
873
+ }
874
+
875
+ await this.mesh.startMedia(options);
876
+
877
+ this.log(`๐ŸŽฅ Media started (Video: ${enableVideo}, Audio: ${enableAudio})`);
878
+ this.updateMediaButtons(true);
879
+ this.updateCryptoStatus(); // Update crypto display
880
+ } catch (error) {
881
+ this.log(`โŒ Media start error: ${error.message}`, 'error');
882
+ }
883
+ }
884
+
885
+ // === NEW SELECTIVE STREAMING METHODS ===
886
+
887
+ async startSelectiveStreaming() {
888
+ const targetPeerSelect = document.getElementById('target-peer-select');
889
+ const selectedPeerIds = Array.from(targetPeerSelect.selectedOptions).map(option => option.value);
890
+
891
+ if (selectedPeerIds.length === 0) {
892
+ this.log('โŒ Please select at least one peer for selective streaming', 'error');
893
+ return;
894
+ }
895
+
896
+ const enableVideo = document.getElementById('enable-video').checked;
897
+ const enableAudio = document.getElementById('enable-audio').checked;
898
+ const cameraSelect = document.getElementById('camera-select');
899
+ const micSelect = document.getElementById('microphone-select');
900
+
901
+ if (!enableVideo && !enableAudio) {
902
+ this.log('โŒ Please enable at least video or audio', 'error');
903
+ return;
904
+ }
905
+
906
+ const options = {
907
+ video: enableVideo,
908
+ audio: enableAudio,
909
+ deviceIds: {}
910
+ };
911
+
912
+ if (enableVideo && cameraSelect.value) {
913
+ options.deviceIds.camera = cameraSelect.value;
914
+ }
915
+ if (enableAudio && micSelect.value) {
916
+ options.deviceIds.microphone = micSelect.value;
917
+ }
918
+
919
+ try {
920
+ await this.mesh.initializeMedia();
921
+ await this.mesh.startSelectiveStream(selectedPeerIds, options);
922
+
923
+ const streamType = selectedPeerIds.length === 1 ? '1:1' : '1:many';
924
+ this.log(`๐ŸŽฏ Selective ${streamType} streaming started to: ${selectedPeerIds.map(id => id.substring(0, 8) + '...').join(', ')}`);
925
+ this.updateMediaButtons(true);
926
+ } catch (error) {
927
+ this.log(`โŒ Selective streaming error: ${error.message}`, 'error');
928
+ }
929
+ }
930
+
931
+ async stopSelectiveStreaming() {
932
+ try {
933
+ await this.mesh.stopSelectiveStream(false); // Stop entirely
934
+ this.log('๐Ÿ›‘ Selective streaming stopped');
935
+ this.updateMediaButtons(false);
936
+ } catch (error) {
937
+ this.log(`โŒ Stop selective streaming error: ${error.message}`, 'error');
938
+ }
939
+ }
940
+
941
+ async switchToBroadcastMode() {
942
+ try {
943
+ await this.mesh.stopSelectiveStream(true); // Return to broadcast
944
+ this.log('๐Ÿ“ก Switched to broadcast mode - streaming to all peers');
945
+ } catch (error) {
946
+ this.log(`โŒ Switch to broadcast error: ${error.message}`, 'error');
947
+ }
948
+ }
949
+
950
+ async blockStreamingToPeer() {
951
+ const targetPeerSelect = document.getElementById('target-peer-select');
952
+ const selectedPeerIds = Array.from(targetPeerSelect.selectedOptions).map(option => option.value);
953
+
954
+ if (selectedPeerIds.length === 0) {
955
+ this.log('โŒ Please select peers to block streaming to', 'error');
956
+ return;
957
+ }
958
+
959
+ try {
960
+ await this.mesh.blockStreamingToPeers(selectedPeerIds);
961
+ this.log(`๐Ÿšซ Blocked streaming to: ${selectedPeerIds.map(id => id.substring(0, 8) + '...').join(', ')}`);
962
+ } catch (error) {
963
+ this.log(`โŒ Block streaming error: ${error.message}`, 'error');
964
+ }
965
+ }
966
+
967
+ async allowStreamingToPeer() {
968
+ const targetPeerSelect = document.getElementById('target-peer-select');
969
+ const selectedPeerIds = Array.from(targetPeerSelect.selectedOptions).map(option => option.value);
970
+
971
+ if (selectedPeerIds.length === 0) {
972
+ this.log('โŒ Please select peers to allow streaming to', 'error');
973
+ return;
974
+ }
975
+
976
+ try {
977
+ await this.mesh.allowStreamingToPeers(selectedPeerIds);
978
+ this.log(`โœ… Allowed streaming to: ${selectedPeerIds.map(id => id.substring(0, 8) + '...').join(', ')}`);
979
+ } catch (error) {
980
+ this.log(`โŒ Allow streaming error: ${error.message}`, 'error');
981
+ }
982
+ }
983
+
984
+ showStreamingStatus() {
985
+ const streamingPeers = this.mesh.getStreamingPeers();
986
+ const blockedPeers = this.mesh.getBlockedStreamingPeers();
987
+ const isStreamingToAll = this.mesh.isStreamingToAll();
988
+
989
+ this.log('๐Ÿ“Š Current Streaming Status:');
990
+ this.log(`๐ŸŽฏ Mode: ${isStreamingToAll ? 'Broadcast (All Peers)' : 'Selective'}`);
991
+ this.log(`๐Ÿ“ก Streaming to ${streamingPeers.length} peer(s): ${streamingPeers.map(id => id.substring(0, 8) + '...').join(', ')}`);
992
+ if (blockedPeers.length > 0) {
993
+ this.log(`๐Ÿšซ Blocked ${blockedPeers.length} peer(s): ${blockedPeers.map(id => id.substring(0, 8) + '...').join(', ')}`);
994
+ }
995
+
996
+ // Update UI status display
997
+ const statusDiv = document.getElementById('streaming-status');
998
+ if (statusDiv) {
999
+ statusDiv.innerHTML = `
1000
+ <div><strong>Mode:</strong> ${isStreamingToAll ? 'Broadcast' : 'Selective'}</div>
1001
+ <div><strong>Streaming to:</strong> ${streamingPeers.length} peer(s)</div>
1002
+ <div><strong>Blocked:</strong> ${blockedPeers.length} peer(s)</div>
1003
+ `;
1004
+ }
1005
+ }
1006
+
1007
+ async stopMedia() {
1008
+ try {
1009
+ // CRITICAL FIX: Only block remote streams if crypto security is required
1010
+ // For video streaming tests, we want streams to flow freely
1011
+ const isVideoStreamingTest = window.location.search.includes('test=video') ||
1012
+ document.title.includes('Video Test') ||
1013
+ this.testMode === 'video' ||
1014
+ window.DISABLE_CRYPTO_BLOCKING === true ||
1015
+ navigator.userAgent.includes('HeadlessChrome');
1016
+
1017
+ console.log('๐Ÿ” STOP MEDIA DEBUG:', {
1018
+ url: window.location.href,
1019
+ search: window.location.search,
1020
+ title: document.title,
1021
+ testMode: this.testMode,
1022
+ disableCrypto: window.DISABLE_CRYPTO_BLOCKING,
1023
+ userAgent: navigator.userAgent.includes('HeadlessChrome'),
1024
+ isVideoTest: isVideoStreamingTest
1025
+ });
1026
+
1027
+ if (!isVideoStreamingTest && this.mesh.connectionManager) {
1028
+ // Only block streams in secure/production mode
1029
+ console.log('๐Ÿ”’ BLOCKING remote streams (non-test mode)');
1030
+ const connections = this.mesh.connectionManager.getAllConnections();
1031
+ for (const connection of connections) {
1032
+ if (connection.blockRemoteStreamEmission) {
1033
+ connection.blockRemoteStreamEmission();
1034
+ this.log(`๐Ÿ”’ Disabled remote streams from ${connection.peerId.substring(0, 8)}...`);
1035
+ }
1036
+ }
1037
+ } else if (isVideoStreamingTest) {
1038
+ console.log('๐Ÿ”“ KEEPING remote streams enabled (video test mode detected)');
1039
+ this.log('๐Ÿ”“ Video test mode: Keeping remote streams enabled for testing');
1040
+ }
1041
+
1042
+ await this.mesh.stopMedia();
1043
+ this.log('๐ŸŽฅ Media stopped');
1044
+ this.updateMediaButtons(false);
1045
+ } catch (error) {
1046
+ this.log(`โŒ Media stop error: ${error.message}`, 'error');
1047
+ }
1048
+ }
1049
+
1050
+ toggleVideo() {
1051
+ try {
1052
+ const enabled = this.mesh.toggleVideo();
1053
+ this.log(`๐ŸŽฅ Video ${enabled ? 'enabled' : 'disabled'}`);
1054
+ this.updateMediaInfo();
1055
+ } catch (error) {
1056
+ this.log(`โŒ Video toggle error: ${error.message}`, 'error');
1057
+ }
1058
+ }
1059
+
1060
+ toggleAudio() {
1061
+ try {
1062
+ const enabled = this.mesh.toggleAudio();
1063
+ this.log(`๐ŸŽค Audio ${enabled ? 'enabled' : 'disabled'}`);
1064
+ this.updateMediaInfo();
1065
+ } catch (error) {
1066
+ this.log(`โŒ Audio toggle error: ${error.message}`, 'error');
1067
+ }
1068
+ }
1069
+
1070
+ async enumerateDevices() {
1071
+ try {
1072
+ const devices = await this.mesh.enumerateMediaDevices();
1073
+ this.populateDeviceSelectors(devices);
1074
+ this.log(`๐ŸŽฅ Found ${devices.cameras.length} cameras, ${devices.microphones.length} microphones`);
1075
+ } catch (error) {
1076
+ this.log(`โŒ Device enumeration error: ${error.message}`, 'error');
1077
+ }
1078
+ }
1079
+
1080
+ // DHT Operations
1081
+ async dhtPut() {
1082
+ const key = document.getElementById('dht-key').value.trim();
1083
+ const valueStr = document.getElementById('dht-value').value.trim();
1084
+ const ttl = document.getElementById('dht-ttl').value;
1085
+
1086
+ if (!key || !valueStr) {
1087
+ this.log('โŒ Please enter both key and value', 'error');
1088
+ return;
1089
+ }
1090
+
1091
+ try {
1092
+ let value;
1093
+ try {
1094
+ value = JSON.parse(valueStr);
1095
+ } catch {
1096
+ value = valueStr; // Use as string if not valid JSON
1097
+ }
1098
+
1099
+ const options = {};
1100
+ if (ttl) options.ttl = parseInt(ttl);
1101
+
1102
+ await this.mesh.dhtPut(key, value, options);
1103
+ this.logDHT(`โœ… DHT PUT (raw): ${key} = ${JSON.stringify(value)}`);
1104
+ } catch (error) {
1105
+ this.logDHT(`โŒ PUT error: ${error.message}`, 'error');
1106
+ }
1107
+ }
1108
+
1109
+ async dhtUpdate() {
1110
+ const key = document.getElementById('dht-key').value.trim();
1111
+ const valueStr = document.getElementById('dht-value').value.trim();
1112
+
1113
+ if (!key || !valueStr) {
1114
+ this.log('โŒ Please enter both key and value', 'error');
1115
+ return;
1116
+ }
1117
+
1118
+ try {
1119
+ let value;
1120
+ try {
1121
+ value = JSON.parse(valueStr);
1122
+ } catch {
1123
+ value = valueStr;
1124
+ }
1125
+
1126
+ await this.mesh.dhtUpdate(key, value);
1127
+ this.logDHT(`๐Ÿ”„ DHT UPDATE (raw): ${key} = ${JSON.stringify(value)}`);
1128
+ } catch (error) {
1129
+ this.logDHT(`โŒ UPDATE error: ${error.message}`, 'error');
1130
+ }
1131
+ }
1132
+
1133
+ async dhtGet() {
1134
+ const key = document.getElementById('dht-get-key').value.trim();
1135
+ if (!key) {
1136
+ this.log('โŒ Please enter a key', 'error');
1137
+ return;
1138
+ }
1139
+
1140
+ try {
1141
+ const value = await this.mesh.dhtGet(key);
1142
+ const resultDiv = document.getElementById('dht-result');
1143
+
1144
+ if (value !== null) {
1145
+ resultDiv.innerHTML = `<strong>Key:</strong> ${key}<br><strong>Value:</strong> <pre>${JSON.stringify(value, null, 2)}</pre>`;
1146
+ this.logDHT(`โœ… DHT GET (raw): ${key} = ${JSON.stringify(value)}`);
1147
+ } else {
1148
+ resultDiv.innerHTML = `<strong>Key:</strong> ${key}<br><strong>Value:</strong> <em>Not found</em>`;
1149
+ this.logDHT(`โŒ DHT GET (raw): ${key} not found`);
1150
+ }
1151
+ } catch (error) {
1152
+ this.logDHT(`โŒ GET error: ${error.message}`, 'error');
1153
+ }
1154
+ }
1155
+
1156
+ async dhtDelete() {
1157
+ const key = document.getElementById('dht-get-key').value.trim();
1158
+ if (!key) {
1159
+ this.log('โŒ Please enter a key', 'error');
1160
+ return;
1161
+ }
1162
+
1163
+ try {
1164
+ const deleted = await this.mesh.dhtDelete(key);
1165
+ if (deleted) {
1166
+ this.logDHT(`๐Ÿ—‘๏ธ DHT DELETE (raw): ${key} removed`);
1167
+ } else {
1168
+ this.logDHT(`โŒ DHT DELETE (raw): ${key} not found`);
1169
+ }
1170
+ } catch (error) {
1171
+ this.logDHT(`โŒ DELETE error: ${error.message}`, 'error');
1172
+ }
1173
+ }
1174
+
1175
+ async dhtSubscribe() {
1176
+ const key = document.getElementById('dht-subscribe-key').value.trim();
1177
+ if (!key) {
1178
+ this.log('โŒ Please enter a key', 'error');
1179
+ return;
1180
+ }
1181
+
1182
+ try {
1183
+ await this.mesh.dhtSubscribe(key);
1184
+ this.activeSubscriptions.add(key);
1185
+ this.updateSubscriptionsList();
1186
+ this.logDHT(`๐Ÿ”” DHT SUBSCRIBE (raw): ${key}`);
1187
+ } catch (error) {
1188
+ this.logDHT(`โŒ SUBSCRIBE error: ${error.message}`, 'error');
1189
+ }
1190
+ }
1191
+
1192
+ async dhtUnsubscribe() {
1193
+ const key = document.getElementById('dht-subscribe-key').value.trim();
1194
+ if (!key) {
1195
+ this.log('โŒ Please enter a key', 'error');
1196
+ return;
1197
+ }
1198
+
1199
+ try {
1200
+ await this.mesh.dhtUnsubscribe(key);
1201
+ this.activeSubscriptions.delete(key);
1202
+ this.updateSubscriptionsList();
1203
+ this.logDHT(`๐Ÿ”• DHT UNSUBSCRIBE (raw): ${key}`);
1204
+ } catch (error) {
1205
+ this.logDHT(`โŒ UNSUBSCRIBE error: ${error.message}`, 'error');
1206
+ }
1207
+ }
1208
+
1209
+ // Crypto Operations
1210
+ async sendEncryptedMessage() {
1211
+ const message = document.getElementById('encrypted-message').value.trim();
1212
+ const groupId = document.getElementById('group-id').value.trim() || null;
1213
+
1214
+ if (!message) {
1215
+ this.log('โŒ Please enter a message', 'error');
1216
+ return;
1217
+ }
1218
+
1219
+ try {
1220
+ const messageId = await this.mesh.sendEncryptedBroadcast(message, groupId);
1221
+ if (messageId) {
1222
+ this.logCrypto(`๐Ÿ” Encrypted broadcast sent (ID: ${messageId.substring(0, 8)}...)`);
1223
+ this.addMessageToHistory('encrypted', 'You', `๐Ÿ” ${message}`);
1224
+ } else {
1225
+ this.logCrypto('โŒ Failed to send encrypted message', 'error');
1226
+ }
1227
+ } catch (error) {
1228
+ this.logCrypto(`โŒ Encryption error: ${error.message}`, 'error');
1229
+ }
1230
+
1231
+ document.getElementById('encrypted-message').value = '';
1232
+ }
1233
+
1234
+ async exchangeKeys() {
1235
+ const peerId = document.getElementById('key-exchange-peer').value.trim();
1236
+ if (!peerId) {
1237
+ this.log('โŒ Please enter a peer ID', 'error');
1238
+ return;
1239
+ }
1240
+
1241
+ try {
1242
+ await this.mesh.exchangeKeysWithPeer(peerId);
1243
+ this.logCrypto(`๐Ÿ” Key exchange initiated with ${peerId.substring(0, 8)}...`);
1244
+ } catch (error) {
1245
+ this.logCrypto(`โŒ Key exchange error: ${error.message}`, 'error');
1246
+ }
1247
+ }
1248
+
1249
+ async addPeerKey() {
1250
+ const peerId = document.getElementById('manual-peer-id').value.trim();
1251
+ const publicKey = document.getElementById('manual-public-key').value.trim();
1252
+
1253
+ if (!peerId || !publicKey) {
1254
+ this.log('โŒ Please enter both peer ID and public key', 'error');
1255
+ return;
1256
+ }
1257
+
1258
+ try {
1259
+ await this.mesh.addPeerKey(peerId, publicKey);
1260
+ this.logCrypto(`๐Ÿ” Public key added for ${peerId.substring(0, 8)}...`);
1261
+ this.updateCryptoStatus();
1262
+ } catch (error) {
1263
+ this.logCrypto(`โŒ Add key error: ${error.message}`, 'error');
1264
+ }
1265
+ }
1266
+
1267
+ async forceCryptoInit() {
1268
+ this.log('๐Ÿ”ง Force initializing crypto system...');
1269
+
1270
+ try {
1271
+ if (!this.mesh.cryptoManager) {
1272
+ this.log('โŒ Crypto manager not available', 'error');
1273
+ return;
1274
+ }
1275
+
1276
+ // Force keypair generation if not already done
1277
+ if (this.mesh.cryptoManager && !this.mesh.cryptoManager.keypair) {
1278
+ this.log('๐Ÿ”‘ Generating keypair...');
1279
+ await this.mesh.cryptoManager.generateKeypair();
1280
+ this.log('โœ… Keypair generated');
1281
+ } else if (this.mesh.cryptoManager) {
1282
+ this.log('โœ… Keypair already exists');
1283
+ }
1284
+
1285
+ // Update status
1286
+ this.updateCryptoStatus();
1287
+
1288
+ // Log crypto system state
1289
+ const publicKey = this.mesh.cryptoManager?.getPublicKey() || this.mesh.exportPublicKey?.();
1290
+ this.logCrypto(`๐Ÿ” Crypto system initialized. Public key: ${publicKey ? publicKey.substring(0, 16) + '...' : 'Not available'}`);
1291
+
1292
+ } catch (error) {
1293
+ this.log(`โŒ Failed to initialize crypto: ${error.message}`, 'error');
1294
+ }
1295
+ }
1296
+
1297
+ async exchangeKeysWithConnectedPeers() {
1298
+ this.log('๐Ÿ”‘ Initiating key exchange with all connected peers...');
1299
+
1300
+ try {
1301
+ if (!this.mesh.cryptoManager) {
1302
+ this.log('โŒ Crypto manager not available', 'error');
1303
+ return;
1304
+ }
1305
+
1306
+ const connectedPeers = this.getConnectedPeers();
1307
+ if (connectedPeers.length === 0) {
1308
+ this.log('โš ๏ธ No connected peers to exchange keys with', 'warn');
1309
+ return;
1310
+ }
1311
+
1312
+ this.log(`๐Ÿ”„ Exchanging keys with ${connectedPeers.length} connected peer(s)...`);
1313
+
1314
+ const exchanges = connectedPeers.map(async (peer) => {
1315
+ try {
1316
+ this.log(`๐Ÿ” Exchanging keys with ${peer.id.substring(0, 8)}...`);
1317
+ await this.mesh.exchangeKeysWithPeer(peer.id);
1318
+ this.log(`โœ… Key exchange completed with ${peer.id.substring(0, 8)}...`);
1319
+ } catch (error) {
1320
+ this.log(`โŒ Key exchange failed with ${peer.id.substring(0, 8)}...: ${error.message}`, 'error');
1321
+ }
1322
+ });
1323
+
1324
+ await Promise.all(exchanges);
1325
+
1326
+ // Update status after all exchanges
1327
+ setTimeout(() => {
1328
+ this.updateCryptoStatus();
1329
+ }, 1000);
1330
+
1331
+ this.log('๐ŸŽ‰ Key exchange process completed');
1332
+
1333
+ } catch (error) {
1334
+ this.log(`โŒ Failed to exchange keys: ${error.message}`, 'error');
1335
+ }
1336
+ }
1337
+
1338
+ // Network Information
1339
+ updateNetworkInfo() {
1340
+ const status = this.mesh.getStatus();
1341
+ const connectedPeers = this.getConnectedPeers();
1342
+
1343
+ document.getElementById('network-connected').textContent = status.connected ? 'Yes' : 'No';
1344
+ document.getElementById('network-peer-count').textContent = connectedPeers.length;
1345
+ document.getElementById('network-discovered-count').textContent = status.discoveredCount;
1346
+ document.getElementById('network-signaling-url').textContent = status.signalingUrl || 'None';
1347
+ document.getElementById('network-uptime').textContent = this.formatUptime(status.uptime);
1348
+ document.getElementById('network-can-accept').textContent = this.mesh.canAcceptMorePeers() ? 'Yes' : 'No';
1349
+ }
1350
+
1351
+ getConnectedPeers() {
1352
+ if (!this.mesh.connectionManager) return [];
1353
+ const connections = this.mesh.connectionManager.getAllConnections();
1354
+ return connections
1355
+ .filter(conn => conn.getStatus() === 'connected')
1356
+ .map(conn => ({ id: conn.peerId, connection: conn }));
1357
+ }
1358
+
1359
+ getPeerStates() {
1360
+ const summary = this.mesh.getPeerStateSummary();
1361
+ const summaryDiv = document.getElementById('peer-state-summary');
1362
+
1363
+ summaryDiv.innerHTML = `
1364
+ <div class="peer-state-overview">
1365
+ <div>Total: ${summary.total}</div>
1366
+ <div>Connected: ${summary.connected}</div>
1367
+ <div>Connecting: ${summary.connecting}</div>
1368
+ <div>Failed: ${summary.failed}</div>
1369
+ </div>
1370
+ <div class="peer-states-detail">
1371
+ ${Object.entries(summary.states).map(([peerId, state]) =>
1372
+ `<div class="peer-state-item">
1373
+ <span class="peer-id">${peerId.substring(0, 8)}...</span>
1374
+ <span class="peer-state ${state}">${state}</span>
1375
+ </div>`
1376
+ ).join('')}
1377
+ </div>
1378
+ `;
1379
+ }
1380
+
1381
+ startConnectionMonitoring() {
1382
+ this.mesh.startConnectionMonitoring();
1383
+ this.isMonitoring = true;
1384
+ document.getElementById('start-monitoring-btn').disabled = true;
1385
+ document.getElementById('stop-monitoring-btn').disabled = false;
1386
+ this.log('๐Ÿ“Š Connection monitoring started');
1387
+ }
1388
+
1389
+ stopConnectionMonitoring() {
1390
+ this.mesh.stopConnectionMonitoring();
1391
+ this.isMonitoring = false;
1392
+ document.getElementById('start-monitoring-btn').disabled = false;
1393
+ document.getElementById('stop-monitoring-btn').disabled = true;
1394
+ this.log('๐Ÿ“Š Connection monitoring stopped');
1395
+ }
1396
+
1397
+ debugConnectivity() {
1398
+ this.mesh.debugConnectivity();
1399
+ this.log('๐Ÿ” Connectivity debug information logged to console');
1400
+ }
1401
+
1402
+ // Testing Functions
1403
+ validatePeerId() {
1404
+ const peerId = document.getElementById('test-peer-id').value.trim();
1405
+ if (!peerId) {
1406
+ this.log('โŒ Please enter a peer ID', 'error');
1407
+ return;
1408
+ }
1409
+
1410
+ const isValid = PeerPigeon.PeerPigeonMesh.validatePeerId(peerId);
1411
+ const result = isValid ? 'โœ… Valid peer ID' : 'โŒ Invalid peer ID';
1412
+
1413
+ document.getElementById('utility-results').innerHTML = `
1414
+ <div>Peer ID: ${peerId}</div>
1415
+ <div>Result: ${result}</div>
1416
+ <div>Length: ${peerId.length} characters</div>
1417
+ <div>Expected: 40 characters (hex)</div>
1418
+ `;
1419
+
1420
+ this.addTestResult('Peer ID Validation', result, isValid ? 'success' : 'error');
1421
+ }
1422
+
1423
+ async runPerformanceTest() {
1424
+ const messageCount = parseInt(document.getElementById('test-message-count').value);
1425
+ const messageSize = parseInt(document.getElementById('test-message-size').value);
1426
+
1427
+ this.log(`๐Ÿƒ Starting performance test: ${messageCount} messages of ${messageSize} characters`);
1428
+
1429
+ const testMessage = 'x'.repeat(messageSize);
1430
+ const startTime = Date.now();
1431
+ let successCount = 0;
1432
+ let failCount = 0;
1433
+
1434
+ for (let i = 0; i < messageCount; i++) {
1435
+ try {
1436
+ const messageId = this.mesh.sendMessage(`${testMessage} #${i + 1}`);
1437
+ if (messageId) {
1438
+ successCount++;
1439
+ } else {
1440
+ failCount++;
1441
+ }
1442
+
1443
+ // Small delay to prevent overwhelming the system
1444
+ if (i % 10 === 0) {
1445
+ await new Promise(resolve => setTimeout(resolve, 10));
1446
+ }
1447
+ } catch (error) {
1448
+ failCount++;
1449
+ }
1450
+ }
1451
+
1452
+ const endTime = Date.now();
1453
+ const duration = endTime - startTime;
1454
+ const messagesPerSecond = ((successCount / duration) * 1000).toFixed(2);
1455
+
1456
+ const result = `
1457
+ Duration: ${duration}ms
1458
+ Success: ${successCount}/${messageCount}
1459
+ Failed: ${failCount}
1460
+ Rate: ${messagesPerSecond} msg/sec
1461
+ `;
1462
+
1463
+ document.getElementById('performance-results').innerHTML = `<pre>${result}</pre>`;
1464
+ this.addTestResult('Performance Test', result, successCount > failCount ? 'success' : 'warning');
1465
+ }
1466
+
1467
+ async runStressTest() {
1468
+ this.log('โš ๏ธ Starting stress test - this may impact performance');
1469
+
1470
+ // Stress test with rapid WebDHT operations and message sending
1471
+ const operations = [];
1472
+ const startTime = Date.now();
1473
+
1474
+ // WebDHT stress test
1475
+ for (let i = 0; i < 20; i++) {
1476
+ operations.push(
1477
+ this.mesh.dhtPut(`stress-test-${i}`, { value: i, timestamp: Date.now() })
1478
+ .catch(err => ({ error: err.message }))
1479
+ );
1480
+ }
1481
+
1482
+ // Message stress test
1483
+ for (let i = 0; i < 50; i++) {
1484
+ try {
1485
+ this.mesh.sendMessage(`Stress test message #${i + 1}`);
1486
+ } catch (error) {
1487
+ operations.push(Promise.resolve({ error: error.message }));
1488
+ }
1489
+ }
1490
+
1491
+ const results = await Promise.allSettled(operations);
1492
+ const endTime = Date.now();
1493
+ const duration = endTime - startTime;
1494
+
1495
+ const successful = results.filter(r => r.status === 'fulfilled' && !r.value?.error).length;
1496
+ const failed = results.length - successful;
1497
+
1498
+ const result = `
1499
+ Duration: ${duration}ms
1500
+ Operations: ${results.length}
1501
+ Successful: ${successful}
1502
+ Failed: ${failed}
1503
+ Success Rate: ${((successful / results.length) * 100).toFixed(1)}%
1504
+ `;
1505
+
1506
+ document.getElementById('performance-results').innerHTML = `<pre>${result}</pre>`;
1507
+ this.addTestResult('Stress Test', result, successful > failed ? 'success' : 'warning');
1508
+ }
1509
+
1510
+ testInvalidPeerConnection() {
1511
+ const invalidPeerId = 'invalid-peer-id-12345';
1512
+ try {
1513
+ // This should fail gracefully
1514
+ this.mesh.sendDirectMessage(invalidPeerId, 'Test message');
1515
+ this.addTestResult('Invalid Peer Test', 'Message sent (unexpected)', 'warning');
1516
+ } catch (error) {
1517
+ this.addTestResult('Invalid Peer Test', `Handled gracefully: ${error.message}`, 'success');
1518
+ }
1519
+ }
1520
+
1521
+ testMalformedMessage() {
1522
+ try {
1523
+ // Test with various malformed messages
1524
+ const malformedMessages = [
1525
+ undefined,
1526
+ null,
1527
+ { circular: {} },
1528
+ new Date(),
1529
+ () => {}
1530
+ ];
1531
+
1532
+ malformedMessages[2].circular.ref = malformedMessages[2]; // Create circular reference
1533
+
1534
+ const results = [];
1535
+ malformedMessages.forEach((msg, index) => {
1536
+ try {
1537
+ const messageId = this.mesh.sendMessage(msg);
1538
+ results.push(`Message ${index + 1}: ${messageId ? 'Sent' : 'Failed'}`);
1539
+ } catch (error) {
1540
+ results.push(`Message ${index + 1}: Error handled - ${error.message}`);
1541
+ }
1542
+ });
1543
+
1544
+ this.addTestResult('Malformed Message Test', results.join('\n'), 'success');
1545
+ } catch (error) {
1546
+ this.addTestResult('Malformed Message Test', `Error: ${error.message}`, 'error');
1547
+ }
1548
+ }
1549
+
1550
+ async testDHTLimits() {
1551
+ try {
1552
+ // Test with very large data
1553
+ const largeData = 'x'.repeat(1000000); // 1MB string
1554
+ const startTime = Date.now();
1555
+
1556
+ await this.mesh.dhtPut('large-data-test', largeData);
1557
+ const stored = await this.mesh.dhtGet('large-data-test');
1558
+ const endTime = Date.now();
1559
+
1560
+ const success = stored === largeData;
1561
+ const result = `
1562
+ Data size: 1MB
1563
+ Duration: ${endTime - startTime}ms
1564
+ Success: ${success}
1565
+ `;
1566
+
1567
+ this.addTestResult('DHT Limits Test', result, success ? 'success' : 'error');
1568
+ } catch (error) {
1569
+ this.addTestResult('DHT Limits Test', `Limit enforced: ${error.message}`, 'success');
1570
+ }
1571
+ }
1572
+
1573
+ exportLogs() {
1574
+ const logs = {
1575
+ systemLog: this.getLogEntries('system-log'),
1576
+ messageHistory: this.messageHistory,
1577
+ testResults: this.testResults,
1578
+ dhtLog: this.getLogEntries('dht-log'),
1579
+ cryptoLog: this.getLogEntries('crypto-log'),
1580
+ networkStatus: this.mesh.getStatus(),
1581
+ timestamp: new Date().toISOString()
1582
+ };
1583
+
1584
+ const dataStr = JSON.stringify(logs, null, 2);
1585
+ const dataBlob = new Blob([dataStr], { type: 'application/json' });
1586
+ const url = URL.createObjectURL(dataBlob);
1587
+
1588
+ const link = document.createElement('a');
1589
+ link.href = url;
1590
+ link.download = `peerpigeon-logs-${Date.now()}.json`;
1591
+ link.click();
1592
+
1593
+ URL.revokeObjectURL(url);
1594
+ this.log('๐Ÿ“ Logs exported successfully');
1595
+ }
1596
+
1597
+ // Event Handlers
1598
+ handleStatusChange(data) {
1599
+ this.updatePeerInfo();
1600
+ this.updateNetworkInfo();
1601
+ this.updateNetworkStatus();
1602
+
1603
+ switch (data.type) {
1604
+ case 'connected':
1605
+ this.log('๐ŸŸข Connected to signaling server');
1606
+ this.updateConnectionButtons(true);
1607
+ break;
1608
+ case 'disconnected':
1609
+ this.log('๐Ÿ”ด Disconnected from signaling server');
1610
+ this.updateConnectionButtons(false);
1611
+ break;
1612
+ case 'connecting':
1613
+ this.log('๐ŸŸก Connecting to signaling server...');
1614
+ break;
1615
+ case 'error':
1616
+ this.log(`โŒ ${data.message}`, 'error');
1617
+ break;
1618
+ case 'network':
1619
+ this.log(`๐ŸŒ Network: ${data.message}`, data.fallbackMode ? 'warning' : 'info');
1620
+ if (data.fallbackMode) {
1621
+ this.log(`โš ๏ธ Switched to global fallback from ${data.originalNetwork}`, 'warning');
1622
+ }
1623
+ break;
1624
+ case 'setting':
1625
+ if (data.setting === 'networkName') {
1626
+ this.log(`๐ŸŒ Network name changed to: ${data.value}`, 'info');
1627
+ }
1628
+ break;
1629
+ }
1630
+ }
1631
+
1632
+ handleMessageReceived(data) {
1633
+ if (data.from !== this.mesh.peerId) {
1634
+ console.log('๐Ÿ” DEBUG handleMessageReceived:', data);
1635
+
1636
+ const messageType = data.direct ? 'direct' : 'broadcast';
1637
+ const sender = data.from.substring(0, 8) + '...';
1638
+
1639
+ // Handle content properly - it might be an object or string
1640
+ let content = data.content;
1641
+ let isEncrypted = false;
1642
+
1643
+ if (typeof content === 'object') {
1644
+ // Check if it's an encrypted message object
1645
+ if (content.encrypted && content.data) {
1646
+ content = content.data;
1647
+ isEncrypted = true;
1648
+ } else if (content.message) {
1649
+ content = content.message;
1650
+ } else if (content.broadcast && content.data) {
1651
+ content = content.data;
1652
+ isEncrypted = content.encrypted || false;
1653
+ } else {
1654
+ // Fallback: stringify the object
1655
+ content = JSON.stringify(content);
1656
+ }
1657
+ }
1658
+
1659
+ // Also check if data.encrypted flag is set
1660
+ if (data.encrypted) {
1661
+ isEncrypted = true;
1662
+ }
1663
+
1664
+ const finalContent = data.direct ? `(DM) ${content}` : content;
1665
+
1666
+ this.addMessageToHistory(messageType, sender, finalContent, isEncrypted);
1667
+ this.performanceMetrics.messagesReceived++;
1668
+ }
1669
+ }
1670
+
1671
+ handleDHTValueChanged(data) {
1672
+ this.logDHT(`๐Ÿ”” DHT value changed (raw): ${data.key} = ${JSON.stringify(data.newValue)}`);
1673
+ }
1674
+
1675
+ handleLocalStreamStarted(data) {
1676
+ const localVideo = document.getElementById('local-video');
1677
+ localVideo.srcObject = data.stream;
1678
+ localVideo.style.display = 'block';
1679
+ document.getElementById('media-status').textContent = 'Local stream active';
1680
+ this.updateMediaInfo();
1681
+ }
1682
+
1683
+ handleLocalStreamStopped() {
1684
+ const localVideo = document.getElementById('local-video');
1685
+ localVideo.srcObject = null;
1686
+ localVideo.style.display = 'none';
1687
+ document.getElementById('media-status').textContent = 'No active media stream';
1688
+ this.updateMediaInfo();
1689
+ }
1690
+
1691
+ handleRemoteStream(data) {
1692
+ this.addRemoteStream(data.peerId, data.stream);
1693
+ this.log(`๐ŸŽฅ Remote stream received from ${data.peerId.substring(0, 8)}...`);
1694
+ }
1695
+
1696
+ // UI Update Methods
1697
+ updatePeerInfo() {
1698
+ document.getElementById('peer-id').textContent = this.mesh.peerId || 'Generating...';
1699
+
1700
+ const status = this.mesh.getStatus();
1701
+ const statusElement = document.getElementById('status');
1702
+ statusElement.textContent = status.connected ? 'Connected' : 'Disconnected';
1703
+ statusElement.className = `status ${status.connected ? 'connected' : 'disconnected'}`;
1704
+
1705
+ // Use the same method as updatePeersList for consistency
1706
+ const connectedPeers = this.getConnectedPeers();
1707
+ document.getElementById('peer-count').textContent = connectedPeers.length;
1708
+ }
1709
+
1710
+ updateConnectionButtons(connected) {
1711
+ document.getElementById('connect-btn').disabled = connected;
1712
+ document.getElementById('disconnect-btn').disabled = !connected;
1713
+ document.getElementById('cleanup-btn').disabled = !connected;
1714
+ }
1715
+
1716
+ updateMediaButtons(active) {
1717
+ document.getElementById('start-media-btn').disabled = active;
1718
+ document.getElementById('stop-media-btn').disabled = !active;
1719
+ document.getElementById('toggle-video-btn').disabled = !active;
1720
+ document.getElementById('toggle-audio-btn').disabled = !active;
1721
+ }
1722
+
1723
+ updatePeersList() {
1724
+ const connectedPeers = this.getConnectedPeers();
1725
+ const peersList = document.getElementById('peers-list');
1726
+ const targetPeerSelect = document.getElementById('target-peer-select');
1727
+
1728
+ // Update main peers list
1729
+ if (connectedPeers.length === 0) {
1730
+ peersList.innerHTML = '<p class="empty-state">No peers connected</p>';
1731
+ } else {
1732
+ const peersHtml = connectedPeers.map(peer => `
1733
+ <div class="peer-item">
1734
+ <div class="peer-info-item">
1735
+ <div class="peer-id">${peer.id.substring(0, 8)}...${peer.id.substring(-8)}</div>
1736
+ <div class="peer-status">${peer.connection.getStatus()}</div>
1737
+ </div>
1738
+ </div>
1739
+ `).join('');
1740
+ peersList.innerHTML = peersHtml;
1741
+ }
1742
+
1743
+ // Update peer selector dropdown for messaging and selective streaming
1744
+ if (targetPeerSelect) {
1745
+ // Store current selections to preserve them
1746
+ const currentSelections = Array.from(targetPeerSelect.selectedOptions).map(option => option.value);
1747
+
1748
+ targetPeerSelect.innerHTML = '<option value="">Select peers for streaming control...</option>';
1749
+
1750
+ if (connectedPeers.length > 0) {
1751
+ connectedPeers.forEach(peer => {
1752
+ const option = document.createElement('option');
1753
+ option.value = peer.id;
1754
+ option.textContent = `${peer.id.substring(0, 8)}...${peer.id.substring(-8)} (${peer.connection.getStatus()})`;
1755
+
1756
+ // Restore selection if it was previously selected
1757
+ if (currentSelections.includes(peer.id)) {
1758
+ option.selected = true;
1759
+ }
1760
+
1761
+ targetPeerSelect.appendChild(option);
1762
+ });
1763
+ }
1764
+ }
1765
+
1766
+ // Update peer count display
1767
+ document.getElementById('peer-count').textContent = connectedPeers.length;
1768
+
1769
+ // Update streaming status if needed
1770
+ if (this.mesh && this.mesh.getStreamingStatus) {
1771
+ try {
1772
+ this.showStreamingStatus();
1773
+ } catch (error) {
1774
+ // Ignore errors if streaming status methods aren't available yet
1775
+ }
1776
+ }
1777
+ }
1778
+
1779
+ updateDiscoveredPeers() {
1780
+ const discovered = this.mesh.getDiscoveredPeers();
1781
+ const discoveredDiv = document.getElementById('discovered-peers');
1782
+
1783
+ if (discovered.length === 0) {
1784
+ discoveredDiv.innerHTML = '<p class="empty-state">No peers discovered</p>';
1785
+ return;
1786
+ }
1787
+
1788
+ const discoveredHtml = discovered.map(peer => `
1789
+ <div class="discovered-peer-item">
1790
+ <span class="peer-id">${peer.peerId}</span>
1791
+ <span class="discovery-time">${new Date(peer.discoveredAt).toLocaleTimeString()}</span>
1792
+ </div>
1793
+ `).join('');
1794
+
1795
+ discoveredDiv.innerHTML = discoveredHtml;
1796
+ }
1797
+
1798
+ async initializeMediaDevices() {
1799
+ try {
1800
+ await this.mesh.initializeMedia();
1801
+ const devices = await this.mesh.enumerateMediaDevices();
1802
+ this.populateDeviceSelectors(devices);
1803
+ } catch (error) {
1804
+ this.log(`๐ŸŽฅ Media initialization error: ${error.message}`, 'warning');
1805
+ }
1806
+ }
1807
+
1808
+ populateDeviceSelectors(devices) {
1809
+ const cameraSelect = document.getElementById('camera-select');
1810
+ const micSelect = document.getElementById('microphone-select');
1811
+
1812
+ // Clear existing options
1813
+ cameraSelect.innerHTML = '<option value="">Select camera...</option>';
1814
+ micSelect.innerHTML = '<option value="">Select microphone...</option>';
1815
+
1816
+ // Add camera options
1817
+ devices.cameras.forEach(device => {
1818
+ const option = document.createElement('option');
1819
+ option.value = device.deviceId;
1820
+ option.textContent = device.label || `Camera ${device.deviceId.substring(0, 8)}...`;
1821
+ cameraSelect.appendChild(option);
1822
+ });
1823
+
1824
+ // Add microphone options
1825
+ devices.microphones.forEach(device => {
1826
+ const option = document.createElement('option');
1827
+ option.value = device.deviceId;
1828
+ option.textContent = device.label || `Microphone ${device.deviceId.substring(0, 8)}...`;
1829
+ micSelect.appendChild(option);
1830
+ });
1831
+ }
1832
+
1833
+ updateMediaInfo() {
1834
+ const mediaState = this.mesh.getMediaState();
1835
+
1836
+ document.getElementById('local-stream-status').textContent = mediaState.hasStream ? 'Active' : 'None';
1837
+ document.getElementById('video-enabled-status').textContent = mediaState.isVideoEnabled ? 'Yes' : 'No';
1838
+ document.getElementById('audio-enabled-status').textContent = mediaState.isAudioEnabled ? 'Yes' : 'No';
1839
+ document.getElementById('active-camera').textContent = mediaState.videoDeviceId || 'None';
1840
+ document.getElementById('active-microphone').textContent = mediaState.audioDeviceId || 'None';
1841
+ }
38
1842
 
39
- // Initialize the application
40
- document.addEventListener('DOMContentLoaded', () => {
41
- const peerPigeonApp = new PeerPigeonApp();
1843
+ addRemoteStream(peerId, stream) {
1844
+ const remoteStreams = document.getElementById('remote-streams');
1845
+ const existingStream = document.getElementById(`remote-${peerId}`);
1846
+
1847
+ if (existingStream) {
1848
+ existingStream.remove();
1849
+ }
1850
+
1851
+ const streamDiv = document.createElement('div');
1852
+ streamDiv.id = `remote-${peerId}`;
1853
+ streamDiv.className = 'remote-stream-item';
1854
+ streamDiv.innerHTML = `
1855
+ <video autoplay playsinline></video>
1856
+ <div class="remote-stream-label">${peerId.substring(0, 8)}...</div>
1857
+ `;
1858
+
1859
+ const video = streamDiv.querySelector('video');
1860
+ video.srcObject = stream;
1861
+
1862
+ if (remoteStreams.querySelector('.empty-state')) {
1863
+ remoteStreams.innerHTML = '';
1864
+ }
1865
+
1866
+ remoteStreams.appendChild(streamDiv);
1867
+ }
1868
+
1869
+ updateCryptoStatus() {
1870
+ // Use the correct method names
1871
+ const publicKey = this.mesh.cryptoManager?.getPublicKey() || this.mesh.exportPublicKey?.();
1872
+ const connectedPeers = this.getConnectedPeers();
1873
+
1874
+ // Debug logging
1875
+ console.log('๐Ÿ” DEBUG updateCryptoStatus:', {
1876
+ enableCrypto: this.mesh.enableCrypto,
1877
+ cryptoManager: !!this.mesh.cryptoManager,
1878
+ keypair: this.mesh.cryptoManager?.keypair,
1879
+ publicKey,
1880
+ connectedPeers: connectedPeers.length
1881
+ });
1882
+
1883
+ // Check if crypto is enabled and working - use the correct property names
1884
+ const cryptoEnabled = this.mesh.enableCrypto && this.mesh.cryptoManager;
1885
+ const hasKeypair = cryptoEnabled && this.mesh.cryptoManager && this.mesh.cryptoManager.keypair;
1886
+
1887
+ document.getElementById('crypto-enabled-status').textContent =
1888
+ cryptoEnabled ? (hasKeypair ? 'Yes' : 'Initializing...') : 'No';
1889
+
1890
+ document.getElementById('public-key-display').textContent = publicKey
1891
+ ? publicKey.substring(0, 32) + '...'
1892
+ : hasKeypair ? 'Generating...' : 'Not available';
1893
+
1894
+ // Count actual key exchanges with connected peers
1895
+ let keyExchangeCount = 0;
1896
+ if (this.mesh.cryptoManager && this.mesh.cryptoManager.peerKeys) {
1897
+ keyExchangeCount = connectedPeers.filter(peer =>
1898
+ this.mesh.cryptoManager.peerKeys.has(peer.id)
1899
+ ).length;
1900
+
1901
+ // Debug logging for peer keys
1902
+ console.log('๐Ÿ” DEBUG Peer Keys:', {
1903
+ totalPeerKeys: this.mesh.cryptoManager.peerKeys.size,
1904
+ peerKeyIds: Array.from(this.mesh.cryptoManager.peerKeys.keys()),
1905
+ connectedPeerIds: connectedPeers.map(p => p.id),
1906
+ matchingKeys: keyExchangeCount
1907
+ });
1908
+ }
1909
+
1910
+ document.getElementById('key-exchanges-count').textContent = keyExchangeCount;
1911
+
1912
+ // Log the final values being set
1913
+ console.log('๐Ÿ” Setting crypto status values:', {
1914
+ enabled: document.getElementById('crypto-enabled-status').textContent,
1915
+ publicKey: document.getElementById('public-key-display').textContent,
1916
+ keyExchanges: document.getElementById('key-exchanges-count').textContent
1917
+ });
1918
+ }
1919
+
1920
+ updateSubscriptionsList() {
1921
+ const subscriptionsDiv = document.getElementById('dht-subscriptions');
1922
+
1923
+ if (this.activeSubscriptions.size === 0) {
1924
+ subscriptionsDiv.innerHTML = '<p class="empty-state">No active subscriptions</p>';
1925
+ return;
1926
+ }
1927
+
1928
+ const subscriptionsHtml = Array.from(this.activeSubscriptions).map(key => `
1929
+ <div class="subscription-item">
1930
+ <span>${key}</span>
1931
+ <button class="btn tertiary" onclick="testSuite.dhtUnsubscribeKey('${key}')">Unsubscribe</button>
1932
+ </div>
1933
+ `).join('');
1934
+
1935
+ subscriptionsDiv.innerHTML = subscriptionsHtml;
1936
+ }
1937
+
1938
+ async dhtUnsubscribeKey(key) {
1939
+ try {
1940
+ await this.mesh.dhtUnsubscribe(key);
1941
+ this.activeSubscriptions.delete(key);
1942
+ this.updateSubscriptionsList();
1943
+ this.logDHT(`๐Ÿ”• UNSUBSCRIBE: ${key}`);
1944
+ } catch (error) {
1945
+ this.logDHT(`โŒ UNSUBSCRIBE error: ${error.message}`, 'error');
1946
+ }
1947
+ }
1948
+
1949
+ updateConnectionStats(stats) {
1950
+ const statsDiv = document.getElementById('connection-stats');
1951
+ statsDiv.innerHTML = `
1952
+ <div class="stats-item">
1953
+ <label>Bandwidth In:</label>
1954
+ <span>${this.formatBytes(stats.bytesReceived || 0)}/s</span>
1955
+ </div>
1956
+ <div class="stats-item">
1957
+ <label>Bandwidth Out:</label>
1958
+ <span>${this.formatBytes(stats.bytesSent || 0)}/s</span>
1959
+ </div>
1960
+ <div class="stats-item">
1961
+ <label>Packets Lost:</label>
1962
+ <span>${stats.packetsLost || 0}</span>
1963
+ </div>
1964
+ <div class="stats-item">
1965
+ <label>Round Trip Time:</label>
1966
+ <span>${stats.roundTripTime || 0}ms</span>
1967
+ </div>
1968
+ `;
1969
+ }
1970
+
1971
+ // Message and Log Management
1972
+ addMessageToHistory(type, sender, content, encrypted = false) {
1973
+ const message = {
1974
+ type,
1975
+ sender,
1976
+ content,
1977
+ encrypted,
1978
+ timestamp: Date.now()
1979
+ };
1980
+
1981
+ this.messageHistory.push(message);
1982
+ this.displayMessage(message);
1983
+
1984
+ // Keep only last 100 messages
1985
+ if (this.messageHistory.length > 100) {
1986
+ this.messageHistory = this.messageHistory.slice(-100);
1987
+ }
1988
+ }
1989
+
1990
+ displayMessage(message) {
1991
+ const historyDiv = document.getElementById('message-history');
1992
+
1993
+ if (historyDiv.querySelector('.empty-state')) {
1994
+ historyDiv.innerHTML = '';
1995
+ }
1996
+
1997
+ const messageDiv = document.createElement('div');
1998
+ messageDiv.className = `message-item ${message.type}`;
1999
+
2000
+ const encryptionIcon = message.encrypted ? '๐Ÿ”’' : '';
2001
+ const typeIcon = this.getMessageTypeIcon(message.type);
2002
+
2003
+ // Ensure content is properly formatted for display
2004
+ let displayContent = message.content;
2005
+ if (typeof displayContent === 'object') {
2006
+ displayContent = JSON.stringify(displayContent, null, 2);
2007
+ } else if (displayContent === undefined || displayContent === null) {
2008
+ displayContent = '(empty message)';
2009
+ }
2010
+
2011
+ messageDiv.innerHTML = `
2012
+ <div class="message-header">
2013
+ <span class="message-type">${typeIcon}</span>
2014
+ <span class="message-sender">${message.sender}</span>
2015
+ <span class="message-encryption">${encryptionIcon}</span>
2016
+ <span class="message-time">${new Date(message.timestamp).toLocaleTimeString()}</span>
2017
+ </div>
2018
+ <div class="message-content">${displayContent}</div>
2019
+ `;
2020
+
2021
+ historyDiv.appendChild(messageDiv);
2022
+ historyDiv.scrollTop = historyDiv.scrollHeight;
2023
+ }
2024
+
2025
+ getMessageTypeIcon(type) {
2026
+ const icons = {
2027
+ broadcast: '๐Ÿ“ข',
2028
+ direct: '๐Ÿ“ง',
2029
+ encrypted: '๐Ÿ”',
2030
+ group: '๐Ÿ‘ฅ',
2031
+ system: 'โš™๏ธ'
2032
+ };
2033
+ return icons[type] || '๐Ÿ’ฌ';
2034
+ }
2035
+
2036
+ clearMessageHistory() {
2037
+ this.messageHistory = [];
2038
+ document.getElementById('message-history').innerHTML = '<p class="empty-state">No messages yet</p>';
2039
+ }
2040
+
2041
+ log(message, level = 'info') {
2042
+ const timestamp = new Date().toLocaleTimeString();
2043
+ const logEntry = `[${timestamp}] ${message}`;
2044
+
2045
+ this.addLogEntry('system-log', logEntry, level);
2046
+ }
2047
+
2048
+ logDHT(message, level = 'info') {
2049
+ const timestamp = new Date().toLocaleTimeString();
2050
+ const logEntry = `[${timestamp}] ${message}`;
2051
+
2052
+ this.addLogEntry('dht-log', logEntry, level);
2053
+ }
2054
+
2055
+ logCrypto(message, level = 'info') {
2056
+ const timestamp = new Date().toLocaleTimeString();
2057
+ const logEntry = `[${timestamp}] ${message}`;
2058
+
2059
+ this.addLogEntry('crypto-log', logEntry, level);
2060
+ }
2061
+
2062
+ addLogEntry(logId, message, level = 'info') {
2063
+ const logDiv = document.getElementById(logId);
2064
+
2065
+ if (logDiv.querySelector('.empty-state')) {
2066
+ logDiv.innerHTML = '';
2067
+ }
2068
+
2069
+ const entryDiv = document.createElement('div');
2070
+ entryDiv.className = `log-entry ${level}`;
2071
+ entryDiv.textContent = message;
2072
+
2073
+ logDiv.appendChild(entryDiv);
2074
+ logDiv.scrollTop = logDiv.scrollHeight;
2075
+
2076
+ // Keep only last 50 entries per log
2077
+ const entries = logDiv.querySelectorAll('.log-entry');
2078
+ if (entries.length > 50) {
2079
+ entries[0].remove();
2080
+ }
2081
+ }
2082
+
2083
+ addTestResult(testName, result, level = 'info') {
2084
+ const testResult = {
2085
+ name: testName,
2086
+ result,
2087
+ level,
2088
+ timestamp: Date.now()
2089
+ };
2090
+
2091
+ this.testResults.push(testResult);
2092
+ this.displayTestResult(testResult);
2093
+
2094
+ // Keep only last 20 test results
2095
+ if (this.testResults.length > 20) {
2096
+ this.testResults = this.testResults.slice(-20);
2097
+ }
2098
+ }
2099
+
2100
+ displayTestResult(testResult) {
2101
+ const testLogDiv = document.getElementById('test-log');
2102
+
2103
+ if (testLogDiv.querySelector('.empty-state')) {
2104
+ testLogDiv.innerHTML = '';
2105
+ }
2106
+
2107
+ const resultDiv = document.createElement('div');
2108
+ resultDiv.className = `test-result ${testResult.level}`;
2109
+ resultDiv.innerHTML = `
2110
+ <div class="test-header">${testResult.name}</div>
2111
+ <div class="test-content">${testResult.result}</div>
2112
+ <div class="test-time">${new Date(testResult.timestamp).toLocaleString()}</div>
2113
+ `;
2114
+
2115
+ testLogDiv.appendChild(resultDiv);
2116
+ testLogDiv.scrollTop = testLogDiv.scrollHeight;
2117
+ }
2118
+
2119
+ clearDHTLog() {
2120
+ document.getElementById('dht-log').innerHTML = '<p class="empty-state">No DHT activity yet</p>';
2121
+ }
2122
+
2123
+ clearCryptoLog() {
2124
+ document.getElementById('crypto-log').innerHTML = '<p class="empty-state">No encryption activity yet</p>';
2125
+ }
2126
+
2127
+ clearTestLog() {
2128
+ this.testResults = [];
2129
+ document.getElementById('test-log').innerHTML = '<p class="empty-state">No test results yet</p>';
2130
+ }
2131
+
2132
+ clearSystemLog() {
2133
+ document.getElementById('system-log').innerHTML = '<p class="empty-state">System log will appear here...</p>';
2134
+ }
2135
+
2136
+ getLogEntries(logId) {
2137
+ const logDiv = document.getElementById(logId);
2138
+ const entries = logDiv.querySelectorAll('.log-entry');
2139
+ return Array.from(entries).map(entry => entry.textContent);
2140
+ }
2141
+
2142
+ // Distributed Storage Functions
2143
+ async enableDistributedStorage() {
2144
+ try {
2145
+ if (!this.mesh.distributedStorage) {
2146
+ this.logStorage('โŒ Distributed storage not available in this mesh instance');
2147
+ return;
2148
+ }
2149
+
2150
+ await this.mesh.distributedStorage.enable();
2151
+ this.logStorage('โœ… Distributed storage enabled');
2152
+ this.updateStorageStatus();
2153
+ } catch (error) {
2154
+ this.logStorage(`โŒ Failed to enable storage: ${error.message}`, 'error');
2155
+ }
2156
+ }
2157
+
2158
+ async disableDistributedStorage() {
2159
+ try {
2160
+ if (!this.mesh.distributedStorage) {
2161
+ this.logStorage('โŒ Distributed storage not available');
2162
+ return;
2163
+ }
2164
+
2165
+ await this.mesh.distributedStorage.disable();
2166
+ this.logStorage('โš ๏ธ Distributed storage disabled');
2167
+ this.updateStorageStatus();
2168
+ } catch (error) {
2169
+ this.logStorage(`โŒ Failed to disable storage: ${error.message}`, 'error');
2170
+ }
2171
+ }
2172
+
2173
+ async getStorageStatus() {
2174
+ try {
2175
+ if (!this.mesh.distributedStorage) {
2176
+ this.logStorage('โŒ Distributed storage not available');
2177
+ return;
2178
+ }
2179
+
2180
+ const status = await this.mesh.distributedStorage.getStatus();
2181
+ this.logStorage(`๐Ÿ“Š Storage Status: ${JSON.stringify(status, null, 2)}`);
2182
+
2183
+ document.getElementById('storage-result').innerHTML = `
2184
+ <h4>Storage Status</h4>
2185
+ <pre>${JSON.stringify(status, null, 2)}</pre>
2186
+ `;
2187
+ } catch (error) {
2188
+ this.logStorage(`โŒ Failed to get storage status: ${error.message}`, 'error');
2189
+ }
2190
+ }
2191
+
2192
+ async putStorageData() {
2193
+ const key = document.getElementById('storage-key').value.trim();
2194
+ const dataText = document.getElementById('storage-data').value.trim();
2195
+ const space = document.getElementById('storage-space').value;
2196
+
2197
+ if (!key || !dataText) {
2198
+ this.logStorage('โŒ Please enter both key and data', 'error');
2199
+ return;
2200
+ }
2201
+
2202
+ try {
2203
+ const data = JSON.parse(dataText);
2204
+
2205
+ if (!this.mesh.distributedStorage) {
2206
+ this.logStorage('โŒ Distributed storage not available');
2207
+ return;
2208
+ }
2209
+
2210
+ const options = {};
2211
+ if (space) options.space = space;
2212
+
2213
+ await this.mesh.distributedStorage.store(key, data, options);
2214
+ this.logStorage(`โœ… Stored data with key: ${key} (space: ${space})`);
2215
+
2216
+ document.getElementById('storage-result').innerHTML = `
2217
+ <h4>Storage Success</h4>
2218
+ <p><strong>Key:</strong> ${key}</p>
2219
+ <p><strong>Space:</strong> ${space}</p>
2220
+ <p><strong>Data:</strong> <pre>${JSON.stringify(data, null, 2)}</pre></p>
2221
+ `;
2222
+ } catch (error) {
2223
+ this.logStorage(`โŒ Failed to store data: ${error.message}`, 'error');
2224
+ }
2225
+ }
2226
+
2227
+ async getStorageData() {
2228
+ const key = document.getElementById('storage-key').value.trim();
2229
+
2230
+ if (!key) {
2231
+ this.logStorage('โŒ Please enter a key to retrieve', 'error');
2232
+ return;
2233
+ }
2234
+
2235
+ try {
2236
+ if (!this.mesh.distributedStorage) {
2237
+ this.logStorage('โŒ Distributed storage not available');
2238
+ return;
2239
+ }
2240
+
2241
+ const data = await this.mesh.distributedStorage.retrieve(key, { forceRefresh: true });
2242
+ this.logStorage(`๐Ÿ“ฅ Retrieved data for key: ${key}`);
2243
+
2244
+ document.getElementById('storage-result').innerHTML = `
2245
+ <h4>Retrieved Data</h4>
2246
+ <p><strong>Key:</strong> ${key}</p>
2247
+ <p><strong>Data:</strong> <pre>${JSON.stringify(data, null, 2)}</pre></p>
2248
+ `;
2249
+ } catch (error) {
2250
+ this.logStorage(`โŒ Failed to retrieve data: ${error.message}`, 'error');
2251
+ }
2252
+ }
2253
+
2254
+ async deleteStorageData() {
2255
+ const key = document.getElementById('storage-key').value.trim();
2256
+
2257
+ if (!key) {
2258
+ this.logStorage('โŒ Please enter a key to delete', 'error');
2259
+ return;
2260
+ }
2261
+
2262
+ if (!confirm(`Are you sure you want to delete the data for key "${key}"?`)) {
2263
+ return;
2264
+ }
2265
+
2266
+ try {
2267
+ if (!this.mesh.distributedStorage) {
2268
+ this.logStorage('โŒ Distributed storage not available');
2269
+ return;
2270
+ }
2271
+
2272
+ await this.mesh.distributedStorage.delete(key);
2273
+ this.logStorage(`๐Ÿ—‘๏ธ Deleted data for key: ${key}`);
2274
+
2275
+ document.getElementById('storage-result').innerHTML = `
2276
+ <h4>Data Deleted</h4>
2277
+ <p><strong>Key:</strong> ${key}</p>
2278
+ <p>Data has been removed from distributed storage</p>
2279
+ `;
2280
+ } catch (error) {
2281
+ this.logStorage(`โŒ Failed to delete data: ${error.message}`, 'error');
2282
+ }
2283
+ }
2284
+
2285
+ async listStorageKeys() {
2286
+ try {
2287
+ if (!this.mesh.distributedStorage) {
2288
+ this.logStorage('โŒ Distributed storage not available');
2289
+ return;
2290
+ }
2291
+
2292
+ const keys = await this.mesh.distributedStorage.listKeys();
2293
+ this.logStorage(`๐Ÿ“‹ Found ${keys.length} stored keys`);
2294
+
2295
+ document.getElementById('storage-result').innerHTML = `
2296
+ <h4>Stored Keys</h4>
2297
+ <ul>
2298
+ ${keys.map(key => `<li>${key}</li>`).join('')}
2299
+ </ul>
2300
+ `;
2301
+ } catch (error) {
2302
+ this.logStorage(`โŒ Failed to list keys: ${error.message}`, 'error');
2303
+ }
2304
+ }
2305
+
2306
+ async getStorageStats() {
2307
+ try {
2308
+ if (!this.mesh.distributedStorage) {
2309
+ this.logStorage('โŒ Distributed storage not available');
2310
+ return;
2311
+ }
2312
+
2313
+ const stats = await this.mesh.distributedStorage.getStats();
2314
+ this.logStorage('๐Ÿ“Š Storage statistics retrieved');
2315
+
2316
+ document.getElementById('storage-result').innerHTML = `
2317
+ <h4>Storage Statistics</h4>
2318
+ <pre>${JSON.stringify(stats, null, 2)}</pre>
2319
+ `;
2320
+ } catch (error) {
2321
+ this.logStorage(`โŒ Failed to get storage stats: ${error.message}`, 'error');
2322
+ }
2323
+ }
2324
+
2325
+ async clearAllStorage() {
2326
+ if (!confirm('Are you sure you want to clear ALL stored data? This cannot be undone.')) {
2327
+ return;
2328
+ }
2329
+
2330
+ try {
2331
+ if (!this.mesh.distributedStorage) {
2332
+ this.logStorage('โŒ Distributed storage not available');
2333
+ return;
2334
+ }
2335
+
2336
+ await this.mesh.distributedStorage.clear();
2337
+ this.logStorage('๐Ÿงน All storage data cleared');
2338
+
2339
+ document.getElementById('storage-result').innerHTML = `
2340
+ <h4>Storage Cleared</h4>
2341
+ <p>All distributed storage data has been removed</p>
2342
+ `;
2343
+ } catch (error) {
2344
+ this.logStorage(`โŒ Failed to clear storage: ${error.message}`, 'error');
2345
+ }
2346
+ }
2347
+
2348
+ logStorage(message, level = 'info') {
2349
+ const timestamp = new Date().toLocaleTimeString();
2350
+ const logDiv = document.getElementById('storage-log');
2351
+
2352
+ if (logDiv.querySelector('.empty-state')) {
2353
+ logDiv.innerHTML = '';
2354
+ }
2355
+
2356
+ const logEntry = document.createElement('div');
2357
+ logEntry.className = `log-entry ${level}`;
2358
+ logEntry.innerHTML = `[${timestamp}] ${message}`;
2359
+
2360
+ logDiv.appendChild(logEntry);
2361
+ logDiv.scrollTop = logDiv.scrollHeight;
2362
+ }
2363
+
2364
+ clearStorageLog() {
2365
+ document.getElementById('storage-log').innerHTML = '<p class="empty-state">No storage activity yet</p>';
2366
+ }
2367
+
2368
+ updateStorageStatus() {
2369
+ // This could be enhanced to show storage status in the UI
2370
+ if (this.mesh.distributedStorage) {
2371
+ this.logStorage('๐Ÿ”„ Storage status updated');
2372
+ }
2373
+ }
2374
+
2375
+ // Utility Methods
2376
+ checkAndNotifyMediaReadiness() {
2377
+ const connectedPeers = this.getConnectedPeers();
2378
+ if (connectedPeers.length === 0) return;
2379
+
2380
+ // Check that ALL connected peers have data channels ready AND keys exchanged
2381
+ const peersWithDataChannels = connectedPeers.filter(peer =>
2382
+ this.mesh.connectionManager && this.mesh.connectionManager.peers && this.mesh.connectionManager.peers.get(peer.id)?.dataChannelReady === true
2383
+ );
2384
+
2385
+ const peersWithKeys = connectedPeers.filter(peer =>
2386
+ this.mesh.cryptoManager && this.mesh.cryptoManager.peerKeys && this.mesh.cryptoManager.peerKeys.get(peer.id)
2387
+ );
2388
+
2389
+ if (peersWithDataChannels.length === connectedPeers.length &&
2390
+ peersWithKeys.length === connectedPeers.length) {
2391
+ this.log(`โœ… MEDIA READY: All ${connectedPeers.length} peers have data channels + key exchange complete. You can now safely start media!`, 'success');
2392
+ }
2393
+ }
2394
+
2395
+ formatUptime(milliseconds) {
2396
+ if (!milliseconds) return '0s';
2397
+
2398
+ const seconds = Math.floor(milliseconds / 1000);
2399
+ const minutes = Math.floor(seconds / 60);
2400
+ const hours = Math.floor(minutes / 60);
2401
+
2402
+ if (hours > 0) {
2403
+ return `${hours}h ${minutes % 60}m`;
2404
+ } else if (minutes > 0) {
2405
+ return `${minutes}m ${seconds % 60}s`;
2406
+ } else {
2407
+ return `${seconds}s`;
2408
+ }
2409
+ }
2410
+
2411
+ formatBytes(bytes) {
2412
+ if (bytes === 0) return '0 B';
2413
+
2414
+ const k = 1024;
2415
+ const sizes = ['B', 'KB', 'MB', 'GB'];
2416
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
2417
+
2418
+ return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
2419
+ }
2420
+ }
42
2421
 
43
- // Expose for debugging and global access
44
- window.peerPigeonApp = peerPigeonApp;
45
- window.peerPigeonMesh = peerPigeonApp.mesh;
46
- window.peerPigeonUI = peerPigeonApp.ui;
47
- window.ui = peerPigeonApp.ui; // Also expose as 'ui' for compatibility with discovered peers buttons
48
- window.peerPigeonSignaling = peerPigeonApp.mesh.signalingClient;
49
- window.getPeerPigeonState = () => peerPigeonApp.mesh.getStatus();
2422
+ // Initialize the test suite when the page loads
2423
+ let testSuite;
50
2424
 
51
- // Expose PeerPigeonMesh class for static validation in UI
52
- window.PeerPigeonMesh = PeerPigeonMesh;
2425
+ window.addEventListener('DOMContentLoaded', () => {
2426
+ testSuite = new PeerPigeonTestSuite();
2427
+ // Make testSuite globally available for testing
2428
+ window.peerPigeonTestSuite = testSuite;
2429
+ window.testSuite = testSuite;
53
2430
  });