peerpigeon 1.0.9 โ†’ 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);
@@ -43,6 +48,13 @@ export class PeerPigeonServer extends EventEmitter {
43
48
  this.isRunning = false;
44
49
  this.cleanupTimer = null;
45
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
46
58
  }
47
59
 
48
60
  /**
@@ -162,7 +174,9 @@ export class PeerPigeonServer extends EventEmitter {
162
174
 
163
175
  // Clean up stale connections
164
176
  stalePeers.forEach(peerId => {
165
- 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
+ }
166
180
  this.cleanupPeer(peerId);
167
181
  });
168
182
 
@@ -319,8 +333,12 @@ export class PeerPigeonServer extends EventEmitter {
319
333
  try {
320
334
  const result = await this.tryPort(this.port);
321
335
 
322
- // 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
323
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();
324
342
  await this.connectToBootstrapHubs();
325
343
  }
326
344
 
@@ -331,6 +349,323 @@ export class PeerPigeonServer extends EventEmitter {
331
349
  }
332
350
  }
333
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
+
334
669
  /**
335
670
  * Stop the WebSocket server
336
671
  */
@@ -342,6 +677,22 @@ export class PeerPigeonServer extends EventEmitter {
342
677
  return new Promise((resolve) => {
343
678
  console.log('๐Ÿ›‘ Stopping PeerPigeon WebSocket server...');
344
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
+
345
696
  // Disconnect from bootstrap hubs if this is a hub
346
697
  if (this.isHub) {
347
698
  this.disconnectFromBootstrapHubs();
@@ -537,38 +888,47 @@ export class PeerPigeonServer extends EventEmitter {
537
888
  }
538
889
 
539
890
  /**
540
- * 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)
541
892
  */
542
893
  announceLocalPeersToHub(ws) {
543
894
  let totalAnnounced = 0;
544
895
 
896
+ console.log(`๐Ÿ“ก Announcing local peers to bootstrap hub (${this.networkPeers.size} networks)`);
897
+
545
898
  // Iterate through all networks and announce their peers
546
899
  for (const [networkName, peerSet] of this.networkPeers) {
547
- // Skip the hub mesh namespace
548
- if (networkName === this.hubMeshNamespace) {
549
- continue;
550
- }
900
+ console.log(` Network '${networkName}': ${peerSet.size} peers`);
551
901
 
552
902
  for (const peerId of peerSet) {
553
903
  const peerData = this.peerData.get(peerId);
554
904
 
555
- // Skip hubs, only announce regular peers
556
- 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}`);
557
914
  continue;
558
915
  }
559
916
 
560
917
  // Skip if not connected or not announced
561
918
  const connection = this.connections.get(peerId);
562
919
  if (!connection || connection.readyState !== WebSocket.OPEN || !peerData?.announced) {
920
+ console.log(` Skipping ${peerId.substring(0, 8)}... (not connected or not announced)`);
563
921
  continue;
564
922
  }
565
923
 
924
+ console.log(` โœ… Announcing ${peerId.substring(0, 8)}... from network '${networkName}'`);
925
+
566
926
  // Send peer-discovered message to bootstrap hub
567
927
  const peerAnnouncement = {
568
928
  type: 'peer-discovered',
569
929
  data: {
570
930
  peerId,
571
- isHub: false,
931
+ isHub: networkName === this.hubMeshNamespace,
572
932
  ...peerData.data
573
933
  },
574
934
  networkName: networkName,
@@ -666,6 +1026,26 @@ export class PeerPigeonServer extends EventEmitter {
666
1026
  if (data?.isHub) {
667
1027
  console.log(`๐Ÿข Discovered hub via bootstrap: ${data.peerId?.substring(0, 8)}...`);
668
1028
  this.emit('hubDiscovered', { peerId: data.peerId, via: uri, data });
1029
+
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 => {
1036
+ const localConnection = this.connections.get(localPeerId);
1037
+ if (localConnection) {
1038
+ this.sendToConnection(localConnection, {
1039
+ type: 'peer-discovered',
1040
+ data,
1041
+ networkName: discoveredNetwork,
1042
+ fromPeerId: 'system',
1043
+ targetPeerId: localPeerId,
1044
+ timestamp: Date.now()
1045
+ });
1046
+ }
1047
+ });
1048
+ }
669
1049
  } else if (data?.peerId) {
670
1050
  // Regular peer discovered on another hub - notify our local peers in same network
671
1051
  const discoveredPeerId = data.peerId;
@@ -858,7 +1238,9 @@ export class PeerPigeonServer extends EventEmitter {
858
1238
  const { type, data: messageData, targetPeerId, networkName, fromPeerId: originalFromPeerId } = message;
859
1239
 
860
1240
  // Log message type
861
- 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
+ }
862
1244
 
863
1245
  // Preserve the original fromPeerId if it exists (for relayed messages from other hubs)
864
1246
  // Otherwise use the peerId of the connection
@@ -894,7 +1276,9 @@ export class PeerPigeonServer extends EventEmitter {
894
1276
  this.handleCleanup(peerId, message);
895
1277
  break;
896
1278
  default:
897
- 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
+ }
898
1282
  const connection = this.connections.get(peerId);
899
1283
  if (connection && connection.readyState === WebSocket.OPEN) {
900
1284
  this.sendToConnection(connection, {
@@ -917,10 +1301,12 @@ export class PeerPigeonServer extends EventEmitter {
917
1301
  // Detect if this peer is a hub
918
1302
  const isHub = message.data?.isHub === true || peerNetworkName === this.hubMeshNamespace;
919
1303
 
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}`);
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
+ }
924
1310
  }
925
1311
 
926
1312
  // Update peer data with network information
@@ -941,6 +1327,16 @@ export class PeerPigeonServer extends EventEmitter {
941
1327
  connectedAt: peerInfo?.connectedAt || Date.now()
942
1328
  });
943
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
+
944
1340
  // When a new hub announces itself, send it all our local peers
945
1341
  if (this.isHub) {
946
1342
  console.log(`๐Ÿ“ก New hub connected, sending our local peers to ${peerId.substring(0, 8)}...`);
@@ -1005,6 +1401,36 @@ export class PeerPigeonServer extends EventEmitter {
1005
1401
  }
1006
1402
  }
1007
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
+ });
1431
+ }
1432
+ }
1433
+
1008
1434
  // Get active peers in the same network
1009
1435
  const activePeers = this.getActivePeers(peerId, peerNetworkName);
1010
1436
 
@@ -1065,7 +1491,9 @@ export class PeerPigeonServer extends EventEmitter {
1065
1491
  * Handle peer goodbye
1066
1492
  */
1067
1493
  handleGoodbye(peerId, message, responseMessage) {
1068
- console.log(`๐Ÿ‘‹ Peer goodbye: ${peerId.substring(0, 8)}...`);
1494
+ if (this.verboseLogging) {
1495
+ console.log(`๐Ÿ‘‹ Peer goodbye: ${peerId.substring(0, 8)}...`);
1496
+ }
1069
1497
 
1070
1498
  // Broadcast to closest peers before removing peer data
1071
1499
  this.broadcastToClosestPeers(peerId, responseMessage);
@@ -1082,10 +1510,14 @@ export class PeerPigeonServer extends EventEmitter {
1082
1510
  const targetPeerId = message.targetPeerId;
1083
1511
  const networkName = message.networkName || 'global';
1084
1512
 
1085
- 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
+ }
1086
1516
 
1087
1517
  if (!targetPeerId) {
1088
- 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
+ }
1089
1521
  return;
1090
1522
  }
1091
1523
 
@@ -1097,12 +1529,16 @@ export class PeerPigeonServer extends EventEmitter {
1097
1529
  const targetNetwork = targetPeerData?.networkName || 'global';
1098
1530
 
1099
1531
  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`);
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
+ }
1101
1535
  return;
1102
1536
  }
1103
1537
 
1104
1538
  // Target is local - forward directly
1105
- 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
+ }
1106
1542
  this.sendToConnection(targetConnection, responseMessage);
1107
1543
  } else {
1108
1544
  // Target peer not on this hub - relay to other hubs
@@ -1110,9 +1546,19 @@ export class PeerPigeonServer extends EventEmitter {
1110
1546
 
1111
1547
  let relayed = false;
1112
1548
 
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)`);
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)`);
1116
1562
 
1117
1563
  for (const [uri, connInfo] of this.bootstrapConnections) {
1118
1564
  if (connInfo.connected && connInfo.ws.readyState === WebSocket.OPEN) {
@@ -1123,9 +1569,9 @@ export class PeerPigeonServer extends EventEmitter {
1123
1569
  }
1124
1570
  }
1125
1571
 
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)`);
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)`);
1129
1575
 
1130
1576
  for (const [hubPeerId, hubInfo] of this.hubs) {
1131
1577
  const hubConnection = this.connections.get(hubPeerId);
@@ -1139,6 +1585,7 @@ export class PeerPigeonServer extends EventEmitter {
1139
1585
 
1140
1586
  if (!relayed) {
1141
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}`);
1142
1589
  console.log(` - Bootstrap connections: ${this.bootstrapConnections.size}`);
1143
1590
  console.log(` - Connected hubs: ${this.hubs.size}`);
1144
1591
  }
@@ -1227,7 +1674,9 @@ export class PeerPigeonServer extends EventEmitter {
1227
1674
  * Handle peer disconnection
1228
1675
  */
1229
1676
  handleDisconnection(peerId, code, reason) {
1230
- 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
+ }
1231
1680
 
1232
1681
  // Notify other peers about disconnection
1233
1682
  this.broadcastToOthers(peerId, {
@@ -1276,7 +1725,9 @@ export class PeerPigeonServer extends EventEmitter {
1276
1725
 
1277
1726
  if (wasConnected) {
1278
1727
  const peerType = isHub ? 'hub' : 'peer';
1279
- 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
+ }
1280
1731
 
1281
1732
  // Notify other peers in the same network about disconnection
1282
1733
  if (peerInfo && peerInfo.networkName) {
@@ -1336,7 +1787,9 @@ export class PeerPigeonServer extends EventEmitter {
1336
1787
  }
1337
1788
  }
1338
1789
  }
1339
- console.log(`๐Ÿ“ก Broadcast to ${sentCount} peers`);
1790
+ if (this.verboseLogging) {
1791
+ console.log(`๐Ÿ“ก Broadcast to ${sentCount} peers`);
1792
+ }
1340
1793
  return sentCount;
1341
1794
  }
1342
1795
 
@@ -1349,7 +1802,9 @@ export class PeerPigeonServer extends EventEmitter {
1349
1802
  const activePeers = this.getActivePeers(fromPeerId, networkName);
1350
1803
  const closestPeers = this.findClosestPeers(fromPeerId, activePeers, maxPeers);
1351
1804
 
1352
- 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
+ }
1353
1808
 
1354
1809
  closestPeers.forEach(peerId => {
1355
1810
  this.sendToConnection(this.connections.get(peerId), message);