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,3010 +0,0 @@
1
- // Updated: 2025-07-04 - Fixed getConnectionStatus method name
2
- export class PeerPigeonUI {
3
- constructor(mesh) {
4
- this.mesh = mesh;
5
- this.lastCleanupTime = 0; // Track when we last did cleanup
6
- this.setupEventListeners();
7
- this.bindDOMEvents();
8
- this.initializeMedia();
9
- }
10
-
11
- setupEventListeners() {
12
- this.mesh.addEventListener('statusChanged', (data) => {
13
- this.handleStatusChange(data);
14
- });
15
-
16
- this.mesh.addEventListener('peerDiscovered', (_data) => {
17
- this.updateDiscoveredPeers();
18
- });
19
-
20
- this.mesh.addEventListener('peerConnected', (_data) => {
21
- this.updateUI();
22
- this.updateDiscoveredPeers();
23
- });
24
-
25
- this.mesh.addEventListener('peerDisconnected', (data) => {
26
- this.addMessage('System', `Peer ${data.peerId.substring(0, 8)}... disconnected (${data.reason})`);
27
- this.updateUI();
28
- this.updateDiscoveredPeers();
29
- });
30
-
31
- this.mesh.addEventListener('messageReceived', (data) => {
32
- // Only show messages from other peers, not self
33
- if (data.from !== this.mesh.peerId) {
34
- if (data.direct) {
35
- this.addMessage(`${data.from.substring(0, 8)}...`, `(DM) ${data.content}`, 'dm');
36
- } else {
37
- this.addMessage(`${data.from.substring(0, 8)}...`, data.content);
38
- }
39
- }
40
- });
41
-
42
- this.mesh.addEventListener('peerEvicted', (_data) => {
43
- this.updateUI();
44
- this.updateDiscoveredPeers();
45
- });
46
-
47
- this.mesh.addEventListener('peersUpdated', () => {
48
- this.updateDiscoveredPeers();
49
- });
50
-
51
- this.mesh.addEventListener('connectionStats', (_stats) => {
52
- // Handle connection stats if needed
53
- });
54
-
55
- // DHT event listeners
56
- this.mesh.addEventListener('dhtValueChanged', (data) => {
57
- const { key, newValue, timestamp } = data;
58
- this.addDHTLogEntry(`🔔 Value Changed: ${key} = ${JSON.stringify(newValue)} (timestamp: ${timestamp})`);
59
- });
60
-
61
- // Media event listeners
62
- this.mesh.addEventListener('localStreamStarted', (data) => {
63
- this.handleLocalStreamStarted(data);
64
- });
65
-
66
- this.mesh.addEventListener('localStreamStopped', () => {
67
- this.handleLocalStreamStopped();
68
- });
69
-
70
- this.mesh.addEventListener('mediaError', (data) => {
71
- this.addMessage('System', `Media error: ${data.error.message}`, 'error');
72
- });
73
-
74
- // Listen for remote streams
75
- this.mesh.addEventListener('remoteStream', (data) => {
76
- this.handleRemoteStream(data);
77
- });
78
-
79
- // Crypto event listeners
80
- this.mesh.addEventListener('cryptoReady', (_data) => {
81
- this.addMessage('System', '🔐 Crypto initialized successfully', 'success');
82
- this.updateCryptoStatus();
83
- });
84
-
85
- this.mesh.addEventListener('cryptoError', (data) => {
86
- this.addMessage('System', `🔐 Crypto error: ${data.error}`, 'error');
87
- this.addCryptoTestResult(`❌ Crypto Error: ${data.error}`, 'error');
88
- });
89
-
90
- this.mesh.addEventListener('peerKeyAdded', (data) => {
91
- this.addMessage('System', `🔐 Public key received from ${data.peerId.substring(0, 8)}...`);
92
- this.updateCryptoStatus();
93
- });
94
-
95
- this.mesh.addEventListener('userAuthenticated', (data) => {
96
- this.addMessage('System', `🔐 Authenticated as ${data.alias}`, 'success');
97
- this.updateCryptoStatus();
98
- });
99
- }
100
-
101
- handleStatusChange(data) {
102
- switch (data.type) {
103
- case 'initialized':
104
- this.updateUI();
105
- break;
106
- case 'connecting':
107
- this.addMessage('System', 'Connecting to signaling server...');
108
- this.updateUI();
109
- break;
110
- case 'connected':
111
- this.addMessage('System', 'Connected to signaling server');
112
- this.updateUI();
113
- break;
114
- case 'disconnected':
115
- this.addMessage('System', 'Disconnected from signaling server');
116
- this.updateUI();
117
- this.updateDiscoveredPeers();
118
- break;
119
- case 'error':
120
- this.addMessage('System', data.message, 'error');
121
- this.updateUI();
122
- break;
123
- case 'warning':
124
- this.addMessage('System', data.message, 'warning');
125
- break;
126
- case 'info':
127
- this.addMessage('System', data.message);
128
- break;
129
- case 'urlLoaded':
130
- document.getElementById('signaling-url').value = data.signalingUrl;
131
- this.addMessage('System', `API Gateway URL loaded: ${data.signalingUrl}`);
132
- break;
133
- case 'setting': {
134
- const settingName = data.setting === 'autoDiscovery'
135
- ? 'Auto discovery'
136
- : data.setting === 'evictionStrategy'
137
- ? 'Smart eviction strategy'
138
- : data.setting === 'xorRouting'
139
- ? 'XOR-based routing'
140
- : data.setting === 'connectionType' ? 'Connection type' : data.setting;
141
-
142
- if (data.setting === 'connectionType') {
143
- this.addMessage('System', `${settingName} set to: ${data.value}`);
144
- } else {
145
- this.addMessage('System', `${settingName} ${data.value ? 'enabled' : 'disabled'}`);
146
- }
147
- break;
148
- }
149
- }
150
- }
151
-
152
- bindDOMEvents() {
153
- // Connection controls
154
- document.getElementById('connect-btn').addEventListener('click', () => {
155
- this.handleConnect();
156
- });
157
-
158
- document.getElementById('disconnect-btn').addEventListener('click', () => {
159
- this.handleDisconnect();
160
- });
161
-
162
- document.getElementById('cleanup-btn').addEventListener('click', () => {
163
- this.handleCleanup();
164
- });
165
-
166
- document.getElementById('health-check-btn').addEventListener('click', () => {
167
- this.handleHealthCheck();
168
- });
169
-
170
- document.getElementById('refresh-btn').addEventListener('click', () => {
171
- window.location.reload();
172
- });
173
-
174
- // Messaging
175
- document.getElementById('send-message-btn').addEventListener('click', () => {
176
- this.sendMessage();
177
- });
178
-
179
- document.getElementById('message-input').addEventListener('keypress', (e) => {
180
- if (e.key === 'Enter') {
181
- this.sendMessage();
182
- }
183
- });
184
-
185
- // Manual connection
186
- document.getElementById('connect-peer-btn').addEventListener('click', () => {
187
- this.connectToPeer();
188
- });
189
-
190
- document.getElementById('target-peer').addEventListener('keypress', (e) => {
191
- if (e.key === 'Enter') {
192
- this.connectToPeer();
193
- }
194
- });
195
-
196
- // Settings
197
- document.getElementById('min-peers').addEventListener('change', (e) => {
198
- this.mesh.setMinPeers(parseInt(e.target.value));
199
- });
200
-
201
- document.getElementById('max-peers').addEventListener('change', (e) => {
202
- this.mesh.setMaxPeers(parseInt(e.target.value));
203
- });
204
-
205
- document.getElementById('auto-discovery-toggle').addEventListener('change', (e) => {
206
- this.mesh.setAutoDiscovery(e.target.checked);
207
- });
208
-
209
- document.getElementById('eviction-strategy-toggle').addEventListener('change', (e) => {
210
- this.mesh.setEvictionStrategy(e.target.checked);
211
- });
212
-
213
- document.getElementById('xor-routing-toggle').addEventListener('change', (e) => {
214
- this.mesh.setXorRouting(e.target.checked);
215
- });
216
-
217
- // DHT controls
218
- this.setupDHTControls();
219
-
220
- // Storage controls
221
- this.setupStorageControls();
222
-
223
- // Crypto controls
224
- this.setupCryptoControls();
225
-
226
- // Collapsible sections
227
- this.setupCollapsibleSections();
228
-
229
- // Media controls
230
- this.setupMediaControls();
231
- }
232
-
233
- setupDHTControls() {
234
- // DHT input fields and controls
235
- const dhtKey = document.getElementById('dht-key');
236
- const dhtValue = document.getElementById('dht-value');
237
- const dhtGetKey = document.getElementById('dht-get-key'); // Separate key field for retrieval
238
- const dhtSubscribeKey = document.getElementById('dht-subscribe-key'); // Separate key field for subscription
239
- const dhtPutBtn = document.getElementById('dht-put-btn');
240
- const dhtUpdateBtn = document.getElementById('dht-update-btn');
241
- const dhtGetBtn = document.getElementById('dht-get-btn');
242
- const dhtSubscribeBtn = document.getElementById('dht-subscribe-btn');
243
- const dhtUnsubscribeBtn = document.getElementById('dht-unsubscribe-btn');
244
- const dhtEnableTtl = document.getElementById('dht-enable-ttl');
245
- const dhtTtlGroup = document.getElementById('dht-ttl-group');
246
- const dhtTtl = document.getElementById('dht-ttl');
247
-
248
- // Debug: Check if elements are found
249
- console.log('DHT Controls setup - Elements found:', {
250
- dhtKey: !!dhtKey,
251
- dhtValue: !!dhtValue,
252
- dhtGetKey: !!dhtGetKey,
253
- dhtSubscribeKey: !!dhtSubscribeKey,
254
- dhtPutBtn: !!dhtPutBtn,
255
- dhtUpdateBtn: !!dhtUpdateBtn,
256
- dhtGetBtn: !!dhtGetBtn,
257
- dhtSubscribeBtn: !!dhtSubscribeBtn,
258
- dhtUnsubscribeBtn: !!dhtUnsubscribeBtn
259
- });
260
-
261
- if (!dhtKey) {
262
- console.error('DHT key input element not found!');
263
- this.addDHTLogEntry('❌ Error: DHT key input field not found in DOM');
264
- }
265
-
266
- if (!dhtValue) {
267
- console.error('DHT value input element not found!');
268
- this.addDHTLogEntry('❌ Error: DHT value input field not found in DOM');
269
- }
270
-
271
- if (!dhtGetKey) {
272
- console.error('DHT get-key input element not found!');
273
- this.addDHTLogEntry('❌ Error: DHT get-key input field not found in DOM');
274
- }
275
-
276
- // Toggle TTL input visibility
277
- if (dhtEnableTtl && dhtTtlGroup) {
278
- dhtEnableTtl.addEventListener('change', (e) => {
279
- dhtTtlGroup.style.display = e.target.checked ? 'block' : 'none';
280
- });
281
- }
282
-
283
- // Store in DHT
284
- if (dhtPutBtn) {
285
- dhtPutBtn.addEventListener('click', async () => {
286
- const key = dhtKey?.value?.trim();
287
- const value = dhtValue?.value?.trim();
288
-
289
- // Debug logging
290
- console.log('DHT PUT - Elements found:', {
291
- dhtKey: !!dhtKey,
292
- dhtValue: !!dhtValue,
293
- keyValue: key,
294
- valueValue: value
295
- });
296
-
297
- if (!key || !value) {
298
- this.addDHTLogEntry('❌ Error: Both key and value are required');
299
- this.addDHTLogEntry(` Debug: key="${key}", value="${value}"`);
300
- return;
301
- }
302
-
303
- if (!this.mesh.isDHTEnabled()) {
304
- this.addDHTLogEntry('❌ Error: WebDHT is disabled');
305
- return;
306
- }
307
-
308
- try {
309
- let parsedValue;
310
- try {
311
- parsedValue = JSON.parse(value);
312
- } catch {
313
- parsedValue = value; // Use as string if not valid JSON
314
- }
315
-
316
- const options = {};
317
- if (dhtEnableTtl?.checked && dhtTtl?.value) {
318
- options.ttl = parseInt(dhtTtl.value) * 1000; // Convert to milliseconds
319
- }
320
-
321
- const success = await this.mesh.dhtPut(key, parsedValue, options);
322
- if (success) {
323
- this.addDHTLogEntry(`✅ Stored: ${key} = ${JSON.stringify(parsedValue)}`);
324
- if (options.ttl) {
325
- this.addDHTLogEntry(` TTL: ${options.ttl / 1000} seconds`);
326
- }
327
- this.addDHTLogEntry(` 🏆 This peer is now an ORIGINAL STORING PEER for "${key}"`);
328
-
329
- // Auto-subscribe to the key we just stored (essential for original storing peers)
330
- try {
331
- await this.mesh.dhtSubscribe(key);
332
- this.addDHTLogEntry(`🔔 Auto-subscribed as original storing peer: ${key}`);
333
- this.addDHTLogEntry(' 📡 Will receive and relay all future updates for this key');
334
- } catch (subscribeError) {
335
- this.addDHTLogEntry(`⚠️ Failed to auto-subscribe to ${key}: ${subscribeError.message}`);
336
- }
337
- } else {
338
- this.addDHTLogEntry(`❌ Failed to store: ${key}`);
339
- }
340
- } catch (error) {
341
- this.addDHTLogEntry(`❌ Error storing ${key}: ${error.message}`);
342
- }
343
- });
344
- }
345
-
346
- // Update in DHT
347
- if (dhtUpdateBtn) {
348
- dhtUpdateBtn.addEventListener('click', async () => {
349
- const key = dhtKey?.value?.trim();
350
- const value = dhtValue?.value?.trim();
351
-
352
- // Debug logging
353
- console.log('DHT UPDATE - Elements found:', {
354
- dhtKey: !!dhtKey,
355
- dhtValue: !!dhtValue,
356
- keyValue: key,
357
- valueValue: value
358
- });
359
-
360
- if (!key || !value) {
361
- this.addDHTLogEntry('❌ Error: Both key and value are required');
362
- this.addDHTLogEntry(` Debug: key="${key}", value="${value}"`);
363
- return;
364
- }
365
-
366
- if (!this.mesh.isDHTEnabled()) {
367
- this.addDHTLogEntry('❌ Error: WebDHT is disabled');
368
- return;
369
- }
370
-
371
- try {
372
- let parsedValue;
373
- try {
374
- parsedValue = JSON.parse(value);
375
- } catch {
376
- parsedValue = value; // Use as string if not valid JSON
377
- }
378
-
379
- const options = {};
380
- if (dhtEnableTtl?.checked && dhtTtl?.value) {
381
- options.ttl = parseInt(dhtTtl.value) * 1000; // Convert to milliseconds
382
- }
383
-
384
- const success = await this.mesh.dhtUpdate(key, parsedValue, options);
385
- if (success) {
386
- this.addDHTLogEntry(`🔄 Updated: ${key} = ${JSON.stringify(parsedValue)}`);
387
- if (options.ttl) {
388
- this.addDHTLogEntry(` TTL: ${options.ttl / 1000} seconds`);
389
- }
390
- this.addDHTLogEntry(` 🏆 This peer is now an ORIGINAL STORING PEER for "${key}"`);
391
-
392
- // Auto-subscribe to the key we just updated (essential for original storing peers)
393
- try {
394
- await this.mesh.dhtSubscribe(key);
395
- this.addDHTLogEntry(`🔔 Auto-subscribed as original storing peer: ${key}`);
396
- this.addDHTLogEntry(' 📡 Will receive and relay all future updates for this key');
397
- } catch (subscribeError) {
398
- this.addDHTLogEntry(`⚠️ Failed to auto-subscribe to ${key}: ${subscribeError.message}`);
399
- }
400
- } else {
401
- this.addDHTLogEntry(`❌ Failed to update: ${key}`);
402
- }
403
- } catch (error) {
404
- this.addDHTLogEntry(`❌ Error updating ${key}: ${error.message}`);
405
- }
406
- });
407
- }
408
-
409
- // Get from DHT
410
- if (dhtGetBtn) {
411
- dhtGetBtn.addEventListener('click', async () => {
412
- const key = dhtGetKey?.value?.trim(); // Fixed: Use dhtGetKey instead of dhtKey
413
-
414
- // Debug logging
415
- console.log('DHT GET - Elements found:', {
416
- dhtGetKey: !!dhtGetKey,
417
- keyValue: key
418
- });
419
-
420
- if (!key) {
421
- this.addDHTLogEntry('❌ Error: Key is required');
422
- this.addDHTLogEntry(` Debug: key="${key}"`);
423
- return;
424
- }
425
-
426
- if (!this.mesh.isDHTEnabled()) {
427
- this.addDHTLogEntry('❌ Error: WebDHT is disabled');
428
- return;
429
- }
430
-
431
- try {
432
- this.addDHTLogEntry(`🔍 Fetching from ORIGINAL STORING PEERS: ${key}`);
433
- this.addDHTLogEntry(' 📡 Bypassing local cache to ensure fresh data');
434
-
435
- // Force fresh retrieval from original storing peers
436
- const value = await this.mesh.dhtGet(key, { forceRefresh: true });
437
- if (value !== null) {
438
- this.addDHTLogEntry(`📥 Retrieved from original peers: ${key} = ${JSON.stringify(value)}`);
439
- this.addDHTLogEntry(' ✅ Data is FRESH from authoritative source');
440
- if (dhtValue) {
441
- dhtValue.value = typeof value === 'string' ? value : JSON.stringify(value);
442
- }
443
-
444
- // Auto-subscribe to the key we just retrieved for future updates
445
- try {
446
- await this.mesh.dhtSubscribe(key);
447
- this.addDHTLogEntry(`🔔 Auto-subscribed for future updates: ${key}`);
448
- this.addDHTLogEntry(' 📡 Will receive notifications when original peers update this key');
449
- } catch (subscribeError) {
450
- this.addDHTLogEntry(`⚠️ Failed to auto-subscribe to ${key}: ${subscribeError.message}`);
451
- }
452
- } else {
453
- this.addDHTLogEntry(`❌ Not found on original storing peers: ${key}`);
454
- this.addDHTLogEntry(' 💡 Key may not exist or all original storing peers are offline');
455
- }
456
- } catch (error) {
457
- this.addDHTLogEntry(`❌ Error retrieving ${key}: ${error.message}`);
458
- }
459
- });
460
- }
461
-
462
- // Subscribe to DHT key
463
- if (dhtSubscribeBtn) {
464
- dhtSubscribeBtn.addEventListener('click', async () => {
465
- // Use the dedicated subscription key field
466
- const key = dhtSubscribeKey?.value?.trim();
467
-
468
- if (!key) {
469
- this.addDHTLogEntry('❌ Error: Key is required for subscription');
470
- return;
471
- }
472
-
473
- if (!this.mesh.isDHTEnabled()) {
474
- this.addDHTLogEntry('❌ Error: WebDHT is disabled');
475
- return;
476
- }
477
-
478
- try {
479
- this.addDHTLogEntry(`🔔 Explicitly subscribing to key: ${key}`);
480
- this.addDHTLogEntry(' 📡 Will receive notifications when original storing peers update this key');
481
-
482
- const value = await this.mesh.dhtSubscribe(key);
483
- this.addDHTLogEntry(`✅ Subscribed to: ${key}`);
484
- if (value !== null) {
485
- this.addDHTLogEntry(` Current value from original storing peers: ${JSON.stringify(value)}`);
486
- } else {
487
- this.addDHTLogEntry(' No current value found on original storing peers');
488
- }
489
-
490
- // Clear the subscription key field after successful subscription
491
- if (dhtSubscribeKey) {
492
- dhtSubscribeKey.value = '';
493
- }
494
- } catch (error) {
495
- this.addDHTLogEntry(`❌ Error subscribing to ${key}: ${error.message}`);
496
- }
497
- });
498
- }
499
-
500
- // Unsubscribe from DHT key
501
- if (dhtUnsubscribeBtn) {
502
- dhtUnsubscribeBtn.addEventListener('click', async () => {
503
- // Use the dedicated subscription key field
504
- const key = dhtSubscribeKey?.value?.trim();
505
-
506
- if (!key) {
507
- this.addDHTLogEntry('❌ Error: Key is required for unsubscription');
508
- return;
509
- }
510
-
511
- if (!this.mesh.isDHTEnabled()) {
512
- this.addDHTLogEntry('❌ Error: WebDHT is disabled');
513
- return;
514
- }
515
-
516
- try {
517
- await this.mesh.dhtUnsubscribe(key);
518
- this.addDHTLogEntry(`🔕 Unsubscribed from: ${key}`);
519
-
520
- // Clear the subscription key field after successful unsubscription
521
- if (dhtSubscribeKey) {
522
- dhtSubscribeKey.value = '';
523
- }
524
- } catch (error) {
525
- this.addDHTLogEntry(`❌ Error unsubscribing from ${key}: ${error.message}`);
526
- }
527
- });
528
- }
529
- }
530
-
531
- setupStorageControls() {
532
- // Ensure storage section starts collapsed with robust hiding
533
- const storageSection = document.querySelector('.storage');
534
- const storageToggle = document.getElementById('storage-toggle');
535
- const storageContent = document.getElementById('storage-content');
536
-
537
- if (storageSection && storageToggle && storageContent) {
538
- // Force initial collapsed state with multiple approaches
539
- storageSection.setAttribute('aria-expanded', 'false');
540
- storageToggle.setAttribute('aria-expanded', 'false');
541
-
542
- // Use multiple ways to hide the content
543
- storageContent.style.display = 'none';
544
- storageContent.style.visibility = 'hidden';
545
- storageContent.style.maxHeight = '0';
546
- storageContent.style.overflow = 'hidden';
547
- storageContent.classList.add('collapsed');
548
-
549
- // Ensure the toggle button shows collapsed state
550
- if (storageToggle.textContent && !storageToggle.textContent.includes('▶')) {
551
- storageToggle.textContent = storageToggle.textContent.replace('▼', '▶');
552
- }
553
- }
554
-
555
- // Enable/Disable Storage
556
- const storageEnableBtn = document.getElementById('storage-enable-btn');
557
- const storageDisableBtn = document.getElementById('storage-disable-btn');
558
- const storageClearBtn = document.getElementById('storage-clear-btn');
559
-
560
- if (storageEnableBtn) {
561
- storageEnableBtn.addEventListener('click', async () => {
562
- try {
563
- if (!this.mesh.distributedStorage) {
564
- this.addStorageLogEntry('❌ Error: Distributed storage not available');
565
- return;
566
- }
567
-
568
- await this.mesh.distributedStorage.enable();
569
- this.addStorageLogEntry('✅ Distributed storage enabled');
570
- this.updateStorageStatus();
571
- } catch (error) {
572
- this.addStorageLogEntry(`❌ Error enabling storage: ${error.message}`);
573
- }
574
- });
575
- }
576
-
577
- if (storageDisableBtn) {
578
- storageDisableBtn.addEventListener('click', async () => {
579
- try {
580
- if (!this.mesh.distributedStorage) {
581
- this.addStorageLogEntry('❌ Error: Distributed storage not available');
582
- return;
583
- }
584
-
585
- await this.mesh.distributedStorage.disable();
586
- this.addStorageLogEntry('⚠️ Distributed storage disabled');
587
- this.updateStorageStatus();
588
- } catch (error) {
589
- this.addStorageLogEntry(`❌ Error disabling storage: ${error.message}`);
590
- }
591
- });
592
- }
593
-
594
- if (storageClearBtn) {
595
- storageClearBtn.addEventListener('click', async () => {
596
- if (!confirm('Are you sure you want to clear all stored data? This cannot be undone.')) {
597
- return;
598
- }
599
-
600
- try {
601
- if (!this.mesh.distributedStorage) {
602
- this.addStorageLogEntry('❌ Error: Distributed storage not available');
603
- return;
604
- }
605
-
606
- await this.mesh.distributedStorage.clear();
607
- this.addStorageLogEntry('🗑️ All stored data cleared');
608
- this.updateStorageStatus();
609
- } catch (error) {
610
- this.addStorageLogEntry(`❌ Error clearing storage: ${error.message}`);
611
- }
612
- });
613
- }
614
-
615
- // Store Data
616
- const storageStoreBtn = document.getElementById('storage-store-btn');
617
- const storageUpdateBtn = document.getElementById('storage-update-btn');
618
-
619
- if (storageStoreBtn) {
620
- storageStoreBtn.addEventListener('click', async () => {
621
- await this.handleStorageStore(false);
622
- });
623
- }
624
-
625
- if (storageUpdateBtn) {
626
- storageUpdateBtn.addEventListener('click', async () => {
627
- await this.handleStorageStore(true);
628
- });
629
- }
630
-
631
- // Retrieve Data
632
- const storageGetBtn = document.getElementById('storage-get-btn');
633
- const storageDeleteBtn = document.getElementById('storage-delete-btn');
634
-
635
- if (storageGetBtn) {
636
- storageGetBtn.addEventListener('click', async () => {
637
- const key = document.getElementById('storage-get-key')?.value?.trim();
638
-
639
- if (!key) {
640
- this.addStorageLogEntry('❌ Error: Key is required');
641
- return;
642
- }
643
-
644
- try {
645
- if (!this.mesh.distributedStorage) {
646
- this.addStorageLogEntry('❌ Error: Distributed storage not available');
647
- return;
648
- }
649
-
650
- const result = await this.mesh.distributedStorage.retrieve(key);
651
- if (result !== null) {
652
- this.addStorageLogEntry(`📋 Retrieved: ${key} = ${JSON.stringify(result)}`);
653
-
654
- // Get key info for metadata display
655
- try {
656
- const keyInfo = await this.mesh.distributedStorage.getKeyInfo(key);
657
- if (keyInfo) {
658
- this.addStorageLogEntry(` Metadata: public=${keyInfo.isPublic}, immutable=${keyInfo.isImmutable}, owner=${keyInfo.owner?.substring(0, 8)}...`);
659
- this.addStorageLogEntry(` Created: ${new Date(keyInfo.createdAt).toLocaleString()}`);
660
- }
661
- } catch (metaError) {
662
- // Metadata display is optional, don't fail the retrieval
663
- console.warn('Could not get metadata for display:', metaError);
664
- }
665
- } else {
666
- this.addStorageLogEntry(`❌ Key not found or access denied: ${key}`);
667
- }
668
- } catch (error) {
669
- this.addStorageLogEntry(`❌ Error retrieving ${key}: ${error.message}`);
670
- }
671
- });
672
- }
673
-
674
- if (storageDeleteBtn) {
675
- storageDeleteBtn.addEventListener('click', async () => {
676
- const key = document.getElementById('storage-get-key')?.value?.trim();
677
-
678
- if (!key) {
679
- this.addStorageLogEntry('❌ Error: Key is required');
680
- return;
681
- }
682
-
683
- if (!confirm(`Are you sure you want to delete "${key}"? This cannot be undone.`)) {
684
- return;
685
- }
686
-
687
- try {
688
- if (!this.mesh.distributedStorage) {
689
- this.addStorageLogEntry('❌ Error: Distributed storage not available');
690
- return;
691
- }
692
-
693
- const success = await this.mesh.distributedStorage.delete(key);
694
- if (success) {
695
- this.addStorageLogEntry(`🗑️ Deleted: ${key}`);
696
- this.updateStorageStatus();
697
- } else {
698
- this.addStorageLogEntry(`❌ Failed to delete: ${key}`);
699
- }
700
- } catch (error) {
701
- this.addStorageLogEntry(`❌ Error deleting ${key}: ${error.message}`);
702
- }
703
- });
704
- }
705
-
706
- // Access Control
707
- const storageGrantAccessBtn = document.getElementById('storage-grant-access-btn');
708
- const storageRevokeAccessBtn = document.getElementById('storage-revoke-access-btn');
709
-
710
- if (storageGrantAccessBtn) {
711
- storageGrantAccessBtn.addEventListener('click', async () => {
712
- const key = document.getElementById('storage-access-key')?.value?.trim();
713
- const peerId = document.getElementById('storage-access-peer')?.value?.trim();
714
- const level = document.getElementById('storage-access-level')?.value;
715
-
716
- if (!key || !peerId) {
717
- this.addStorageLogEntry('❌ Error: Key and peer ID are required');
718
- return;
719
- }
720
-
721
- try {
722
- if (!this.mesh.distributedStorage) {
723
- this.addStorageLogEntry('❌ Error: Distributed storage not available');
724
- return;
725
- }
726
-
727
- const success = await this.mesh.distributedStorage.grantAccess(key, peerId, level);
728
- if (success) {
729
- this.addStorageLogEntry(`✅ Granted ${level} access to ${peerId.substring(0, 8)}... for key: ${key}`);
730
- } else {
731
- this.addStorageLogEntry('❌ Failed to grant access');
732
- }
733
- } catch (error) {
734
- this.addStorageLogEntry(`❌ Error granting access: ${error.message}`);
735
- }
736
- });
737
- }
738
-
739
- if (storageRevokeAccessBtn) {
740
- storageRevokeAccessBtn.addEventListener('click', async () => {
741
- const key = document.getElementById('storage-revoke-key')?.value?.trim();
742
- const peerId = document.getElementById('storage-revoke-peer')?.value?.trim();
743
-
744
- if (!key || !peerId) {
745
- this.addStorageLogEntry('❌ Error: Key and peer ID are required');
746
- return;
747
- }
748
-
749
- try {
750
- if (!this.mesh.distributedStorage) {
751
- this.addStorageLogEntry('❌ Error: Distributed storage not available');
752
- return;
753
- }
754
-
755
- const success = await this.mesh.distributedStorage.revokeAccess(key, peerId);
756
- if (success) {
757
- this.addStorageLogEntry(`✅ Revoked access from ${peerId.substring(0, 8)}... for key: ${key}`);
758
- } else {
759
- this.addStorageLogEntry('❌ Failed to revoke access');
760
- }
761
- } catch (error) {
762
- this.addStorageLogEntry(`❌ Error revoking access: ${error.message}`);
763
- }
764
- });
765
- }
766
-
767
- // Bulk Operations
768
- const storageListBtn = document.getElementById('storage-list-btn');
769
- const storageBulkDeleteBtn = document.getElementById('storage-bulk-delete-btn');
770
-
771
- if (storageListBtn) {
772
- storageListBtn.addEventListener('click', async () => {
773
- const prefix = document.getElementById('storage-prefix')?.value?.trim() || '';
774
-
775
- try {
776
- if (!this.mesh.distributedStorage) {
777
- this.addStorageLogEntry('❌ Error: Distributed storage not available');
778
- return;
779
- }
780
-
781
- const keys = await this.mesh.distributedStorage.listKeys(prefix);
782
- if (keys.length > 0) {
783
- this.addStorageLogEntry(`📋 Found ${keys.length} keys with prefix "${prefix}":`);
784
- keys.forEach(key => {
785
- this.addStorageLogEntry(` • ${key}`);
786
- });
787
- } else {
788
- this.addStorageLogEntry(`❌ No keys found with prefix "${prefix}"`);
789
- }
790
- } catch (error) {
791
- this.addStorageLogEntry(`❌ Error listing keys: ${error.message}`);
792
- }
793
- });
794
- }
795
-
796
- if (storageBulkDeleteBtn) {
797
- storageBulkDeleteBtn.addEventListener('click', async () => {
798
- const prefix = document.getElementById('storage-prefix')?.value?.trim();
799
-
800
- if (!prefix) {
801
- this.addStorageLogEntry('❌ Error: Prefix is required for bulk delete');
802
- return;
803
- }
804
-
805
- if (!confirm(`Are you sure you want to delete all keys with prefix "${prefix}"? This cannot be undone.`)) {
806
- return;
807
- }
808
-
809
- try {
810
- if (!this.mesh.distributedStorage) {
811
- this.addStorageLogEntry('❌ Error: Distributed storage not available');
812
- return;
813
- }
814
-
815
- const count = await this.mesh.distributedStorage.bulkDelete(prefix);
816
- this.addStorageLogEntry(`🗑️ Bulk deleted ${count} keys with prefix "${prefix}"`);
817
- this.updateStorageStatus();
818
- } catch (error) {
819
- this.addStorageLogEntry(`❌ Error bulk deleting: ${error.message}`);
820
- }
821
- });
822
- }
823
-
824
- // Search
825
- const storageSearchBtn = document.getElementById('storage-search-btn');
826
-
827
- if (storageSearchBtn) {
828
- storageSearchBtn.addEventListener('click', async () => {
829
- const query = document.getElementById('storage-search-query')?.value?.trim();
830
- const type = document.getElementById('storage-search-type')?.value || 'key';
831
-
832
- if (!query) {
833
- this.addStorageLogEntry('❌ Error: Search query is required');
834
- return;
835
- }
836
-
837
- try {
838
- if (!this.mesh.distributedStorage) {
839
- this.addStorageLogEntry('❌ Error: Distributed storage not available');
840
- return;
841
- }
842
-
843
- const results = await this.mesh.distributedStorage.search(query, type);
844
- if (results.length > 0) {
845
- this.addStorageLogEntry(`🔍 Found ${results.length} results for "${query}" in ${type}:`);
846
- results.forEach(result => {
847
- this.addStorageLogEntry(` • ${result.key}: ${JSON.stringify(result.value).substring(0, 100)}...`);
848
- });
849
- } else {
850
- this.addStorageLogEntry(`❌ No results found for "${query}" in ${type}`);
851
- }
852
- } catch (error) {
853
- this.addStorageLogEntry(`❌ Error searching: ${error.message}`);
854
- }
855
- });
856
- }
857
-
858
- // Backup/Restore
859
- const storageBackupBtn = document.getElementById('storage-backup-btn');
860
- const storageRestoreBtn = document.getElementById('storage-restore-btn');
861
- const storageRestoreFile = document.getElementById('storage-restore-file');
862
-
863
- if (storageBackupBtn) {
864
- storageBackupBtn.addEventListener('click', async () => {
865
- try {
866
- if (!this.mesh.distributedStorage) {
867
- this.addStorageLogEntry('❌ Error: Distributed storage not available');
868
- return;
869
- }
870
-
871
- const backup = await this.mesh.distributedStorage.backup();
872
- const blob = new Blob([JSON.stringify(backup, null, 2)], { type: 'application/json' });
873
- const url = URL.createObjectURL(blob);
874
-
875
- const a = document.createElement('a');
876
- a.href = url;
877
- a.download = `peerpigeon-storage-backup-${new Date().toISOString().replace(/[:.]/g, '-')}.json`;
878
- a.click();
879
-
880
- URL.revokeObjectURL(url);
881
- this.addStorageLogEntry(`💾 Backup created with ${backup.items.length} items`);
882
- } catch (error) {
883
- this.addStorageLogEntry(`❌ Error creating backup: ${error.message}`);
884
- }
885
- });
886
- }
887
-
888
- if (storageRestoreBtn) {
889
- storageRestoreBtn.addEventListener('click', () => {
890
- storageRestoreFile?.click();
891
- });
892
- }
893
-
894
- if (storageRestoreFile) {
895
- storageRestoreFile.addEventListener('change', async (e) => {
896
- const file = e.target.files[0];
897
- if (!file) return;
898
-
899
- try {
900
- const text = await file.text();
901
- const backup = JSON.parse(text);
902
-
903
- if (!this.mesh.distributedStorage) {
904
- this.addStorageLogEntry('❌ Error: Distributed storage not available');
905
- return;
906
- }
907
-
908
- const result = await this.mesh.distributedStorage.restore(backup);
909
- this.addStorageLogEntry(`📥 Restored ${result.restored} items (${result.failed} failed)`);
910
- this.updateStorageStatus();
911
- } catch (error) {
912
- this.addStorageLogEntry(`❌ Error restoring backup: ${error.message}`);
913
- }
914
-
915
- // Clear the file input
916
- e.target.value = '';
917
- });
918
- }
919
- }
920
-
921
- async handleStorageStore(isUpdate = false) {
922
- const key = document.getElementById('storage-key')?.value?.trim();
923
- const value = document.getElementById('storage-value')?.value?.trim();
924
- const encrypt = document.getElementById('storage-encrypt')?.checked ?? true;
925
- const isPublic = document.getElementById('storage-public')?.checked ?? false;
926
- const immutable = document.getElementById('storage-immutable')?.checked ?? false;
927
- const enableCrdt = document.getElementById('storage-crdt')?.checked ?? false;
928
- const ttl = parseInt(document.getElementById('storage-ttl')?.value) || 0;
929
-
930
- if (!key || !value) {
931
- this.addStorageLogEntry('❌ Error: Both key and value are required');
932
- return;
933
- }
934
-
935
- try {
936
- if (!this.mesh.distributedStorage) {
937
- this.addStorageLogEntry('❌ Error: Distributed storage not available');
938
- return;
939
- }
940
-
941
- let parsedValue;
942
- try {
943
- parsedValue = JSON.parse(value);
944
- } catch {
945
- parsedValue = value; // Use as string if not valid JSON
946
- }
947
-
948
- const options = {
949
- encrypt,
950
- isPublic,
951
- isImmutable: immutable,
952
- enableCRDT: enableCrdt,
953
- ttl: ttl > 0 ? ttl * 1000 : undefined // Convert to milliseconds
954
- };
955
-
956
- let success;
957
- if (isUpdate) {
958
- success = await this.mesh.distributedStorage.update(key, parsedValue, options);
959
- if (success) {
960
- this.addStorageLogEntry(`🔄 Updated: ${key} = ${JSON.stringify(parsedValue)}`);
961
- } else {
962
- this.addStorageLogEntry(`❌ Failed to update: ${key}`);
963
- }
964
- } else {
965
- success = await this.mesh.distributedStorage.store(key, parsedValue, options);
966
- if (success) {
967
- this.addStorageLogEntry(`💾 Stored: ${key} = ${JSON.stringify(parsedValue)}`);
968
- } else {
969
- this.addStorageLogEntry(`❌ Failed to store: ${key}`);
970
- }
971
- }
972
-
973
- if (success) {
974
- const optionsStr = [];
975
- if (encrypt) optionsStr.push('encrypted');
976
- if (isPublic) optionsStr.push('public');
977
- if (immutable) optionsStr.push('immutable');
978
- if (enableCrdt) optionsStr.push('CRDT');
979
- if (ttl > 0) optionsStr.push(`TTL: ${ttl}s`);
980
-
981
- if (optionsStr.length > 0) {
982
- this.addStorageLogEntry(` Options: ${optionsStr.join(', ')}`);
983
- }
984
-
985
- this.updateStorageStatus();
986
- }
987
- } catch (error) {
988
- this.addStorageLogEntry(`❌ Error ${isUpdate ? 'updating' : 'storing'} ${key}: ${error.message}`);
989
- }
990
- }
991
-
992
- addStorageLogEntry(message) {
993
- const logElement = document.getElementById('storage-log');
994
- if (!logElement) return;
995
-
996
- const entry = document.createElement('div');
997
- entry.className = 'log-entry';
998
- entry.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
999
-
1000
- logElement.appendChild(entry);
1001
- logElement.scrollTop = logElement.scrollHeight;
1002
-
1003
- // Keep only last 100 entries
1004
- while (logElement.children.length > 100) {
1005
- logElement.removeChild(logElement.firstChild);
1006
- }
1007
- }
1008
-
1009
- updateStorageStatus() {
1010
- if (!this.mesh.distributedStorage) {
1011
- document.getElementById('storage-status').textContent = 'Not Available';
1012
- document.getElementById('storage-item-count').textContent = '0';
1013
- document.getElementById('storage-total-size').textContent = '0 bytes';
1014
- return;
1015
- }
1016
-
1017
- const isEnabled = this.mesh.distributedStorage.isEnabled();
1018
- document.getElementById('storage-status').textContent = isEnabled ? 'Enabled' : 'Disabled';
1019
-
1020
- // Get storage stats if available
1021
- this.mesh.distributedStorage.getStats().then(stats => {
1022
- document.getElementById('storage-item-count').textContent = stats.itemCount.toString();
1023
- document.getElementById('storage-total-size').textContent = this.formatBytes(stats.totalSize);
1024
- }).catch(() => {
1025
- document.getElementById('storage-item-count').textContent = '0';
1026
- document.getElementById('storage-total-size').textContent = '0 bytes';
1027
- });
1028
- }
1029
-
1030
- formatBytes(bytes) {
1031
- if (bytes === 0) return '0 bytes';
1032
- const k = 1024;
1033
- const sizes = ['bytes', 'KB', 'MB', 'GB'];
1034
- const i = Math.floor(Math.log(bytes) / Math.log(k));
1035
- return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
1036
- }
1037
-
1038
- setupCryptoControls() {
1039
- // Key Management Controls
1040
- const generateBtn = document.getElementById('crypto-generate-btn');
1041
- const resetBtn = document.getElementById('crypto-reset-btn');
1042
- const selfTestBtn = document.getElementById('crypto-self-test-btn');
1043
-
1044
- // User Authentication Controls
1045
- const loginBtn = document.getElementById('crypto-login-btn');
1046
- const aliasInput = document.getElementById('crypto-alias');
1047
- const passwordInput = document.getElementById('crypto-password');
1048
-
1049
- // Messaging Controls
1050
- const testMessageInput = document.getElementById('crypto-test-message');
1051
- const testPeerInput = document.getElementById('crypto-test-peer');
1052
- const sendEncryptedBtn = document.getElementById('crypto-send-encrypted-btn');
1053
-
1054
- // Group Encryption Controls
1055
- const groupIdInput = document.getElementById('crypto-group-id');
1056
- const createGroupBtn = document.getElementById('crypto-create-group-btn');
1057
- const groupMessageInput = document.getElementById('crypto-group-message');
1058
- const groupSelect = document.getElementById('crypto-group-select');
1059
- const sendGroupBtn = document.getElementById('crypto-send-group-btn');
1060
-
1061
- // Advanced Controls
1062
- const exportKeyBtn = document.getElementById('crypto-export-key-btn');
1063
- const importPeerKeyBtn = document.getElementById('crypto-import-peer-key-btn');
1064
- const benchmarkBtn = document.getElementById('crypto-benchmark-btn');
1065
-
1066
- // Import Form Controls
1067
- const importForm = document.getElementById('crypto-import-form');
1068
- const importPeerIdInput = document.getElementById('crypto-import-peer-id');
1069
- const importPublicKeyInput = document.getElementById('crypto-import-public-key');
1070
- const importConfirmBtn = document.getElementById('crypto-import-confirm-btn');
1071
- const importCancelBtn = document.getElementById('crypto-import-cancel-btn');
1072
-
1073
- // Key Management Event Handlers
1074
- if (generateBtn) {
1075
- generateBtn.addEventListener('click', async () => {
1076
- try {
1077
- this.addCryptoTestResult('🔄 Generating new keypair...', 'info');
1078
- await this.mesh.initCrypto({ generateKeypair: true });
1079
- this.addCryptoTestResult('✅ New keypair generated successfully', 'success');
1080
- this.updateCryptoStatus();
1081
- } catch (error) {
1082
- this.addCryptoTestResult(`❌ Failed to generate keypair: ${error.message}`, 'error');
1083
- }
1084
- });
1085
- }
1086
-
1087
- if (resetBtn) {
1088
- resetBtn.addEventListener('click', () => {
1089
- if (confirm('This will clear all crypto keys and reset the crypto system. Continue?')) {
1090
- try {
1091
- this.mesh.resetCrypto();
1092
- this.addCryptoTestResult('✅ Crypto system reset', 'success');
1093
- this.updateCryptoStatus();
1094
- this.clearCryptoTestResults();
1095
- } catch (error) {
1096
- this.addCryptoTestResult(`❌ Failed to reset crypto: ${error.message}`, 'error');
1097
- }
1098
- }
1099
- });
1100
- }
1101
-
1102
- if (selfTestBtn) {
1103
- selfTestBtn.addEventListener('click', async () => {
1104
- try {
1105
- this.addCryptoTestResult('🔄 Running crypto self-tests...', 'info');
1106
- const results = await this.mesh.runCryptoTests();
1107
-
1108
- // Handle the actual format returned by CryptoManager
1109
- if (results.keypairGeneration !== undefined) {
1110
- const status = results.keypairGeneration ? '✅' : '❌';
1111
- const type = results.keypairGeneration ? 'success' : 'error';
1112
- this.addCryptoTestResult(`${status} keypairGeneration: ${results.keypairGeneration}`, type);
1113
- }
1114
-
1115
- if (results.encryption !== undefined) {
1116
- const status = results.encryption ? '✅' : '❌';
1117
- const type = results.encryption ? 'success' : 'error';
1118
- this.addCryptoTestResult(`${status} encryption: ${results.encryption}`, type);
1119
- }
1120
-
1121
- if (results.decryption !== undefined) {
1122
- const status = results.decryption ? '✅' : '❌';
1123
- const type = results.decryption ? 'success' : 'error';
1124
- this.addCryptoTestResult(`${status} decryption: ${results.decryption}`, type);
1125
- }
1126
-
1127
- if (results.signing !== undefined) {
1128
- const status = results.signing ? '✅' : '❌';
1129
- const type = results.signing ? 'success' : 'error';
1130
- this.addCryptoTestResult(`${status} signing: ${results.signing}`, type);
1131
- }
1132
-
1133
- if (results.verification !== undefined) {
1134
- const status = results.verification ? '✅' : '❌';
1135
- const type = results.verification ? 'success' : 'error';
1136
- this.addCryptoTestResult(`${status} verification: ${results.verification}`, type);
1137
- }
1138
-
1139
- if (results.groupEncryption !== undefined) {
1140
- const status = results.groupEncryption ? '✅' : '❌';
1141
- const type = results.groupEncryption ? 'success' : 'error';
1142
- this.addCryptoTestResult(`${status} groupEncryption: ${results.groupEncryption}`, type);
1143
- }
1144
-
1145
- if (results.errors && results.errors.length > 0) {
1146
- results.errors.forEach(error => {
1147
- this.addCryptoTestResult(`❌ errors: ${error}`, 'error');
1148
- });
1149
- }
1150
- } catch (error) {
1151
- this.addCryptoTestResult(`❌ Self-test failed: ${error.message}`, 'error');
1152
- }
1153
- });
1154
- }
1155
-
1156
- // User Authentication Event Handlers
1157
- if (loginBtn && aliasInput && passwordInput) {
1158
- loginBtn.addEventListener('click', async () => {
1159
- const alias = aliasInput.value.trim();
1160
- const password = passwordInput.value.trim();
1161
-
1162
- if (!alias || !password) {
1163
- this.addCryptoTestResult('❌ Both alias and password are required', 'error');
1164
- return;
1165
- }
1166
-
1167
- try {
1168
- this.addCryptoTestResult(`🔄 Authenticating as ${alias}...`, 'info');
1169
- await this.mesh.initCrypto({ alias, password });
1170
- this.addCryptoTestResult(`✅ Authenticated as ${alias}`, 'success');
1171
- this.updateCryptoStatus();
1172
-
1173
- // Clear password for security
1174
- passwordInput.value = '';
1175
- } catch (error) {
1176
- this.addCryptoTestResult(`❌ Authentication failed: ${error.message}`, 'error');
1177
- }
1178
- });
1179
- }
1180
-
1181
- // Messaging Event Handlers
1182
- if (sendEncryptedBtn && testMessageInput && testPeerInput) {
1183
- sendEncryptedBtn.addEventListener('click', async () => {
1184
- const message = testMessageInput.value.trim();
1185
- const peerId = testPeerInput.value.trim();
1186
-
1187
- if (!message) {
1188
- this.addCryptoTestResult('❌ Message is required', 'error');
1189
- return;
1190
- }
1191
-
1192
- if (!peerId) {
1193
- this.addCryptoTestResult('❌ Target peer ID is required', 'error');
1194
- return;
1195
- }
1196
-
1197
- try {
1198
- this.addCryptoTestResult(`🔄 Sending encrypted message to ${peerId.substring(0, 8)}...`, 'info');
1199
- await this.mesh.sendEncryptedMessage(peerId, message);
1200
- this.addCryptoTestResult('✅ Encrypted message sent', 'success');
1201
- testMessageInput.value = '';
1202
- } catch (error) {
1203
- this.addCryptoTestResult(`❌ Failed to send encrypted message: ${error.message}`, 'error');
1204
- }
1205
- });
1206
- }
1207
-
1208
- // Group Encryption Event Handlers
1209
- if (createGroupBtn && groupIdInput) {
1210
- createGroupBtn.addEventListener('click', async () => {
1211
- const groupId = groupIdInput.value.trim();
1212
-
1213
- if (!groupId) {
1214
- this.addCryptoTestResult('❌ Group ID is required', 'error');
1215
- return;
1216
- }
1217
-
1218
- try {
1219
- this.addCryptoTestResult(`🔄 Creating group key for ${groupId}...`, 'info');
1220
- await this.mesh.generateGroupKey(groupId);
1221
- this.addCryptoTestResult(`✅ Group key created for ${groupId}`, 'success');
1222
- this.updateGroupSelect();
1223
- groupIdInput.value = '';
1224
- } catch (error) {
1225
- this.addCryptoTestResult(`❌ Failed to create group key: ${error.message}`, 'error');
1226
- }
1227
- });
1228
- }
1229
-
1230
- if (sendGroupBtn && groupMessageInput && groupSelect) {
1231
- sendGroupBtn.addEventListener('click', async () => {
1232
- const message = groupMessageInput.value.trim();
1233
- const groupId = groupSelect.value;
1234
-
1235
- if (!message) {
1236
- this.addCryptoTestResult('❌ Group message is required', 'error');
1237
- return;
1238
- }
1239
-
1240
- if (!groupId) {
1241
- this.addCryptoTestResult('❌ Please select a group', 'error');
1242
- return;
1243
- }
1244
-
1245
- try {
1246
- this.addCryptoTestResult(`🔄 Sending encrypted group message to ${groupId}...`, 'info');
1247
- await this.mesh.sendEncryptedBroadcast(message, groupId);
1248
- this.addCryptoTestResult('✅ Encrypted group message sent', 'success');
1249
- groupMessageInput.value = '';
1250
- } catch (error) {
1251
- this.addCryptoTestResult(`❌ Failed to send group message: ${error.message}`, 'error');
1252
- }
1253
- });
1254
- }
1255
-
1256
- // Advanced Controls Event Handlers
1257
- if (exportKeyBtn) {
1258
- exportKeyBtn.addEventListener('click', () => {
1259
- try {
1260
- const keyData = this.mesh.exportPublicKey();
1261
- if (keyData) {
1262
- const exportText = JSON.stringify(keyData, null, 2);
1263
- navigator.clipboard.writeText(exportText).then(() => {
1264
- this.addCryptoTestResult('✅ Public key copied to clipboard', 'success');
1265
- }).catch(() => {
1266
- // Fallback - show in alert
1267
- alert('Public Key:\n\n' + exportText);
1268
- this.addCryptoTestResult('✅ Public key exported (check dialog)', 'success');
1269
- });
1270
- } else {
1271
- this.addCryptoTestResult('❌ No public key available to export', 'error');
1272
- }
1273
- } catch (error) {
1274
- this.addCryptoTestResult(`❌ Failed to export key: ${error.message}`, 'error');
1275
- }
1276
- });
1277
- }
1278
-
1279
- if (importPeerKeyBtn && importForm) {
1280
- importPeerKeyBtn.addEventListener('click', () => {
1281
- importForm.style.display = importForm.style.display === 'none' ? 'block' : 'none';
1282
- });
1283
- }
1284
-
1285
- if (importConfirmBtn && importPeerIdInput && importPublicKeyInput && importForm) {
1286
- importConfirmBtn.addEventListener('click', () => {
1287
- const peerId = importPeerIdInput.value.trim();
1288
- const publicKey = importPublicKeyInput.value.trim();
1289
-
1290
- if (!peerId || peerId.length !== 40) {
1291
- this.addCryptoTestResult('❌ Valid 40-character peer ID is required', 'error');
1292
- return;
1293
- }
1294
-
1295
- if (!publicKey) {
1296
- this.addCryptoTestResult('❌ Public key is required', 'error');
1297
- return;
1298
- }
1299
-
1300
- try {
1301
- // Try to parse as JSON first (for full keypair with pub/epub)
1302
- let keyData;
1303
- try {
1304
- keyData = JSON.parse(publicKey);
1305
- // Validate that it has the expected structure
1306
- if (!keyData.pub && !keyData.epub && !keyData.publicKey) {
1307
- throw new Error('Invalid key format');
1308
- }
1309
- } catch (jsonError) {
1310
- // If JSON parsing fails, treat as plain string (legacy format)
1311
- keyData = publicKey;
1312
- }
1313
-
1314
- const success = this.mesh.addPeerPublicKey(peerId, keyData);
1315
- if (success) {
1316
- const keyType = typeof keyData === 'object'
1317
- ? (keyData.pub && keyData.epub ? 'complete keypair' : 'partial key')
1318
- : 'legacy key';
1319
- this.addCryptoTestResult(`✅ Public key imported for ${peerId.substring(0, 8)}... (${keyType})`, 'success');
1320
- if (typeof keyData === 'string' || !keyData.epub) {
1321
- this.addCryptoTestResult('⚠️ Warning: Only signing key imported. Encryption may not work.', 'warning');
1322
- }
1323
- this.updateCryptoStatus();
1324
- importPeerIdInput.value = '';
1325
- importPublicKeyInput.value = '';
1326
- importForm.style.display = 'none';
1327
- } else {
1328
- this.addCryptoTestResult('❌ Failed to import public key', 'error');
1329
- }
1330
- } catch (error) {
1331
- this.addCryptoTestResult(`❌ Failed to import key: ${error.message}`, 'error');
1332
- }
1333
- });
1334
- }
1335
-
1336
- if (importCancelBtn && importForm) {
1337
- importCancelBtn.addEventListener('click', () => {
1338
- importForm.style.display = 'none';
1339
- if (importPeerIdInput) importPeerIdInput.value = '';
1340
- if (importPublicKeyInput) importPublicKeyInput.value = '';
1341
- });
1342
- }
1343
-
1344
- if (benchmarkBtn) {
1345
- benchmarkBtn.addEventListener('click', async () => {
1346
- try {
1347
- this.addCryptoTestResult('🔄 Running crypto benchmark...', 'info');
1348
-
1349
- const testData = 'This is a test message for benchmarking crypto performance.';
1350
- const iterations = 100;
1351
-
1352
- // Test encryption/decryption performance
1353
- const startTime = performance.now();
1354
- for (let i = 0; i < iterations; i++) {
1355
- const encrypted = await this.mesh.encryptMessage(testData);
1356
- await this.mesh.decryptMessage(encrypted);
1357
- }
1358
- const endTime = performance.now();
1359
-
1360
- const totalTime = endTime - startTime;
1361
- const avgTime = totalTime / iterations;
1362
-
1363
- this.addCryptoTestResult(`✅ Benchmark completed: ${iterations} iterations`, 'success');
1364
- this.addCryptoTestResult(` Total time: ${totalTime.toFixed(2)}ms`, 'info');
1365
- this.addCryptoTestResult(` Average time per cycle: ${avgTime.toFixed(2)}ms`, 'info');
1366
- } catch (error) {
1367
- this.addCryptoTestResult(`❌ Benchmark failed: ${error.message}`, 'error');
1368
- }
1369
- });
1370
- }
1371
- }
1372
-
1373
- setupMediaControls() {
1374
- // Start media button
1375
- document.getElementById('start-media-btn').addEventListener('click', async () => {
1376
- await this.startMedia();
1377
- });
1378
-
1379
- // Stop media button
1380
- document.getElementById('stop-media-btn').addEventListener('click', async () => {
1381
- await this.stopMedia();
1382
- });
1383
-
1384
- // Toggle video button
1385
- document.getElementById('toggle-video-btn').addEventListener('click', () => {
1386
- this.toggleVideo();
1387
- });
1388
-
1389
- // Toggle audio button
1390
- document.getElementById('toggle-audio-btn').addEventListener('click', () => {
1391
- this.toggleAudio();
1392
- });
1393
-
1394
- // Audio test button
1395
- document.getElementById('test-audio-btn').addEventListener('click', () => {
1396
- this.testAudio();
1397
- });
1398
-
1399
- // Media type checkboxes
1400
- document.getElementById('enable-video').addEventListener('change', () => {
1401
- this.updateMediaButtonStates();
1402
- });
1403
-
1404
- document.getElementById('enable-audio').addEventListener('change', () => {
1405
- this.updateMediaButtonStates();
1406
- });
1407
-
1408
- // Device selection dropdowns
1409
- document.getElementById('camera-select').addEventListener('change', () => {
1410
- // Auto-restart media if it's currently active
1411
- if (this.mesh.getMediaState().hasLocalStream) {
1412
- this.startMedia();
1413
- }
1414
- });
1415
-
1416
- document.getElementById('microphone-select').addEventListener('change', () => {
1417
- // Auto-restart media if it's currently active
1418
- if (this.mesh.getMediaState().hasLocalStream) {
1419
- this.startMedia();
1420
- }
1421
- });
1422
- }
1423
-
1424
- setupCollapsibleSections() {
1425
- const sections = [
1426
- 'discovered-peers',
1427
- 'connected-peers',
1428
- 'manual-connection',
1429
- 'settings',
1430
- 'dht',
1431
- 'storage',
1432
- 'crypto',
1433
- 'media'
1434
- ];
1435
-
1436
- sections.forEach(sectionId => {
1437
- const toggle = document.getElementById(`${sectionId}-toggle`);
1438
- const content = document.getElementById(`${sectionId}-content`);
1439
- const section = document.querySelector(`.${sectionId}`);
1440
-
1441
- if (toggle && content && section) {
1442
- // Force all sections to start collapsed with multiple approaches
1443
- section.setAttribute('aria-expanded', 'false');
1444
- toggle.setAttribute('aria-expanded', 'false');
1445
-
1446
- // Use multiple ways to hide the content
1447
- content.style.display = 'none';
1448
- content.style.visibility = 'hidden';
1449
- content.style.maxHeight = '0';
1450
- content.style.overflow = 'hidden';
1451
- content.classList.add('collapsed');
1452
-
1453
- // Ensure the toggle button shows collapsed state
1454
- if (toggle.textContent && !toggle.textContent.includes('▶')) {
1455
- toggle.textContent = toggle.textContent.replace('▼', '▶');
1456
- }
1457
-
1458
- toggle.addEventListener('click', () => {
1459
- this.toggleSection(sectionId);
1460
- });
1461
- }
1462
- });
1463
- }
1464
-
1465
- toggleSection(sectionId) {
1466
- const toggle = document.getElementById(`${sectionId}-toggle`);
1467
- const content = document.getElementById(`${sectionId}-content`);
1468
-
1469
- if (!toggle || !content) {
1470
- console.warn(`Could not find elements for section: ${sectionId}`);
1471
- return;
1472
- }
1473
-
1474
- const section = toggle.closest(`.${sectionId}`);
1475
-
1476
- if (!section) {
1477
- console.warn(`Could not find section container for: ${sectionId}`, {
1478
- toggle,
1479
- toggleParent: toggle.parentElement,
1480
- toggleParentParent: toggle.parentElement?.parentElement,
1481
- classList: toggle.parentElement?.parentElement?.classList
1482
- });
1483
- return;
1484
- }
1485
-
1486
- const isExpanded = toggle.getAttribute('aria-expanded') === 'true';
1487
-
1488
- toggle.setAttribute('aria-expanded', !isExpanded);
1489
-
1490
- // Add null check before calling setAttribute
1491
- if (section) {
1492
- section.setAttribute('aria-expanded', !isExpanded);
1493
- }
1494
-
1495
- if (isExpanded) {
1496
- // Collapse - hide with multiple approaches
1497
- content.style.display = 'none';
1498
- content.style.visibility = 'hidden';
1499
- content.style.maxHeight = '0';
1500
- content.style.overflow = 'hidden';
1501
- content.classList.add('collapsed');
1502
- toggle.textContent = toggle.textContent.replace('▼', '▶');
1503
- } else {
1504
- // Expand - show and reset styles
1505
- content.style.display = 'block';
1506
- content.style.visibility = 'visible';
1507
- content.style.maxHeight = 'none';
1508
- content.style.overflow = 'visible';
1509
- content.classList.remove('collapsed');
1510
- toggle.textContent = toggle.textContent.replace('▶', '▼');
1511
- }
1512
- }
1513
-
1514
- // Media-related methods
1515
- async initializeMedia() {
1516
- try {
1517
- // Initialize media manager
1518
- await this.mesh.initializeMedia();
1519
-
1520
- // Populate device lists
1521
- await this.updateDeviceLists();
1522
-
1523
- // Update button states
1524
- this.updateMediaButtonStates();
1525
-
1526
- console.log('Media initialized successfully');
1527
- } catch (error) {
1528
- console.error('Failed to initialize media:', error);
1529
- this.addMessage('System', `Failed to initialize media: ${error.message}`, 'error');
1530
- }
1531
- }
1532
-
1533
- async updateDeviceLists() {
1534
- try {
1535
- const devices = await this.mesh.enumerateMediaDevices();
1536
-
1537
- // Update camera list
1538
- const cameraSelect = document.getElementById('camera-select');
1539
- if (cameraSelect) {
1540
- cameraSelect.innerHTML = '<option value="">Select camera...</option>';
1541
- devices.cameras.forEach(device => {
1542
- const option = document.createElement('option');
1543
- option.value = device.deviceId;
1544
- option.textContent = device.label || `Camera ${device.deviceId.substring(0, 8)}...`;
1545
- cameraSelect.appendChild(option);
1546
- });
1547
- cameraSelect.disabled = devices.cameras.length === 0;
1548
- }
1549
-
1550
- // Update microphone list
1551
- const micSelect = document.getElementById('microphone-select');
1552
- if (micSelect) {
1553
- micSelect.innerHTML = '<option value="">Select microphone...</option>';
1554
- devices.microphones.forEach(device => {
1555
- const option = document.createElement('option');
1556
- option.value = device.deviceId;
1557
- option.textContent = device.label || `Microphone ${device.deviceId.substring(0, 8)}...`;
1558
- micSelect.appendChild(option);
1559
- });
1560
- micSelect.disabled = devices.microphones.length === 0;
1561
- }
1562
- } catch (error) {
1563
- console.error('Failed to update device lists:', error);
1564
- }
1565
- }
1566
-
1567
- updateMediaButtonStates() {
1568
- const videoEnabled = document.getElementById('enable-video')?.checked || false;
1569
- const audioEnabled = document.getElementById('enable-audio')?.checked || false;
1570
- const mediaState = this.mesh.getMediaState();
1571
-
1572
- // Enable start button if at least one media type is selected
1573
- const startBtn = document.getElementById('start-media-btn');
1574
- if (startBtn) {
1575
- startBtn.disabled = !(videoEnabled || audioEnabled) || mediaState.hasLocalStream;
1576
- }
1577
-
1578
- // Enable stop button if media is active
1579
- const stopBtn = document.getElementById('stop-media-btn');
1580
- if (stopBtn) {
1581
- stopBtn.disabled = !mediaState.hasLocalStream;
1582
- }
1583
-
1584
- // Enable toggle buttons if media is active
1585
- const toggleVideoBtn = document.getElementById('toggle-video-btn');
1586
- const toggleAudioBtn = document.getElementById('toggle-audio-btn');
1587
-
1588
- if (toggleVideoBtn) {
1589
- toggleVideoBtn.disabled = !mediaState.hasLocalStream;
1590
- toggleVideoBtn.textContent = mediaState.videoEnabled ? 'Turn Off Video' : 'Turn On Video';
1591
- }
1592
-
1593
- if (toggleAudioBtn) {
1594
- toggleAudioBtn.disabled = !mediaState.hasLocalStream;
1595
- toggleAudioBtn.textContent = mediaState.audioEnabled ? 'Turn Off Audio' : 'Turn On Audio';
1596
- }
1597
- }
1598
-
1599
- async startMedia() {
1600
- try {
1601
- const videoEnabled = document.getElementById('enable-video')?.checked || false;
1602
- const audioEnabled = document.getElementById('enable-audio')?.checked || false;
1603
-
1604
- // Initialize audio context for better audio support
1605
- if (audioEnabled && (window.AudioContext || window.webkitAudioContext)) {
1606
- const AudioContext = window.AudioContext || window.webkitAudioContext;
1607
- try {
1608
- const audioContext = new AudioContext();
1609
- if (audioContext.state === 'suspended') {
1610
- await audioContext.resume();
1611
- console.log('Audio context resumed for local media');
1612
- }
1613
- console.log('Audio context state:', audioContext.state);
1614
- } catch (e) {
1615
- console.log('Could not initialize audio context:', e);
1616
- }
1617
- }
1618
-
1619
- const deviceIds = {};
1620
- const cameraSelect = document.getElementById('camera-select');
1621
- const micSelect = document.getElementById('microphone-select');
1622
-
1623
- if (cameraSelect?.value) {
1624
- deviceIds.camera = cameraSelect.value;
1625
- }
1626
-
1627
- if (micSelect?.value) {
1628
- deviceIds.microphone = micSelect.value;
1629
- }
1630
-
1631
- await this.mesh.startMedia({
1632
- video: videoEnabled,
1633
- audio: audioEnabled,
1634
- deviceIds
1635
- });
1636
-
1637
- this.addMessage('System', 'Media started successfully');
1638
- this.updateMediaButtonStates();
1639
- } catch (error) {
1640
- console.error('Failed to start media:', error);
1641
- this.addMessage('System', `Failed to start media: ${error.message}`, 'error');
1642
- }
1643
- }
1644
-
1645
- async stopMedia() {
1646
- try {
1647
- await this.mesh.stopMedia();
1648
- this.addMessage('System', 'Media stopped');
1649
- this.updateMediaButtonStates();
1650
- this.clearLocalVideo();
1651
- } catch (error) {
1652
- console.error('Failed to stop media:', error);
1653
- this.addMessage('System', `Failed to stop media: ${error.message}`, 'error');
1654
- }
1655
- }
1656
-
1657
- toggleVideo() {
1658
- try {
1659
- const enabled = this.mesh.toggleVideo();
1660
- this.addMessage('System', `Video ${enabled ? 'enabled' : 'disabled'}`);
1661
- this.updateMediaButtonStates();
1662
- } catch (error) {
1663
- console.error('Failed to toggle video:', error);
1664
- this.addMessage('System', `Failed to toggle video: ${error.message}`, 'error');
1665
- }
1666
- }
1667
-
1668
- toggleAudio() {
1669
- try {
1670
- const enabled = this.mesh.toggleAudio();
1671
- this.addMessage('System', `Audio ${enabled ? 'enabled' : 'disabled'}`);
1672
- this.updateMediaButtonStates();
1673
- } catch (error) {
1674
- console.error('Failed to toggle audio:', error);
1675
- this.addMessage('System', `Failed to toggle audio: ${error.message}`, 'error');
1676
- }
1677
- }
1678
-
1679
- async testAudio() {
1680
- try {
1681
- console.log('🔊 Starting audio test...');
1682
- this.addMessage('System', '🔊 Testing audio system...', 'info');
1683
-
1684
- // First, run diagnostics to understand current state
1685
- this.logPeerDiagnostics();
1686
-
1687
- // Test 0: Verify we have actual peer connections (not just self)
1688
- const allPeers = this.mesh.getPeers();
1689
- const connectedPeers = allPeers.filter(peer => peer.status === 'connected');
1690
- const peersWithMedia = allPeers.filter(peer => {
1691
- const peerConnection = this.mesh.connectionManager.getPeer(peer.peerId);
1692
- return peerConnection && (peerConnection.remoteStream || peerConnection.connection?.connectionState === 'connected');
1693
- });
1694
-
1695
- console.log('🔊 All peers:', allPeers.length);
1696
- console.log('🔊 Connected peers (data channel):', connectedPeers.length);
1697
- console.log('🔊 Peers with media/WebRTC:', peersWithMedia.length);
1698
-
1699
- // Log detailed peer status
1700
- allPeers.forEach(peer => {
1701
- const peerConnection = this.mesh.connectionManager.getPeer(peer.peerId);
1702
- console.log(`🔊 Peer ${peer.peerId.substring(0, 8)}:`, {
1703
- status: peer.status,
1704
- webrtcState: peerConnection?.connection?.connectionState,
1705
- dataChannelState: peerConnection?.dataChannel?.readyState,
1706
- hasRemoteStream: !!peerConnection?.remoteStream,
1707
- hasLocalStream: !!peerConnection?.localStream
1708
- });
1709
- });
1710
-
1711
- this.addMessage('System', `🔊 Found ${allPeers.length} total peers (${connectedPeers.length} with data channel, ${peersWithMedia.length} with media)`, 'info');
1712
-
1713
- if (peersWithMedia.length === 0) {
1714
- this.addMessage('System', '❌ No peers with active media! You need to open this in TWO different browser tabs/windows and connect them.', 'error');
1715
- console.log('❌ NO PEERS WITH MEDIA: Open this URL in two different browser tabs and ensure they connect to each other');
1716
- return;
1717
- }
1718
-
1719
- // Test each peer connection individually
1720
- peersWithMedia.forEach((peer, index) => {
1721
- const connection = this.mesh.connectionManager.peers.get(peer.peerId);
1722
- if (connection) {
1723
- console.log(`🔊 Peer ${index + 1} (${peer.peerId.substring(0, 8)}...):`);
1724
-
1725
- const localStream = connection.getLocalStream();
1726
- const remoteStream = connection.getRemoteStream();
1727
-
1728
- // Check local stream
1729
- if (localStream) {
1730
- const localAudioTracks = localStream.getAudioTracks();
1731
- console.log(` - Local audio tracks: ${localAudioTracks.length}`);
1732
- this.addMessage('System', ` Peer ${index + 1} - Local audio: ${localAudioTracks.length} tracks`, 'info');
1733
- localAudioTracks.forEach((track, i) => {
1734
- console.log(` Track ${i}: enabled=${track.enabled}, id=${track.id.substring(0, 8)}...`);
1735
- });
1736
- } else {
1737
- console.log(' - No local stream');
1738
- this.addMessage('System', ` Peer ${index + 1} - No local stream`, 'warning');
1739
- }
1740
-
1741
- // Check remote stream
1742
- if (remoteStream) {
1743
- const remoteAudioTracks = remoteStream.getAudioTracks();
1744
- console.log(` - Remote audio tracks: ${remoteAudioTracks.length}`);
1745
- this.addMessage('System', ` Peer ${index + 1} - Remote audio: ${remoteAudioTracks.length} tracks`, remoteAudioTracks.length > 0 ? 'success' : 'warning');
1746
-
1747
- remoteAudioTracks.forEach((track, i) => {
1748
- console.log(` Track ${i}: enabled=${track.enabled}, id=${track.id.substring(0, 8)}..., readyState=${track.readyState}`);
1749
- });
1750
-
1751
- // CRITICAL: Check if remote stream ID matches local stream ID (loopback detection)
1752
- if (localStream && remoteStream.id === localStream.id) {
1753
- console.error('❌ LOOPBACK DETECTED: Remote stream ID matches local stream ID!');
1754
- this.addMessage('System', `❌ Peer ${index + 1} - LOOPBACK: Getting own audio back!`, 'error');
1755
- } else {
1756
- console.log(`✅ Stream IDs different: local=${localStream?.id.substring(0, 8) || 'none'}, remote=${remoteStream.id.substring(0, 8)}`);
1757
- this.addMessage('System', `✅ Peer ${index + 1} - Stream IDs are different (good!)`, 'success');
1758
- }
1759
-
1760
- // Check video elements playing this stream
1761
- const videoElements = document.querySelectorAll('video');
1762
- let foundVideoElement = false;
1763
- videoElements.forEach(video => {
1764
- if (video.srcObject === remoteStream) {
1765
- foundVideoElement = true;
1766
- console.log(` - Video element: volume=${video.volume}, muted=${video.muted}, paused=${video.paused}, readyState=${video.readyState}`);
1767
- this.addMessage('System', ` Peer ${index + 1} - Video element: volume=${video.volume}, muted=${video.muted}`, video.muted ? 'warning' : 'success');
1768
- }
1769
- });
1770
-
1771
- if (!foundVideoElement) {
1772
- console.log(' - ❌ No video element found for this remote stream');
1773
- this.addMessage('System', ` Peer ${index + 1} - ❌ No video element displaying this stream`, 'error');
1774
- }
1775
- } else {
1776
- console.log(' - ❌ No remote stream');
1777
- this.addMessage('System', ` Peer ${index + 1} - ❌ No remote stream received`, 'error');
1778
- }
1779
- } else {
1780
- console.log(`❌ No connection object found for peer ${peer.peerId}`);
1781
- this.addMessage('System', `❌ No connection for peer ${index + 1}`, 'error');
1782
- }
1783
- });
1784
-
1785
- // Test 1: Audio Context
1786
- if (window.AudioContext || window.webkitAudioContext) {
1787
- const AudioContext = window.AudioContext || window.webkitAudioContext;
1788
- const audioContext = new AudioContext();
1789
- console.log('Audio context state:', audioContext.state);
1790
-
1791
- if (audioContext.state === 'suspended') {
1792
- await audioContext.resume();
1793
- console.log('Audio context resumed');
1794
- }
1795
-
1796
- // Generate a test tone
1797
- const oscillator = audioContext.createOscillator();
1798
- const gainNode = audioContext.createGain();
1799
-
1800
- oscillator.connect(gainNode);
1801
- gainNode.connect(audioContext.destination);
1802
-
1803
- oscillator.frequency.setValueAtTime(440, audioContext.currentTime); // A4 note
1804
- gainNode.gain.setValueAtTime(0.1, audioContext.currentTime); // Low volume
1805
-
1806
- oscillator.start();
1807
- oscillator.stop(audioContext.currentTime + 0.5); // Play for 0.5 seconds
1808
-
1809
- this.addMessage('System', '🔊 Audio test tone played (440Hz for 0.5s)', 'success');
1810
- } else {
1811
- this.addMessage('System', '❌ Audio context not supported', 'error');
1812
- }
1813
-
1814
- // Test 2: Check current media streams
1815
- const peers = this.mesh.getPeers();
1816
- console.log('Current peers:', peers.length);
1817
-
1818
- peers.forEach(peer => {
1819
- const connection = this.mesh.connectionManager.peers.get(peer.peerId);
1820
- if (connection) {
1821
- const localStream = connection.getLocalStream();
1822
- const remoteStream = connection.getRemoteStream();
1823
-
1824
- console.log(`Peer ${peer.peerId.substring(0, 8)}:`);
1825
- if (localStream) {
1826
- const audioTracks = localStream.getAudioTracks();
1827
- console.log(`- Local audio tracks: ${audioTracks.length}`);
1828
- audioTracks.forEach((track, i) => {
1829
- console.log(` Track ${i}: enabled=${track.enabled}, readyState=${track.readyState}, muted=${track.muted}`);
1830
- });
1831
- }
1832
-
1833
- if (remoteStream) {
1834
- const audioTracks = remoteStream.getAudioTracks();
1835
- console.log(`- Remote audio tracks: ${audioTracks.length}`);
1836
- audioTracks.forEach((track, i) => {
1837
- console.log(` Track ${i}: enabled=${track.enabled}, readyState=${track.readyState}, muted=${track.muted}`);
1838
- });
1839
-
1840
- // Check if there are video elements for this stream
1841
- const videoElements = document.querySelectorAll('video');
1842
- videoElements.forEach(video => {
1843
- if (video.srcObject === remoteStream) {
1844
- console.log(`- Video element: volume=${video.volume}, muted=${video.muted}, paused=${video.paused}`);
1845
- }
1846
- });
1847
- }
1848
- }
1849
- });
1850
-
1851
- // Test 3: Check microphone access
1852
- try {
1853
- const testStream = await navigator.mediaDevices.getUserMedia({ audio: true });
1854
- console.log('✅ Microphone access working');
1855
- this.addMessage('System', '✅ Microphone access: OK', 'success');
1856
- testStream.getTracks().forEach(track => track.stop());
1857
- } catch (error) {
1858
- console.log('❌ Microphone access failed:', error);
1859
- this.addMessage('System', `❌ Microphone access failed: ${error.message}`, 'error');
1860
- }
1861
- } catch (error) {
1862
- console.error('Audio test failed:', error);
1863
- this.addMessage('System', `❌ Audio test failed: ${error.message}`, 'error');
1864
- }
1865
- }
1866
-
1867
- handleLocalStreamStarted(data) {
1868
- this.updateMediaButtonStates();
1869
-
1870
- // Display local video if video is enabled
1871
- if (data.video) {
1872
- this.displayLocalVideo(data.stream);
1873
- }
1874
-
1875
- const mediaTypes = [];
1876
- if (data.video) mediaTypes.push('video');
1877
- if (data.audio) mediaTypes.push('audio');
1878
-
1879
- this.addMessage('System', `Local ${mediaTypes.join(' and ')} started`);
1880
- }
1881
-
1882
- handleLocalStreamStopped() {
1883
- this.updateMediaButtonStates();
1884
- this.clearLocalVideo();
1885
- this.addMessage('System', 'Local media stopped');
1886
- }
1887
-
1888
- displayLocalVideo(stream) {
1889
- const localVideoContainer = document.getElementById('local-video-container');
1890
- if (!localVideoContainer) return;
1891
-
1892
- let video = localVideoContainer.querySelector('video');
1893
- if (!video) {
1894
- video = document.createElement('video');
1895
- video.autoplay = true;
1896
- video.muted = true;
1897
- video.playsInline = true;
1898
- video.style.width = '100%';
1899
- video.style.borderRadius = '8px';
1900
- localVideoContainer.appendChild(video);
1901
- }
1902
-
1903
- video.srcObject = stream;
1904
- }
1905
-
1906
- clearLocalVideo() {
1907
- const localVideoContainer = document.getElementById('local-video-container');
1908
- if (localVideoContainer) {
1909
- const video = localVideoContainer.querySelector('video');
1910
- if (video) {
1911
- video.srcObject = null;
1912
- video.remove();
1913
- }
1914
- }
1915
- }
1916
-
1917
- handleRemoteStream(data) {
1918
- console.log('🎵 Handling remote stream:', data);
1919
- const { peerId, stream } = data;
1920
-
1921
- // CRITICAL: Prevent audio loopback - check if this is our own stream
1922
- if (peerId === this.mesh.peerId) {
1923
- console.warn('🚨 LOOPBACK DETECTED: Received our own stream as remote! This should not happen.');
1924
- console.warn('Stream ID:', stream.id);
1925
- // Still display it but it will be muted by displayRemoteVideo
1926
- }
1927
-
1928
- // Detailed audio analysis
1929
- const audioTracks = stream.getAudioTracks();
1930
- const videoTracks = stream.getVideoTracks();
1931
-
1932
- console.log(`Stream from ${peerId.substring(0, 8)}: ${audioTracks.length} audio, ${videoTracks.length} video tracks`);
1933
-
1934
- audioTracks.forEach((track, i) => {
1935
- console.log(`🎵 Audio track ${i}:`, {
1936
- id: track.id,
1937
- kind: track.kind,
1938
- enabled: track.enabled,
1939
- readyState: track.readyState,
1940
- muted: track.muted,
1941
- label: track.label
1942
- });
1943
-
1944
- // Add track event listeners for state monitoring
1945
- track.addEventListener('ended', () => {
1946
- console.log(`🎵 Audio track ${i} from peer ${peerId.substring(0, 8)} ENDED`);
1947
- });
1948
-
1949
- track.addEventListener('mute', () => {
1950
- console.log(`🎵 Audio track ${i} from peer ${peerId.substring(0, 8)} MUTED`);
1951
- });
1952
-
1953
- track.addEventListener('unmute', () => {
1954
- console.log(`🎵 Audio track ${i} from peer ${peerId.substring(0, 8)} UNMUTED`);
1955
- });
1956
- });
1957
-
1958
- this.displayRemoteVideo(peerId, stream);
1959
-
1960
- // Audio data summary
1961
- const audioSummary = {
1962
- peerIdShort: peerId.substring(0, 8),
1963
- audioTrackCount: audioTracks.length,
1964
- videoTrackCount: videoTracks.length,
1965
- audioTracksEnabled: audioTracks.filter(t => t.enabled).length,
1966
- streamActive: stream.active,
1967
- streamId: stream.id
1968
- };
1969
-
1970
- console.log(`🎵 AUDIO DATA EXPECTATION for peer ${audioSummary.peerIdShort}:`, audioSummary);
1971
-
1972
- if (audioTracks.length > 0) {
1973
- console.log(`✅ EXPECTING AUDIO DATA from peer ${audioSummary.peerIdShort} - ${audioSummary.audioTracksEnabled}/${audioSummary.audioTrackCount} tracks enabled`);
1974
- } else {
1975
- console.log(`❌ NO AUDIO TRACKS from peer ${audioSummary.peerIdShort} - video only`);
1976
- }
1977
-
1978
- this.addMessage('System', `🎵 Remote stream received from ${peerId.substring(0, 8)}... (${audioTracks.length} audio, ${videoTracks.length} video)`);
1979
- }
1980
-
1981
- displayRemoteVideo(peerId, stream) {
1982
- console.log(`Displaying remote video for ${peerId}:`, stream);
1983
- console.log('Stream tracks:', stream.getTracks().map(t => ({ kind: t.kind, enabled: t.enabled })));
1984
-
1985
- // CRITICAL: Prevent audio loopback - check if this is our own stream
1986
- const isOwnStream = peerId === this.mesh.peerId;
1987
- if (isOwnStream) {
1988
- console.warn('🚨 LOOPBACK DETECTED: Received our own stream! Muting audio to prevent feedback.');
1989
- }
1990
-
1991
- const remoteVideosContainer = document.getElementById('remote-videos-container');
1992
- if (!remoteVideosContainer) return;
1993
-
1994
- let remoteVideoItem = remoteVideosContainer.querySelector(`[data-peer-id="${peerId}"]`);
1995
-
1996
- if (!remoteVideoItem) {
1997
- remoteVideoItem = document.createElement('div');
1998
- remoteVideoItem.className = 'remote-video-item';
1999
- remoteVideoItem.setAttribute('data-peer-id', peerId);
2000
-
2001
- const title = document.createElement('div');
2002
- title.className = 'video-title';
2003
- title.textContent = `Peer ${peerId.substring(0, 8)}...`;
2004
-
2005
- const video = document.createElement('video');
2006
- video.autoplay = true;
2007
- video.playsInline = true;
2008
- video.controls = true;
2009
- // CRITICAL: Mute if this is our own stream to prevent audio feedback
2010
- video.muted = isOwnStream; // Mute our own audio, unmute others
2011
- video.style.width = '100%';
2012
- video.style.borderRadius = '8px';
2013
-
2014
- // Enhanced audio debugging
2015
- video.addEventListener('loadedmetadata', () => {
2016
- console.log('Video element loaded metadata:', {
2017
- duration: video.duration,
2018
- audioTracks: video.audioTracks?.length || 'N/A',
2019
- volume: video.volume,
2020
- muted: video.muted
2021
- });
2022
-
2023
- video.play().then(() => {
2024
- console.log('Video/audio playback started successfully');
2025
- // Check audio context state
2026
- if (window.AudioContext || window.webkitAudioContext) {
2027
- const AudioContext = window.AudioContext || window.webkitAudioContext;
2028
- const audioContext = new AudioContext();
2029
- console.log('Audio context state:', audioContext.state);
2030
- if (audioContext.state === 'suspended') {
2031
- console.log('Audio context is suspended - may need user interaction');
2032
- }
2033
- }
2034
- // Hide any play button if playback started
2035
- const playButton = remoteVideoItem.querySelector('.manual-play-button');
2036
- if (playButton) {
2037
- playButton.style.display = 'none';
2038
- }
2039
- }).catch(error => {
2040
- console.log('Autoplay failed, user interaction required:', error);
2041
- // Show a manual play button
2042
- const playButton = document.createElement('button');
2043
- playButton.className = 'manual-play-button';
2044
- playButton.textContent = '▶ Click to Play Audio';
2045
- playButton.style.cssText = 'position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); z-index: 10; padding: 10px; background: #007bff; color: white; border: none; border-radius: 5px; cursor: pointer;';
2046
-
2047
- playButton.addEventListener('click', async () => {
2048
- try {
2049
- await video.play();
2050
- playButton.style.display = 'none';
2051
- console.log('Manual play successful');
2052
- } catch (e) {
2053
- console.error('Manual play failed:', e);
2054
- }
2055
- });
2056
-
2057
- remoteVideoItem.style.position = 'relative';
2058
- remoteVideoItem.appendChild(playButton);
2059
- });
2060
- });
2061
-
2062
- // Add event listeners for audio debugging
2063
- video.addEventListener('play', () => {
2064
- console.log('Video element started playing');
2065
- });
2066
-
2067
- video.addEventListener('pause', () => {
2068
- console.log('Video element paused');
2069
- });
2070
-
2071
- video.addEventListener('volumechange', () => {
2072
- console.log('Volume changed:', video.volume, 'Muted:', video.muted);
2073
- });
2074
-
2075
- const status = document.createElement('div');
2076
- status.className = 'video-status';
2077
-
2078
- remoteVideoItem.appendChild(title);
2079
- remoteVideoItem.appendChild(video);
2080
- remoteVideoItem.appendChild(status);
2081
-
2082
- remoteVideosContainer.appendChild(remoteVideoItem);
2083
- }
2084
-
2085
- const video = remoteVideoItem.querySelector('video');
2086
- const status = remoteVideoItem.querySelector('.video-status');
2087
-
2088
- video.srcObject = stream;
2089
-
2090
- // EXPLICIT AUDIO DEBUGGING
2091
- console.log('🎵 Setting srcObject for video element:', {
2092
- stream,
2093
- streamId: stream.id,
2094
- streamActive: stream.active,
2095
- videoElement: video,
2096
- videoMuted: video.muted,
2097
- videoVolume: video.volume,
2098
- isOwnStream
2099
- });
2100
-
2101
- const audioTracks = stream.getAudioTracks();
2102
- const videoTracks = stream.getVideoTracks();
2103
-
2104
- console.log('🎵 Stream tracks assigned:', {
2105
- audioTracks: audioTracks.map(t => ({
2106
- id: t.id,
2107
- enabled: t.enabled,
2108
- readyState: t.readyState,
2109
- muted: t.muted
2110
- })),
2111
- videoTracks: videoTracks.map(t => ({
2112
- id: t.id,
2113
- enabled: t.enabled,
2114
- readyState: t.readyState,
2115
- muted: t.muted
2116
- }))
2117
- });
2118
-
2119
- // CRITICAL: Set audio state based on whether this is our own stream
2120
- if (isOwnStream) {
2121
- console.warn('🚨 Muting our own stream to prevent audio feedback');
2122
- video.muted = true;
2123
- video.volume = 0;
2124
- } else {
2125
- // Only unmute if this is NOT our own stream
2126
- video.muted = false;
2127
- video.volume = 1.0;
2128
-
2129
- // Setup audio playback monitoring for remote streams
2130
- this.setupAudioPlaybackMonitoring(video, peerId, audioTracks);
2131
- }
2132
-
2133
- // Update status based on stream tracks
2134
- console.log(`Video tracks: ${videoTracks.length}, Audio tracks: ${audioTracks.length}`);
2135
- audioTracks.forEach((track, i) => {
2136
- console.log(`Audio track ${i}:`, { enabled: track.enabled, muted: track.muted, label: track.label });
2137
- });
2138
-
2139
- // For audio-only streams, ensure the video element is properly configured
2140
- if (audioTracks.length > 0 && videoTracks.length === 0) {
2141
- console.log('Audio-only stream detected - configuring for audio playback');
2142
- video.style.height = '60px'; // Smaller height for audio-only
2143
- video.style.backgroundColor = '#f0f0f0';
2144
-
2145
- // Force audio to play by trying to resume audio context
2146
- if (window.AudioContext || window.webkitAudioContext) {
2147
- const AudioContext = window.AudioContext || window.webkitAudioContext;
2148
- try {
2149
- const audioContext = new AudioContext();
2150
- if (audioContext.state === 'suspended') {
2151
- audioContext.resume().then(() => {
2152
- console.log('Audio context resumed for remote stream');
2153
- });
2154
- }
2155
-
2156
- // Test audio by creating a brief analysis
2157
- try {
2158
- const source = audioContext.createMediaStreamSource(stream);
2159
- const analyser = audioContext.createAnalyser();
2160
- source.connect(analyser);
2161
-
2162
- const dataArray = new Uint8Array(analyser.frequencyBinCount);
2163
- const checkAudio = () => {
2164
- analyser.getByteFrequencyData(dataArray);
2165
- const sum = dataArray.reduce((a, b) => a + b, 0);
2166
- if (sum > 0) {
2167
- console.log('Remote audio data detected! Sum:', sum);
2168
- }
2169
- };
2170
-
2171
- // Check audio data periodically
2172
- const audioChecker = setInterval(checkAudio, 1000);
2173
- setTimeout(() => clearInterval(audioChecker), 10000); // Stop after 10 seconds
2174
- } catch (audioAnalysisError) {
2175
- console.log('Could not analyze remote audio:', audioAnalysisError);
2176
- }
2177
- } catch (e) {
2178
- console.log('Could not create/resume audio context:', e);
2179
- }
2180
- }
2181
- }
2182
-
2183
- const statusText = [];
2184
- if (videoTracks.length > 0) statusText.push('Video');
2185
- if (audioTracks.length > 0) statusText.push('Audio');
2186
-
2187
- status.textContent = statusText.length > 0 ? statusText.join(' + ') : 'Audio only';
2188
- status.style.color = '#28a745';
2189
-
2190
- this.addMessage('System', `Receiving ${statusText.join(' + ')} from ${peerId.substring(0, 8)}...`);
2191
- }
2192
-
2193
- /**
2194
- * Setup audio playback monitoring for video elements playing remote streams
2195
- */
2196
- setupAudioPlaybackMonitoring(videoElement, peerId, audioTracks) {
2197
- const peerIdShort = peerId.substring(0, 8);
2198
- console.log(`🎵 Setting up audio playback monitoring for peer ${peerIdShort}`);
2199
-
2200
- if (audioTracks.length === 0) {
2201
- console.log(`🎵 No audio tracks to monitor for peer ${peerIdShort}`);
2202
- return;
2203
- }
2204
-
2205
- try {
2206
- // Monitor video element audio events
2207
- videoElement.addEventListener('play', () => {
2208
- console.log(`🎵 Video element started playing for peer ${peerIdShort}`, {
2209
- muted: videoElement.muted,
2210
- volume: videoElement.volume,
2211
- audioTracks: audioTracks.length
2212
- });
2213
- });
2214
-
2215
- videoElement.addEventListener('pause', () => {
2216
- console.log(`🎵 Video element paused for peer ${peerIdShort}`);
2217
- });
2218
-
2219
- videoElement.addEventListener('volumechange', () => {
2220
- console.log(`🎵 Volume changed for peer ${peerIdShort}:`, {
2221
- volume: videoElement.volume,
2222
- muted: videoElement.muted
2223
- });
2224
- });
2225
-
2226
- // Create audio context for monitoring actual audio data playback
2227
- const AudioContext = window.AudioContext || window.webkitAudioContext;
2228
- if (!AudioContext) {
2229
- console.warn('🎵 AudioContext not available - basic monitoring only');
2230
- return;
2231
- }
2232
-
2233
- // Wait for video to load before setting up audio analysis
2234
- const setupAudioAnalysis = () => {
2235
- try {
2236
- const audioContext = new AudioContext();
2237
- const source = audioContext.createMediaElementSource(videoElement);
2238
- const analyser = audioContext.createAnalyser();
2239
- const gainNode = audioContext.createGain();
2240
-
2241
- analyser.fftSize = 256;
2242
- const bufferLength = analyser.frequencyBinCount;
2243
- const dataArray = new Uint8Array(bufferLength);
2244
-
2245
- // Connect: source -> analyser -> gain -> destination
2246
- source.connect(analyser);
2247
- analyser.connect(gainNode);
2248
- gainNode.connect(audioContext.destination);
2249
-
2250
- let lastLogTime = 0;
2251
- let totalSamples = 0;
2252
- let playbackSamples = 0;
2253
- let maxPlaybackLevel = 0;
2254
-
2255
- const monitorPlayback = () => {
2256
- if (videoElement.paused || videoElement.ended) {
2257
- return; // Stop monitoring if playback stopped
2258
- }
2259
-
2260
- analyser.getByteFrequencyData(dataArray);
2261
-
2262
- // Calculate playback audio level
2263
- const average = dataArray.reduce((sum, value) => sum + value, 0) / bufferLength;
2264
- const currentTime = Date.now();
2265
-
2266
- totalSamples++;
2267
- if (average > 3) { // Lower threshold for playback detection
2268
- playbackSamples++;
2269
- maxPlaybackLevel = Math.max(maxPlaybackLevel, average);
2270
- }
2271
-
2272
- // Log every 3 seconds
2273
- if (currentTime - lastLogTime > 3000) {
2274
- const playbackActivity = totalSamples > 0 ? (playbackSamples / totalSamples * 100) : 0;
2275
- console.log(`🔊 Audio PLAYBACK from peer ${peerIdShort}:`, {
2276
- videoElementMuted: videoElement.muted,
2277
- videoElementVolume: videoElement.volume,
2278
- currentPlaybackLevel: Math.round(average),
2279
- maxPlaybackLevel: Math.round(maxPlaybackLevel),
2280
- playbackActivityPercent: Math.round(playbackActivity),
2281
- samplesAnalyzed: totalSamples,
2282
- audioBeingPlayed: playbackSamples > 0,
2283
- audioContextState: audioContext.state
2284
- });
2285
-
2286
- lastLogTime = currentTime;
2287
- totalSamples = 0;
2288
- playbackSamples = 0;
2289
- maxPlaybackLevel = 0;
2290
- }
2291
-
2292
- // Continue monitoring
2293
- if (!videoElement.paused && !videoElement.ended) {
2294
- requestAnimationFrame(monitorPlayback);
2295
- }
2296
- };
2297
-
2298
- // Start monitoring when video plays
2299
- videoElement.addEventListener('play', () => {
2300
- console.log(`🔊 Starting audio playback monitoring for peer ${peerIdShort}`);
2301
- if (audioContext.state === 'suspended') {
2302
- audioContext.resume().then(() => {
2303
- requestAnimationFrame(monitorPlayback);
2304
- });
2305
- } else {
2306
- requestAnimationFrame(monitorPlayback);
2307
- }
2308
- });
2309
-
2310
- console.log(`🔊 Audio playback analysis setup complete for peer ${peerIdShort}`);
2311
- } catch (error) {
2312
- console.error(`🔊 Failed to setup audio playback analysis for peer ${peerIdShort}:`, error);
2313
- }
2314
- };
2315
-
2316
- if (videoElement.readyState >= 1) {
2317
- // Video metadata already loaded
2318
- setupAudioAnalysis();
2319
- } else {
2320
- // Wait for metadata to load
2321
- videoElement.addEventListener('loadedmetadata', setupAudioAnalysis, { once: true });
2322
- }
2323
- } catch (error) {
2324
- console.error(`🎵 Failed to setup audio playback monitoring for peer ${peerIdShort}:`, error);
2325
- }
2326
- }
2327
-
2328
- /**
2329
- * Diagnostic method to log complete peer connection state
2330
- */
2331
- logPeerDiagnostics() {
2332
- console.log('🔍 PEER DIAGNOSTICS:');
2333
- const allPeers = this.mesh.getPeers();
2334
-
2335
- console.log(`📊 Total peers in mesh: ${allPeers.length}`);
2336
-
2337
- allPeers.forEach((peer, index) => {
2338
- const peerConnection = this.mesh.connectionManager.getPeer(peer.peerId);
2339
-
2340
- console.log(`\n🔍 Peer ${index + 1}: ${peer.peerId.substring(0, 8)}...`);
2341
- console.log(` Status: ${peer.status}`);
2342
-
2343
- if (peerConnection) {
2344
- console.log(` WebRTC Connection State: ${peerConnection.connection?.connectionState || 'none'}`);
2345
- console.log(` ICE Connection State: ${peerConnection.connection?.iceConnectionState || 'none'}`);
2346
- console.log(` Data Channel State: ${peerConnection.dataChannel?.readyState || 'none'}`);
2347
- console.log(` Data Channel Ready: ${peerConnection.dataChannelReady}`);
2348
- console.log(` Has Local Stream: ${!!peerConnection.localStream}`);
2349
- console.log(` Has Remote Stream: ${!!peerConnection.remoteStream}`);
2350
-
2351
- if (peerConnection.localStream) {
2352
- const audioTracks = peerConnection.localStream.getAudioTracks();
2353
- const videoTracks = peerConnection.localStream.getVideoTracks();
2354
- console.log(` Local Stream Tracks: ${audioTracks.length} audio, ${videoTracks.length} video`);
2355
- }
2356
-
2357
- if (peerConnection.remoteStream) {
2358
- const audioTracks = peerConnection.remoteStream.getAudioTracks();
2359
- const videoTracks = peerConnection.remoteStream.getVideoTracks();
2360
- console.log(` Remote Stream Tracks: ${audioTracks.length} audio, ${videoTracks.length} video`);
2361
- }
2362
- } else {
2363
- console.log(' ❌ No PeerConnection object found');
2364
- }
2365
- });
2366
-
2367
- console.log('\n🔍 END PEER DIAGNOSTICS\n');
2368
- }
2369
-
2370
- // Existing UI methods (keeping the rest of the original functionality)
2371
- async handleConnect() {
2372
- const url = document.getElementById('signaling-url').value.trim();
2373
- if (!url) {
2374
- this.addMessage('System', 'Please enter a signaling server URL', 'error');
2375
- return;
2376
- }
2377
-
2378
- try {
2379
- this.updateButtonStates({ connecting: true });
2380
- await this.mesh.connect(url);
2381
- } catch (error) {
2382
- console.error('Connection failed:', error);
2383
- this.addMessage('System', `Connection failed: ${error.message}`, 'error');
2384
- this.updateButtonStates({ connecting: false });
2385
- }
2386
- }
2387
-
2388
- async handleDisconnect() {
2389
- try {
2390
- this.updateButtonStates({ disconnecting: true });
2391
- await this.mesh.disconnect();
2392
- } catch (error) {
2393
- console.error('Disconnection failed:', error);
2394
- this.addMessage('System', `Disconnection failed: ${error.message}`, 'error');
2395
- } finally {
2396
- this.updateButtonStates({ disconnecting: false });
2397
- }
2398
- }
2399
-
2400
- async handleCleanup() {
2401
- const now = Date.now();
2402
- const timeSinceLastCleanup = now - this.lastCleanupTime;
2403
-
2404
- if (timeSinceLastCleanup < 5000) {
2405
- const remaining = Math.ceil((5000 - timeSinceLastCleanup) / 1000);
2406
- this.addMessage('System', `Cleanup on cooldown (${remaining}s remaining)`, 'warning');
2407
- return;
2408
- }
2409
-
2410
- try {
2411
- this.lastCleanupTime = now;
2412
- await this.mesh.cleanupSignalingData();
2413
- this.addMessage('System', 'Signaling data cleanup initiated');
2414
- } catch (error) {
2415
- console.error('Cleanup failed:', error);
2416
- this.addMessage('System', `Cleanup failed: ${error.message}`, 'error');
2417
- }
2418
- }
2419
-
2420
- async handleHealthCheck() {
2421
- try {
2422
- const result = await this.mesh.performHealthCheck();
2423
- if (result.healthy) {
2424
- this.addMessage('System', 'Health check passed - all systems nominal', 'info');
2425
- } else {
2426
- this.addMessage('System', `Health check failed: ${result.issues.join(', ')}`, 'warning');
2427
- }
2428
- } catch (error) {
2429
- console.error('Health check failed:', error);
2430
- this.addMessage('System', `Health check error: ${error.message}`, 'error');
2431
- }
2432
- }
2433
-
2434
- async sendMessage() {
2435
- const messageInput = document.getElementById('message-input');
2436
- const dmTargetInput = document.getElementById('dm-target-input');
2437
- const autoEncryptToggle = document.getElementById('crypto-auto-encrypt');
2438
-
2439
- if (!messageInput) return;
2440
-
2441
- const message = messageInput.value.trim();
2442
- const dmTarget = dmTargetInput ? dmTargetInput.value.trim() : '';
2443
-
2444
- if (!message) return;
2445
-
2446
- try {
2447
- // Check if auto-encrypt is enabled and crypto is available
2448
- const shouldEncrypt = autoEncryptToggle && autoEncryptToggle.checked && this.mesh.getCryptoStatus().enabled;
2449
-
2450
- if (dmTarget) {
2451
- // Validate peer ID format for direct messages
2452
- if (!window.PeerPigeonMesh.validatePeerId(dmTarget)) {
2453
- this.addMessage('System', 'Invalid peer ID format. Must be 40-character SHA-1 hash.', 'error');
2454
- return;
2455
- }
2456
-
2457
- // Send direct message (encrypted or not)
2458
- if (shouldEncrypt) {
2459
- await this.mesh.sendEncryptedMessage(dmTarget, message);
2460
- this.addMessage('You', `🔐 (DM to ${dmTarget.substring(0, 8)}...) ${message}`, 'encrypted');
2461
- } else {
2462
- const success = this.mesh.sendDirectMessage(dmTarget, message);
2463
- if (success) {
2464
- this.addMessage('You', `(DM to ${dmTarget.substring(0, 8)}...) ${message}`, 'own');
2465
- } else {
2466
- this.addMessage('System', `Failed to send direct message to ${dmTarget.substring(0, 8)}...`, 'error');
2467
- }
2468
- }
2469
- } else {
2470
- // Send broadcast message (encrypted or not)
2471
- if (shouldEncrypt) {
2472
- // Get all connected peers for encryption
2473
- const connectedPeers = this.mesh.getPeers();
2474
- if (connectedPeers.length > 0) {
2475
- // Send encrypted message to all connected peers
2476
- for (const peer of connectedPeers) {
2477
- try {
2478
- await this.mesh.sendEncryptedMessage(peer.peerId, message);
2479
- } catch (error) {
2480
- console.warn(`Failed to send encrypted message to ${peer.peerId}:`, error);
2481
- }
2482
- }
2483
- this.addMessage('You', `🔐 ${message}`, 'encrypted');
2484
- } else {
2485
- this.addMessage('System', 'No connected peers to send encrypted message to', 'error');
2486
- }
2487
- } else {
2488
- // Send regular unencrypted message
2489
- this.mesh.sendMessage(message);
2490
- this.addMessage('You', message, 'own');
2491
- }
2492
- }
2493
-
2494
- messageInput.value = '';
2495
- } catch (error) {
2496
- console.error('Failed to send message:', error);
2497
- this.addMessage('System', `Failed to send message: ${error.message}`, 'error');
2498
- }
2499
- }
2500
-
2501
- connectToPeer() {
2502
- const targetPeerInput = document.getElementById('target-peer');
2503
- const targetPeerId = targetPeerInput.value.trim();
2504
-
2505
- if (!targetPeerId) {
2506
- this.addMessage('System', 'Please enter a peer ID', 'error');
2507
- return;
2508
- }
2509
-
2510
- if (!window.PeerPigeonMesh.validatePeerId(targetPeerId)) {
2511
- this.addMessage('System', 'Invalid peer ID format. Must be 40-character SHA-1 hash.', 'error');
2512
- return;
2513
- }
2514
-
2515
- if (targetPeerId === this.mesh.peerId) {
2516
- this.addMessage('System', 'Cannot connect to yourself', 'error');
2517
- return;
2518
- }
2519
-
2520
- try {
2521
- this.mesh.connectToPeer(targetPeerId);
2522
- this.addMessage('System', `Attempting to connect to ${targetPeerId.substring(0, 8)}...`);
2523
- targetPeerInput.value = '';
2524
- } catch (error) {
2525
- console.error('Failed to initiate connection:', error);
2526
- this.addMessage('System', `Failed to connect: ${error.message}`, 'error');
2527
- }
2528
- }
2529
-
2530
- /**
2531
- * Connect to peer from button click (for onclick handlers)
2532
- */
2533
- connectToPeerFromButton(button) {
2534
- const peerId = button.getAttribute('data-peer-id');
2535
- if (!peerId) {
2536
- this.addMessage('System', 'Invalid peer ID in button', 'error');
2537
- return;
2538
- }
2539
-
2540
- // Disable button to prevent double-clicks
2541
- button.disabled = true;
2542
- button.textContent = 'Connecting...';
2543
-
2544
- try {
2545
- this.mesh.connectToPeer(peerId);
2546
- this.addMessage('System', `Attempting to connect to ${peerId.substring(0, 8)}...`);
2547
-
2548
- // Re-enable button after a delay
2549
- setTimeout(() => {
2550
- button.disabled = false;
2551
- button.textContent = 'Connect';
2552
- }, 3000);
2553
- } catch (error) {
2554
- console.error('Failed to initiate connection:', error);
2555
- this.addMessage('System', `Failed to connect: ${error.message}`, 'error');
2556
-
2557
- // Re-enable button immediately on error
2558
- button.disabled = false;
2559
- button.textContent = 'Connect';
2560
- }
2561
- }
2562
-
2563
- updateUI() {
2564
- // Update peer ID display
2565
- const peerIdElement = document.getElementById('peer-id');
2566
- if (peerIdElement && this.mesh.peerId) {
2567
- peerIdElement.textContent = this.mesh.peerId;
2568
- }
2569
-
2570
- // Update status
2571
- this.updateStatus();
2572
-
2573
- // Update button states
2574
- this.updateButtonStates();
2575
-
2576
- // Update peer lists
2577
- this.updateConnectedPeers();
2578
- this.updateDiscoveredPeers();
2579
-
2580
- // Update settings from mesh state
2581
- this.updateSettings();
2582
-
2583
- // Update DHT status
2584
- this.updateDHTStatus();
2585
-
2586
- // Update storage status
2587
- this.updateStorageStatus();
2588
- }
2589
-
2590
- updateStatus() {
2591
- const statusElement = document.getElementById('status');
2592
- if (!statusElement) return;
2593
-
2594
- const status = this.mesh.getStatus();
2595
- const connectionStatus = status.connected ? 'connected' : 'disconnected';
2596
- statusElement.textContent = connectionStatus.charAt(0).toUpperCase() + connectionStatus.slice(1);
2597
- statusElement.className = `status ${connectionStatus.toLowerCase()}`;
2598
- }
2599
-
2600
- updateButtonStates(options = {}) {
2601
- const connectBtn = document.getElementById('connect-btn');
2602
- const disconnectBtn = document.getElementById('disconnect-btn');
2603
- const cleanupBtn = document.getElementById('cleanup-btn');
2604
- const healthCheckBtn = document.getElementById('health-check-btn');
2605
-
2606
- const isConnected = this.mesh.connected;
2607
- const isConnecting = options.connecting || false;
2608
- const isDisconnecting = options.disconnecting || false;
2609
-
2610
- if (connectBtn) {
2611
- connectBtn.disabled = isConnected || isConnecting;
2612
- connectBtn.textContent = isConnecting ? 'Connecting...' : 'Connect';
2613
- }
2614
-
2615
- if (disconnectBtn) {
2616
- disconnectBtn.disabled = !isConnected || isDisconnecting;
2617
- disconnectBtn.textContent = isDisconnecting ? 'Disconnecting...' : 'Disconnect';
2618
- }
2619
-
2620
- if (cleanupBtn) {
2621
- cleanupBtn.disabled = !isConnected;
2622
- }
2623
-
2624
- if (healthCheckBtn) {
2625
- healthCheckBtn.disabled = !isConnected;
2626
- }
2627
- }
2628
-
2629
- updateConnectedPeers() {
2630
- const peersList = document.getElementById('peers-list');
2631
- const connectedPeersCount = document.getElementById('connected-peers-count');
2632
-
2633
- if (!peersList || !connectedPeersCount) return;
2634
-
2635
- const peers = this.mesh.getPeers();
2636
- connectedPeersCount.textContent = peers.length;
2637
-
2638
- if (peers.length === 0) {
2639
- peersList.innerHTML = '<p class="empty-state">No peers connected</p>';
2640
- return;
2641
- }
2642
-
2643
- peersList.innerHTML = peers.map(peer => {
2644
- // peer is a plain object: { peerId, status, isInitiator, connectionStartTime }
2645
- const statusClass = peer.status === 'connected' ? 'connected' : 'connecting';
2646
- const connectionTime = ((Date.now() - peer.connectionStartTime) / 1000).toFixed(1);
2647
-
2648
- return `
2649
- <div class="peer-item">
2650
- <div class="peer-info">
2651
- <span class="peer-id">${peer.peerId.substring(0, 16)}...</span>
2652
- <span class="peer-status ${statusClass}">${peer.status}</span>
2653
- </div>
2654
- <div class="peer-details">
2655
- <small>Connected: ${connectionTime}s ago</small>
2656
- <small>Role: ${peer.isInitiator ? 'Initiator' : 'Receiver'}</small>
2657
- </div>
2658
- </div>
2659
- `;
2660
- }).join('');
2661
- }
2662
-
2663
- updateDiscoveredPeers() {
2664
- const discoveredPeersList = document.getElementById('discovered-peers-list');
2665
- const discoveredPeersCount = document.getElementById('discovered-peers-count');
2666
-
2667
- if (!discoveredPeersList || !discoveredPeersCount) return;
2668
-
2669
- const discoveredPeers = this.mesh.getDiscoveredPeers();
2670
- const connectedPeerIds = this.mesh.getPeers().map(p => p.peerId);
2671
-
2672
- // Filter out already connected peers
2673
- const availablePeers = discoveredPeers.filter(peer =>
2674
- !connectedPeerIds.includes(peer.peerId) && peer.peerId !== this.mesh.peerId
2675
- );
2676
-
2677
- discoveredPeersCount.textContent = availablePeers.length;
2678
-
2679
- if (availablePeers.length === 0) {
2680
- discoveredPeersList.innerHTML = '<p class="empty-state">No peers discovered</p>';
2681
- return;
2682
- }
2683
-
2684
- discoveredPeersList.innerHTML = availablePeers.map(peer => {
2685
- const lastSeen = peer.lastSeen
2686
- ? `${Math.round((Date.now() - peer.lastSeen) / 1000)}s ago`
2687
- : 'Unknown';
2688
-
2689
- return `
2690
- <div class="peer-item discovered">
2691
- <div class="peer-info">
2692
- <span class="peer-id">${peer.peerId.substring(0, 16)}...</span>
2693
- <button class="btn small" data-peer-id="${peer.peerId}" onclick="window.peerPigeonUI.connectToPeerFromButton(this)">
2694
- Connect
2695
- </button>
2696
- </div>
2697
- <div class="peer-details">
2698
- <small>Last seen: ${lastSeen}</small>
2699
- <small>Distance: ${peer.distance || 'Unknown'}</small>
2700
- </div>
2701
- </div>
2702
- `;
2703
- }).join('');
2704
- }
2705
-
2706
- updateSettings() {
2707
- // Update form values to match mesh state
2708
- const minPeersInput = document.getElementById('min-peers');
2709
- const maxPeersInput = document.getElementById('max-peers');
2710
- const autoDiscoveryToggle = document.getElementById('auto-discovery-toggle');
2711
- const evictionStrategyToggle = document.getElementById('eviction-strategy-toggle');
2712
- const xorRoutingToggle = document.getElementById('xor-routing-toggle');
2713
- const webdhtToggle = document.getElementById('webdht-toggle');
2714
-
2715
- if (minPeersInput) minPeersInput.value = this.mesh.minPeers;
2716
- if (maxPeersInput) maxPeersInput.value = this.mesh.maxPeers;
2717
- if (autoDiscoveryToggle) autoDiscoveryToggle.checked = this.mesh.autoDiscovery;
2718
- if (evictionStrategyToggle) evictionStrategyToggle.checked = this.mesh.evictionStrategy;
2719
- if (xorRoutingToggle) xorRoutingToggle.checked = this.mesh.xorRouting;
2720
-
2721
- // Update WebDHT status (read-only)
2722
- if (webdhtToggle) {
2723
- const isDHTEnabled = this.mesh && this.mesh.isDHTEnabled && this.mesh.isDHTEnabled();
2724
- webdhtToggle.checked = isDHTEnabled;
2725
-
2726
- // Update the visual styling based on status
2727
- const parent = webdhtToggle.closest('.auto-discovery-control');
2728
- if (parent) {
2729
- if (isDHTEnabled) {
2730
- parent.style.opacity = '1';
2731
- parent.title = 'WebDHT is enabled and running';
2732
- } else {
2733
- parent.style.opacity = '0.6';
2734
- parent.title = 'WebDHT is disabled (restart required to enable)';
2735
- }
2736
- }
2737
- }
2738
- }
2739
-
2740
- /**
2741
- * Add a message to the UI message log
2742
- * @param {string} sender - Message sender identifier
2743
- * @param {string} content - Message content
2744
- * @param {string} type - Message type ('info', 'error', 'warning', 'own', 'dm')
2745
- */
2746
- addMessage(sender, content, type = 'info') {
2747
- // System messages go to the system-messages container (below connection buttons)
2748
- // Chat messages go to the messages-log container (at the bottom)
2749
- if (sender === 'System') {
2750
- this.addSystemMessage(content, type);
2751
- } else {
2752
- this.addChatMessage(sender, content, type);
2753
- }
2754
- }
2755
-
2756
- /**
2757
- * Add a system message to the system messages container below connection buttons
2758
- * @param {string} content - Message content
2759
- * @param {string} type - Message type ('info', 'error', 'warning')
2760
- */
2761
- addSystemMessage(content, type = 'info') {
2762
- const systemMessages = document.getElementById('system-messages');
2763
- if (!systemMessages) return;
2764
-
2765
- const messageElement = document.createElement('div');
2766
- messageElement.className = `system-message ${type}`;
2767
-
2768
- const timestamp = new Date().toLocaleTimeString();
2769
-
2770
- messageElement.innerHTML = `
2771
- <div class="system-message-header">
2772
- <span class="system-message-time">${timestamp}</span>
2773
- <span class="system-message-type">${type.toUpperCase()}</span>
2774
- </div>
2775
- <div class="system-message-content">${content}</div>
2776
- `;
2777
-
2778
- systemMessages.appendChild(messageElement);
2779
- systemMessages.scrollTop = systemMessages.scrollHeight;
2780
-
2781
- // Limit message history to prevent memory issues
2782
- const messages = systemMessages.children;
2783
- if (messages.length > 50) {
2784
- systemMessages.removeChild(messages[0]);
2785
- }
2786
- }
2787
-
2788
- /**
2789
- * Add a chat message to the messages log at the bottom
2790
- * @param {string} sender - Message sender identifier
2791
- * @param {string} content - Message content
2792
- * @param {string} type - Message type ('own', 'dm', 'encrypted')
2793
- */
2794
- addChatMessage(sender, content, type = 'info') {
2795
- const messagesLog = document.getElementById('messages-log');
2796
- if (!messagesLog) return;
2797
-
2798
- const messageElement = document.createElement('div');
2799
- // Add 'encrypted' class if message type is 'encrypted'
2800
- const classes = `message-item ${type}`;
2801
- messageElement.className = classes;
2802
-
2803
- const timestamp = new Date().toLocaleTimeString();
2804
- const senderDisplay = sender === 'You' ? 'You' : sender.substring(0, 3);
2805
-
2806
- messageElement.innerHTML = `
2807
- <div class="avatar">${senderDisplay}</div>
2808
- <div class="message-body">
2809
- <div class="message-header">
2810
- ${sender} • ${timestamp}
2811
- </div>
2812
- <div class="message-content">${content}</div>
2813
- </div>
2814
- `;
2815
-
2816
- messagesLog.appendChild(messageElement);
2817
- messagesLog.scrollTop = messagesLog.scrollHeight;
2818
-
2819
- // Limit message history to prevent memory issues
2820
- const messages = messagesLog.children;
2821
- if (messages.length > 100) {
2822
- messagesLog.removeChild(messages[0]);
2823
- }
2824
- }
2825
-
2826
- /**
2827
- * Add an entry to the DHT log
2828
- * @param {string} message - The log message
2829
- */
2830
- addDHTLogEntry(message) {
2831
- const dhtLog = document.getElementById('dht-log');
2832
- if (!dhtLog) return;
2833
-
2834
- const logEntry = document.createElement('div');
2835
- logEntry.className = 'dht-log-entry';
2836
-
2837
- const timestamp = new Date().toLocaleTimeString();
2838
- logEntry.innerHTML = `
2839
- <span class="dht-log-time">${timestamp}</span>
2840
- <span class="dht-log-message">${message}</span>
2841
- `;
2842
-
2843
- dhtLog.appendChild(logEntry);
2844
- dhtLog.scrollTop = dhtLog.scrollHeight;
2845
-
2846
- // Limit log entries to prevent memory issues
2847
- const entries = dhtLog.children;
2848
- if (entries.length > 100) {
2849
- dhtLog.removeChild(entries[0]);
2850
- }
2851
- }
2852
-
2853
- /**
2854
- * Update the DHT status display
2855
- */
2856
- updateDHTStatus() {
2857
- const dhtStatusElement = document.getElementById('dht-status');
2858
- if (!dhtStatusElement) return;
2859
-
2860
- const isDHTEnabled = this.mesh && this.mesh.isDHTEnabled && this.mesh.isDHTEnabled();
2861
- dhtStatusElement.textContent = isDHTEnabled ? 'Enabled' : 'Disabled';
2862
- dhtStatusElement.className = `status ${isDHTEnabled ? 'connected' : 'disconnected'}`;
2863
- }
2864
-
2865
- // Crypto Helper Methods
2866
- // =====================
2867
-
2868
- /**
2869
- * Update the crypto status display
2870
- */
2871
- updateCryptoStatus() {
2872
- // Update main crypto status
2873
- const statusElement = document.getElementById('crypto-status');
2874
- if (statusElement) {
2875
- const status = this.mesh.getCryptoStatus();
2876
- statusElement.textContent = status.enabled ? 'Enabled' : 'Disabled';
2877
- statusElement.className = `status ${status.enabled ? 'enabled' : 'disabled'}`;
2878
- }
2879
-
2880
- // Update public key display
2881
- const publicKeyElement = document.getElementById('crypto-public-key');
2882
- if (publicKeyElement) {
2883
- const status = this.mesh.getCryptoStatus();
2884
- if (status.enabled && status.publicKey) {
2885
- publicKeyElement.textContent = status.publicKey.substring(0, 40) + '...';
2886
- publicKeyElement.title = status.publicKey; // Full key in tooltip
2887
- } else {
2888
- publicKeyElement.textContent = 'None';
2889
- publicKeyElement.title = '';
2890
- }
2891
- }
2892
-
2893
- // Update peer keys count
2894
- const peerCountElement = document.getElementById('crypto-peer-count');
2895
- if (peerCountElement) {
2896
- const status = this.mesh.getCryptoStatus();
2897
- const count = status.peerKeys ? Object.keys(status.peerKeys).length : 0;
2898
- peerCountElement.textContent = count.toString();
2899
- }
2900
-
2901
- // Update performance statistics
2902
- this.updateCryptoStats();
2903
- }
2904
-
2905
- /**
2906
- * Update crypto performance statistics
2907
- */
2908
- updateCryptoStats() {
2909
- const status = this.mesh.getCryptoStatus();
2910
- if (!status.performance) return;
2911
-
2912
- const stats = status.performance;
2913
-
2914
- // Update stat elements
2915
- const updateStat = (id, value) => {
2916
- const element = document.getElementById(id);
2917
- if (element) element.textContent = value.toString();
2918
- };
2919
-
2920
- updateStat('crypto-stats-encrypted', stats.messagesEncrypted || 0);
2921
- updateStat('crypto-stats-decrypted', stats.messagesDecrypted || 0);
2922
- updateStat('crypto-stats-encrypt-time', `${(stats.avgEncryptTime || 0).toFixed(2)}ms`);
2923
- updateStat('crypto-stats-decrypt-time', `${(stats.avgDecryptTime || 0).toFixed(2)}ms`);
2924
- updateStat('crypto-stats-key-exchanges', stats.keyExchanges || 0);
2925
- }
2926
-
2927
- /**
2928
- * Add a crypto test result to the test log
2929
- */
2930
- addCryptoTestResult(message, type = 'info') {
2931
- const testLog = document.getElementById('crypto-test-log');
2932
- if (!testLog) return;
2933
-
2934
- // Remove empty state message
2935
- const emptyState = testLog.querySelector('.empty-state');
2936
- if (emptyState) {
2937
- emptyState.remove();
2938
- }
2939
-
2940
- const logEntry = document.createElement('div');
2941
- logEntry.className = `test-result ${type}`;
2942
-
2943
- const timestamp = new Date().toLocaleTimeString();
2944
- logEntry.innerHTML = `
2945
- <span class="test-time">${timestamp}</span>
2946
- <span class="test-message">${message}</span>
2947
- `;
2948
-
2949
- testLog.appendChild(logEntry);
2950
- testLog.scrollTop = testLog.scrollHeight;
2951
-
2952
- // Limit log entries to prevent memory issues
2953
- const entries = testLog.querySelectorAll('.test-result');
2954
- if (entries.length > 50) {
2955
- entries[0].remove();
2956
- }
2957
- }
2958
-
2959
- /**
2960
- * Clear all crypto test results
2961
- */
2962
- clearCryptoTestResults() {
2963
- const testLog = document.getElementById('crypto-test-log');
2964
- if (!testLog) return;
2965
-
2966
- testLog.innerHTML = '<p class="empty-state">No tests run yet</p>';
2967
- }
2968
-
2969
- /**
2970
- * Update the group select dropdown
2971
- */
2972
- updateGroupSelect() {
2973
- const groupSelect = document.getElementById('crypto-group-select');
2974
- const groupsList = document.getElementById('crypto-groups-list');
2975
- if (!groupSelect || !groupsList) return;
2976
-
2977
- const status = this.mesh.getCryptoStatus();
2978
- const groups = status.groups || {};
2979
-
2980
- // Clear existing options (except placeholder)
2981
- const placeholder = groupSelect.querySelector('option[value=""]');
2982
- groupSelect.innerHTML = '';
2983
- if (placeholder) groupSelect.appendChild(placeholder);
2984
-
2985
- // Add group options
2986
- Object.keys(groups).forEach(groupId => {
2987
- const option = document.createElement('option');
2988
- option.value = groupId;
2989
- option.textContent = groupId;
2990
- groupSelect.appendChild(option);
2991
- });
2992
-
2993
- // Update groups list display
2994
- const groupCount = Object.keys(groups).length;
2995
- if (groupCount === 0) {
2996
- groupsList.innerHTML = '<h4>Active Groups:</h4><div class="empty-state">No groups created</div>';
2997
- } else {
2998
- let html = '<h4>Active Groups:</h4>';
2999
- Object.entries(groups).forEach(([groupId, groupInfo]) => {
3000
- html += `
3001
- <div class="group-item">
3002
- <strong>${groupId}</strong>
3003
- <small>Created: ${new Date(groupInfo.created).toLocaleString()}</small>
3004
- </div>
3005
- `;
3006
- });
3007
- groupsList.innerHTML = html;
3008
- }
3009
- }
3010
- }