peerpigeon 1.0.9 โ†’ 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/server/index.js CHANGED
@@ -3,6 +3,13 @@ import { WebSocketServer, WebSocket } from 'ws';
3
3
  import { createServer } from 'http';
4
4
  import { EventEmitter } from 'events';
5
5
  import { URL } from 'url';
6
+ import { PeerPigeonMesh } from '../src/PeerPigeonMesh.js';
7
+
8
+ // Inject WebSocket into global scope for use by SignalingClient in Node.js
9
+ // This is necessary for hub mesh initialization
10
+ if (typeof global !== 'undefined' && typeof global.WebSocket === 'undefined') {
11
+ global.WebSocket = WebSocket;
12
+ }
6
13
 
7
14
  /**
8
15
  * PeerPigeon WebSocket signaling server
@@ -20,6 +27,7 @@ export class PeerPigeonServer extends EventEmitter {
20
27
  this.corsOrigin = options.corsOrigin || '*';
21
28
  this.maxMessageSize = options.maxMessageSize || 1048576; // 1MB
22
29
  this.maxPortRetries = options.maxPortRetries || 10; // Try up to 10 ports
30
+ this.verboseLogging = options.verboseLogging === true; // Default false, set true to enable verbose logs
23
31
 
24
32
 
25
33
  // Hub configuration
@@ -29,6 +37,9 @@ export class PeerPigeonServer extends EventEmitter {
29
37
  this.autoConnect = options.autoConnect !== false; // Auto-connect to bootstrap hubs (default: true)
30
38
  this.reconnectInterval = options.reconnectInterval || 5000; // Reconnect interval in ms
31
39
  this.maxReconnectAttempts = options.maxReconnectAttempts || 10; // Max reconnection attempts
40
+ this.hubMeshMaxPeers = options.hubMeshMaxPeers || 3; // Max P2P connections in hub mesh (for partial mesh)
41
+ this.hubMeshMinPeers = options.hubMeshMinPeers || 2; // Min P2P connections in hub mesh
42
+ this.meshMigrationDelay = options.meshMigrationDelay || 10000; // Delay before closing WS connections after mesh is ready (10s)
32
43
 
33
44
  // Generate hub peer ID if this is a hub
34
45
  this.hubPeerId = options.hubPeerId || (this.isHub ? this.generatePeerId() : null);
@@ -40,9 +51,19 @@ export class PeerPigeonServer extends EventEmitter {
40
51
  this.networkPeers = new Map(); // networkName -> Set of peerIds
41
52
  this.hubs = new Map(); // peerId -> hub info (for peers identified as hubs)
42
53
  this.bootstrapConnections = new Map(); // bootstrapUri -> connection info
54
+ this.crossHubDiscoveredPeers = new Map(); // networkName -> Map(peerId -> peerData) for peers on other hubs
55
+ this.recentlyRelayedMessages = new Map(); // messageId -> timestamp (for deduplication)
56
+ this.relayedMessageTTL = 5000; // Keep relay records for 5 seconds
43
57
  this.isRunning = false;
44
58
  this.cleanupTimer = null;
45
59
  this.startTime = null;
60
+
61
+ // Hub mesh P2P properties
62
+ this.hubMesh = null; // PeerPigeonMesh instance for hub-to-hub P2P connections
63
+ this.hubMeshReady = false; // Whether the P2P mesh is established
64
+ this.hubMeshPeers = new Map(); // hubPeerId -> { p2pConnected: boolean, wsConnection: WebSocket }
65
+ this.migratedToP2P = new Set(); // Set of hub peer IDs that have migrated from WS to P2P
66
+ this.migrationTimer = null; // Timer for WS disconnection after mesh establishment
46
67
  }
47
68
 
48
69
  /**
@@ -65,6 +86,21 @@ export class PeerPigeonServer extends EventEmitter {
65
86
  return peerId;
66
87
  }
67
88
 
89
+ /**
90
+ * Create a simple hash of signal data for deduplication
91
+ */
92
+ hashSignalData(data) {
93
+ if (!data) return 'null';
94
+ const str = JSON.stringify(data);
95
+ let hash = 0;
96
+ for (let i = 0; i < str.length; i++) {
97
+ const char = str.charCodeAt(i);
98
+ hash = ((hash << 5) - hash) + char;
99
+ hash = hash & hash; // Convert to 32bit integer
100
+ }
101
+ return hash.toString(16);
102
+ }
103
+
68
104
  /**
69
105
  * Check if a peer is registered as a hub
70
106
  */
@@ -162,7 +198,9 @@ export class PeerPigeonServer extends EventEmitter {
162
198
 
163
199
  // Clean up stale connections
164
200
  stalePeers.forEach(peerId => {
165
- console.log(`๐Ÿงน Cleaning up stale connection: ${peerId.substring(0, 8)}...`);
201
+ if (this.verboseLogging) {
202
+ console.log(`๐Ÿงน Cleaning up stale connection: ${peerId.substring(0, 8)}...`);
203
+ }
166
204
  this.cleanupPeer(peerId);
167
205
  });
168
206
 
@@ -319,8 +357,12 @@ export class PeerPigeonServer extends EventEmitter {
319
357
  try {
320
358
  const result = await this.tryPort(this.port);
321
359
 
322
- // If this is a hub, connect to bootstrap hubs
360
+ // If this is a hub, initialize hub mesh AFTER server is running, then connect to bootstrap hubs
323
361
  if (this.isHub && this.autoConnect) {
362
+ // Give the server a moment to be fully ready for connections
363
+ await new Promise(resolve => setTimeout(resolve, 1000));
364
+
365
+ await this.initializeHubMesh();
324
366
  await this.connectToBootstrapHubs();
325
367
  }
326
368
 
@@ -331,6 +373,330 @@ export class PeerPigeonServer extends EventEmitter {
331
373
  }
332
374
  }
333
375
 
376
+ /**
377
+ * Initialize the hub P2P mesh
378
+ */
379
+ async initializeHubMesh() {
380
+ if (!this.isHub || this.hubMesh) {
381
+ return;
382
+ }
383
+
384
+ console.log(`๐Ÿ”— Initializing hub P2P mesh on namespace: ${this.hubMeshNamespace}`);
385
+ console.log(` Hub Peer ID: ${this.hubPeerId.substring(0, 8)}...`);
386
+ console.log(` Max P2P connections: ${this.hubMeshMaxPeers} (partial mesh with XOR routing)`);
387
+
388
+ // Create PeerPigeonMesh instance for hub-to-hub connections
389
+ this.hubMesh = new PeerPigeonMesh({
390
+ peerId: this.hubPeerId,
391
+ networkName: this.hubMeshNamespace,
392
+ maxPeers: this.hubMeshMaxPeers,
393
+ minPeers: this.hubMeshMinPeers,
394
+ autoConnect: true,
395
+ autoDiscovery: true,
396
+ xorRouting: true, // Use XOR routing for partial mesh
397
+ enableWebDHT: false, // Don't need DHT for hub mesh
398
+ enableCrypto: false // Hubs don't need encryption between themselves
399
+ });
400
+
401
+ // Initialize the mesh (required before connecting)
402
+ await this.hubMesh.init();
403
+
404
+ // Set up hub mesh event handlers
405
+ this.setupHubMeshEventHandlers();
406
+
407
+ // Connect to local signaling server (ourselves)
408
+ // Use 127.0.0.1 for localhost to avoid potential DNS issues
409
+ const host = this.host === '0.0.0.0' ? '127.0.0.1' : this.host;
410
+ const signalingUrl = `ws://${host}:${this.port}`;
411
+
412
+ console.log(`๐Ÿ”Œ Connecting hub mesh to local signaling: ${signalingUrl}`);
413
+ await this.hubMesh.connect(signalingUrl);
414
+
415
+ console.log(`โœ… Hub mesh connected to local signaling`);
416
+ }
417
+
418
+ /**
419
+ * Set up event handlers for the hub P2P mesh
420
+ */
421
+ setupHubMeshEventHandlers() {
422
+ if (!this.hubMesh) return;
423
+
424
+ // Track P2P connections to other hubs
425
+ this.hubMesh.addEventListener('peerConnected', (event) => {
426
+ const hubPeerId = event.peerId;
427
+ console.log(`๐Ÿ”— P2P connection established with hub: ${hubPeerId.substring(0, 8)}...`);
428
+
429
+ // Update hub peer tracking
430
+ if (!this.hubMeshPeers.has(hubPeerId)) {
431
+ this.hubMeshPeers.set(hubPeerId, { p2pConnected: false, wsConnection: null });
432
+ }
433
+ const hubInfo = this.hubMeshPeers.get(hubPeerId);
434
+ hubInfo.p2pConnected = true;
435
+
436
+ this.emit('hubP2PConnected', { hubPeerId });
437
+
438
+ // Check if we should migrate to P2P-only
439
+ this.checkMeshReadiness();
440
+ });
441
+
442
+ this.hubMesh.addEventListener('peerDisconnected', (event) => {
443
+ const hubPeerId = event.peerId;
444
+ console.log(`๐Ÿ”Œ P2P connection lost with hub: ${hubPeerId.substring(0, 8)}...`);
445
+
446
+ const hubInfo = this.hubMeshPeers.get(hubPeerId);
447
+ if (hubInfo) {
448
+ hubInfo.p2pConnected = false;
449
+ }
450
+
451
+ this.migratedToP2P.delete(hubPeerId);
452
+ this.emit('hubP2PDisconnected', { hubPeerId });
453
+ });
454
+
455
+ // Handle messages from other hubs via P2P
456
+ this.hubMesh.addEventListener('messageReceived', (event) => {
457
+ this.handleHubP2PMessage(event.from, event.data);
458
+ });
459
+
460
+ // Track mesh status updates
461
+ this.hubMesh.addEventListener('peersUpdated', () => {
462
+ const connectedCount = this.hubMesh.connectionManager.getConnectedPeers().length;
463
+ console.log(`๐Ÿ“Š Hub mesh status: ${connectedCount} P2P connections active`);
464
+ this.checkMeshReadiness();
465
+ });
466
+ }
467
+
468
+ /**
469
+ * Check if the hub mesh is ready and trigger migration from WS to P2P
470
+ */
471
+ checkMeshReadiness() {
472
+ if (!this.isHub || !this.hubMesh || this.hubMeshReady) {
473
+ return;
474
+ }
475
+
476
+ const connectedP2PPeers = this.hubMesh.connectionManager.getConnectedPeers().length;
477
+ const discoveredHubs = this.hubs.size;
478
+
479
+ // Consider mesh ready if we have P2P connections to at least minPeers hubs
480
+ // OR if there are fewer than minPeers total hubs available
481
+ const isReady = connectedP2PPeers >= this.hubMeshMinPeers ||
482
+ (discoveredHubs < this.hubMeshMinPeers && connectedP2PPeers >= discoveredHubs);
483
+
484
+ if (isReady && !this.hubMeshReady) {
485
+ this.hubMeshReady = true;
486
+ console.log(`โœ… Hub mesh is READY! ${connectedP2PPeers} P2P connections established`);
487
+ console.log(` Migrating to P2P-only immediately...`);
488
+
489
+ this.emit('hubMeshReady', {
490
+ p2pConnections: connectedP2PPeers,
491
+ totalHubs: discoveredHubs
492
+ });
493
+
494
+ // Migrate immediately from WebSocket to P2P-only
495
+ if (this.migrationTimer) {
496
+ clearTimeout(this.migrationTimer);
497
+ this.migrationTimer = null;
498
+ }
499
+
500
+ // Use setImmediate to allow current processing to complete before migration
501
+ setImmediate(() => {
502
+ this.migrateToP2POnly();
503
+ });
504
+ }
505
+ }
506
+
507
+ /**
508
+ * Migrate from WebSocket connections to P2P-only for hub-to-hub communication
509
+ */
510
+ migrateToP2POnly() {
511
+ if (!this.isHub || !this.hubMesh) {
512
+ return;
513
+ }
514
+
515
+ console.log(`๐Ÿ”„ MIGRATING to P2P-only hub mesh...`);
516
+
517
+ const p2pConnectedHubs = this.hubMesh.connectionManager.getConnectedPeers();
518
+ let migratedCount = 0;
519
+ let skippedCount = 0;
520
+
521
+ for (const hubPeerId of p2pConnectedHubs) {
522
+ // Check if this hub has both WS and P2P connections
523
+ const hubInfo = this.hubMeshPeers.get(hubPeerId);
524
+ if (!hubInfo || !hubInfo.p2pConnected) {
525
+ continue;
526
+ }
527
+
528
+ // Check if we have a direct WebSocket connection to this hub (incoming)
529
+ const directWsConnection = this.connections.get(hubPeerId);
530
+ if (directWsConnection && directWsConnection.readyState === WebSocket.OPEN) {
531
+ console.log(`๐Ÿ”Œ Closing direct WebSocket to hub ${hubPeerId.substring(0, 8)}... (P2P active)`);
532
+
533
+ try {
534
+ directWsConnection.close(1000, 'Migrated to P2P mesh');
535
+ this.migratedToP2P.add(hubPeerId);
536
+ migratedCount++;
537
+ } catch (error) {
538
+ console.error(`โŒ Error closing WebSocket for hub ${hubPeerId.substring(0, 8)}...:`, error);
539
+ }
540
+ } else {
541
+ skippedCount++;
542
+ }
543
+ }
544
+
545
+ // Also close ALL bootstrap WebSocket connections - we're on P2P mesh now
546
+ console.log(`๐Ÿ”Œ Closing ALL bootstrap WebSocket connections (P2P mesh active)...`);
547
+ let bootstrapClosed = 0;
548
+
549
+ for (const [uri, connInfo] of this.bootstrapConnections) {
550
+ if (connInfo.connected && connInfo.ws && connInfo.ws.readyState === WebSocket.OPEN) {
551
+ console.log(`๐Ÿ”Œ Closing bootstrap WebSocket: ${uri}`);
552
+ try {
553
+ connInfo.ws.close(1000, 'Migrated to P2P mesh');
554
+ connInfo.connected = false;
555
+ bootstrapClosed++;
556
+ } catch (error) {
557
+ console.error(`โŒ Error closing bootstrap WebSocket ${uri}:`, error);
558
+ }
559
+ }
560
+ }
561
+
562
+ console.log(`โœ… Migration complete:`);
563
+ console.log(` - ${migratedCount} direct hub WebSocket connections closed`);
564
+ console.log(` - ${bootstrapClosed} bootstrap WebSocket connections closed`);
565
+ console.log(` - ${skippedCount} connections already closed or non-existent`);
566
+ console.log(`๐ŸŒ Hub mesh now operating on P2P (${p2pConnectedHubs.length} connections)`);
567
+
568
+ this.emit('hubMeshMigrated', {
569
+ migratedCount: migratedCount + bootstrapClosed,
570
+ p2pConnections: p2pConnectedHubs.length
571
+ });
572
+ }
573
+
574
+ /**
575
+ * Handle P2P messages from other hubs
576
+ */
577
+ handleHubP2PMessage(fromHubPeerId, message) {
578
+ console.log(`๐Ÿ“จ P2P message from hub ${fromHubPeerId.substring(0, 8)}...: ${message.type || 'unknown'}`);
579
+
580
+ // Handle signaling relay through P2P mesh
581
+ if (message.type === 'client-signal-relay') {
582
+ this.handleClientSignalRelay(fromHubPeerId, message);
583
+ return;
584
+ }
585
+
586
+ // Handle peer announcements through P2P mesh
587
+ if (message.type === 'peer-announce-relay') {
588
+ this.handlePeerAnnounceRelay(fromHubPeerId, message);
589
+ return;
590
+ }
591
+
592
+ // Default: log unknown message types
593
+ console.log(`โš ๏ธ Unknown P2P message type from hub: ${message.type}`);
594
+ }
595
+
596
+ /**
597
+ * Handle client signaling relay through P2P hub mesh
598
+ */
599
+ handleClientSignalRelay(fromHubPeerId, message) {
600
+ const { targetPeerId, signalData } = message;
601
+
602
+ if (!targetPeerId || !signalData) {
603
+ console.log(`โš ๏ธ Invalid client signal relay from ${fromHubPeerId.substring(0, 8)}...`);
604
+ return;
605
+ }
606
+
607
+ // Deduplicate relay: create hash from targetPeer + signal type + data hash
608
+ const relayHash = `${targetPeerId}:${signalData.type}:${this.hashSignalData(signalData.data)}`;
609
+ if (this.recentlyRelayedMessages.has(relayHash)) {
610
+ console.log(`๐Ÿ” Duplicate P2P signal relay detected for ${targetPeerId.substring(0, 8)}..., ignoring`);
611
+ return;
612
+ }
613
+ this.recentlyRelayedMessages.set(relayHash, Date.now());
614
+
615
+ // Check if target peer is connected to this hub
616
+ const targetConnection = this.connections.get(targetPeerId);
617
+ if (targetConnection && targetConnection.readyState === WebSocket.OPEN) {
618
+ console.log(`๐Ÿ“ฅ Relaying signal to local client ${targetPeerId.substring(0, 8)}...`);
619
+ this.sendToConnection(targetConnection, signalData);
620
+ } else {
621
+ // Forward to other hubs via P2P if we have more connections
622
+ console.log(`๐Ÿ”„ Client ${targetPeerId.substring(0, 8)}... not local, forwarding to other hubs`);
623
+ this.forwardSignalToHubMesh(targetPeerId, signalData, fromHubPeerId);
624
+ }
625
+ }
626
+
627
+ /**
628
+ * Handle peer announcement relay through P2P hub mesh
629
+ */
630
+ handlePeerAnnounceRelay(fromHubPeerId, message) {
631
+ const { peerId, networkName, peerData } = message;
632
+
633
+ if (!peerId || !networkName) {
634
+ console.log(`โš ๏ธ Invalid peer announce relay from ${fromHubPeerId.substring(0, 8)}...`);
635
+ return;
636
+ }
637
+
638
+ console.log(`๐Ÿ“ฃ Peer ${peerId.substring(0, 8)}... announced via hub ${fromHubPeerId.substring(0, 8)}... on network: ${networkName}`);
639
+
640
+ // Forward to local clients in the same network
641
+ const localPeers = this.getActivePeers(null, networkName);
642
+ localPeers.forEach(localPeerId => {
643
+ const localConnection = this.connections.get(localPeerId);
644
+ if (localConnection) {
645
+ this.sendToConnection(localConnection, {
646
+ type: 'peer-discovered',
647
+ data: peerData,
648
+ networkName,
649
+ fromPeerId: 'system',
650
+ targetPeerId: localPeerId,
651
+ timestamp: Date.now()
652
+ });
653
+ }
654
+ });
655
+ }
656
+
657
+ /**
658
+ * Forward signaling message to hub mesh via P2P
659
+ */
660
+ forwardSignalToHubMesh(targetPeerId, signalData, excludeHubPeerId = null) {
661
+ if (!this.hubMesh) {
662
+ return;
663
+ }
664
+
665
+ const connectedHubConnections = this.hubMesh.connectionManager.getConnectedPeers();
666
+ const connectedHubs = connectedHubConnections
667
+ .map(conn => conn.peerId)
668
+ .filter(hubId => hubId !== excludeHubPeerId);
669
+
670
+ if (connectedHubs.length === 0) {
671
+ console.log(`โš ๏ธ No other hubs available in P2P mesh for forwarding`);
672
+ return;
673
+ }
674
+
675
+ const relayMessage = {
676
+ type: 'client-signal-relay',
677
+ targetPeerId,
678
+ signalData,
679
+ timestamp: Date.now()
680
+ };
681
+
682
+ // Use XOR routing to find closest hubs
683
+ const closestHubs = this.findClosestPeers(targetPeerId, connectedHubs, 2);
684
+
685
+ closestHubs.forEach(hubPeerIdObj => {
686
+ const hubPeerId = typeof hubPeerIdObj === 'string' ? hubPeerIdObj : hubPeerIdObj.peerId;
687
+ console.log(`๐Ÿ“ค Forwarding signal to hub ${hubPeerId.substring(0, 8)}... via P2P`);
688
+
689
+ // Get the peer connection and send the message
690
+ const peerConnection = this.hubMesh.connectionManager.peers.get(hubPeerId);
691
+ if (peerConnection && peerConnection.sendMessage) {
692
+ peerConnection.sendMessage(relayMessage);
693
+ console.log(`โœ… Sent signal via P2P to hub ${hubPeerId.substring(0, 8)}...`);
694
+ } else {
695
+ console.error(`โŒ No peer connection found for hub ${hubPeerId.substring(0, 8)}...`);
696
+ }
697
+ });
698
+ }
699
+
334
700
  /**
335
701
  * Stop the WebSocket server
336
702
  */
@@ -342,6 +708,22 @@ export class PeerPigeonServer extends EventEmitter {
342
708
  return new Promise((resolve) => {
343
709
  console.log('๐Ÿ›‘ Stopping PeerPigeon WebSocket server...');
344
710
 
711
+ // Stop migration timer if running
712
+ if (this.migrationTimer) {
713
+ clearTimeout(this.migrationTimer);
714
+ this.migrationTimer = null;
715
+ }
716
+
717
+ // Disconnect hub mesh if this is a hub
718
+ if (this.isHub && this.hubMesh) {
719
+ console.log('๐Ÿ”Œ Disconnecting hub P2P mesh...');
720
+ this.hubMesh.disconnect();
721
+ this.hubMesh = null;
722
+ this.hubMeshReady = false;
723
+ this.hubMeshPeers.clear();
724
+ this.migratedToP2P.clear();
725
+ }
726
+
345
727
  // Disconnect from bootstrap hubs if this is a hub
346
728
  if (this.isHub) {
347
729
  this.disconnectFromBootstrapHubs();
@@ -352,6 +734,9 @@ export class PeerPigeonServer extends EventEmitter {
352
734
  clearInterval(this.cleanupTimer);
353
735
  this.cleanupTimer = null;
354
736
  }
737
+
738
+ // Clear relay deduplication cache
739
+ this.recentlyRelayedMessages.clear();
355
740
 
356
741
  // Close all WebSocket connections
357
742
  for (const [peerId, ws] of this.connections) {
@@ -537,38 +922,47 @@ export class PeerPigeonServer extends EventEmitter {
537
922
  }
538
923
 
539
924
  /**
540
- * Announce all local (non-hub) peers to a bootstrap hub
925
+ * Announce all local peers to a bootstrap hub (including hub mesh peers for P2P discovery)
541
926
  */
542
927
  announceLocalPeersToHub(ws) {
543
928
  let totalAnnounced = 0;
544
929
 
930
+ console.log(`๐Ÿ“ก Announcing local peers to bootstrap hub (${this.networkPeers.size} networks)`);
931
+
545
932
  // Iterate through all networks and announce their peers
546
933
  for (const [networkName, peerSet] of this.networkPeers) {
547
- // Skip the hub mesh namespace
548
- if (networkName === this.hubMeshNamespace) {
549
- continue;
550
- }
934
+ console.log(` Network '${networkName}': ${peerSet.size} peers`);
551
935
 
552
936
  for (const peerId of peerSet) {
553
937
  const peerData = this.peerData.get(peerId);
554
938
 
555
- // Skip hubs, only announce regular peers
556
- if (peerData?.isHub) {
939
+ // For hub mesh namespace, only announce our own hub mesh client (not other hubs)
940
+ if (networkName === this.hubMeshNamespace && peerId !== this.hubPeerId) {
941
+ console.log(` Skipping hub ${peerId.substring(0, 8)}... (not our mesh client)`);
942
+ continue;
943
+ }
944
+
945
+ // For other namespaces, skip hub peers
946
+ if (networkName !== this.hubMeshNamespace && peerData?.isHub) {
947
+ console.log(` Skipping hub peer ${peerId.substring(0, 8)}... in network ${networkName}`);
557
948
  continue;
558
949
  }
559
950
 
560
951
  // Skip if not connected or not announced
561
952
  const connection = this.connections.get(peerId);
562
953
  if (!connection || connection.readyState !== WebSocket.OPEN || !peerData?.announced) {
954
+ console.log(` Skipping ${peerId.substring(0, 8)}... (not connected or not announced)`);
563
955
  continue;
564
956
  }
565
957
 
958
+ console.log(` โœ… Announcing ${peerId.substring(0, 8)}... from network '${networkName}'`);
959
+
566
960
  // Send peer-discovered message to bootstrap hub
567
961
  const peerAnnouncement = {
568
962
  type: 'peer-discovered',
569
963
  data: {
570
964
  peerId,
571
- isHub: false,
965
+ isHub: networkName === this.hubMeshNamespace,
572
966
  ...peerData.data
573
967
  },
574
968
  networkName: networkName,
@@ -664,7 +1058,9 @@ export class PeerPigeonServer extends EventEmitter {
664
1058
 
665
1059
  case 'peer-discovered':
666
1060
  if (data?.isHub) {
667
- console.log(`๐Ÿข Discovered hub via bootstrap: ${data.peerId?.substring(0, 8)}...`);
1061
+ // Hub discovered via bootstrap - DON'T forward to prevent loops
1062
+ // Hubs will discover each other via their local mesh namespace connections
1063
+ console.log(`๐Ÿข Hub ${data.peerId?.substring(0, 8)}... seen via bootstrap ${uri} (not forwarding to prevent loop)`);
668
1064
  this.emit('hubDiscovered', { peerId: data.peerId, via: uri, data });
669
1065
  } else if (data?.peerId) {
670
1066
  // Regular peer discovered on another hub - notify our local peers in same network
@@ -673,8 +1069,15 @@ export class PeerPigeonServer extends EventEmitter {
673
1069
 
674
1070
  console.log(`๐Ÿ“ฅ Peer ${discoveredPeerId.substring(0, 8)}... discovered on another hub (network: ${discoveredNetwork})`);
675
1071
 
1072
+ // Cache for late joiners (so peers announcing later still learn about this peer)
1073
+ if (!this.crossHubDiscoveredPeers.has(discoveredNetwork)) {
1074
+ this.crossHubDiscoveredPeers.set(discoveredNetwork, new Map());
1075
+ }
1076
+ this.crossHubDiscoveredPeers.get(discoveredNetwork).set(discoveredPeerId, { ...data, cachedAt: Date.now() });
1077
+
676
1078
  // Forward to all our local peers in the same network
677
1079
  const localPeers = this.getActivePeers(null, discoveredNetwork);
1080
+ let forwardCount = 0;
678
1081
  localPeers.forEach(localPeerId => {
679
1082
  const localConnection = this.connections.get(localPeerId);
680
1083
  if (localConnection) {
@@ -686,8 +1089,10 @@ export class PeerPigeonServer extends EventEmitter {
686
1089
  targetPeerId: localPeerId,
687
1090
  timestamp: Date.now()
688
1091
  });
1092
+ forwardCount++;
689
1093
  }
690
1094
  });
1095
+ console.log(`๐Ÿ“ค Forwarded to ${forwardCount} local peer(s) in network '${discoveredNetwork}'`);
691
1096
  }
692
1097
  break;
693
1098
 
@@ -708,13 +1113,15 @@ export class PeerPigeonServer extends EventEmitter {
708
1113
  console.log(`๐Ÿ“ฅ Received ${type} from ${fromPeerId?.substring(0, 8)}... for local peer ${targetPeerId.substring(0, 8)}...`);
709
1114
  this.sendToConnection(targetConnection, message);
710
1115
  } else {
711
- // Not our peer, relay to other bootstrap hubs
712
- console.log(`๐Ÿ”„ Relaying ${type} from ${fromPeerId?.substring(0, 8)}... for ${targetPeerId.substring(0, 8)}... (not local)`);
713
- for (const [otherUri, connInfo] of this.bootstrapConnections) {
714
- if (otherUri !== uri && connInfo.connected && connInfo.ws.readyState === WebSocket.OPEN) {
715
- connInfo.ws.send(JSON.stringify(message));
716
- }
1116
+ // Not our peer - check if we should relay
1117
+
1118
+ // CRITICAL: DO NOT relay via bootstrap WebSocket - this causes loops
1119
+ // Clients should signal directly through their hub, and hubs use P2P mesh
1120
+ if (this.verboseLogging) {
1121
+ console.log(`โญ๏ธ Skipping bootstrap relay of ${type} - not relaying client signaling via bootstrap`);
717
1122
  }
1123
+ // Completely disable bootstrap relay to prevent loops
1124
+ break;
718
1125
  }
719
1126
  } else {
720
1127
  console.log(`โš ๏ธ Received ${type} without targetPeerId via ${uri}`);
@@ -858,7 +1265,9 @@ export class PeerPigeonServer extends EventEmitter {
858
1265
  const { type, data: messageData, targetPeerId, networkName, fromPeerId: originalFromPeerId } = message;
859
1266
 
860
1267
  // Log message type
861
- console.log(`๐Ÿ“จ Received ${type} from ${peerId.substring(0, 8)}... in network: ${networkName || 'global'}`);
1268
+ if (this.verboseLogging) {
1269
+ console.log(`๐Ÿ“จ Received ${type} from ${peerId.substring(0, 8)}... in network: ${networkName || 'global'}`);
1270
+ }
862
1271
 
863
1272
  // Preserve the original fromPeerId if it exists (for relayed messages from other hubs)
864
1273
  // Otherwise use the peerId of the connection
@@ -894,7 +1303,9 @@ export class PeerPigeonServer extends EventEmitter {
894
1303
  this.handleCleanup(peerId, message);
895
1304
  break;
896
1305
  default:
897
- console.log(`โš ๏ธ Ignoring non-signaling message type '${type}' - peers should route their own messages`);
1306
+ if (this.verboseLogging) {
1307
+ console.log(`โš ๏ธ Ignoring non-signaling message type '${type}' - peers should route their own messages`);
1308
+ }
898
1309
  const connection = this.connections.get(peerId);
899
1310
  if (connection && connection.readyState === WebSocket.OPEN) {
900
1311
  this.sendToConnection(connection, {
@@ -917,10 +1328,12 @@ export class PeerPigeonServer extends EventEmitter {
917
1328
  // Detect if this peer is a hub
918
1329
  const isHub = message.data?.isHub === true || peerNetworkName === this.hubMeshNamespace;
919
1330
 
920
- if (isHub) {
921
- console.log(`๐Ÿ“ข Hub announced: ${peerId.substring(0, 8)}... in network: ${peerNetworkName}`);
922
- } else {
923
- console.log(`๐Ÿ“ข Peer announced: ${peerId.substring(0, 8)}... in network: ${peerNetworkName}`);
1331
+ if (this.verboseLogging) {
1332
+ if (isHub) {
1333
+ console.log(`๐Ÿ“ข Hub announced: ${peerId.substring(0, 8)}... in network: ${peerNetworkName}`);
1334
+ } else {
1335
+ console.log(`๐Ÿ“ข Peer announced: ${peerId.substring(0, 8)}... in network: ${peerNetworkName}`);
1336
+ }
924
1337
  }
925
1338
 
926
1339
  // Update peer data with network information
@@ -941,6 +1354,43 @@ export class PeerPigeonServer extends EventEmitter {
941
1354
  connectedAt: peerInfo?.connectedAt || Date.now()
942
1355
  });
943
1356
 
1357
+ // Track WebSocket connection with this hub
1358
+ const wsConnection = this.connections.get(peerId);
1359
+ if (wsConnection) {
1360
+ if (!this.hubMeshPeers.has(peerId)) {
1361
+ this.hubMeshPeers.set(peerId, { p2pConnected: false, wsConnection: null });
1362
+ }
1363
+ this.hubMeshPeers.get(peerId).wsConnection = wsConnection;
1364
+ console.log(`๐Ÿ“Š Tracking hub ${peerId.substring(0, 8)}... WebSocket connection for migration`);
1365
+ }
1366
+
1367
+ // CRITICAL: Forward hub announcement to local hub mesh for P2P discovery
1368
+ // When Hub A announces to Hub B, Hub B's hubMesh needs to know about Hub A
1369
+ if (this.isHub && this.hubMesh && peerId !== this.hubPeerId) {
1370
+ console.log(`๐Ÿ”— Forwarding hub ${peerId.substring(0, 8)}... to local hub mesh for P2P discovery`);
1371
+
1372
+ // Send peer-discovered to this hub's local signaling connection
1373
+ // This will trigger the hub mesh to discover and connect to the announcing hub
1374
+ const localConnection = this.connections.get(this.hubPeerId);
1375
+ if (localConnection && localConnection.readyState === WebSocket.OPEN) {
1376
+ this.sendToConnection(localConnection, {
1377
+ type: 'peer-discovered',
1378
+ data: {
1379
+ peerId,
1380
+ isHub: true,
1381
+ ...message.data
1382
+ },
1383
+ networkName: this.hubMeshNamespace,
1384
+ fromPeerId: 'system',
1385
+ targetPeerId: this.hubPeerId,
1386
+ timestamp: Date.now()
1387
+ });
1388
+ console.log(`โœ… Sent peer-discovered to local hub mesh for ${peerId.substring(0, 8)}...`);
1389
+ } else {
1390
+ console.log(`โš ๏ธ Local hub mesh connection not ready, cannot forward hub announcement`);
1391
+ }
1392
+ }
1393
+
944
1394
  // When a new hub announces itself, send it all our local peers
945
1395
  if (this.isHub) {
946
1396
  console.log(`๐Ÿ“ก New hub connected, sending our local peers to ${peerId.substring(0, 8)}...`);
@@ -954,52 +1404,89 @@ export class PeerPigeonServer extends EventEmitter {
954
1404
  }
955
1405
  this.networkPeers.get(peerNetworkName).add(peerId);
956
1406
 
957
- // If this is a hub, broadcast this peer to ALL other connected hubs (both bootstrap and incoming)
1407
+ // If this is a hub, broadcast this peer to other connected hubs
1408
+ // CRITICAL: Do NOT broadcast hub mesh peers (isHub=true) to prevent discovery loops
958
1409
  if (this.isHub && !isHub) {
959
- const connectedHubs = [];
1410
+ // Check if there are any other hubs at all
1411
+ const hasOtherHubs = this.hubs.size > 0 || this.bootstrapConnections.size > 0;
960
1412
 
961
- // 1. Add outgoing bootstrap connections
962
- for (const [uri, connInfo] of this.bootstrapConnections) {
963
- if (connInfo.connected && connInfo.ws.readyState === WebSocket.OPEN) {
964
- connectedHubs.push({ type: 'bootstrap', ws: connInfo.ws, id: uri });
1413
+ // PRIORITY: Use P2P hub mesh if ready AND there are other hubs
1414
+ if (this.hubMesh && this.hubMeshReady && hasOtherHubs) {
1415
+ const p2pConnectedHubs = this.hubMesh.connectionManager.getConnectedPeers();
1416
+ if (p2pConnectedHubs.length > 0) {
1417
+ console.log(`๐Ÿ“ก Broadcasting peer ${peerId.substring(0, 8)}... to ${p2pConnectedHubs.length} P2P-connected hub(s) [MESH MODE]`);
1418
+
1419
+ const p2pRelayMessage = {
1420
+ type: 'peer-announce-relay',
1421
+ peerId,
1422
+ networkName: peerNetworkName,
1423
+ peerData: {
1424
+ peerId,
1425
+ isHub: false,
1426
+ ...message.data
1427
+ },
1428
+ timestamp: Date.now()
1429
+ };
1430
+
1431
+ p2pConnectedHubs.forEach(hubPeerConnection => {
1432
+ try {
1433
+ const hubPeerId = hubPeerConnection.peerId;
1434
+ this.hubMesh.sendMessage(p2pRelayMessage, hubPeerId);
1435
+ } catch (error) {
1436
+ const hubPeerId = hubPeerConnection.peerId || 'unknown';
1437
+ console.error(`โŒ Error broadcasting to P2P hub ${hubPeerId.substring(0, 8)}...:`, error.message);
1438
+ }
1439
+ });
965
1440
  }
966
- }
967
-
968
- // 2. Add incoming hub connections (hubs that connected to us)
969
- for (const [hubPeerId, hubInfo] of this.hubs) {
970
- // Skip self and the announcing hub
971
- if (hubPeerId === this.hubPeerId || hubPeerId === peerId) {
972
- continue;
1441
+ // When mesh is ready and we have other hubs, ONLY use P2P - skip WebSocket broadcast
1442
+ // (Fall through to peer list broadcast below)
1443
+ } else if (hasOtherHubs) {
1444
+ // Fallback: Use WebSocket connections (only when mesh NOT ready)
1445
+ const connectedHubs = [];
1446
+
1447
+ // 1. Add outgoing bootstrap connections
1448
+ for (const [uri, connInfo] of this.bootstrapConnections) {
1449
+ if (connInfo.connected && connInfo.ws.readyState === WebSocket.OPEN) {
1450
+ connectedHubs.push({ type: 'bootstrap', ws: connInfo.ws, id: uri });
1451
+ }
973
1452
  }
974
- const hubConnection = this.connections.get(hubPeerId);
975
- if (hubConnection && hubConnection.readyState === WebSocket.OPEN) {
976
- connectedHubs.push({ type: 'incoming', ws: hubConnection, id: hubPeerId });
1453
+
1454
+ // 2. Add incoming hub connections (hubs that connected to us)
1455
+ for (const [hubPeerId, hubInfo] of this.hubs) {
1456
+ // Skip self and the announcing hub
1457
+ if (hubPeerId === this.hubPeerId || hubPeerId === peerId) {
1458
+ continue;
1459
+ }
1460
+ const hubConnection = this.connections.get(hubPeerId);
1461
+ if (hubConnection && hubConnection.readyState === WebSocket.OPEN) {
1462
+ connectedHubs.push({ type: 'incoming', ws: hubConnection, id: hubPeerId });
1463
+ }
977
1464
  }
978
- }
979
-
980
- if (connectedHubs.length > 0) {
981
- console.log(`๐Ÿ“ก Broadcasting peer ${peerId.substring(0, 8)}... to ${connectedHubs.length} connected hub(s)`);
982
- const peerAnnouncement = {
983
- type: 'peer-discovered',
984
- data: {
985
- peerId,
986
- isHub: false,
987
- ...message.data
988
- },
989
- networkName: peerNetworkName,
990
- fromPeerId: 'system',
991
- timestamp: Date.now()
992
- };
993
1465
 
994
- for (const hub of connectedHubs) {
995
- try {
996
- if (hub.type === 'bootstrap') {
997
- hub.ws.send(JSON.stringify(peerAnnouncement));
998
- } else {
999
- this.sendToConnection(hub.ws, peerAnnouncement);
1466
+ if (connectedHubs.length > 0) {
1467
+ console.log(`๐Ÿ“ก Broadcasting peer ${peerId.substring(0, 8)}... to ${connectedHubs.length} WebSocket hub(s) [BOOTSTRAP MODE]`);
1468
+ const peerAnnouncement = {
1469
+ type: 'peer-discovered',
1470
+ data: {
1471
+ peerId,
1472
+ isHub: false,
1473
+ ...message.data
1474
+ },
1475
+ networkName: peerNetworkName,
1476
+ fromPeerId: 'system',
1477
+ timestamp: Date.now()
1478
+ };
1479
+
1480
+ for (const hub of connectedHubs) {
1481
+ try {
1482
+ if (hub.type === 'bootstrap') {
1483
+ hub.ws.send(JSON.stringify(peerAnnouncement));
1484
+ } else {
1485
+ this.sendToConnection(hub.ws, peerAnnouncement);
1486
+ }
1487
+ } catch (error) {
1488
+ console.error(`โŒ Error broadcasting to hub ${hub.id}:`, error.message);
1000
1489
  }
1001
- } catch (error) {
1002
- console.error(`โŒ Error broadcasting to hub ${hub.id}:`, error.message);
1003
1490
  }
1004
1491
  }
1005
1492
  }
@@ -1058,6 +1545,27 @@ export class PeerPigeonServer extends EventEmitter {
1058
1545
  });
1059
1546
  });
1060
1547
 
1548
+ // Include ALL cached cross-hub peers immediately (original behavior) to maximize candidate pool
1549
+ const cachedRemotePeers = this.crossHubDiscoveredPeers.get(peerNetworkName);
1550
+ if (cachedRemotePeers && newPeerConnection && newPeerConnection.readyState === newPeerConnection.OPEN) {
1551
+ let sentCount = 0;
1552
+ for (const [remotePeerId, remotePeerData] of cachedRemotePeers) {
1553
+ if (validatedPeers.includes(remotePeerId)) continue;
1554
+ this.sendToConnection(newPeerConnection, {
1555
+ type: 'peer-discovered',
1556
+ data: { peerId: remotePeerId, isHub: remotePeerData.isHub || false, ...remotePeerData },
1557
+ networkName: peerNetworkName,
1558
+ fromPeerId: 'system',
1559
+ targetPeerId: peerId,
1560
+ timestamp: Date.now()
1561
+ });
1562
+ sentCount++;
1563
+ }
1564
+ if (sentCount > 0) {
1565
+ console.log(`๐Ÿ“ฆ Sent ${sentCount} cached cross-hub peer(s) to late joiner ${peerId.substring(0,8)}... in network '${peerNetworkName}'`);
1566
+ }
1567
+ }
1568
+
1061
1569
  this.emit('peerAnnounced', { peerId, networkName: peerNetworkName, isHub });
1062
1570
  }
1063
1571
 
@@ -1065,7 +1573,9 @@ export class PeerPigeonServer extends EventEmitter {
1065
1573
  * Handle peer goodbye
1066
1574
  */
1067
1575
  handleGoodbye(peerId, message, responseMessage) {
1068
- console.log(`๐Ÿ‘‹ Peer goodbye: ${peerId.substring(0, 8)}...`);
1576
+ if (this.verboseLogging) {
1577
+ console.log(`๐Ÿ‘‹ Peer goodbye: ${peerId.substring(0, 8)}...`);
1578
+ }
1069
1579
 
1070
1580
  // Broadcast to closest peers before removing peer data
1071
1581
  this.broadcastToClosestPeers(peerId, responseMessage);
@@ -1082,10 +1592,14 @@ export class PeerPigeonServer extends EventEmitter {
1082
1592
  const targetPeerId = message.targetPeerId;
1083
1593
  const networkName = message.networkName || 'global';
1084
1594
 
1085
- console.log(`๐Ÿ” SIGNALING DEBUG: Received ${message.type} from ${peerId.substring(0, 8)}... to ${targetPeerId?.substring(0, 8)}... in network '${networkName}'`);
1595
+ if (this.verboseLogging) {
1596
+ console.log(`๐Ÿ” SIGNALING DEBUG: Received ${message.type} from ${peerId.substring(0, 8)}... to ${targetPeerId?.substring(0, 8)}... in network '${networkName}'`);
1597
+ }
1086
1598
 
1087
1599
  if (!targetPeerId) {
1088
- console.log(`โŒ No target peer ID in signaling message from ${peerId.substring(0, 8)}...`);
1600
+ if (this.verboseLogging) {
1601
+ console.log(`โŒ No target peer ID in signaling message from ${peerId.substring(0, 8)}...`);
1602
+ }
1089
1603
  return;
1090
1604
  }
1091
1605
 
@@ -1097,22 +1611,65 @@ export class PeerPigeonServer extends EventEmitter {
1097
1611
  const targetNetwork = targetPeerData?.networkName || 'global';
1098
1612
 
1099
1613
  if (networkName !== targetNetwork) {
1100
- console.log(`๐Ÿšซ Blocking ${message.type} from ${peerId.substring(0, 8)}... (network: ${networkName}) to ${targetPeerId.substring(0, 8)}... (network: ${targetNetwork}) - different networks`);
1614
+ if (this.verboseLogging) {
1615
+ console.log(`๐Ÿšซ Blocking ${message.type} from ${peerId.substring(0, 8)}... (network: ${networkName}) to ${targetPeerId.substring(0, 8)}... (network: ${targetNetwork}) - different networks`);
1616
+ }
1101
1617
  return;
1102
1618
  }
1103
1619
 
1104
1620
  // Target is local - forward directly
1105
- console.log(`โœ… Forwarding ${message.type} to LOCAL peer ${targetPeerId.substring(0, 8)}...`);
1621
+ if (this.verboseLogging) {
1622
+ console.log(`โœ… Forwarding ${message.type} to LOCAL peer ${targetPeerId.substring(0, 8)}...`);
1623
+ }
1106
1624
  this.sendToConnection(targetConnection, responseMessage);
1107
1625
  } else {
1108
1626
  // Target peer not on this hub - relay to other hubs
1627
+
1628
+ // Create unique message ID for deduplication (include signal data hash)
1629
+ const dataHash = this.hashSignalData(message.data);
1630
+ const messageId = `${message.type}:${peerId}:${targetPeerId}:${dataHash}`;
1631
+
1632
+ // Check if we've already relayed this message recently
1633
+ if (this.recentlyRelayedMessages.has(messageId)) {
1634
+ if (this.verboseLogging) {
1635
+ console.log(`โญ๏ธ Skipping duplicate relay of ${message.type} (${messageId})`);
1636
+ }
1637
+ return;
1638
+ }
1639
+
1640
+ // Mark message as relayed
1641
+ this.recentlyRelayedMessages.set(messageId, Date.now());
1642
+
1109
1643
  console.log(`๐Ÿ”„ Target peer ${targetPeerId.substring(0, 8)}... NOT LOCAL, relaying to other hubs (network: ${networkName})`);
1110
1644
 
1111
1645
  let relayed = false;
1112
1646
 
1113
- // First try relaying through bootstrap hubs (if we're not the bootstrap)
1114
- if (this.bootstrapConnections.size > 0) {
1115
- console.log(`๏ฟฝ Relaying ${message.type} through ${this.bootstrapConnections.size} bootstrap connection(s)`);
1647
+ // Check if there are any other hubs at all
1648
+ const hasOtherHubs = this.hubs.size > 0 || this.bootstrapConnections.size > 0;
1649
+
1650
+ // PRIORITY: Try P2P hub mesh first if available and ready
1651
+ if (this.isHub && this.hubMesh && this.hubMeshReady && hasOtherHubs) {
1652
+ const p2pConnectedHubs = this.hubMesh.connectionManager.getConnectedPeers();
1653
+ if (p2pConnectedHubs.length > 0) {
1654
+ console.log(`๐Ÿ“ก Relaying ${message.type} through P2P hub mesh (${p2pConnectedHubs.length} hubs)`);
1655
+ this.forwardSignalToHubMesh(targetPeerId, responseMessage);
1656
+ relayed = true;
1657
+ } else {
1658
+ console.log(`โš ๏ธ Hub mesh ready but no P2P connections available`);
1659
+ }
1660
+
1661
+ // CRITICAL: When mesh is ready AND we have other hubs, ONLY use P2P - do NOT fall back to WebSocket
1662
+ if (this.hubMeshReady && hasOtherHubs) {
1663
+ if (!relayed) {
1664
+ console.log(`โŒ FAILED TO RELAY via P2P: Mesh ready but no connections for ${targetPeerId.substring(0, 8)}...`);
1665
+ }
1666
+ return; // Exit early - no WebSocket fallback when mesh is ready and other hubs exist
1667
+ }
1668
+ }
1669
+
1670
+ // Fallback: Try relaying through WebSocket bootstrap hubs (ONLY if mesh not ready)
1671
+ if (!relayed && this.bootstrapConnections.size > 0) {
1672
+ console.log(`๐Ÿ”— Relaying ${message.type} through ${this.bootstrapConnections.size} WebSocket bootstrap connection(s)`);
1116
1673
 
1117
1674
  for (const [uri, connInfo] of this.bootstrapConnections) {
1118
1675
  if (connInfo.connected && connInfo.ws.readyState === WebSocket.OPEN) {
@@ -1123,9 +1680,9 @@ export class PeerPigeonServer extends EventEmitter {
1123
1680
  }
1124
1681
  }
1125
1682
 
1126
- // If we're the bootstrap hub (or bootstrap relay failed), forward to all connected hubs
1127
- if (this.hubs.size > 0) {
1128
- console.log(`๏ฟฝ Forwarding ${message.type} to ${this.hubs.size} connected hub(s)`);
1683
+ // Final fallback: Forward to WebSocket-connected hubs (ONLY if mesh not ready)
1684
+ if (!relayed && this.hubs.size > 0) {
1685
+ console.log(`๐Ÿ”— Forwarding ${message.type} to ${this.hubs.size} WebSocket-connected hub(s)`);
1129
1686
 
1130
1687
  for (const [hubPeerId, hubInfo] of this.hubs) {
1131
1688
  const hubConnection = this.connections.get(hubPeerId);
@@ -1139,6 +1696,7 @@ export class PeerPigeonServer extends EventEmitter {
1139
1696
 
1140
1697
  if (!relayed) {
1141
1698
  console.log(`โŒ FAILED TO RELAY: No hubs available for ${targetPeerId.substring(0, 8)}... (network: ${networkName})`);
1699
+ console.log(` - P2P hub mesh: ${this.hubMesh ? this.hubMesh.connectionManager.getConnectedPeers().length : 0}`);
1142
1700
  console.log(` - Bootstrap connections: ${this.bootstrapConnections.size}`);
1143
1701
  console.log(` - Connected hubs: ${this.hubs.size}`);
1144
1702
  }
@@ -1182,12 +1740,15 @@ export class PeerPigeonServer extends EventEmitter {
1182
1740
  return;
1183
1741
  }
1184
1742
 
1185
- // Check if sender is a hub
1743
+ // Check if sender is a hub (either a regular hub or a hub via bootstrap)
1186
1744
  const senderPeerData = this.peerData.get(fromHubPeerId);
1187
- const isFromHub = senderPeerData?.isHub || senderPeerData?.networkName === this.hubMeshNamespace;
1745
+ const isFromHub = senderPeerData?.isHub ||
1746
+ senderPeerData?.networkName === this.hubMeshNamespace ||
1747
+ this.hubs.has(fromHubPeerId);
1188
1748
 
1189
1749
  if (!isFromHub) {
1190
1750
  console.log(`โš ๏ธ Received peer-discovered from non-hub peer ${fromHubPeerId.substring(0, 8)}... - ignoring`);
1751
+ console.log(` Debug: isHub=${senderPeerData?.isHub}, networkName=${senderPeerData?.networkName}, inHubsMap=${this.hubs.has(fromHubPeerId)}`);
1191
1752
  return;
1192
1753
  }
1193
1754
 
@@ -1227,7 +1788,9 @@ export class PeerPigeonServer extends EventEmitter {
1227
1788
  * Handle peer disconnection
1228
1789
  */
1229
1790
  handleDisconnection(peerId, code, reason) {
1230
- console.log(`โŒ Peer disconnected: ${peerId.substring(0, 8)}... (code: ${code}, reason: ${reason})`);
1791
+ if (this.verboseLogging) {
1792
+ console.log(`โŒ Peer disconnected: ${peerId.substring(0, 8)}... (code: ${code}, reason: ${reason})`);
1793
+ }
1231
1794
 
1232
1795
  // Notify other peers about disconnection
1233
1796
  this.broadcastToOthers(peerId, {
@@ -1276,7 +1839,9 @@ export class PeerPigeonServer extends EventEmitter {
1276
1839
 
1277
1840
  if (wasConnected) {
1278
1841
  const peerType = isHub ? 'hub' : 'peer';
1279
- console.log(`๐Ÿงน Cleaned up ${peerType}: ${peerId.substring(0, 8)}... from network: ${peerInfo?.networkName || 'unknown'}`);
1842
+ if (this.verboseLogging) {
1843
+ console.log(`๐Ÿงน Cleaned up ${peerType}: ${peerId.substring(0, 8)}... from network: ${peerInfo?.networkName || 'unknown'}`);
1844
+ }
1280
1845
 
1281
1846
  // Notify other peers in the same network about disconnection
1282
1847
  if (peerInfo && peerInfo.networkName) {
@@ -1336,7 +1901,9 @@ export class PeerPigeonServer extends EventEmitter {
1336
1901
  }
1337
1902
  }
1338
1903
  }
1339
- console.log(`๐Ÿ“ก Broadcast to ${sentCount} peers`);
1904
+ if (this.verboseLogging) {
1905
+ console.log(`๐Ÿ“ก Broadcast to ${sentCount} peers`);
1906
+ }
1340
1907
  return sentCount;
1341
1908
  }
1342
1909
 
@@ -1349,7 +1916,9 @@ export class PeerPigeonServer extends EventEmitter {
1349
1916
  const activePeers = this.getActivePeers(fromPeerId, networkName);
1350
1917
  const closestPeers = this.findClosestPeers(fromPeerId, activePeers, maxPeers);
1351
1918
 
1352
- console.log(`Broadcasting from ${fromPeerId.substring(0, 8)}... to ${closestPeers.length} closest peers in network: ${networkName}`);
1919
+ if (this.verboseLogging) {
1920
+ console.log(`Broadcasting from ${fromPeerId.substring(0, 8)}... to ${closestPeers.length} closest peers in network: ${networkName}`);
1921
+ }
1353
1922
 
1354
1923
  closestPeers.forEach(peerId => {
1355
1924
  this.sendToConnection(this.connections.get(peerId), message);
@@ -1381,6 +1950,20 @@ export class PeerPigeonServer extends EventEmitter {
1381
1950
  if (cleanedUp > 0) {
1382
1951
  console.log(`๐Ÿงน Periodic cleanup: removed ${cleanedUp} stale connections, ${this.connections.size} active across ${this.networkPeers.size} networks`);
1383
1952
  }
1953
+
1954
+ // Clean up old relayed message records
1955
+ const now = Date.now();
1956
+ let relayRecordsRemoved = 0;
1957
+ for (const [messageId, timestamp] of this.recentlyRelayedMessages) {
1958
+ if (now - timestamp > this.relayedMessageTTL) {
1959
+ this.recentlyRelayedMessages.delete(messageId);
1960
+ relayRecordsRemoved++;
1961
+ }
1962
+ }
1963
+
1964
+ if (relayRecordsRemoved > 0 && this.verboseLogging) {
1965
+ console.log(`๐Ÿงน Cleaned up ${relayRecordsRemoved} old relay records`);
1966
+ }
1384
1967
  }
1385
1968
 
1386
1969
  /**