peerpigeon 1.0.7 → 1.0.9

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "peerpigeon",
3
- "version": "1.0.7",
3
+ "version": "1.0.9",
4
4
  "description": "WebRTC-based peer-to-peer mesh networking library with intelligent routing and signaling server",
5
5
  "main": "index.js",
6
6
  "type": "module",
package/server/index.js CHANGED
@@ -99,36 +99,11 @@ export class PeerPigeonServer extends EventEmitter {
99
99
  /**
100
100
  * Get all connected hubs
101
101
  */
102
- /**
103
- * Get all connected hubs (directly connected via WebSocket)
104
- */
105
102
  getConnectedHubs(excludePeerId = null) {
106
103
  const hubList = [];
107
104
  for (const [peerId, hubInfo] of this.hubs) {
108
105
  if (peerId !== excludePeerId && this.connections.has(peerId)) {
109
- hubList.push({
110
- peerId,
111
- connected: true,
112
- ...hubInfo
113
- });
114
- }
115
- }
116
- return hubList;
117
- }
118
-
119
- /**
120
- * Get all known hubs (both directly connected and remotely discovered)
121
- */
122
- getAllKnownHubs(excludePeerId = null) {
123
- const hubList = [];
124
- for (const [peerId, hubInfo] of this.hubs) {
125
- if (peerId !== excludePeerId) {
126
- hubList.push({
127
- peerId,
128
- connected: this.connections.has(peerId),
129
- remote: hubInfo.remote || false,
130
- ...hubInfo
131
- });
106
+ hubList.push({ peerId, ...hubInfo });
132
107
  }
133
108
  }
134
109
  return hubList;
@@ -244,7 +219,7 @@ export class PeerPigeonServer extends EventEmitter {
244
219
  res.end(JSON.stringify({
245
220
  timestamp: new Date().toISOString(),
246
221
  totalHubs: this.hubs.size,
247
- hubs: this.getAllKnownHubs()
222
+ hubs: this.getConnectedHubs()
248
223
  }));
249
224
  return;
250
225
  }
@@ -423,17 +398,18 @@ export class PeerPigeonServer extends EventEmitter {
423
398
  return;
424
399
  }
425
400
 
426
- // Default Fly.io bootstrap hubs
427
- const DEFAULT_FLY_HUBS = [
428
- 'wss://pigeonhub.fly.dev',
429
- 'wss://pigeonhub-c.fly.dev'
430
- ];
431
-
432
- // Use provided bootstrap hubs, or default to Fly.io hubs
401
+ // If no bootstrap hubs specified, try default port 3000
433
402
  let bootstrapUris = this.bootstrapHubs;
434
403
  if (!bootstrapUris || bootstrapUris.length === 0) {
435
- bootstrapUris = DEFAULT_FLY_HUBS;
436
- console.log(`🔗 No bootstrap hubs specified, using default Fly.io hubs: ${bootstrapUris.join(', ')}`);
404
+ // Don't connect to ourselves
405
+ const defaultPort = 3000;
406
+ if (this.port !== defaultPort) {
407
+ bootstrapUris = [`ws://${this.host}:${defaultPort}`];
408
+ console.log(`🔗 No bootstrap hubs specified, trying default: ws://${this.host}:${defaultPort}`);
409
+ } else {
410
+ console.log('â„šī¸ No bootstrap hubs to connect to (running on default port 3000)');
411
+ return;
412
+ }
437
413
  }
438
414
 
439
415
  console.log(`🔗 Connecting to ${bootstrapUris.length} bootstrap hub(s)...`);
@@ -508,19 +484,7 @@ export class PeerPigeonServer extends EventEmitter {
508
484
 
509
485
  this.emit('bootstrapDisconnected', { uri, code, reason });
510
486
 
511
- // Don't reconnect to localhost hubs - they're likely just not running
512
- const url = new URL(uri);
513
- const isLocalhost = url.hostname === 'localhost' ||
514
- url.hostname === '127.0.0.1' ||
515
- url.hostname === '0.0.0.0';
516
-
517
- if (isLocalhost) {
518
- console.log(`â„šī¸ Not reconnecting to localhost hub ${uri} - assuming it's not running`);
519
- this.bootstrapConnections.delete(uri);
520
- return;
521
- }
522
-
523
- // Attempt to reconnect for non-localhost hubs
487
+ // Attempt to reconnect
524
488
  if (this.isRunning && attemptNumber < this.maxReconnectAttempts) {
525
489
  connectionInfo.reconnectTimer = setTimeout(() => {
526
490
  console.log(`🔄 Reconnecting to ${uri}...`);
@@ -535,22 +499,7 @@ export class PeerPigeonServer extends EventEmitter {
535
499
  ws.on('error', (error) => {
536
500
  console.error(`❌ WebSocket error for ${uri}:`, error.message);
537
501
 
538
- // Check if it's a localhost hub
539
- const url = new URL(uri);
540
- const isLocalhost = url.hostname === 'localhost' ||
541
- url.hostname === '127.0.0.1' ||
542
- url.hostname === '0.0.0.0';
543
-
544
- if (isLocalhost) {
545
- console.log(`â„šī¸ Localhost hub ${uri} not available - skipping reconnection attempts`);
546
- this.bootstrapConnections.delete(uri);
547
- if (attemptNumber === 0) {
548
- reject(error);
549
- }
550
- return;
551
- }
552
-
553
- // Only reject on first attempt for non-localhost, otherwise we'll retry
502
+ // Only reject on first attempt, otherwise we'll retry
554
503
  if (attemptNumber === 0) {
555
504
  this.bootstrapConnections.delete(uri);
556
505
  reject(error);
@@ -572,7 +521,6 @@ export class PeerPigeonServer extends EventEmitter {
572
521
  type: 'announce',
573
522
  networkName: this.hubMeshNamespace,
574
523
  data: {
575
- peerId: this.hubPeerId, // CRITICAL: Include hub's peerId so it can be properly registered
576
524
  isHub: true,
577
525
  port: this.port,
578
526
  host: this.host,
@@ -582,7 +530,7 @@ export class PeerPigeonServer extends EventEmitter {
582
530
  };
583
531
 
584
532
  ws.send(JSON.stringify(announcement));
585
- console.log(`đŸ“ĸ Announced hub ${this.hubPeerId.substring(0, 8)}... to bootstrap hub on namespace '${this.hubMeshNamespace}'`);
533
+ console.log(`đŸ“ĸ Announced to bootstrap hub on ${this.hubMeshNamespace}`);
586
534
 
587
535
  // Announce all existing local peers to the bootstrap hub
588
536
  this.announceLocalPeersToHub(ws);
@@ -716,59 +664,30 @@ export class PeerPigeonServer extends EventEmitter {
716
664
 
717
665
  case 'peer-discovered':
718
666
  if (data?.isHub) {
719
- const hubPeerId = data.peerId;
720
- console.log(`đŸĸ Discovered hub via bootstrap: ${hubPeerId?.substring(0, 8)}...`);
721
-
722
- // Register this remotely discovered hub (even though it's not directly connected to us)
723
- // This helps with hub awareness and statistics
724
- if (hubPeerId && !this.hubs.has(hubPeerId)) {
725
- this.hubs.set(hubPeerId, {
726
- peerId: hubPeerId,
727
- registeredAt: Date.now(),
728
- lastActivity: Date.now(),
729
- discoveredVia: uri,
730
- remote: true, // Not directly connected to us
731
- ...data
732
- });
733
- console.log(`📝 Registered remote hub: ${hubPeerId.substring(0, 8)}... (${this.hubs.size} total hubs)`);
734
- }
735
-
736
- this.emit('hubDiscovered', { peerId: hubPeerId, via: uri, data });
667
+ console.log(`đŸĸ Discovered hub via bootstrap: ${data.peerId?.substring(0, 8)}...`);
668
+ this.emit('hubDiscovered', { peerId: data.peerId, via: uri, data });
737
669
  } else if (data?.peerId) {
738
- // Regular peer discovered on another hub - notify our local CLIENT peers in same network
670
+ // Regular peer discovered on another hub - notify our local peers in same network
739
671
  const discoveredPeerId = data.peerId;
740
672
  const discoveredNetwork = networkName || 'global';
741
673
 
742
674
  console.log(`đŸ“Ĩ Peer ${discoveredPeerId.substring(0, 8)}... discovered on another hub (network: ${discoveredNetwork})`);
743
675
 
744
- // Forward to all our local CLIENT peers in the same network (exclude hubs)
745
- const localPeersInNetwork = this.networkPeers.get(discoveredNetwork);
746
- if (localPeersInNetwork && localPeersInNetwork.size > 0) {
747
- let forwardedCount = 0;
748
- for (const localPeerId of localPeersInNetwork) {
749
- // Skip hubs - only forward to client peers
750
- const localPeerData = this.peerData.get(localPeerId);
751
- if (localPeerData?.isHub) {
752
- continue;
753
- }
754
-
755
- const localConnection = this.connections.get(localPeerId);
756
- if (localConnection && localConnection.readyState === WebSocket.OPEN) {
757
- this.sendToConnection(localConnection, {
758
- type: 'peer-discovered',
759
- data,
760
- networkName: discoveredNetwork,
761
- fromPeerId: 'system',
762
- targetPeerId: localPeerId,
763
- timestamp: Date.now()
764
- });
765
- forwardedCount++;
766
- }
676
+ // Forward to all our local peers in the same network
677
+ const localPeers = this.getActivePeers(null, discoveredNetwork);
678
+ localPeers.forEach(localPeerId => {
679
+ const localConnection = this.connections.get(localPeerId);
680
+ if (localConnection) {
681
+ this.sendToConnection(localConnection, {
682
+ type: 'peer-discovered',
683
+ data,
684
+ networkName: discoveredNetwork,
685
+ fromPeerId: 'system',
686
+ targetPeerId: localPeerId,
687
+ timestamp: Date.now()
688
+ });
767
689
  }
768
- console.log(`✅ Forwarded peer-discovered to ${forwardedCount} local client peer(s) in network '${discoveredNetwork}'`);
769
- } else {
770
- console.log(`â„šī¸ No local peers in network '${discoveredNetwork}' to forward to`);
771
- }
690
+ });
772
691
  }
773
692
  break;
774
693
 
@@ -1035,8 +954,8 @@ export class PeerPigeonServer extends EventEmitter {
1035
954
  }
1036
955
  this.networkPeers.get(peerNetworkName).add(peerId);
1037
956
 
1038
- // If this is a hub, broadcast BOTH hubs and regular peers to ALL other connected hubs
1039
- if (this.isHub) {
957
+ // If this is a hub, broadcast this peer to ALL other connected hubs (both bootstrap and incoming)
958
+ if (this.isHub && !isHub) {
1040
959
  const connectedHubs = [];
1041
960
 
1042
961
  // 1. Add outgoing bootstrap connections
@@ -1059,13 +978,12 @@ export class PeerPigeonServer extends EventEmitter {
1059
978
  }
1060
979
 
1061
980
  if (connectedHubs.length > 0) {
1062
- const peerType = isHub ? 'hub' : 'peer';
1063
- console.log(`📡 Broadcasting ${peerType} ${peerId.substring(0, 8)}... (network: ${peerNetworkName}) to ${connectedHubs.length} connected hub(s)`);
981
+ console.log(`📡 Broadcasting peer ${peerId.substring(0, 8)}... to ${connectedHubs.length} connected hub(s)`);
1064
982
  const peerAnnouncement = {
1065
983
  type: 'peer-discovered',
1066
984
  data: {
1067
985
  peerId,
1068
- isHub,
986
+ isHub: false,
1069
987
  ...message.data
1070
988
  },
1071
989
  networkName: peerNetworkName,
@@ -1076,19 +994,14 @@ export class PeerPigeonServer extends EventEmitter {
1076
994
  for (const hub of connectedHubs) {
1077
995
  try {
1078
996
  if (hub.type === 'bootstrap') {
1079
- console.log(` → Sending to bootstrap hub: ${hub.id}`);
1080
997
  hub.ws.send(JSON.stringify(peerAnnouncement));
1081
998
  } else {
1082
- console.log(` → Sending to incoming hub: ${hub.id.substring(0, 8)}...`);
1083
999
  this.sendToConnection(hub.ws, peerAnnouncement);
1084
1000
  }
1085
1001
  } catch (error) {
1086
1002
  console.error(`❌ Error broadcasting to hub ${hub.id}:`, error.message);
1087
1003
  }
1088
1004
  }
1089
- } else if (!isHub) {
1090
- // Log when we have no hubs to broadcast to (only for client peers, not hubs)
1091
- console.log(`âš ī¸ No connected hubs to broadcast peer ${peerId.substring(0, 8)}... to`);
1092
1005
  }
1093
1006
  }
1094
1007
 
@@ -1269,10 +1182,9 @@ export class PeerPigeonServer extends EventEmitter {
1269
1182
  return;
1270
1183
  }
1271
1184
 
1272
- // Check if sender is a hub or if it's from bootstrap
1273
- const isFromBootstrap = fromHubPeerId === 'bootstrap' || message.fromPeerId === 'system';
1185
+ // Check if sender is a hub
1274
1186
  const senderPeerData = this.peerData.get(fromHubPeerId);
1275
- const isFromHub = isFromBootstrap || senderPeerData?.isHub || senderPeerData?.networkName === this.hubMeshNamespace;
1187
+ const isFromHub = senderPeerData?.isHub || senderPeerData?.networkName === this.hubMeshNamespace;
1276
1188
 
1277
1189
  if (!isFromHub) {
1278
1190
  console.log(`âš ī¸ Received peer-discovered from non-hub peer ${fromHubPeerId.substring(0, 8)}... - ignoring`);
@@ -1281,55 +1193,6 @@ export class PeerPigeonServer extends EventEmitter {
1281
1193
 
1282
1194
  console.log(`🔍 Received peer discovery from hub ${fromHubPeerId.substring(0, 8)}... - Peer ${discoveredPeerId.substring(0, 8)}... in network '${networkName}'`);
1283
1195
 
1284
- // If this is a hub, relay this peer to OTHER connected hubs as well (to ensure full mesh awareness)
1285
- if (this.isHub) {
1286
- const relayedToHubs = [];
1287
-
1288
- // Relay to outgoing bootstrap connections (except the one we received from)
1289
- for (const [uri, connInfo] of this.bootstrapConnections) {
1290
- if (connInfo.connected && connInfo.ws.readyState === WebSocket.OPEN) {
1291
- try {
1292
- connInfo.ws.send(JSON.stringify({
1293
- type: 'peer-discovered',
1294
- data: messageData,
1295
- networkName,
1296
- fromPeerId: 'system',
1297
- timestamp: Date.now()
1298
- }));
1299
- relayedToHubs.push(uri);
1300
- } catch (error) {
1301
- console.error(`❌ Error relaying to bootstrap hub ${uri}:`, error.message);
1302
- }
1303
- }
1304
- }
1305
-
1306
- // Relay to incoming hub connections (except the sender)
1307
- for (const [hubPeerId, hubInfo] of this.hubs) {
1308
- if (hubPeerId === fromHubPeerId || hubPeerId === this.hubPeerId) {
1309
- continue; // Skip sender and self
1310
- }
1311
- const hubConnection = this.connections.get(hubPeerId);
1312
- if (hubConnection && hubConnection.readyState === WebSocket.OPEN) {
1313
- try {
1314
- this.sendToConnection(hubConnection, {
1315
- type: 'peer-discovered',
1316
- data: messageData,
1317
- networkName,
1318
- fromPeerId: 'system',
1319
- timestamp: Date.now()
1320
- });
1321
- relayedToHubs.push(hubPeerId.substring(0, 8) + '...');
1322
- } catch (error) {
1323
- console.error(`❌ Error relaying to hub ${hubPeerId.substring(0, 8)}...:`, error.message);
1324
- }
1325
- }
1326
- }
1327
-
1328
- if (relayedToHubs.length > 0) {
1329
- console.log(`🔄 Relayed peer-discovered to ${relayedToHubs.length} other hub(s): ${relayedToHubs.join(', ')}`);
1330
- }
1331
- }
1332
-
1333
1196
  // Forward to all local CLIENT peers in the same network (exclude hubs)
1334
1197
  const localPeers = this.networkPeers.get(networkName);
1335
1198
  if (localPeers && localPeers.size > 0) {
@@ -65,37 +65,14 @@ export class ConnectionManager extends EventEmitter {
65
65
 
66
66
  // Enhanced duplicate connection prevention
67
67
  if (this.peers.has(targetPeerId)) {
68
- const existingPeer = this.peers.get(targetPeerId);
69
- const status = existingPeer.getStatus();
70
-
71
- // If already connected, don't retry
72
- if (status === 'connected') {
73
- this.debug.log(`Already connected to ${targetPeerId.substring(0, 8)}... (status: ${status})`);
74
- return;
75
- }
76
-
77
- // If connecting but stuck, allow retry after timeout
78
- if (status === 'connecting') {
79
- const connectionAge = Date.now() - (existingPeer.createdAt || 0);
80
- if (connectionAge < 10000) { // Wait 10 seconds before considering it stuck
81
- this.debug.log(`Connection to ${targetPeerId.substring(0, 8)}... still in progress (${Math.round(connectionAge / 1000)}s)`);
82
- return;
83
- }
84
- this.debug.log(`Connection to ${targetPeerId.substring(0, 8)}... appears stuck (${Math.round(connectionAge / 1000)}s), will retry`);
85
- this.cleanupFailedConnection(targetPeerId);
86
- }
68
+ this.debug.log(`Already connected to ${targetPeerId.substring(0, 8)}...`);
69
+ return;
87
70
  }
88
71
 
89
72
  // Check if we're already attempting through PeerDiscovery
90
73
  if (this.mesh.peerDiscovery.isAttemptingConnection(targetPeerId)) {
91
- const attemptAge = Date.now() - (this.lastConnectionAttempt.get(targetPeerId) || 0);
92
- // Allow retry if attempt is old (more than 10 seconds)
93
- if (attemptAge < 10000) {
94
- this.debug.log(`Already attempting connection to ${targetPeerId.substring(0, 8)}... via PeerDiscovery (${Math.round(attemptAge / 1000)}s ago)`);
95
- return;
96
- }
97
- this.debug.log(`Old connection attempt to ${targetPeerId.substring(0, 8)}... (${Math.round(attemptAge / 1000)}s ago), allowing retry`);
98
- this.mesh.peerDiscovery.clearConnectionAttempt(targetPeerId);
74
+ this.debug.log(`Already attempting connection to ${targetPeerId.substring(0, 8)}... via PeerDiscovery`);
75
+ return;
99
76
  }
100
77
 
101
78
  // INITIATOR LOGIC: Use deterministic peer ID comparison to prevent race conditions
@@ -125,22 +102,15 @@ export class ConnectionManager extends EventEmitter {
125
102
 
126
103
  if (now - lastAttempt < retryDelay) {
127
104
  const remaining = retryDelay - (now - lastAttempt);
128
- this.debug.log(`Connection to ${targetPeerId.substring(0, 8)}... on cooldown (${Math.round(remaining)}ms remaining, isolated: ${connectedCount === 0})`);
105
+ this.debug.log(`Connection to ${targetPeerId.substring(0, 8)}... on cooldown (${Math.round(remaining / 1000)}s remaining, isolated: ${connectedCount === 0})`);
129
106
  return;
130
107
  }
131
108
  }
132
109
 
133
- // Check connection attempt count - be more lenient for isolated peers
134
- const connectedCount = this.getConnectedPeerCount();
135
- const maxAttempts = connectedCount === 0 ? this.maxConnectionAttempts * 2 : this.maxConnectionAttempts;
136
-
137
- if (attempts >= maxAttempts) {
138
- this.debug.log(`Max connection attempts (${maxAttempts}) reached for ${targetPeerId.substring(0, 8)}...`);
110
+ // Check connection attempt count
111
+ if (attempts >= this.maxConnectionAttempts) {
139
112
  this.mesh.emit('statusChanged', { type: 'warning', message: `Max connection attempts reached for ${targetPeerId.substring(0, 8)}...` });
140
- // Don't remove from discovered peers immediately - might reconnect later
141
- this.connectionAttempts.delete(targetPeerId);
142
- this.lastConnectionAttempt.delete(targetPeerId);
143
- this.mesh.peerDiscovery.clearConnectionAttempt(targetPeerId);
113
+ this.mesh.peerDiscovery.removeDiscoveredPeer(targetPeerId);
144
114
  return;
145
115
  }
146
116
 
@@ -270,32 +270,27 @@ export class PeerConnection extends EventEmitter {
270
270
  if (this.connection &&
271
271
  this.connection.iceConnectionState === 'disconnected' &&
272
272
  !this.isClosing) {
273
- // ICE "disconnected" state is temporary - WebRTC connections are peer-to-peer
274
- // and should persist even without signaling. Only disconnect on "failed" state.
275
- // Check if we have signaling or mesh connectivity for ICE restart attempts
273
+ // Check if signaling is available before attempting ICE restart
276
274
  const hasSignaling = this.mesh && this.mesh.signalingClient && this.mesh.signalingClient.isConnected();
277
275
  const hasMeshConnectivity = this.mesh && this.mesh.connected && this.mesh.connectionManager.getConnectedPeerCount() > 0;
278
276
 
279
277
  if (hasSignaling || hasMeshConnectivity) {
280
- this.debug.log(`âš ī¸ ICE remained disconnected for ${this.peerId}, attempting restart (signaling: ${hasSignaling}, mesh: ${hasMeshConnectivity})`);
278
+ this.debug.log(`❌ ICE remained disconnected for ${this.peerId}, attempting restart (signaling: ${hasSignaling}, mesh: ${hasMeshConnectivity})`);
281
279
  try {
282
280
  this.restartIceViaSignaling().catch(error => {
283
281
  this.debug.error('Failed to restart ICE after disconnection:', error);
284
- // Don't disconnect on restart failure - wait for ICE to reach "failed" state naturally
285
- this.debug.log(`Will wait for ICE to reach "failed" state before disconnecting ${this.peerId}`);
282
+ this.emit('disconnected', { peerId: this.peerId, reason: 'ICE disconnected' });
286
283
  });
287
284
  } catch (error) {
288
285
  this.debug.error('Failed to restart ICE after disconnection:', error);
289
- // Don't disconnect on restart failure - wait for ICE to reach "failed" state naturally
290
- this.debug.log(`Will wait for ICE to reach "failed" state before disconnecting ${this.peerId}`);
286
+ this.emit('disconnected', { peerId: this.peerId, reason: 'ICE disconnected' });
291
287
  }
292
288
  } else {
293
- // No signaling available, but WebRTC is peer-to-peer
294
- // Don't disconnect unless ICE reaches "failed" state
295
- this.debug.log(`âš ī¸ ICE disconnected for ${this.peerId} without signaling - waiting for ICE state to resolve naturally`);
289
+ this.debug.log(`❌ ICE remained disconnected for ${this.peerId}, disconnecting`);
290
+ this.emit('disconnected', { peerId: this.peerId, reason: 'ICE disconnected' });
296
291
  }
297
292
  }
298
- }, 5000); // Wait 5 seconds for potential ICE reconnection
293
+ }, 5000); // Faster ICE reconnection - 5 seconds
299
294
  }
300
295
  };
301
296
 
@@ -38,46 +38,27 @@ export class PeerDiscovery extends EventEmitter {
38
38
  }
39
39
 
40
40
  addDiscoveredPeer(peerId) {
41
- const wasKnown = this.discoveredPeers.has(peerId);
42
- const now = Date.now();
43
-
44
- // Update or add peer with current timestamp
45
- this.discoveredPeers.set(peerId, now);
46
-
47
- if (wasKnown) {
48
- this.debug.log(`Re-discovered peer ${peerId.substring(0, 8)}... (updating timestamp)`);
49
-
50
- // Clean up stale connection attempt if it's been more than 5 seconds
51
- if (this.connectionAttempts.has(peerId)) {
52
- const attemptTime = this.connectionAttempts.get(peerId);
53
- if (now - attemptTime > 5000) {
54
- this.debug.log(`Clearing stale connection attempt for ${peerId.substring(0, 8)}...`);
55
- this.connectionAttempts.delete(peerId);
56
- }
57
- }
58
- } else {
59
- this.debug.log(`Discovered new peer ${peerId.substring(0, 8)}...`);
60
- this.emit('peerDiscovered', { peerId });
41
+ // Skip if we already know about this peer (prevent duplicate processing)
42
+ if (this.discoveredPeers.has(peerId)) {
43
+ // Update timestamp but don't emit events or trigger connections
44
+ this.discoveredPeers.set(peerId, Date.now());
45
+ return;
61
46
  }
62
47
 
63
- // Check if we should initiate connection
64
- const alreadyTrying = this.connectionAttempts.has(peerId);
65
- const shouldInitiate = this.shouldInitiateConnection(peerId);
66
-
67
- if (this.autoDiscovery && shouldInitiate && !alreadyTrying) {
68
- this.debug.log(`Considering connection to ${peerId.substring(0, 8)}... (shouldInitiate: ${shouldInitiate}, alreadyTrying: ${alreadyTrying})`);
48
+ this.discoveredPeers.set(peerId, Date.now());
49
+ this.emit('peerDiscovered', { peerId });
50
+
51
+ this.debug.log(`Discovered peer ${peerId.substring(0, 8)}...`);
52
+
53
+ // Only auto-connect if we should initiate to this peer and we're not already trying
54
+ if (this.autoDiscovery && this.shouldInitiateConnection(peerId) && !this.connectionAttempts.has(peerId)) {
55
+ this.debug.log(`Considering connection to ${peerId.substring(0, 8)}...`);
69
56
 
70
57
  const canAccept = this.canAcceptMorePeers();
71
58
  if (canAccept) {
72
- this.debug.log(`🔗 Initiating connection to ${peerId.substring(0, 8)}...`);
59
+ this.debug.log(`Connecting to ${peerId.substring(0, 8)}...`);
73
60
  this.emit('connectToPeer', { peerId });
74
- } else {
75
- this.debug.log(`Cannot connect to ${peerId.substring(0, 8)}... (at max peers)`);
76
61
  }
77
- } else if (alreadyTrying) {
78
- this.debug.log(`Already attempting connection to ${peerId.substring(0, 8)}...`);
79
- } else if (!shouldInitiate) {
80
- this.debug.log(`Not initiating to ${peerId.substring(0, 8)}... (should wait for them to initiate)`);
81
62
  }
82
63
 
83
64
  this.scheduleMeshOptimization();
@@ -113,6 +94,10 @@ export class PeerDiscovery extends EventEmitter {
113
94
  }
114
95
 
115
96
  shouldInitiateConnection(targetPeerId) {
97
+ if (this.connectionAttempts.has(targetPeerId)) {
98
+ return false;
99
+ }
100
+
116
101
  // Check current connection count to handle isolation
117
102
  this.emit('checkCapacity');
118
103
  const currentConnectionCount = this._currentConnectionCount || 0;
@@ -100,26 +100,13 @@ export class SignalingHandler extends EventEmitter {
100
100
  }
101
101
 
102
102
  handlePeerAnnouncement(fromPeerId) {
103
- // Check if we already have an active connection to this peer
104
- if (this.connectionManager.hasPeer(fromPeerId)) {
105
- const peerStatus = this.connectionManager.getPeer(fromPeerId).getStatus();
106
- if (peerStatus === 'connected') {
107
- this.debug.log(`Peer ${fromPeerId.substring(0, 8)}... already connected (${peerStatus}), updating timestamp`);
108
- this.mesh.peerDiscovery.updateDiscoveryTimestamp(fromPeerId);
109
- return;
110
- }
111
- this.debug.log(`Peer ${fromPeerId.substring(0, 8)}... exists but not connected (${peerStatus}), allowing re-discovery`);
112
- }
113
-
114
- // Allow re-discovery to refresh timestamps and potentially retry connections
115
- const wasKnown = this.mesh.peerDiscovery.hasPeer(fromPeerId);
116
- if (wasKnown) {
117
- this.debug.log(`Peer ${fromPeerId.substring(0, 8)}... already known, refreshing discovery`);
118
- } else {
119
- this.debug.log(`New peer discovered: ${fromPeerId.substring(0, 8)}...`);
103
+ // Prevent duplicate announcements - only announce if we haven't seen this peer before
104
+ if (this.mesh.peerDiscovery.hasPeer(fromPeerId)) {
105
+ this.debug.log(`Peer ${fromPeerId.substring(0, 8)}... already known, skipping announcement`);
106
+ return;
120
107
  }
121
108
 
122
- this.mesh.emit('statusChanged', { type: 'info', message: `Peer ${fromPeerId.substring(0, 8)}... ${wasKnown ? 're-announced' : 'announced'}` });
109
+ this.mesh.emit('statusChanged', { type: 'info', message: `Peer ${fromPeerId.substring(0, 8)}... announced` });
123
110
  this.debug.log(`Adding discovered peer: ${fromPeerId.substring(0, 8)}... to PeerDiscovery`);
124
111
  this.debug.log(`Current peer count: ${this.connectionManager.getConnectedPeerCount()}/${this.mesh.maxPeers}`);
125
112
  this.debug.log(`All discovered peers: ${Array.from(this.mesh.peerDiscovery.discoveredPeers.keys()).map(p => p.substring(0, 8)).join(', ')}`);