peerpigeon 1.0.8 โ†’ 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/server/index.js CHANGED
@@ -3,6 +3,7 @@ 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';
6
7
 
7
8
  /**
8
9
  * PeerPigeon WebSocket signaling server
@@ -20,6 +21,7 @@ export class PeerPigeonServer extends EventEmitter {
20
21
  this.corsOrigin = options.corsOrigin || '*';
21
22
  this.maxMessageSize = options.maxMessageSize || 1048576; // 1MB
22
23
  this.maxPortRetries = options.maxPortRetries || 10; // Try up to 10 ports
24
+ this.verboseLogging = options.verboseLogging === true; // Default false, set true to enable verbose logs
23
25
 
24
26
 
25
27
  // Hub configuration
@@ -29,6 +31,9 @@ export class PeerPigeonServer extends EventEmitter {
29
31
  this.autoConnect = options.autoConnect !== false; // Auto-connect to bootstrap hubs (default: true)
30
32
  this.reconnectInterval = options.reconnectInterval || 5000; // Reconnect interval in ms
31
33
  this.maxReconnectAttempts = options.maxReconnectAttempts || 10; // Max reconnection attempts
34
+ this.hubMeshMaxPeers = options.hubMeshMaxPeers || 3; // Max P2P connections in hub mesh (for partial mesh)
35
+ this.hubMeshMinPeers = options.hubMeshMinPeers || 2; // Min P2P connections in hub mesh
36
+ this.meshMigrationDelay = options.meshMigrationDelay || 10000; // Delay before closing WS connections after mesh is ready (10s)
32
37
 
33
38
  // Generate hub peer ID if this is a hub
34
39
  this.hubPeerId = options.hubPeerId || (this.isHub ? this.generatePeerId() : null);
@@ -40,11 +45,16 @@ export class PeerPigeonServer extends EventEmitter {
40
45
  this.networkPeers = new Map(); // networkName -> Set of peerIds
41
46
  this.hubs = new Map(); // peerId -> hub info (for peers identified as hubs)
42
47
  this.bootstrapConnections = new Map(); // bootstrapUri -> connection info
43
- this.relayedDiscoveries = new Map(); // Track relayed peer discoveries to prevent loops: "peerId:networkName" -> timestamp
44
- this.relayedSignaling = new Map(); // Track relayed signaling messages to prevent loops: "fromPeerId:targetPeerId:type" -> timestamp
45
48
  this.isRunning = false;
46
49
  this.cleanupTimer = null;
47
50
  this.startTime = null;
51
+
52
+ // Hub mesh P2P properties
53
+ this.hubMesh = null; // PeerPigeonMesh instance for hub-to-hub P2P connections
54
+ this.hubMeshReady = false; // Whether the P2P mesh is established
55
+ this.hubMeshPeers = new Map(); // hubPeerId -> { p2pConnected: boolean, wsConnection: WebSocket }
56
+ this.migratedToP2P = new Set(); // Set of hub peer IDs that have migrated from WS to P2P
57
+ this.migrationTimer = null; // Timer for WS disconnection after mesh establishment
48
58
  }
49
59
 
50
60
  /**
@@ -101,36 +111,11 @@ export class PeerPigeonServer extends EventEmitter {
101
111
  /**
102
112
  * Get all connected hubs
103
113
  */
104
- /**
105
- * Get all connected hubs (directly connected via WebSocket)
106
- */
107
114
  getConnectedHubs(excludePeerId = null) {
108
115
  const hubList = [];
109
116
  for (const [peerId, hubInfo] of this.hubs) {
110
117
  if (peerId !== excludePeerId && this.connections.has(peerId)) {
111
- hubList.push({
112
- peerId,
113
- connected: true,
114
- ...hubInfo
115
- });
116
- }
117
- }
118
- return hubList;
119
- }
120
-
121
- /**
122
- * Get all known hubs (both directly connected and remotely discovered)
123
- */
124
- getAllKnownHubs(excludePeerId = null) {
125
- const hubList = [];
126
- for (const [peerId, hubInfo] of this.hubs) {
127
- if (peerId !== excludePeerId) {
128
- hubList.push({
129
- peerId,
130
- connected: this.connections.has(peerId),
131
- remote: hubInfo.remote || false,
132
- ...hubInfo
133
- });
118
+ hubList.push({ peerId, ...hubInfo });
134
119
  }
135
120
  }
136
121
  return hubList;
@@ -189,7 +174,9 @@ export class PeerPigeonServer extends EventEmitter {
189
174
 
190
175
  // Clean up stale connections
191
176
  stalePeers.forEach(peerId => {
192
- console.log(`๐Ÿงน Cleaning up stale connection: ${peerId.substring(0, 8)}...`);
177
+ if (this.verboseLogging) {
178
+ console.log(`๐Ÿงน Cleaning up stale connection: ${peerId.substring(0, 8)}...`);
179
+ }
193
180
  this.cleanupPeer(peerId);
194
181
  });
195
182
 
@@ -246,7 +233,7 @@ export class PeerPigeonServer extends EventEmitter {
246
233
  res.end(JSON.stringify({
247
234
  timestamp: new Date().toISOString(),
248
235
  totalHubs: this.hubs.size,
249
- hubs: this.getAllKnownHubs()
236
+ hubs: this.getConnectedHubs()
250
237
  }));
251
238
  return;
252
239
  }
@@ -346,8 +333,12 @@ export class PeerPigeonServer extends EventEmitter {
346
333
  try {
347
334
  const result = await this.tryPort(this.port);
348
335
 
349
- // If this is a hub, connect to bootstrap hubs
336
+ // If this is a hub, initialize hub mesh AFTER server is running, then connect to bootstrap hubs
350
337
  if (this.isHub && this.autoConnect) {
338
+ // Give the server a moment to be fully ready for connections
339
+ await new Promise(resolve => setTimeout(resolve, 1000));
340
+
341
+ await this.initializeHubMesh();
351
342
  await this.connectToBootstrapHubs();
352
343
  }
353
344
 
@@ -358,6 +349,323 @@ export class PeerPigeonServer extends EventEmitter {
358
349
  }
359
350
  }
360
351
 
352
+ /**
353
+ * Initialize the hub P2P mesh
354
+ */
355
+ async initializeHubMesh() {
356
+ if (!this.isHub || this.hubMesh) {
357
+ return;
358
+ }
359
+
360
+ console.log(`๐Ÿ”— Initializing hub P2P mesh on namespace: ${this.hubMeshNamespace}`);
361
+ console.log(` Hub Peer ID: ${this.hubPeerId.substring(0, 8)}...`);
362
+ console.log(` Max P2P connections: ${this.hubMeshMaxPeers} (partial mesh with XOR routing)`);
363
+
364
+ // Create PeerPigeonMesh instance for hub-to-hub connections
365
+ this.hubMesh = new PeerPigeonMesh({
366
+ peerId: this.hubPeerId,
367
+ networkName: this.hubMeshNamespace,
368
+ maxPeers: this.hubMeshMaxPeers,
369
+ minPeers: this.hubMeshMinPeers,
370
+ autoConnect: true,
371
+ autoDiscovery: true,
372
+ xorRouting: true, // Use XOR routing for partial mesh
373
+ enableWebDHT: false, // Don't need DHT for hub mesh
374
+ enableCrypto: false // Hubs don't need encryption between themselves
375
+ });
376
+
377
+ // Initialize the mesh (required before connecting)
378
+ await this.hubMesh.init();
379
+
380
+ // Set up hub mesh event handlers
381
+ this.setupHubMeshEventHandlers();
382
+
383
+ // Connect to local signaling server (ourselves)
384
+ // Use 127.0.0.1 for localhost to avoid potential DNS issues
385
+ const host = this.host === '0.0.0.0' ? '127.0.0.1' : this.host;
386
+ const signalingUrl = `ws://${host}:${this.port}`;
387
+
388
+ console.log(`๐Ÿ”Œ Connecting hub mesh to local signaling: ${signalingUrl}`);
389
+ await this.hubMesh.connect(signalingUrl);
390
+
391
+ console.log(`โœ… Hub mesh connected to local signaling`);
392
+ }
393
+
394
+ /**
395
+ * Set up event handlers for the hub P2P mesh
396
+ */
397
+ setupHubMeshEventHandlers() {
398
+ if (!this.hubMesh) return;
399
+
400
+ // Track P2P connections to other hubs
401
+ this.hubMesh.addEventListener('peerConnected', (event) => {
402
+ const hubPeerId = event.peerId;
403
+ console.log(`๐Ÿ”— P2P connection established with hub: ${hubPeerId.substring(0, 8)}...`);
404
+
405
+ // Update hub peer tracking
406
+ if (!this.hubMeshPeers.has(hubPeerId)) {
407
+ this.hubMeshPeers.set(hubPeerId, { p2pConnected: false, wsConnection: null });
408
+ }
409
+ const hubInfo = this.hubMeshPeers.get(hubPeerId);
410
+ hubInfo.p2pConnected = true;
411
+
412
+ this.emit('hubP2PConnected', { hubPeerId });
413
+
414
+ // Check if we should migrate to P2P-only
415
+ this.checkMeshReadiness();
416
+ });
417
+
418
+ this.hubMesh.addEventListener('peerDisconnected', (event) => {
419
+ const hubPeerId = event.peerId;
420
+ console.log(`๐Ÿ”Œ P2P connection lost with hub: ${hubPeerId.substring(0, 8)}...`);
421
+
422
+ const hubInfo = this.hubMeshPeers.get(hubPeerId);
423
+ if (hubInfo) {
424
+ hubInfo.p2pConnected = false;
425
+ }
426
+
427
+ this.migratedToP2P.delete(hubPeerId);
428
+ this.emit('hubP2PDisconnected', { hubPeerId });
429
+ });
430
+
431
+ // Handle messages from other hubs via P2P
432
+ this.hubMesh.addEventListener('messageReceived', (event) => {
433
+ this.handleHubP2PMessage(event.from, event.data);
434
+ });
435
+
436
+ // Track mesh status updates
437
+ this.hubMesh.addEventListener('peersUpdated', () => {
438
+ const connectedCount = this.hubMesh.connectionManager.getConnectedPeers().length;
439
+ console.log(`๐Ÿ“Š Hub mesh status: ${connectedCount} P2P connections active`);
440
+ this.checkMeshReadiness();
441
+ });
442
+ }
443
+
444
+ /**
445
+ * Check if the hub mesh is ready and trigger migration from WS to P2P
446
+ */
447
+ checkMeshReadiness() {
448
+ if (!this.isHub || !this.hubMesh || this.hubMeshReady) {
449
+ return;
450
+ }
451
+
452
+ const connectedP2PPeers = this.hubMesh.connectionManager.getConnectedPeers().length;
453
+ const discoveredHubs = this.hubs.size;
454
+
455
+ // Consider mesh ready if we have P2P connections to at least minPeers hubs
456
+ // OR if there are fewer than minPeers total hubs available
457
+ const isReady = connectedP2PPeers >= this.hubMeshMinPeers ||
458
+ (discoveredHubs < this.hubMeshMinPeers && connectedP2PPeers >= discoveredHubs);
459
+
460
+ if (isReady && !this.hubMeshReady) {
461
+ this.hubMeshReady = true;
462
+ console.log(`โœ… Hub mesh is READY! ${connectedP2PPeers} P2P connections established`);
463
+ console.log(` Scheduling WebSocket migration in ${this.meshMigrationDelay}ms...`);
464
+
465
+ this.emit('hubMeshReady', {
466
+ p2pConnections: connectedP2PPeers,
467
+ totalHubs: discoveredHubs
468
+ });
469
+
470
+ // Schedule migration from WebSocket to P2P-only
471
+ if (this.migrationTimer) {
472
+ clearTimeout(this.migrationTimer);
473
+ }
474
+ this.migrationTimer = setTimeout(() => {
475
+ this.migrateToP2POnly();
476
+ }, this.meshMigrationDelay);
477
+ }
478
+ }
479
+
480
+ /**
481
+ * Migrate from WebSocket connections to P2P-only for hub-to-hub communication
482
+ */
483
+ migrateToP2POnly() {
484
+ if (!this.isHub || !this.hubMesh) {
485
+ return;
486
+ }
487
+
488
+ console.log(`๐Ÿ”„ MIGRATING to P2P-only hub mesh...`);
489
+
490
+ const p2pConnectedHubs = this.hubMesh.connectionManager.getConnectedPeers();
491
+ let migratedCount = 0;
492
+ let skippedCount = 0;
493
+
494
+ for (const hubPeerId of p2pConnectedHubs) {
495
+ // Check if this hub has both WS and P2P connections
496
+ const hubInfo = this.hubMeshPeers.get(hubPeerId);
497
+ if (!hubInfo || !hubInfo.p2pConnected) {
498
+ continue;
499
+ }
500
+
501
+ // Check if we have a direct WebSocket connection to this hub (incoming)
502
+ const directWsConnection = this.connections.get(hubPeerId);
503
+ if (directWsConnection && directWsConnection.readyState === WebSocket.OPEN) {
504
+ console.log(`๐Ÿ”Œ Closing direct WebSocket to hub ${hubPeerId.substring(0, 8)}... (P2P active)`);
505
+
506
+ try {
507
+ directWsConnection.close(1000, 'Migrated to P2P mesh');
508
+ this.migratedToP2P.add(hubPeerId);
509
+ migratedCount++;
510
+ } catch (error) {
511
+ console.error(`โŒ Error closing WebSocket for hub ${hubPeerId.substring(0, 8)}...:`, error);
512
+ }
513
+ } else {
514
+ skippedCount++;
515
+ }
516
+ }
517
+
518
+ // Also close bootstrap WebSocket connections if we have P2P to those hubs
519
+ console.log(`๐Ÿ”Œ Closing bootstrap WebSocket connections (migrating to P2P)...`);
520
+ let bootstrapClosed = 0;
521
+
522
+ for (const [uri, connInfo] of this.bootstrapConnections) {
523
+ if (connInfo.connected && connInfo.ws && connInfo.ws.readyState === WebSocket.OPEN) {
524
+ // Check if we have P2P connection (we may not know the exact peer ID for bootstrap)
525
+ // Close bootstrap connections if we have sufficient P2P connections
526
+ if (p2pConnectedHubs.length >= this.hubMeshMinPeers) {
527
+ console.log(`๐Ÿ”Œ Closing bootstrap WebSocket: ${uri} (sufficient P2P connections)`);
528
+ try {
529
+ connInfo.ws.close(1000, 'Migrated to P2P mesh');
530
+ connInfo.connected = false;
531
+ bootstrapClosed++;
532
+ } catch (error) {
533
+ console.error(`โŒ Error closing bootstrap WebSocket ${uri}:`, error);
534
+ }
535
+ }
536
+ }
537
+ }
538
+
539
+ console.log(`โœ… Migration complete:`);
540
+ console.log(` - ${migratedCount} direct hub WebSocket connections closed`);
541
+ console.log(` - ${bootstrapClosed} bootstrap WebSocket connections closed`);
542
+ console.log(` - ${skippedCount} connections already closed or non-existent`);
543
+ console.log(`๐ŸŒ Hub mesh now operating on P2P (${p2pConnectedHubs.length} connections)`);
544
+
545
+ this.emit('hubMeshMigrated', {
546
+ migratedCount: migratedCount + bootstrapClosed,
547
+ p2pConnections: p2pConnectedHubs.length
548
+ });
549
+ }
550
+
551
+ /**
552
+ * Handle P2P messages from other hubs
553
+ */
554
+ handleHubP2PMessage(fromHubPeerId, message) {
555
+ console.log(`๐Ÿ“จ P2P message from hub ${fromHubPeerId.substring(0, 8)}...: ${message.type || 'unknown'}`);
556
+
557
+ // Handle signaling relay through P2P mesh
558
+ if (message.type === 'client-signal-relay') {
559
+ this.handleClientSignalRelay(fromHubPeerId, message);
560
+ return;
561
+ }
562
+
563
+ // Handle peer announcements through P2P mesh
564
+ if (message.type === 'peer-announce-relay') {
565
+ this.handlePeerAnnounceRelay(fromHubPeerId, message);
566
+ return;
567
+ }
568
+
569
+ // Default: log unknown message types
570
+ console.log(`โš ๏ธ Unknown P2P message type from hub: ${message.type}`);
571
+ }
572
+
573
+ /**
574
+ * Handle client signaling relay through P2P hub mesh
575
+ */
576
+ handleClientSignalRelay(fromHubPeerId, message) {
577
+ const { targetPeerId, signalData } = message;
578
+
579
+ if (!targetPeerId || !signalData) {
580
+ console.log(`โš ๏ธ Invalid client signal relay from ${fromHubPeerId.substring(0, 8)}...`);
581
+ return;
582
+ }
583
+
584
+ // Check if target peer is connected to this hub
585
+ const targetConnection = this.connections.get(targetPeerId);
586
+ if (targetConnection && targetConnection.readyState === WebSocket.OPEN) {
587
+ console.log(`๐Ÿ“ฅ Relaying signal to local client ${targetPeerId.substring(0, 8)}...`);
588
+ this.sendToConnection(targetConnection, signalData);
589
+ } else {
590
+ // Forward to other hubs via P2P if we have more connections
591
+ console.log(`๐Ÿ”„ Client ${targetPeerId.substring(0, 8)}... not local, forwarding to other hubs`);
592
+ this.forwardSignalToHubMesh(targetPeerId, signalData, fromHubPeerId);
593
+ }
594
+ }
595
+
596
+ /**
597
+ * Handle peer announcement relay through P2P hub mesh
598
+ */
599
+ handlePeerAnnounceRelay(fromHubPeerId, message) {
600
+ const { peerId, networkName, peerData } = message;
601
+
602
+ if (!peerId || !networkName) {
603
+ console.log(`โš ๏ธ Invalid peer announce relay from ${fromHubPeerId.substring(0, 8)}...`);
604
+ return;
605
+ }
606
+
607
+ console.log(`๐Ÿ“ฃ Peer ${peerId.substring(0, 8)}... announced via hub ${fromHubPeerId.substring(0, 8)}... on network: ${networkName}`);
608
+
609
+ // Forward to local clients in the same network
610
+ const localPeers = this.getActivePeers(null, networkName);
611
+ localPeers.forEach(localPeerId => {
612
+ const localConnection = this.connections.get(localPeerId);
613
+ if (localConnection) {
614
+ this.sendToConnection(localConnection, {
615
+ type: 'peer-discovered',
616
+ data: peerData,
617
+ networkName,
618
+ fromPeerId: 'system',
619
+ targetPeerId: localPeerId,
620
+ timestamp: Date.now()
621
+ });
622
+ }
623
+ });
624
+ }
625
+
626
+ /**
627
+ * Forward signaling message to hub mesh via P2P
628
+ */
629
+ forwardSignalToHubMesh(targetPeerId, signalData, excludeHubPeerId = null) {
630
+ if (!this.hubMesh) {
631
+ return;
632
+ }
633
+
634
+ const connectedHubConnections = this.hubMesh.connectionManager.getConnectedPeers();
635
+ const connectedHubs = connectedHubConnections
636
+ .map(conn => conn.peerId)
637
+ .filter(hubId => hubId !== excludeHubPeerId);
638
+
639
+ if (connectedHubs.length === 0) {
640
+ console.log(`โš ๏ธ No other hubs available in P2P mesh for forwarding`);
641
+ return;
642
+ }
643
+
644
+ const relayMessage = {
645
+ type: 'client-signal-relay',
646
+ targetPeerId,
647
+ signalData,
648
+ timestamp: Date.now()
649
+ };
650
+
651
+ // Use XOR routing to find closest hubs
652
+ const closestHubs = this.findClosestPeers(targetPeerId, connectedHubs, 2);
653
+
654
+ closestHubs.forEach(hubPeerIdObj => {
655
+ const hubPeerId = typeof hubPeerIdObj === 'string' ? hubPeerIdObj : hubPeerIdObj.peerId;
656
+ console.log(`๐Ÿ“ค Forwarding signal to hub ${hubPeerId.substring(0, 8)}... via P2P`);
657
+
658
+ // Get the peer connection and send the message
659
+ const peerConnection = this.hubMesh.connectionManager.peers.get(hubPeerId);
660
+ if (peerConnection && peerConnection.sendMessage) {
661
+ peerConnection.sendMessage(relayMessage);
662
+ console.log(`โœ… Sent signal via P2P to hub ${hubPeerId.substring(0, 8)}...`);
663
+ } else {
664
+ console.error(`โŒ No peer connection found for hub ${hubPeerId.substring(0, 8)}...`);
665
+ }
666
+ });
667
+ }
668
+
361
669
  /**
362
670
  * Stop the WebSocket server
363
671
  */
@@ -369,6 +677,22 @@ export class PeerPigeonServer extends EventEmitter {
369
677
  return new Promise((resolve) => {
370
678
  console.log('๐Ÿ›‘ Stopping PeerPigeon WebSocket server...');
371
679
 
680
+ // Stop migration timer if running
681
+ if (this.migrationTimer) {
682
+ clearTimeout(this.migrationTimer);
683
+ this.migrationTimer = null;
684
+ }
685
+
686
+ // Disconnect hub mesh if this is a hub
687
+ if (this.isHub && this.hubMesh) {
688
+ console.log('๐Ÿ”Œ Disconnecting hub P2P mesh...');
689
+ this.hubMesh.disconnect();
690
+ this.hubMesh = null;
691
+ this.hubMeshReady = false;
692
+ this.hubMeshPeers.clear();
693
+ this.migratedToP2P.clear();
694
+ }
695
+
372
696
  // Disconnect from bootstrap hubs if this is a hub
373
697
  if (this.isHub) {
374
698
  this.disconnectFromBootstrapHubs();
@@ -425,17 +749,18 @@ export class PeerPigeonServer extends EventEmitter {
425
749
  return;
426
750
  }
427
751
 
428
- // Default Fly.io bootstrap hubs
429
- const DEFAULT_FLY_HUBS = [
430
- 'wss://pigeonhub.fly.dev',
431
- 'wss://pigeonhub-c.fly.dev'
432
- ];
433
-
434
- // Use provided bootstrap hubs, or default to Fly.io hubs
752
+ // If no bootstrap hubs specified, try default port 3000
435
753
  let bootstrapUris = this.bootstrapHubs;
436
754
  if (!bootstrapUris || bootstrapUris.length === 0) {
437
- bootstrapUris = DEFAULT_FLY_HUBS;
438
- console.log(`๐Ÿ”— No bootstrap hubs specified, using default Fly.io hubs: ${bootstrapUris.join(', ')}`);
755
+ // Don't connect to ourselves
756
+ const defaultPort = 3000;
757
+ if (this.port !== defaultPort) {
758
+ bootstrapUris = [`ws://${this.host}:${defaultPort}`];
759
+ console.log(`๐Ÿ”— No bootstrap hubs specified, trying default: ws://${this.host}:${defaultPort}`);
760
+ } else {
761
+ console.log('โ„น๏ธ No bootstrap hubs to connect to (running on default port 3000)');
762
+ return;
763
+ }
439
764
  }
440
765
 
441
766
  console.log(`๐Ÿ”— Connecting to ${bootstrapUris.length} bootstrap hub(s)...`);
@@ -510,19 +835,7 @@ export class PeerPigeonServer extends EventEmitter {
510
835
 
511
836
  this.emit('bootstrapDisconnected', { uri, code, reason });
512
837
 
513
- // Don't reconnect to localhost hubs - they're likely just not running
514
- const url = new URL(uri);
515
- const isLocalhost = url.hostname === 'localhost' ||
516
- url.hostname === '127.0.0.1' ||
517
- url.hostname === '0.0.0.0';
518
-
519
- if (isLocalhost) {
520
- console.log(`โ„น๏ธ Not reconnecting to localhost hub ${uri} - assuming it's not running`);
521
- this.bootstrapConnections.delete(uri);
522
- return;
523
- }
524
-
525
- // Attempt to reconnect for non-localhost hubs
838
+ // Attempt to reconnect
526
839
  if (this.isRunning && attemptNumber < this.maxReconnectAttempts) {
527
840
  connectionInfo.reconnectTimer = setTimeout(() => {
528
841
  console.log(`๐Ÿ”„ Reconnecting to ${uri}...`);
@@ -537,22 +850,7 @@ export class PeerPigeonServer extends EventEmitter {
537
850
  ws.on('error', (error) => {
538
851
  console.error(`โŒ WebSocket error for ${uri}:`, error.message);
539
852
 
540
- // Check if it's a localhost hub
541
- const url = new URL(uri);
542
- const isLocalhost = url.hostname === 'localhost' ||
543
- url.hostname === '127.0.0.1' ||
544
- url.hostname === '0.0.0.0';
545
-
546
- if (isLocalhost) {
547
- console.log(`โ„น๏ธ Localhost hub ${uri} not available - skipping reconnection attempts`);
548
- this.bootstrapConnections.delete(uri);
549
- if (attemptNumber === 0) {
550
- reject(error);
551
- }
552
- return;
553
- }
554
-
555
- // Only reject on first attempt for non-localhost, otherwise we'll retry
853
+ // Only reject on first attempt, otherwise we'll retry
556
854
  if (attemptNumber === 0) {
557
855
  this.bootstrapConnections.delete(uri);
558
856
  reject(error);
@@ -574,7 +872,6 @@ export class PeerPigeonServer extends EventEmitter {
574
872
  type: 'announce',
575
873
  networkName: this.hubMeshNamespace,
576
874
  data: {
577
- peerId: this.hubPeerId, // CRITICAL: Include hub's peerId so it can be properly registered
578
875
  isHub: true,
579
876
  port: this.port,
580
877
  host: this.host,
@@ -584,45 +881,54 @@ export class PeerPigeonServer extends EventEmitter {
584
881
  };
585
882
 
586
883
  ws.send(JSON.stringify(announcement));
587
- console.log(`๐Ÿ“ข Announced hub ${this.hubPeerId.substring(0, 8)}... to bootstrap hub on namespace '${this.hubMeshNamespace}'`);
884
+ console.log(`๐Ÿ“ข Announced to bootstrap hub on ${this.hubMeshNamespace}`);
588
885
 
589
886
  // Announce all existing local peers to the bootstrap hub
590
887
  this.announceLocalPeersToHub(ws);
591
888
  }
592
889
 
593
890
  /**
594
- * Announce all local (non-hub) peers to a bootstrap hub
891
+ * Announce all local peers to a bootstrap hub (including hub mesh peers for P2P discovery)
595
892
  */
596
893
  announceLocalPeersToHub(ws) {
597
894
  let totalAnnounced = 0;
598
895
 
896
+ console.log(`๐Ÿ“ก Announcing local peers to bootstrap hub (${this.networkPeers.size} networks)`);
897
+
599
898
  // Iterate through all networks and announce their peers
600
899
  for (const [networkName, peerSet] of this.networkPeers) {
601
- // Skip the hub mesh namespace
602
- if (networkName === this.hubMeshNamespace) {
603
- continue;
604
- }
900
+ console.log(` Network '${networkName}': ${peerSet.size} peers`);
605
901
 
606
902
  for (const peerId of peerSet) {
607
903
  const peerData = this.peerData.get(peerId);
608
904
 
609
- // Skip hubs, only announce regular peers
610
- if (peerData?.isHub) {
905
+ // For hub mesh namespace, only announce our own hub mesh client (not other hubs)
906
+ if (networkName === this.hubMeshNamespace && peerId !== this.hubPeerId) {
907
+ console.log(` Skipping hub ${peerId.substring(0, 8)}... (not our mesh client)`);
908
+ continue;
909
+ }
910
+
911
+ // For other namespaces, skip hub peers
912
+ if (networkName !== this.hubMeshNamespace && peerData?.isHub) {
913
+ console.log(` Skipping hub peer ${peerId.substring(0, 8)}... in network ${networkName}`);
611
914
  continue;
612
915
  }
613
916
 
614
917
  // Skip if not connected or not announced
615
918
  const connection = this.connections.get(peerId);
616
919
  if (!connection || connection.readyState !== WebSocket.OPEN || !peerData?.announced) {
920
+ console.log(` Skipping ${peerId.substring(0, 8)}... (not connected or not announced)`);
617
921
  continue;
618
922
  }
619
923
 
924
+ console.log(` โœ… Announcing ${peerId.substring(0, 8)}... from network '${networkName}'`);
925
+
620
926
  // Send peer-discovered message to bootstrap hub
621
927
  const peerAnnouncement = {
622
928
  type: 'peer-discovered',
623
929
  data: {
624
930
  peerId,
625
- isHub: false,
931
+ isHub: networkName === this.hubMeshNamespace,
626
932
  ...peerData.data
627
933
  },
628
934
  networkName: networkName,
@@ -718,51 +1024,17 @@ export class PeerPigeonServer extends EventEmitter {
718
1024
 
719
1025
  case 'peer-discovered':
720
1026
  if (data?.isHub) {
721
- const hubPeerId = data.peerId;
722
-
723
- // CRITICAL: Ignore our own announcements to prevent loops
724
- if (hubPeerId === this.hubPeerId) {
725
- console.log(`๐Ÿ”‡ Ignoring self-announcement from ${uri}`);
726
- break;
727
- }
728
-
729
- console.log(`๐Ÿข Discovered hub via bootstrap: ${hubPeerId?.substring(0, 8)}...`);
730
-
731
- // Register this remotely discovered hub (even though it's not directly connected to us)
732
- // This helps with hub awareness and statistics
733
- if (hubPeerId && !this.hubs.has(hubPeerId)) {
734
- this.hubs.set(hubPeerId, {
735
- peerId: hubPeerId,
736
- registeredAt: Date.now(),
737
- lastActivity: Date.now(),
738
- discoveredVia: uri,
739
- remote: true, // Not directly connected to us
740
- ...data
741
- });
742
- console.log(`๐Ÿ“ Registered remote hub: ${hubPeerId.substring(0, 8)}... (${this.hubs.size} total hubs)`);
743
- }
1027
+ console.log(`๐Ÿข Discovered hub via bootstrap: ${data.peerId?.substring(0, 8)}...`);
1028
+ this.emit('hubDiscovered', { peerId: data.peerId, via: uri, data });
744
1029
 
745
- this.emit('hubDiscovered', { peerId: hubPeerId, via: uri, data });
746
- } else if (data?.peerId) {
747
- // Regular peer discovered on another hub - notify our local CLIENT peers in same network
748
- const discoveredPeerId = data.peerId;
749
- const discoveredNetwork = networkName || 'global';
750
-
751
- console.log(`๐Ÿ“ฅ Peer ${discoveredPeerId.substring(0, 8)}... discovered on another hub (network: ${discoveredNetwork})`);
752
-
753
- // Forward to all our local CLIENT peers in the same network (exclude hubs)
754
- const localPeersInNetwork = this.networkPeers.get(discoveredNetwork);
755
- if (localPeersInNetwork && localPeersInNetwork.size > 0) {
756
- let forwardedCount = 0;
757
- for (const localPeerId of localPeersInNetwork) {
758
- // Skip hubs - only forward to client peers
759
- const localPeerData = this.peerData.get(localPeerId);
760
- if (localPeerData?.isHub) {
761
- continue;
762
- }
763
-
1030
+ // Forward to our local hub mesh client so it can form P2P connections
1031
+ const discoveredNetwork = networkName || this.hubMeshNamespace;
1032
+ if (discoveredNetwork === this.hubMeshNamespace) {
1033
+ console.log(`๐Ÿ“ฅ Forwarding hub ${data.peerId?.substring(0, 8)}... to local mesh client`);
1034
+ const localPeers = this.getActivePeers(null, discoveredNetwork);
1035
+ localPeers.forEach(localPeerId => {
764
1036
  const localConnection = this.connections.get(localPeerId);
765
- if (localConnection && localConnection.readyState === WebSocket.OPEN) {
1037
+ if (localConnection) {
766
1038
  this.sendToConnection(localConnection, {
767
1039
  type: 'peer-discovered',
768
1040
  data,
@@ -771,13 +1043,31 @@ export class PeerPigeonServer extends EventEmitter {
771
1043
  targetPeerId: localPeerId,
772
1044
  timestamp: Date.now()
773
1045
  });
774
- forwardedCount++;
775
1046
  }
776
- }
777
- console.log(`โœ… Forwarded peer-discovered to ${forwardedCount} local client peer(s) in network '${discoveredNetwork}'`);
778
- } else {
779
- console.log(`โ„น๏ธ No local peers in network '${discoveredNetwork}' to forward to`);
1047
+ });
780
1048
  }
1049
+ } else if (data?.peerId) {
1050
+ // Regular peer discovered on another hub - notify our local peers in same network
1051
+ const discoveredPeerId = data.peerId;
1052
+ const discoveredNetwork = networkName || 'global';
1053
+
1054
+ console.log(`๐Ÿ“ฅ Peer ${discoveredPeerId.substring(0, 8)}... discovered on another hub (network: ${discoveredNetwork})`);
1055
+
1056
+ // Forward to all our local peers in the same network
1057
+ const localPeers = this.getActivePeers(null, discoveredNetwork);
1058
+ localPeers.forEach(localPeerId => {
1059
+ const localConnection = this.connections.get(localPeerId);
1060
+ if (localConnection) {
1061
+ this.sendToConnection(localConnection, {
1062
+ type: 'peer-discovered',
1063
+ data,
1064
+ networkName: discoveredNetwork,
1065
+ fromPeerId: 'system',
1066
+ targetPeerId: localPeerId,
1067
+ timestamp: Date.now()
1068
+ });
1069
+ }
1070
+ });
781
1071
  }
782
1072
  break;
783
1073
 
@@ -948,7 +1238,9 @@ export class PeerPigeonServer extends EventEmitter {
948
1238
  const { type, data: messageData, targetPeerId, networkName, fromPeerId: originalFromPeerId } = message;
949
1239
 
950
1240
  // Log message type
951
- console.log(`๐Ÿ“จ Received ${type} from ${peerId.substring(0, 8)}... in network: ${networkName || 'global'}`);
1241
+ if (this.verboseLogging) {
1242
+ console.log(`๐Ÿ“จ Received ${type} from ${peerId.substring(0, 8)}... in network: ${networkName || 'global'}`);
1243
+ }
952
1244
 
953
1245
  // Preserve the original fromPeerId if it exists (for relayed messages from other hubs)
954
1246
  // Otherwise use the peerId of the connection
@@ -984,7 +1276,9 @@ export class PeerPigeonServer extends EventEmitter {
984
1276
  this.handleCleanup(peerId, message);
985
1277
  break;
986
1278
  default:
987
- console.log(`โš ๏ธ Ignoring non-signaling message type '${type}' - peers should route their own messages`);
1279
+ if (this.verboseLogging) {
1280
+ console.log(`โš ๏ธ Ignoring non-signaling message type '${type}' - peers should route their own messages`);
1281
+ }
988
1282
  const connection = this.connections.get(peerId);
989
1283
  if (connection && connection.readyState === WebSocket.OPEN) {
990
1284
  this.sendToConnection(connection, {
@@ -1007,10 +1301,12 @@ export class PeerPigeonServer extends EventEmitter {
1007
1301
  // Detect if this peer is a hub
1008
1302
  const isHub = message.data?.isHub === true || peerNetworkName === this.hubMeshNamespace;
1009
1303
 
1010
- if (isHub) {
1011
- console.log(`๐Ÿ“ข Hub announced: ${peerId.substring(0, 8)}... in network: ${peerNetworkName}`);
1012
- } else {
1013
- console.log(`๐Ÿ“ข Peer announced: ${peerId.substring(0, 8)}... in network: ${peerNetworkName}`);
1304
+ if (this.verboseLogging) {
1305
+ if (isHub) {
1306
+ console.log(`๐Ÿ“ข Hub announced: ${peerId.substring(0, 8)}... in network: ${peerNetworkName}`);
1307
+ } else {
1308
+ console.log(`๐Ÿ“ข Peer announced: ${peerId.substring(0, 8)}... in network: ${peerNetworkName}`);
1309
+ }
1014
1310
  }
1015
1311
 
1016
1312
  // Update peer data with network information
@@ -1031,6 +1327,16 @@ export class PeerPigeonServer extends EventEmitter {
1031
1327
  connectedAt: peerInfo?.connectedAt || Date.now()
1032
1328
  });
1033
1329
 
1330
+ // Track WebSocket connection with this hub
1331
+ const wsConnection = this.connections.get(peerId);
1332
+ if (wsConnection) {
1333
+ if (!this.hubMeshPeers.has(peerId)) {
1334
+ this.hubMeshPeers.set(peerId, { p2pConnected: false, wsConnection: null });
1335
+ }
1336
+ this.hubMeshPeers.get(peerId).wsConnection = wsConnection;
1337
+ console.log(`๐Ÿ“Š Tracking hub ${peerId.substring(0, 8)}... WebSocket connection for migration`);
1338
+ }
1339
+
1034
1340
  // When a new hub announces itself, send it all our local peers
1035
1341
  if (this.isHub) {
1036
1342
  console.log(`๐Ÿ“ก New hub connected, sending our local peers to ${peerId.substring(0, 8)}...`);
@@ -1044,11 +1350,8 @@ export class PeerPigeonServer extends EventEmitter {
1044
1350
  }
1045
1351
  this.networkPeers.get(peerNetworkName).add(peerId);
1046
1352
 
1047
- // If this is a hub, broadcast BOTH hubs and regular peers to ALL other connected hubs
1048
- // BUT only if this is a NEW announcement (not already known)
1049
- const isNewAnnouncement = peerInfo && !peerInfo.broadcastedToHubs;
1050
-
1051
- if (this.isHub && isNewAnnouncement) {
1353
+ // If this is a hub, broadcast this peer to ALL other connected hubs (both bootstrap and incoming)
1354
+ if (this.isHub && !isHub) {
1052
1355
  const connectedHubs = [];
1053
1356
 
1054
1357
  // 1. Add outgoing bootstrap connections
@@ -1071,13 +1374,12 @@ export class PeerPigeonServer extends EventEmitter {
1071
1374
  }
1072
1375
 
1073
1376
  if (connectedHubs.length > 0) {
1074
- const peerType = isHub ? 'hub' : 'peer';
1075
- console.log(`๐Ÿ“ก Broadcasting ${peerType} ${peerId.substring(0, 8)}... (network: ${peerNetworkName}) to ${connectedHubs.length} connected hub(s)`);
1377
+ console.log(`๐Ÿ“ก Broadcasting peer ${peerId.substring(0, 8)}... to ${connectedHubs.length} connected hub(s)`);
1076
1378
  const peerAnnouncement = {
1077
1379
  type: 'peer-discovered',
1078
1380
  data: {
1079
1381
  peerId,
1080
- isHub,
1382
+ isHub: false,
1081
1383
  ...message.data
1082
1384
  },
1083
1385
  networkName: peerNetworkName,
@@ -1085,25 +1387,47 @@ export class PeerPigeonServer extends EventEmitter {
1085
1387
  timestamp: Date.now()
1086
1388
  };
1087
1389
 
1088
- // Mark as broadcasted to prevent re-broadcasting
1089
- peerInfo.broadcastedToHubs = true;
1090
-
1091
1390
  for (const hub of connectedHubs) {
1092
1391
  try {
1093
1392
  if (hub.type === 'bootstrap') {
1094
- console.log(` โ†’ Sending to bootstrap hub: ${hub.id}`);
1095
1393
  hub.ws.send(JSON.stringify(peerAnnouncement));
1096
1394
  } else {
1097
- console.log(` โ†’ Sending to incoming hub: ${hub.id.substring(0, 8)}...`);
1098
1395
  this.sendToConnection(hub.ws, peerAnnouncement);
1099
1396
  }
1100
1397
  } catch (error) {
1101
1398
  console.error(`โŒ Error broadcasting to hub ${hub.id}:`, error.message);
1102
1399
  }
1103
1400
  }
1104
- } else if (!isHub) {
1105
- // Log when we have no hubs to broadcast to (only for client peers, not hubs)
1106
- console.log(`โš ๏ธ No connected hubs to broadcast peer ${peerId.substring(0, 8)}... to`);
1401
+ }
1402
+ }
1403
+
1404
+ // ALSO broadcast through P2P hub mesh if available and mesh is ready
1405
+ if (this.isHub && !isHub && this.hubMesh && this.hubMeshReady) {
1406
+ const p2pConnectedHubs = this.hubMesh.connectionManager.getConnectedPeers();
1407
+ if (p2pConnectedHubs.length > 0) {
1408
+ console.log(`๐Ÿ“ก Broadcasting peer ${peerId.substring(0, 8)}... to ${p2pConnectedHubs.length} P2P-connected hub(s)`);
1409
+
1410
+ const p2pRelayMessage = {
1411
+ type: 'peer-announce-relay',
1412
+ peerId,
1413
+ networkName: peerNetworkName,
1414
+ peerData: {
1415
+ peerId,
1416
+ isHub: false,
1417
+ ...message.data
1418
+ },
1419
+ timestamp: Date.now()
1420
+ };
1421
+
1422
+ p2pConnectedHubs.forEach(hubPeerConnection => {
1423
+ try {
1424
+ const hubPeerId = hubPeerConnection.peerId;
1425
+ this.hubMesh.sendMessage(p2pRelayMessage, hubPeerId);
1426
+ } catch (error) {
1427
+ const hubPeerId = hubPeerConnection.peerId || 'unknown';
1428
+ console.error(`โŒ Error broadcasting to P2P hub ${hubPeerId.substring(0, 8)}...:`, error.message);
1429
+ }
1430
+ });
1107
1431
  }
1108
1432
  }
1109
1433
 
@@ -1167,7 +1491,9 @@ export class PeerPigeonServer extends EventEmitter {
1167
1491
  * Handle peer goodbye
1168
1492
  */
1169
1493
  handleGoodbye(peerId, message, responseMessage) {
1170
- console.log(`๐Ÿ‘‹ Peer goodbye: ${peerId.substring(0, 8)}...`);
1494
+ if (this.verboseLogging) {
1495
+ console.log(`๐Ÿ‘‹ Peer goodbye: ${peerId.substring(0, 8)}...`);
1496
+ }
1171
1497
 
1172
1498
  // Broadcast to closest peers before removing peer data
1173
1499
  this.broadcastToClosestPeers(peerId, responseMessage);
@@ -1184,10 +1510,14 @@ export class PeerPigeonServer extends EventEmitter {
1184
1510
  const targetPeerId = message.targetPeerId;
1185
1511
  const networkName = message.networkName || 'global';
1186
1512
 
1187
- console.log(`๐Ÿ” SIGNALING DEBUG: Received ${message.type} from ${peerId.substring(0, 8)}... to ${targetPeerId?.substring(0, 8)}... in network '${networkName}'`);
1513
+ if (this.verboseLogging) {
1514
+ console.log(`๐Ÿ” SIGNALING DEBUG: Received ${message.type} from ${peerId.substring(0, 8)}... to ${targetPeerId?.substring(0, 8)}... in network '${networkName}'`);
1515
+ }
1188
1516
 
1189
1517
  if (!targetPeerId) {
1190
- console.log(`โŒ No target peer ID in signaling message from ${peerId.substring(0, 8)}...`);
1518
+ if (this.verboseLogging) {
1519
+ console.log(`โŒ No target peer ID in signaling message from ${peerId.substring(0, 8)}...`);
1520
+ }
1191
1521
  return;
1192
1522
  }
1193
1523
 
@@ -1199,36 +1529,36 @@ export class PeerPigeonServer extends EventEmitter {
1199
1529
  const targetNetwork = targetPeerData?.networkName || 'global';
1200
1530
 
1201
1531
  if (networkName !== targetNetwork) {
1202
- console.log(`๐Ÿšซ Blocking ${message.type} from ${peerId.substring(0, 8)}... (network: ${networkName}) to ${targetPeerId.substring(0, 8)}... (network: ${targetNetwork}) - different networks`);
1532
+ if (this.verboseLogging) {
1533
+ console.log(`๐Ÿšซ Blocking ${message.type} from ${peerId.substring(0, 8)}... (network: ${networkName}) to ${targetPeerId.substring(0, 8)}... (network: ${targetNetwork}) - different networks`);
1534
+ }
1203
1535
  return;
1204
1536
  }
1205
1537
 
1206
1538
  // Target is local - forward directly
1207
- console.log(`โœ… Forwarding ${message.type} to LOCAL peer ${targetPeerId.substring(0, 8)}...`);
1539
+ if (this.verboseLogging) {
1540
+ console.log(`โœ… Forwarding ${message.type} to LOCAL peer ${targetPeerId.substring(0, 8)}...`);
1541
+ }
1208
1542
  this.sendToConnection(targetConnection, responseMessage);
1209
1543
  } else {
1210
1544
  // Target peer not on this hub - relay to other hubs
1211
- // CRITICAL: Check if we've already relayed this signaling message to prevent loops
1212
- const signalingKey = `${peerId}:${targetPeerId}:${message.type}`;
1213
- const now = Date.now();
1214
- const lastRelayed = this.relayedSignaling.get(signalingKey);
1215
-
1216
- // If we've relayed this within the last 5 seconds, skip it
1217
- if (lastRelayed && (now - lastRelayed) < 5000) {
1218
- console.log(`๐Ÿ”‡ Skipping relay - already relayed ${message.type} from ${peerId.substring(0, 8)}... to ${targetPeerId.substring(0, 8)}... recently`);
1219
- return;
1220
- }
1221
-
1222
1545
  console.log(`๐Ÿ”„ Target peer ${targetPeerId.substring(0, 8)}... NOT LOCAL, relaying to other hubs (network: ${networkName})`);
1223
1546
 
1224
- // Mark as relayed BEFORE relaying to prevent loops
1225
- this.relayedSignaling.set(signalingKey, now);
1226
-
1227
1547
  let relayed = false;
1228
1548
 
1229
- // First try relaying through bootstrap hubs (if we're not the bootstrap)
1230
- if (this.bootstrapConnections.size > 0) {
1231
- console.log(`๏ฟฝ Relaying ${message.type} through ${this.bootstrapConnections.size} bootstrap connection(s)`);
1549
+ // PRIORITY: Try P2P hub mesh first if available and ready
1550
+ if (this.isHub && this.hubMesh && this.hubMeshReady) {
1551
+ const p2pConnectedHubs = this.hubMesh.connectionManager.getConnectedPeers();
1552
+ if (p2pConnectedHubs.length > 0) {
1553
+ console.log(`๐Ÿ“ก Relaying ${message.type} through P2P hub mesh (${p2pConnectedHubs.length} hubs)`);
1554
+ this.forwardSignalToHubMesh(targetPeerId, responseMessage);
1555
+ relayed = true;
1556
+ }
1557
+ }
1558
+
1559
+ // Fallback: Try relaying through WebSocket bootstrap hubs
1560
+ if (!relayed && this.bootstrapConnections.size > 0) {
1561
+ console.log(`๐Ÿ”— Relaying ${message.type} through ${this.bootstrapConnections.size} WebSocket bootstrap connection(s)`);
1232
1562
 
1233
1563
  for (const [uri, connInfo] of this.bootstrapConnections) {
1234
1564
  if (connInfo.connected && connInfo.ws.readyState === WebSocket.OPEN) {
@@ -1239,9 +1569,9 @@ export class PeerPigeonServer extends EventEmitter {
1239
1569
  }
1240
1570
  }
1241
1571
 
1242
- // If we're the bootstrap hub (or bootstrap relay failed), forward to all connected hubs
1243
- if (this.hubs.size > 0) {
1244
- console.log(`๏ฟฝ Forwarding ${message.type} to ${this.hubs.size} connected hub(s)`);
1572
+ // Final fallback: Forward to WebSocket-connected hubs
1573
+ if (!relayed && this.hubs.size > 0) {
1574
+ console.log(`๐Ÿ”— Forwarding ${message.type} to ${this.hubs.size} WebSocket-connected hub(s)`);
1245
1575
 
1246
1576
  for (const [hubPeerId, hubInfo] of this.hubs) {
1247
1577
  const hubConnection = this.connections.get(hubPeerId);
@@ -1255,6 +1585,7 @@ export class PeerPigeonServer extends EventEmitter {
1255
1585
 
1256
1586
  if (!relayed) {
1257
1587
  console.log(`โŒ FAILED TO RELAY: No hubs available for ${targetPeerId.substring(0, 8)}... (network: ${networkName})`);
1588
+ console.log(` - P2P hub mesh: ${this.hubMesh ? this.hubMesh.connectionManager.getConnectedPeers().length : 0}`);
1258
1589
  console.log(` - Bootstrap connections: ${this.bootstrapConnections.size}`);
1259
1590
  console.log(` - Connected hubs: ${this.hubs.size}`);
1260
1591
  }
@@ -1298,10 +1629,9 @@ export class PeerPigeonServer extends EventEmitter {
1298
1629
  return;
1299
1630
  }
1300
1631
 
1301
- // Check if sender is a hub or if it's from bootstrap
1302
- const isFromBootstrap = fromHubPeerId === 'bootstrap' || message.fromPeerId === 'system';
1632
+ // Check if sender is a hub
1303
1633
  const senderPeerData = this.peerData.get(fromHubPeerId);
1304
- const isFromHub = isFromBootstrap || senderPeerData?.isHub || senderPeerData?.networkName === this.hubMeshNamespace;
1634
+ const isFromHub = senderPeerData?.isHub || senderPeerData?.networkName === this.hubMeshNamespace;
1305
1635
 
1306
1636
  if (!isFromHub) {
1307
1637
  console.log(`โš ๏ธ Received peer-discovered from non-hub peer ${fromHubPeerId.substring(0, 8)}... - ignoring`);
@@ -1310,65 +1640,6 @@ export class PeerPigeonServer extends EventEmitter {
1310
1640
 
1311
1641
  console.log(`๐Ÿ” Received peer discovery from hub ${fromHubPeerId.substring(0, 8)}... - Peer ${discoveredPeerId.substring(0, 8)}... in network '${networkName}'`);
1312
1642
 
1313
- // CRITICAL: Check if we've already relayed this peer discovery to prevent infinite loops
1314
- const discoveryKey = `${discoveredPeerId}:${networkName}`;
1315
- const now = Date.now();
1316
- const lastRelayed = this.relayedDiscoveries.get(discoveryKey);
1317
-
1318
- // If we've relayed this within the last 60 seconds, skip it
1319
- if (lastRelayed && (now - lastRelayed) < 60000) {
1320
- console.log(`๐Ÿ”‡ Skipping relay - already relayed ${discoveredPeerId.substring(0, 8)}... in network '${networkName}' recently`);
1321
- } else if (this.isHub) {
1322
- // Mark as relayed before relaying to prevent loops
1323
- this.relayedDiscoveries.set(discoveryKey, now);
1324
-
1325
- const relayedToHubs = [];
1326
-
1327
- // Relay to outgoing bootstrap connections (except the one we received from)
1328
- for (const [uri, connInfo] of this.bootstrapConnections) {
1329
- if (connInfo.connected && connInfo.ws.readyState === WebSocket.OPEN) {
1330
- try {
1331
- connInfo.ws.send(JSON.stringify({
1332
- type: 'peer-discovered',
1333
- data: messageData,
1334
- networkName,
1335
- fromPeerId: 'system',
1336
- timestamp: Date.now()
1337
- }));
1338
- relayedToHubs.push(uri);
1339
- } catch (error) {
1340
- console.error(`โŒ Error relaying to bootstrap hub ${uri}:`, error.message);
1341
- }
1342
- }
1343
- }
1344
-
1345
- // Relay to incoming hub connections (except the sender)
1346
- for (const [hubPeerId, hubInfo] of this.hubs) {
1347
- if (hubPeerId === fromHubPeerId || hubPeerId === this.hubPeerId) {
1348
- continue; // Skip sender and self
1349
- }
1350
- const hubConnection = this.connections.get(hubPeerId);
1351
- if (hubConnection && hubConnection.readyState === WebSocket.OPEN) {
1352
- try {
1353
- this.sendToConnection(hubConnection, {
1354
- type: 'peer-discovered',
1355
- data: messageData,
1356
- networkName,
1357
- fromPeerId: 'system',
1358
- timestamp: Date.now()
1359
- });
1360
- relayedToHubs.push(hubPeerId.substring(0, 8) + '...');
1361
- } catch (error) {
1362
- console.error(`โŒ Error relaying to hub ${hubPeerId.substring(0, 8)}...:`, error.message);
1363
- }
1364
- }
1365
- }
1366
-
1367
- if (relayedToHubs.length > 0) {
1368
- console.log(`๐Ÿ”„ Relayed peer-discovered to ${relayedToHubs.length} other hub(s): ${relayedToHubs.join(', ')}`);
1369
- }
1370
- }
1371
-
1372
1643
  // Forward to all local CLIENT peers in the same network (exclude hubs)
1373
1644
  const localPeers = this.networkPeers.get(networkName);
1374
1645
  if (localPeers && localPeers.size > 0) {
@@ -1403,7 +1674,9 @@ export class PeerPigeonServer extends EventEmitter {
1403
1674
  * Handle peer disconnection
1404
1675
  */
1405
1676
  handleDisconnection(peerId, code, reason) {
1406
- console.log(`โŒ Peer disconnected: ${peerId.substring(0, 8)}... (code: ${code}, reason: ${reason})`);
1677
+ if (this.verboseLogging) {
1678
+ console.log(`โŒ Peer disconnected: ${peerId.substring(0, 8)}... (code: ${code}, reason: ${reason})`);
1679
+ }
1407
1680
 
1408
1681
  // Notify other peers about disconnection
1409
1682
  this.broadcastToOthers(peerId, {
@@ -1452,7 +1725,9 @@ export class PeerPigeonServer extends EventEmitter {
1452
1725
 
1453
1726
  if (wasConnected) {
1454
1727
  const peerType = isHub ? 'hub' : 'peer';
1455
- console.log(`๐Ÿงน Cleaned up ${peerType}: ${peerId.substring(0, 8)}... from network: ${peerInfo?.networkName || 'unknown'}`);
1728
+ if (this.verboseLogging) {
1729
+ console.log(`๐Ÿงน Cleaned up ${peerType}: ${peerId.substring(0, 8)}... from network: ${peerInfo?.networkName || 'unknown'}`);
1730
+ }
1456
1731
 
1457
1732
  // Notify other peers in the same network about disconnection
1458
1733
  if (peerInfo && peerInfo.networkName) {
@@ -1512,7 +1787,9 @@ export class PeerPigeonServer extends EventEmitter {
1512
1787
  }
1513
1788
  }
1514
1789
  }
1515
- console.log(`๐Ÿ“ก Broadcast to ${sentCount} peers`);
1790
+ if (this.verboseLogging) {
1791
+ console.log(`๐Ÿ“ก Broadcast to ${sentCount} peers`);
1792
+ }
1516
1793
  return sentCount;
1517
1794
  }
1518
1795
 
@@ -1525,7 +1802,9 @@ export class PeerPigeonServer extends EventEmitter {
1525
1802
  const activePeers = this.getActivePeers(fromPeerId, networkName);
1526
1803
  const closestPeers = this.findClosestPeers(fromPeerId, activePeers, maxPeers);
1527
1804
 
1528
- console.log(`Broadcasting from ${fromPeerId.substring(0, 8)}... to ${closestPeers.length} closest peers in network: ${networkName}`);
1805
+ if (this.verboseLogging) {
1806
+ console.log(`Broadcasting from ${fromPeerId.substring(0, 8)}... to ${closestPeers.length} closest peers in network: ${networkName}`);
1807
+ }
1529
1808
 
1530
1809
  closestPeers.forEach(peerId => {
1531
1810
  this.sendToConnection(this.connections.get(peerId), message);
@@ -1557,30 +1836,6 @@ export class PeerPigeonServer extends EventEmitter {
1557
1836
  if (cleanedUp > 0) {
1558
1837
  console.log(`๐Ÿงน Periodic cleanup: removed ${cleanedUp} stale connections, ${this.connections.size} active across ${this.networkPeers.size} networks`);
1559
1838
  }
1560
-
1561
- // Clean up old relay tracking entries (older than 5 minutes)
1562
- const fiveMinutesAgo = Date.now() - 300000;
1563
- let relayEntriesRemoved = 0;
1564
- for (const [key, timestamp] of this.relayedDiscoveries) {
1565
- if (timestamp < fiveMinutesAgo) {
1566
- this.relayedDiscoveries.delete(key);
1567
- relayEntriesRemoved++;
1568
- }
1569
- }
1570
-
1571
- // Clean up old signaling relay tracking entries (older than 1 minute)
1572
- const oneMinuteAgo = Date.now() - 60000;
1573
- let signalingEntriesRemoved = 0;
1574
- for (const [key, timestamp] of this.relayedSignaling) {
1575
- if (timestamp < oneMinuteAgo) {
1576
- this.relayedSignaling.delete(key);
1577
- signalingEntriesRemoved++;
1578
- }
1579
- }
1580
-
1581
- if (relayEntriesRemoved > 0 || signalingEntriesRemoved > 0) {
1582
- console.log(`๐Ÿงน Cleaned up ${relayEntriesRemoved} relay tracking entries, ${signalingEntriesRemoved} signaling relay entries`);
1583
- }
1584
1839
  }
1585
1840
 
1586
1841
  /**