peerpigeon 1.1.0 โ†’ 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
@@ -5,6 +5,12 @@ import { EventEmitter } from 'events';
5
5
  import { URL } from 'url';
6
6
  import { PeerPigeonMesh } from '../src/PeerPigeonMesh.js';
7
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
+ }
13
+
8
14
  /**
9
15
  * PeerPigeon WebSocket signaling server
10
16
  * Can be used programmatically or as a standalone server
@@ -45,6 +51,9 @@ export class PeerPigeonServer extends EventEmitter {
45
51
  this.networkPeers = new Map(); // networkName -> Set of peerIds
46
52
  this.hubs = new Map(); // peerId -> hub info (for peers identified as hubs)
47
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
48
57
  this.isRunning = false;
49
58
  this.cleanupTimer = null;
50
59
  this.startTime = null;
@@ -77,6 +86,21 @@ export class PeerPigeonServer extends EventEmitter {
77
86
  return peerId;
78
87
  }
79
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
+
80
104
  /**
81
105
  * Check if a peer is registered as a hub
82
106
  */
@@ -460,20 +484,23 @@ export class PeerPigeonServer extends EventEmitter {
460
484
  if (isReady && !this.hubMeshReady) {
461
485
  this.hubMeshReady = true;
462
486
  console.log(`โœ… Hub mesh is READY! ${connectedP2PPeers} P2P connections established`);
463
- console.log(` Scheduling WebSocket migration in ${this.meshMigrationDelay}ms...`);
487
+ console.log(` Migrating to P2P-only immediately...`);
464
488
 
465
489
  this.emit('hubMeshReady', {
466
490
  p2pConnections: connectedP2PPeers,
467
491
  totalHubs: discoveredHubs
468
492
  });
469
493
 
470
- // Schedule migration from WebSocket to P2P-only
494
+ // Migrate immediately from WebSocket to P2P-only
471
495
  if (this.migrationTimer) {
472
496
  clearTimeout(this.migrationTimer);
497
+ this.migrationTimer = null;
473
498
  }
474
- this.migrationTimer = setTimeout(() => {
499
+
500
+ // Use setImmediate to allow current processing to complete before migration
501
+ setImmediate(() => {
475
502
  this.migrateToP2POnly();
476
- }, this.meshMigrationDelay);
503
+ });
477
504
  }
478
505
  }
479
506
 
@@ -515,23 +542,19 @@ export class PeerPigeonServer extends EventEmitter {
515
542
  }
516
543
  }
517
544
 
518
- // Also close bootstrap WebSocket connections if we have P2P to those hubs
519
- console.log(`๐Ÿ”Œ Closing bootstrap WebSocket connections (migrating to P2P)...`);
545
+ // Also close ALL bootstrap WebSocket connections - we're on P2P mesh now
546
+ console.log(`๐Ÿ”Œ Closing ALL bootstrap WebSocket connections (P2P mesh active)...`);
520
547
  let bootstrapClosed = 0;
521
548
 
522
549
  for (const [uri, connInfo] of this.bootstrapConnections) {
523
550
  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
- }
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);
535
558
  }
536
559
  }
537
560
  }
@@ -581,6 +604,14 @@ export class PeerPigeonServer extends EventEmitter {
581
604
  return;
582
605
  }
583
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
+
584
615
  // Check if target peer is connected to this hub
585
616
  const targetConnection = this.connections.get(targetPeerId);
586
617
  if (targetConnection && targetConnection.readyState === WebSocket.OPEN) {
@@ -703,6 +734,9 @@ export class PeerPigeonServer extends EventEmitter {
703
734
  clearInterval(this.cleanupTimer);
704
735
  this.cleanupTimer = null;
705
736
  }
737
+
738
+ // Clear relay deduplication cache
739
+ this.recentlyRelayedMessages.clear();
706
740
 
707
741
  // Close all WebSocket connections
708
742
  for (const [peerId, ws] of this.connections) {
@@ -1024,28 +1058,10 @@ export class PeerPigeonServer extends EventEmitter {
1024
1058
 
1025
1059
  case 'peer-discovered':
1026
1060
  if (data?.isHub) {
1027
- 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)`);
1028
1064
  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
- }
1049
1065
  } else if (data?.peerId) {
1050
1066
  // Regular peer discovered on another hub - notify our local peers in same network
1051
1067
  const discoveredPeerId = data.peerId;
@@ -1053,8 +1069,15 @@ export class PeerPigeonServer extends EventEmitter {
1053
1069
 
1054
1070
  console.log(`๐Ÿ“ฅ Peer ${discoveredPeerId.substring(0, 8)}... discovered on another hub (network: ${discoveredNetwork})`);
1055
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
+
1056
1078
  // Forward to all our local peers in the same network
1057
1079
  const localPeers = this.getActivePeers(null, discoveredNetwork);
1080
+ let forwardCount = 0;
1058
1081
  localPeers.forEach(localPeerId => {
1059
1082
  const localConnection = this.connections.get(localPeerId);
1060
1083
  if (localConnection) {
@@ -1066,8 +1089,10 @@ export class PeerPigeonServer extends EventEmitter {
1066
1089
  targetPeerId: localPeerId,
1067
1090
  timestamp: Date.now()
1068
1091
  });
1092
+ forwardCount++;
1069
1093
  }
1070
1094
  });
1095
+ console.log(`๐Ÿ“ค Forwarded to ${forwardCount} local peer(s) in network '${discoveredNetwork}'`);
1071
1096
  }
1072
1097
  break;
1073
1098
 
@@ -1088,13 +1113,15 @@ export class PeerPigeonServer extends EventEmitter {
1088
1113
  console.log(`๐Ÿ“ฅ Received ${type} from ${fromPeerId?.substring(0, 8)}... for local peer ${targetPeerId.substring(0, 8)}...`);
1089
1114
  this.sendToConnection(targetConnection, message);
1090
1115
  } else {
1091
- // Not our peer, relay to other bootstrap hubs
1092
- console.log(`๐Ÿ”„ Relaying ${type} from ${fromPeerId?.substring(0, 8)}... for ${targetPeerId.substring(0, 8)}... (not local)`);
1093
- for (const [otherUri, connInfo] of this.bootstrapConnections) {
1094
- if (otherUri !== uri && connInfo.connected && connInfo.ws.readyState === WebSocket.OPEN) {
1095
- connInfo.ws.send(JSON.stringify(message));
1096
- }
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`);
1097
1122
  }
1123
+ // Completely disable bootstrap relay to prevent loops
1124
+ break;
1098
1125
  }
1099
1126
  } else {
1100
1127
  console.log(`โš ๏ธ Received ${type} without targetPeerId via ${uri}`);
@@ -1337,6 +1364,33 @@ export class PeerPigeonServer extends EventEmitter {
1337
1364
  console.log(`๐Ÿ“Š Tracking hub ${peerId.substring(0, 8)}... WebSocket connection for migration`);
1338
1365
  }
1339
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
+
1340
1394
  // When a new hub announces itself, send it all our local peers
1341
1395
  if (this.isHub) {
1342
1396
  console.log(`๐Ÿ“ก New hub connected, sending our local peers to ${peerId.substring(0, 8)}...`);
@@ -1350,84 +1404,91 @@ export class PeerPigeonServer extends EventEmitter {
1350
1404
  }
1351
1405
  this.networkPeers.get(peerNetworkName).add(peerId);
1352
1406
 
1353
- // 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
1354
1409
  if (this.isHub && !isHub) {
1355
- const connectedHubs = [];
1356
-
1357
- // 1. Add outgoing bootstrap connections
1358
- for (const [uri, connInfo] of this.bootstrapConnections) {
1359
- if (connInfo.connected && connInfo.ws.readyState === WebSocket.OPEN) {
1360
- connectedHubs.push({ type: 'bootstrap', ws: connInfo.ws, id: uri });
1361
- }
1362
- }
1363
-
1364
- // 2. Add incoming hub connections (hubs that connected to us)
1365
- for (const [hubPeerId, hubInfo] of this.hubs) {
1366
- // Skip self and the announcing hub
1367
- if (hubPeerId === this.hubPeerId || hubPeerId === peerId) {
1368
- continue;
1369
- }
1370
- const hubConnection = this.connections.get(hubPeerId);
1371
- if (hubConnection && hubConnection.readyState === WebSocket.OPEN) {
1372
- connectedHubs.push({ type: 'incoming', ws: hubConnection, id: hubPeerId });
1373
- }
1374
- }
1410
+ // Check if there are any other hubs at all
1411
+ const hasOtherHubs = this.hubs.size > 0 || this.bootstrapConnections.size > 0;
1375
1412
 
1376
- if (connectedHubs.length > 0) {
1377
- console.log(`๐Ÿ“ก Broadcasting peer ${peerId.substring(0, 8)}... to ${connectedHubs.length} connected hub(s)`);
1378
- const peerAnnouncement = {
1379
- type: 'peer-discovered',
1380
- data: {
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',
1381
1421
  peerId,
1382
- isHub: false,
1383
- ...message.data
1384
- },
1385
- networkName: peerNetworkName,
1386
- fromPeerId: 'system',
1387
- timestamp: Date.now()
1388
- };
1389
-
1390
- for (const hub of connectedHubs) {
1391
- try {
1392
- if (hub.type === 'bootstrap') {
1393
- hub.ws.send(JSON.stringify(peerAnnouncement));
1394
- } else {
1395
- this.sendToConnection(hub.ws, peerAnnouncement);
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);
1396
1438
  }
1397
- } catch (error) {
1398
- console.error(`โŒ Error broadcasting to hub ${hub.id}:`, error.message);
1439
+ });
1440
+ }
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 });
1399
1451
  }
1400
1452
  }
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
1453
 
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
- };
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
+ }
1464
+ }
1421
1465
 
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);
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);
1489
+ }
1429
1490
  }
1430
- });
1491
+ }
1431
1492
  }
1432
1493
  }
1433
1494
 
@@ -1484,6 +1545,27 @@ export class PeerPigeonServer extends EventEmitter {
1484
1545
  });
1485
1546
  });
1486
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
+
1487
1569
  this.emit('peerAnnounced', { peerId, networkName: peerNetworkName, isHub });
1488
1570
  }
1489
1571
 
@@ -1542,21 +1624,50 @@ export class PeerPigeonServer extends EventEmitter {
1542
1624
  this.sendToConnection(targetConnection, responseMessage);
1543
1625
  } else {
1544
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
+
1545
1643
  console.log(`๐Ÿ”„ Target peer ${targetPeerId.substring(0, 8)}... NOT LOCAL, relaying to other hubs (network: ${networkName})`);
1546
1644
 
1547
1645
  let relayed = false;
1548
1646
 
1647
+ // Check if there are any other hubs at all
1648
+ const hasOtherHubs = this.hubs.size > 0 || this.bootstrapConnections.size > 0;
1649
+
1549
1650
  // PRIORITY: Try P2P hub mesh first if available and ready
1550
- if (this.isHub && this.hubMesh && this.hubMeshReady) {
1651
+ if (this.isHub && this.hubMesh && this.hubMeshReady && hasOtherHubs) {
1551
1652
  const p2pConnectedHubs = this.hubMesh.connectionManager.getConnectedPeers();
1552
1653
  if (p2pConnectedHubs.length > 0) {
1553
1654
  console.log(`๐Ÿ“ก Relaying ${message.type} through P2P hub mesh (${p2pConnectedHubs.length} hubs)`);
1554
1655
  this.forwardSignalToHubMesh(targetPeerId, responseMessage);
1555
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
1556
1667
  }
1557
1668
  }
1558
1669
 
1559
- // Fallback: Try relaying through WebSocket bootstrap hubs
1670
+ // Fallback: Try relaying through WebSocket bootstrap hubs (ONLY if mesh not ready)
1560
1671
  if (!relayed && this.bootstrapConnections.size > 0) {
1561
1672
  console.log(`๐Ÿ”— Relaying ${message.type} through ${this.bootstrapConnections.size} WebSocket bootstrap connection(s)`);
1562
1673
 
@@ -1569,7 +1680,7 @@ export class PeerPigeonServer extends EventEmitter {
1569
1680
  }
1570
1681
  }
1571
1682
 
1572
- // Final fallback: Forward to WebSocket-connected hubs
1683
+ // Final fallback: Forward to WebSocket-connected hubs (ONLY if mesh not ready)
1573
1684
  if (!relayed && this.hubs.size > 0) {
1574
1685
  console.log(`๐Ÿ”— Forwarding ${message.type} to ${this.hubs.size} WebSocket-connected hub(s)`);
1575
1686
 
@@ -1629,12 +1740,15 @@ export class PeerPigeonServer extends EventEmitter {
1629
1740
  return;
1630
1741
  }
1631
1742
 
1632
- // Check if sender is a hub
1743
+ // Check if sender is a hub (either a regular hub or a hub via bootstrap)
1633
1744
  const senderPeerData = this.peerData.get(fromHubPeerId);
1634
- const isFromHub = senderPeerData?.isHub || senderPeerData?.networkName === this.hubMeshNamespace;
1745
+ const isFromHub = senderPeerData?.isHub ||
1746
+ senderPeerData?.networkName === this.hubMeshNamespace ||
1747
+ this.hubs.has(fromHubPeerId);
1635
1748
 
1636
1749
  if (!isFromHub) {
1637
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)}`);
1638
1752
  return;
1639
1753
  }
1640
1754
 
@@ -1836,6 +1950,20 @@ export class PeerPigeonServer extends EventEmitter {
1836
1950
  if (cleanedUp > 0) {
1837
1951
  console.log(`๐Ÿงน Periodic cleanup: removed ${cleanedUp} stale connections, ${this.connections.size} active across ${this.networkPeers.size} networks`);
1838
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
+ }
1839
1967
  }
1840
1968
 
1841
1969
  /**
@@ -79,8 +79,15 @@ export class ConnectionManager extends EventEmitter {
79
79
  // Only become initiator if our peer ID is lexicographically greater than target's
80
80
  const shouldBeInitiator = this.mesh.peerId > targetPeerId;
81
81
  if (!shouldBeInitiator) {
82
- this.debug.log(`๐Ÿ”„ INITIATOR LOGIC: Not becoming initiator for ${targetPeerId.substring(0, 8)}... (our ID: ${this.mesh.peerId.substring(0, 8)}... is smaller)`);
83
- return; // Let the other peer initiate
82
+ // Allow override for low connectivity peers below connectivityFloor
83
+ const connectedCount = this.getConnectedPeerCount();
84
+ const floor = this.mesh.connectivityFloor || 0;
85
+ if (connectedCount < floor) {
86
+ this.debug.log(`๐Ÿ”„ INITIATOR OVERRIDE: Forcing initiation to ${targetPeerId.substring(0,8)}... (connected ${connectedCount} < floor ${floor})`);
87
+ } else {
88
+ this.debug.log(`๐Ÿ”„ INITIATOR LOGIC: Not becoming initiator for ${targetPeerId.substring(0, 8)}... (our ID smaller, connected ${connectedCount} >= floor ${floor})`);
89
+ return; // Let the other peer initiate
90
+ }
84
91
  }
85
92
 
86
93
  this.debug.log(`๐Ÿ”„ INITIATOR LOGIC: Becoming initiator for ${targetPeerId.substring(0, 8)}... (our ID: ${this.mesh.peerId.substring(0, 8)}... is greater)`);
@@ -161,11 +168,61 @@ export class ConnectionManager extends EventEmitter {
161
168
  this.mesh.emit('statusChanged', { type: 'info', message: `Offer sent to ${targetPeerId.substring(0, 8)}...` });
162
169
  } catch (error) {
163
170
  this.debug.error('Failed to connect to peer:', error);
164
- this.mesh.emit('statusChanged', { type: 'error', message: `Failed to connect to ${targetPeerId.substring(0, 8)}...: ${error.message}` });
171
+
172
+ // Check if this was due to a connection timeout (createOffer/setLocalDescription timeout)
173
+ // These are expected and normal in a partial mesh when peers are at capacity
174
+ const isConnectionTimeout = error.message?.includes('timeout');
175
+
176
+ if (!isConnectionTimeout) {
177
+ // Only emit error for non-timeout failures
178
+ this.mesh.emit('statusChanged', {
179
+ type: 'error',
180
+ message: `Failed to connect to ${targetPeerId.substring(0, 8)}...: ${error.message}`
181
+ });
182
+ }
183
+ // Note: connection timeouts are logged to debug but not emitted as errors
184
+
165
185
  this.cleanupFailedConnection(targetPeerId);
166
186
  }
167
187
  }
168
188
 
189
+ /**
190
+ * Force connection attempt ignoring standard initiator lexicographic rule (used for connectivity floor).
191
+ */
192
+ async connectToPeerOverride(targetPeerId) {
193
+ // Skip if already connected
194
+ if (this.peers.has(targetPeerId)) return;
195
+
196
+ const connectedCount = this.getConnectedPeerCount();
197
+ const floor = this.mesh.connectivityFloor || 0;
198
+ if (connectedCount >= floor) return; // Only override if below floor
199
+
200
+ // Don't skip if attempting - override takes precedence when below floor
201
+ this.debug.log(`โšก OVERRIDE CONNECT: initiating to ${targetPeerId.substring(0,8)}... (connected ${connectedCount} < floor ${floor})`);
202
+
203
+ // Clear any existing attempt record to allow override
204
+ this.mesh.peerDiscovery.clearConnectionAttempt(targetPeerId);
205
+
206
+ // Temporarily treat as initiator regardless of lexicographic order
207
+ const options = {
208
+ localStream: null,
209
+ enableAudio: true,
210
+ enableVideo: true
211
+ };
212
+ const peerConnection = new PeerConnection(targetPeerId, true, options);
213
+ this.setupPeerConnectionHandlers(peerConnection);
214
+ this.peers.set(targetPeerId, peerConnection);
215
+ try {
216
+ await peerConnection.createConnection();
217
+ const offer = await peerConnection.createOffer();
218
+ await this.mesh.sendSignalingMessage({ type: 'offer', data: offer }, targetPeerId);
219
+ } catch (e) {
220
+ this.debug.warn(`Override connection failed to ${targetPeerId.substring(0,8)}...: ${e.message}`);
221
+ this.mesh.peerDiscovery.removeDiscoveredPeer(targetPeerId);
222
+ this.peers.delete(targetPeerId);
223
+ }
224
+ }
225
+
169
226
  cleanupFailedConnection(peerId) {
170
227
  this.debug.log(`Cleaning up failed connection for ${peerId.substring(0, 8)}...`);
171
228
 
@@ -243,6 +300,8 @@ export class ConnectionManager extends EventEmitter {
243
300
  this.mesh.peerDiscovery.clearConnectionAttempt(event.peerId);
244
301
  this.mesh.peerDiscovery.updateDiscoveryTimestamp(event.peerId);
245
302
 
303
+ // (Rollback) Removed adaptive gossip resend hook
304
+
246
305
  this.emit('peersUpdated');
247
306
  });
248
307
 
@@ -21,11 +21,14 @@ export class GossipManager extends EventEmitter {
21
21
  this.processedKeyExchanges = new Map(); // "peerId:keyType" -> timestamp
22
22
 
23
23
  // Configuration
24
- this.maxTTL = 10; // Maximum hops before message expires
24
+ // Increased TTL further to improve reliability across multi-hub partial meshes
25
+ this.maxTTL = 40; // allow deeper multi-hop propagation before expiry
25
26
  this.messageExpiryTime = 5 * 60 * 1000; // 5 minutes
26
27
  this.cleanupInterval = 60 * 1000; // 1 minute
27
28
  this.cleanupTimer = null; // Track cleanup timer for proper cleanup
28
29
 
30
+ // (Rollback) Remove adaptive resend structures - rely on pure gossip
31
+
29
32
  this.startCleanupTimer();
30
33
  }
31
34
 
@@ -71,6 +74,8 @@ export class GossipManager extends EventEmitter {
71
74
  });
72
75
  this.messageHistory.set(messageId, message);
73
76
 
77
+ // (Rollback) No adaptive resend tracking
78
+
74
79
  // Send to all connected peers
75
80
  this.propagateMessage(message);
76
81
 
@@ -88,6 +93,12 @@ export class GossipManager extends EventEmitter {
88
93
  return messageId;
89
94
  }
90
95
 
96
+ /**
97
+ * Attempt adaptive resend of recent broadcasts to peers that connected
98
+ * after initial propagation window.
99
+ */
100
+ // (Rollback) attemptAdaptiveResends removed
101
+
91
102
  /**
92
103
  * Send a direct message to a specific peer using gossip routing (DM)
93
104
  * @param {string} targetPeerId - The destination peer's ID