peerpigeon 0.1.1 โ†’ 1.0.2

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.
Files changed (77) hide show
  1. package/README.md +141 -1365
  2. package/cli.js +1382 -0
  3. package/dist/peerpigeon-browser.js +12450 -0
  4. package/dist/peerpigeon-browser.js.map +7 -0
  5. package/docs/API_DOCUMENTATION.md +1976 -0
  6. package/docs/BOOTSTRAP_HUBS.md +319 -0
  7. package/docs/CLI_README.md +371 -0
  8. package/docs/CUSTOM_HUB_NAMESPACES.md +182 -0
  9. package/docs/CUSTOM_NAMESPACE_IMPLEMENTATION.md +187 -0
  10. package/docs/DOCUMENTATION_REORGANIZATION.md +172 -0
  11. package/docs/HUB_QUICK_REF.md +108 -0
  12. package/docs/HUB_SCRIPTS.md +341 -0
  13. package/docs/HUB_SYSTEM.md +599 -0
  14. package/docs/MIGRATION_COMPLETE.md +93 -0
  15. package/docs/NETWORK_NAMESPACES.md +212 -0
  16. package/docs/PIGEONRTC_MIGRATION.md +280 -0
  17. package/docs/README.md +108 -0
  18. package/docs/SELECTIVE_STREAMING_GUIDE.md +427 -0
  19. package/docs/TEST_CLEANUP_COMPLETE.md +80 -0
  20. package/examples/bootstrap-hub-example.js +292 -0
  21. package/examples/browser/README.md +278 -0
  22. package/examples/browser/app.js +2426 -49
  23. package/examples/browser/index.html +481 -630
  24. package/examples/browser/minimal/README.md +55 -0
  25. package/examples/browser/minimal/index.html +75 -0
  26. package/examples/browser/minimal/minimal.js +234 -0
  27. package/examples/browser/styles.css +687 -1425
  28. package/examples/browser/test-bundle.html +35 -0
  29. package/examples/browser-2/index.html +30 -0
  30. package/examples/browser-2/package.json +21 -0
  31. package/examples/browser-2/src/App-simple.vue +21 -0
  32. package/examples/browser-2/src/App.vue +420 -0
  33. package/examples/browser-2/src/components/CryptoView.vue +1661 -0
  34. package/examples/browser-2/src/components/DHTView.vue +1281 -0
  35. package/examples/browser-2/src/components/DebugView.vue +1773 -0
  36. package/examples/browser-2/src/components/MediaView.vue +1048 -0
  37. package/examples/browser-2/src/components/MessagingView.vue +775 -0
  38. package/examples/browser-2/src/components/NetworkView.vue +930 -0
  39. package/examples/browser-2/src/components/StorageView.vue +1376 -0
  40. package/examples/browser-2/src/main.js +5 -0
  41. package/examples/browser-2/src/stores/peerpigeon.js +895 -0
  42. package/examples/browser-2/vite.config.js +6 -0
  43. package/examples/hub-example.js +189 -0
  44. package/examples/multi-hub-test.js +186 -0
  45. package/examples/node/README.md +2 -2
  46. package/examples/programmatic-namespace-example.js +108 -0
  47. package/examples/selective-streaming-demo.html +698 -0
  48. package/examples/standard-events-demo.js +126 -0
  49. package/index.js +7 -1
  50. package/package.json +34 -16
  51. package/server/index.js +1058 -98
  52. package/server/start.js +52 -0
  53. package/src/ConnectionManager.js +239 -225
  54. package/src/CryptoManager.js +147 -18
  55. package/src/DebugLogger.js +0 -7
  56. package/src/DistributedStorageManager.js +224 -205
  57. package/src/EnvironmentDetector.js +88 -4
  58. package/src/EventEmitter.js +79 -1
  59. package/src/EvictionManager.js +10 -9
  60. package/src/GossipManager.js +163 -11
  61. package/src/MediaManager.js +12 -2
  62. package/src/PeerConnection.js +343 -311
  63. package/src/PeerPigeonMesh.js +576 -135
  64. package/src/PigeonRTC-browser.js +247 -0
  65. package/src/SignalingClient.js +14 -243
  66. package/src/SignalingHandler.js +31 -10
  67. package/src/StorageManager.js +0 -39
  68. package/src/WebDHT-Simple.js +389 -0
  69. package/src/WebDHT.js +363 -1165
  70. package/src/browser-entry.js +58 -0
  71. package/examples/browser/assets/images/favicon.png +0 -0
  72. package/examples/browser/assets/images/pigeon.png +0 -0
  73. package/examples/browser/crypto-test.html +0 -427
  74. package/examples/browser/ui-old.js +0 -1926
  75. package/examples/browser/ui.js +0 -3391
  76. package/websocket-server/README.md +0 -247
  77. package/websocket-server/server.js +0 -391
package/server/index.js CHANGED
@@ -1,7 +1,8 @@
1
1
  // PeerPigeon WebSocket Server - Node.js module
2
- import { WebSocketServer } from 'ws';
2
+ import { WebSocketServer, WebSocket } from 'ws';
3
3
  import { createServer } from 'http';
4
4
  import { EventEmitter } from 'events';
5
+ import { URL } from 'url';
5
6
 
6
7
  /**
7
8
  * PeerPigeon WebSocket signaling server
@@ -14,29 +15,168 @@ export class PeerPigeonServer extends EventEmitter {
14
15
  this.port = options.port || 3000;
15
16
  this.host = options.host || 'localhost';
16
17
  this.maxConnections = options.maxConnections || 1000;
17
- this.cleanupInterval = options.cleanupInterval || 60000; // 1 minute
18
+ this.cleanupInterval = options.cleanupInterval || 30000; // 30 seconds
18
19
  this.peerTimeout = options.peerTimeout || 300000; // 5 minutes
19
20
  this.corsOrigin = options.corsOrigin || '*';
20
21
  this.maxMessageSize = options.maxMessageSize || 1048576; // 1MB
22
+ this.maxPortRetries = options.maxPortRetries || 10; // Try up to 10 ports
23
+
24
+
25
+ // Hub configuration
26
+ this.isHub = options.isHub || false; // Whether this server is a hub
27
+ this.hubMeshNamespace = options.hubMeshNamespace || 'pigeonhub-mesh'; // Reserved namespace for hubs (default: 'pigeonhub-mesh')
28
+ this.bootstrapHubs = options.bootstrapHubs || []; // URIs of bootstrap hubs to connect to
29
+ this.autoConnect = options.autoConnect !== false; // Auto-connect to bootstrap hubs (default: true)
30
+ this.reconnectInterval = options.reconnectInterval || 5000; // Reconnect interval in ms
31
+ this.maxReconnectAttempts = options.maxReconnectAttempts || 10; // Max reconnection attempts
32
+
33
+ // Generate hub peer ID if this is a hub
34
+ this.hubPeerId = options.hubPeerId || (this.isHub ? this.generatePeerId() : null);
21
35
 
22
36
  this.httpServer = null;
23
37
  this.wss = null;
24
38
  this.connections = new Map(); // peerId -> WebSocket
25
39
  this.peerData = new Map(); // peerId -> peer info
40
+ this.networkPeers = new Map(); // networkName -> Set of peerIds
41
+ this.hubs = new Map(); // peerId -> hub info (for peers identified as hubs)
42
+ this.bootstrapConnections = new Map(); // bootstrapUri -> connection info
26
43
  this.isRunning = false;
27
44
  this.cleanupTimer = null;
45
+ this.startTime = null;
28
46
  }
29
47
 
30
48
  /**
31
- * Start the WebSocket server
49
+ * Validate peer ID format
32
50
  */
33
- async start() {
34
- if (this.isRunning) {
35
- throw new Error('Server is already running');
51
+ validatePeerId(peerId) {
52
+ return typeof peerId === 'string' && /^[a-fA-F0-9]{40}$/.test(peerId);
53
+ }
54
+
55
+ /**
56
+ * Generate a random peer ID (40 hex characters)
57
+ */
58
+ generatePeerId() {
59
+ // Generate random hex string
60
+ const chars = '0123456789abcdef';
61
+ let peerId = '';
62
+ for (let i = 0; i < 40; i++) {
63
+ peerId += chars[Math.floor(Math.random() * 16)];
64
+ }
65
+ return peerId;
66
+ }
67
+
68
+ /**
69
+ * Check if a peer is registered as a hub
70
+ */
71
+ isPeerHub(peerId) {
72
+ return this.hubs.has(peerId);
73
+ }
74
+
75
+ /**
76
+ * Register a peer as a hub
77
+ */
78
+ registerHub(peerId, hubInfo = {}) {
79
+ this.hubs.set(peerId, {
80
+ peerId,
81
+ registeredAt: Date.now(),
82
+ lastActivity: Date.now(),
83
+ ...hubInfo
84
+ });
85
+ console.log(`๐Ÿข Registered hub: ${peerId.substring(0, 8)}... (${this.hubs.size} total hubs)`);
86
+ this.emit('hubRegistered', { peerId, totalHubs: this.hubs.size });
87
+ }
88
+
89
+ /**
90
+ * Unregister a hub
91
+ */
92
+ unregisterHub(peerId) {
93
+ if (this.hubs.delete(peerId)) {
94
+ console.log(`๐Ÿข Unregistered hub: ${peerId.substring(0, 8)}... (${this.hubs.size} remaining hubs)`);
95
+ this.emit('hubUnregistered', { peerId, totalHubs: this.hubs.size });
96
+ }
97
+ }
98
+
99
+ /**
100
+ * Get all connected hubs
101
+ */
102
+ getConnectedHubs(excludePeerId = null) {
103
+ const hubList = [];
104
+ for (const [peerId, hubInfo] of this.hubs) {
105
+ if (peerId !== excludePeerId && this.connections.has(peerId)) {
106
+ hubList.push({ peerId, ...hubInfo });
107
+ }
108
+ }
109
+ return hubList;
110
+ }
111
+
112
+ /**
113
+ * Find closest peers using XOR distance
114
+ */
115
+ findClosestPeers(targetPeerId, allPeerIds, maxPeers = 3) {
116
+ if (!targetPeerId || !allPeerIds || allPeerIds.length === 0) {
117
+ return [];
118
+ }
119
+
120
+ // XOR distance calculation (simplified)
121
+ const distances = allPeerIds.map(peerId => {
122
+ let distance = 0;
123
+ const minLength = Math.min(targetPeerId.length, peerId.length);
124
+
125
+ for (let i = 0; i < minLength; i++) {
126
+ const xor = parseInt(targetPeerId[i], 16) ^ parseInt(peerId[i], 16);
127
+ distance += xor;
128
+ }
129
+
130
+ return { peerId, distance };
131
+ });
132
+
133
+ // Sort by distance and return closest peers
134
+ distances.sort((a, b) => a.distance - b.distance);
135
+ return distances.slice(0, maxPeers).map(item => item.peerId);
136
+ }
137
+
138
+ /**
139
+ * Get active peers in a network
140
+ */
141
+ getActivePeers(excludePeerId = null, networkName = 'global') {
142
+ const peers = [];
143
+ const stalePeers = [];
144
+
145
+ // Get peers for the specific network
146
+ const networkPeerSet = this.networkPeers.get(networkName);
147
+ if (!networkPeerSet) {
148
+ return peers; // No peers in this network
149
+ }
150
+
151
+ for (const peerId of networkPeerSet) {
152
+ if (peerId !== excludePeerId) {
153
+ const connection = this.connections.get(peerId);
154
+ if (connection && connection.readyState === connection.OPEN) {
155
+ peers.push(peerId);
156
+ } else {
157
+ // Mark stale connections for cleanup
158
+ stalePeers.push(peerId);
159
+ }
160
+ }
36
161
  }
37
162
 
163
+ // Clean up stale connections
164
+ stalePeers.forEach(peerId => {
165
+ console.log(`๐Ÿงน Cleaning up stale connection: ${peerId.substring(0, 8)}...`);
166
+ this.cleanupPeer(peerId);
167
+ });
168
+
169
+ return peers;
170
+ }
171
+
172
+ /**
173
+ * Try to start server on a specific port
174
+ */
175
+ async tryPort(port, maxRetries = null) {
176
+ maxRetries = maxRetries !== null ? maxRetries : this.maxPortRetries;
177
+
38
178
  return new Promise((resolve, reject) => {
39
- try {
179
+ const attemptPort = (currentPort, retriesLeft) => {
40
180
  // Create HTTP server
41
181
  this.httpServer = createServer((req, res) => {
42
182
  // Handle CORS preflight
@@ -60,13 +200,30 @@ export class PeerPigeonServer extends EventEmitter {
60
200
  status: 'healthy',
61
201
  timestamp: new Date().toISOString(),
62
202
  uptime: process.uptime(),
203
+ isHub: this.isHub,
63
204
  connections: this.connections.size,
64
205
  peers: this.peerData.size,
206
+ hubs: this.hubs.size,
207
+ networks: this.networkPeers.size,
65
208
  memory: process.memoryUsage()
66
209
  }));
67
210
  return;
68
211
  }
69
212
 
213
+ // Hubs endpoint - list connected hubs
214
+ if (req.url === '/hubs') {
215
+ res.writeHead(200, {
216
+ 'Content-Type': 'application/json',
217
+ 'Access-Control-Allow-Origin': this.corsOrigin
218
+ });
219
+ res.end(JSON.stringify({
220
+ timestamp: new Date().toISOString(),
221
+ totalHubs: this.hubs.size,
222
+ hubs: this.getConnectedHubs()
223
+ }));
224
+ return;
225
+ }
226
+
70
227
  // Default response
71
228
  res.writeHead(200, {
72
229
  'Content-Type': 'text/plain',
@@ -83,33 +240,97 @@ export class PeerPigeonServer extends EventEmitter {
83
240
 
84
241
  this.setupWebSocketHandlers();
85
242
 
243
+ // Handle port in use error
244
+ const errorHandler = (error) => {
245
+ if (error.code === 'EADDRINUSE') {
246
+ console.log(`โš ๏ธ Port ${currentPort} is already in use`);
247
+
248
+ // Clean up failed server
249
+ this.httpServer.removeAllListeners();
250
+ if (this.wss) {
251
+ this.wss.close();
252
+ }
253
+ this.httpServer = null;
254
+ this.wss = null;
255
+
256
+ if (retriesLeft > 0) {
257
+ const nextPort = currentPort + 1;
258
+ console.log(`๐Ÿ”„ Trying port ${nextPort}...`);
259
+ attemptPort(nextPort, retriesLeft - 1);
260
+ } else {
261
+ reject(new Error(`Failed to find available port after ${maxRetries} attempts (tried ${port}-${currentPort})`));
262
+ }
263
+ } else {
264
+ console.error('โŒ HTTP server error:', error);
265
+ this.emit('error', error);
266
+ reject(error);
267
+ }
268
+ };
269
+
270
+ this.httpServer.once('error', errorHandler);
271
+
86
272
  // Start HTTP server
87
- this.httpServer.listen(this.port, this.host, () => {
273
+ this.httpServer.listen(currentPort, this.host, () => {
274
+ // Remove error handler after successful start
275
+ this.httpServer.removeListener('error', errorHandler);
276
+
277
+ // Update port to the actual port used
278
+ this.port = currentPort;
88
279
  this.isRunning = true;
280
+ this.startTime = Date.now();
89
281
  this.startCleanupTimer();
90
282
 
91
- console.log(`๐Ÿš€ PeerPigeon WebSocket server started on ws://${this.host}:${this.port}`);
283
+ if (currentPort !== port) {
284
+ console.log(`โœ… Port ${port} was in use, using port ${currentPort} instead`);
285
+ }
286
+
287
+ const serverType = this.isHub ? '๐Ÿข PeerPigeon Hub Server' : '๐Ÿš€ PeerPigeon WebSocket Server';
288
+ console.log(`${serverType} started on ws://${this.host}:${this.port}`);
289
+ if (this.isHub) {
290
+ console.log(`๐ŸŒ Hub mesh namespace: ${this.hubMeshNamespace}`);
291
+ }
92
292
  console.log(`๐Ÿ“Š Max connections: ${this.maxConnections}`);
93
293
  console.log(`๐Ÿงน Cleanup interval: ${this.cleanupInterval}ms`);
94
294
  console.log(`โฐ Peer timeout: ${this.peerTimeout}ms`);
95
295
 
96
296
  this.emit('started', { host: this.host, port: this.port });
97
- resolve();
98
- });
297
+ resolve({ host: this.host, port: this.port });
99
298
 
100
- this.httpServer.on('error', (error) => {
101
- console.error('โŒ HTTP server error:', error);
102
- this.emit('error', error);
103
- reject(error);
299
+ // Add persistent error handler after successful start
300
+ this.httpServer.on('error', (error) => {
301
+ console.error('โŒ HTTP server error:', error);
302
+ this.emit('error', error);
303
+ });
104
304
  });
305
+ };
105
306
 
106
- } catch (error) {
107
- console.error('โŒ Failed to start server:', error);
108
- reject(error);
109
- }
307
+ attemptPort(port, maxRetries);
110
308
  });
111
309
  }
112
310
 
311
+ /**
312
+ * Start the WebSocket server
313
+ */
314
+ async start() {
315
+ if (this.isRunning) {
316
+ throw new Error('Server is already running');
317
+ }
318
+
319
+ try {
320
+ const result = await this.tryPort(this.port);
321
+
322
+ // If this is a hub, connect to bootstrap hubs
323
+ if (this.isHub && this.autoConnect) {
324
+ await this.connectToBootstrapHubs();
325
+ }
326
+
327
+ return result;
328
+ } catch (error) {
329
+ console.error('โŒ Failed to start server:', error);
330
+ throw error;
331
+ }
332
+ }
333
+
113
334
  /**
114
335
  * Stop the WebSocket server
115
336
  */
@@ -121,6 +342,11 @@ export class PeerPigeonServer extends EventEmitter {
121
342
  return new Promise((resolve) => {
122
343
  console.log('๐Ÿ›‘ Stopping PeerPigeon WebSocket server...');
123
344
 
345
+ // Disconnect from bootstrap hubs if this is a hub
346
+ if (this.isHub) {
347
+ this.disconnectFromBootstrapHubs();
348
+ }
349
+
124
350
  // Stop cleanup timer
125
351
  if (this.cleanupTimer) {
126
352
  clearInterval(this.cleanupTimer);
@@ -163,6 +389,367 @@ export class PeerPigeonServer extends EventEmitter {
163
389
  });
164
390
  }
165
391
 
392
+ /**
393
+ * Connect to bootstrap hubs
394
+ */
395
+ async connectToBootstrapHubs() {
396
+ if (!this.isHub) {
397
+ console.log('โš ๏ธ Not a hub, skipping bootstrap connections');
398
+ return;
399
+ }
400
+
401
+ // If no bootstrap hubs specified, try default port 3000
402
+ let bootstrapUris = this.bootstrapHubs;
403
+ if (!bootstrapUris || bootstrapUris.length === 0) {
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
+ }
413
+ }
414
+
415
+ console.log(`๐Ÿ”— Connecting to ${bootstrapUris.length} bootstrap hub(s)...`);
416
+
417
+ for (const uri of bootstrapUris) {
418
+ try {
419
+ await this.connectToHub(uri);
420
+ } catch (error) {
421
+ console.error(`โŒ Failed to connect to bootstrap hub ${uri}:`, error.message);
422
+ }
423
+ }
424
+ }
425
+
426
+ /**
427
+ * Connect to a specific hub
428
+ */
429
+ async connectToHub(uri, attemptNumber = 0) {
430
+ return new Promise((resolve, reject) => {
431
+ try {
432
+ // Parse URI to check if it's our own server
433
+ const url = new URL(uri);
434
+ const hubPort = parseInt(url.port) || 3000;
435
+ const hubHost = url.hostname;
436
+
437
+ // Don't connect to ourselves
438
+ if (hubHost === this.host && hubPort === this.port) {
439
+ console.log(`โš ๏ธ Skipping self-connection to ${uri}`);
440
+ resolve();
441
+ return;
442
+ }
443
+
444
+ const wsUrl = `${uri}?peerId=${this.hubPeerId}`;
445
+ console.log(`๐Ÿ”— Connecting to hub: ${uri} (attempt ${attemptNumber + 1})`);
446
+
447
+ const ws = new WebSocket(wsUrl);
448
+
449
+ const connectionInfo = {
450
+ uri,
451
+ ws,
452
+ connected: false,
453
+ attemptNumber,
454
+ lastAttempt: Date.now(),
455
+ reconnectTimer: null
456
+ };
457
+
458
+ this.bootstrapConnections.set(uri, connectionInfo);
459
+
460
+ ws.on('open', () => {
461
+ console.log(`โœ… Connected to bootstrap hub: ${uri}`);
462
+ connectionInfo.connected = true;
463
+ connectionInfo.attemptNumber = 0; // Reset attempt counter on success
464
+
465
+ // Announce this hub on the hub mesh
466
+ this.announceToHub(ws);
467
+
468
+ this.emit('bootstrapConnected', { uri });
469
+ resolve();
470
+ });
471
+
472
+ ws.on('message', (data) => {
473
+ try {
474
+ const message = JSON.parse(data.toString());
475
+ this.handleBootstrapMessage(uri, message);
476
+ } catch (error) {
477
+ console.error(`โŒ Error handling message from ${uri}:`, error);
478
+ }
479
+ });
480
+
481
+ ws.on('close', (code, reason) => {
482
+ console.log(`๐Ÿ”Œ Disconnected from bootstrap hub ${uri} (${code}: ${reason})`)
483
+ connectionInfo.connected = false;
484
+
485
+ this.emit('bootstrapDisconnected', { uri, code, reason });
486
+
487
+ // Attempt to reconnect
488
+ if (this.isRunning && attemptNumber < this.maxReconnectAttempts) {
489
+ connectionInfo.reconnectTimer = setTimeout(() => {
490
+ console.log(`๐Ÿ”„ Reconnecting to ${uri}...`);
491
+ this.connectToHub(uri, attemptNumber + 1);
492
+ }, this.reconnectInterval);
493
+ } else if (attemptNumber >= this.maxReconnectAttempts) {
494
+ console.log(`โŒ Max reconnection attempts reached for ${uri}`);
495
+ this.bootstrapConnections.delete(uri);
496
+ }
497
+ });
498
+
499
+ ws.on('error', (error) => {
500
+ console.error(`โŒ WebSocket error for ${uri}:`, error.message);
501
+
502
+ // Only reject on first attempt, otherwise we'll retry
503
+ if (attemptNumber === 0) {
504
+ this.bootstrapConnections.delete(uri);
505
+ reject(error);
506
+ }
507
+ });
508
+
509
+ } catch (error) {
510
+ console.error(`โŒ Failed to create connection to ${uri}:`, error);
511
+ reject(error);
512
+ }
513
+ });
514
+ }
515
+
516
+ /**
517
+ * Announce this hub to a bootstrap hub
518
+ */
519
+ announceToHub(ws) {
520
+ const announcement = {
521
+ type: 'announce',
522
+ networkName: this.hubMeshNamespace,
523
+ data: {
524
+ isHub: true,
525
+ port: this.port,
526
+ host: this.host,
527
+ capabilities: ['signaling', 'relay'],
528
+ timestamp: Date.now()
529
+ }
530
+ };
531
+
532
+ ws.send(JSON.stringify(announcement));
533
+ console.log(`๐Ÿ“ข Announced to bootstrap hub on ${this.hubMeshNamespace}`);
534
+
535
+ // Announce all existing local peers to the bootstrap hub
536
+ this.announceLocalPeersToHub(ws);
537
+ }
538
+
539
+ /**
540
+ * Announce all local (non-hub) peers to a bootstrap hub
541
+ */
542
+ announceLocalPeersToHub(ws) {
543
+ let totalAnnounced = 0;
544
+
545
+ // Iterate through all networks and announce their peers
546
+ for (const [networkName, peerSet] of this.networkPeers) {
547
+ // Skip the hub mesh namespace
548
+ if (networkName === this.hubMeshNamespace) {
549
+ continue;
550
+ }
551
+
552
+ for (const peerId of peerSet) {
553
+ const peerData = this.peerData.get(peerId);
554
+
555
+ // Skip hubs, only announce regular peers
556
+ if (peerData?.isHub) {
557
+ continue;
558
+ }
559
+
560
+ // Skip if not connected or not announced
561
+ const connection = this.connections.get(peerId);
562
+ if (!connection || connection.readyState !== WebSocket.OPEN || !peerData?.announced) {
563
+ continue;
564
+ }
565
+
566
+ // Send peer-discovered message to bootstrap hub
567
+ const peerAnnouncement = {
568
+ type: 'peer-discovered',
569
+ data: {
570
+ peerId,
571
+ isHub: false,
572
+ ...peerData.data
573
+ },
574
+ networkName: networkName,
575
+ fromPeerId: 'system',
576
+ timestamp: Date.now()
577
+ };
578
+
579
+ try {
580
+ ws.send(JSON.stringify(peerAnnouncement));
581
+ totalAnnounced++;
582
+ } catch (error) {
583
+ console.error(`โŒ Error announcing peer ${peerId.substring(0, 8)}... to bootstrap:`, error.message);
584
+ }
585
+ }
586
+ }
587
+
588
+ if (totalAnnounced > 0) {
589
+ console.log(`๐Ÿ“ก Announced ${totalAnnounced} local peer(s) to bootstrap hub`);
590
+ }
591
+ }
592
+
593
+ /**
594
+ * Send all local peers to a connected hub (via peerId)
595
+ */
596
+ sendLocalPeersToHub(hubPeerId) {
597
+ const hubConnection = this.connections.get(hubPeerId);
598
+ if (!hubConnection || hubConnection.readyState !== WebSocket.OPEN) {
599
+ console.log(`โš ๏ธ Cannot send peers to hub ${hubPeerId.substring(0, 8)}... - not connected`);
600
+ return;
601
+ }
602
+
603
+ let totalSent = 0;
604
+
605
+ // Iterate through all networks and send their peers
606
+ for (const [networkName, peerSet] of this.networkPeers) {
607
+ // Skip the hub mesh namespace
608
+ if (networkName === this.hubMeshNamespace) {
609
+ continue;
610
+ }
611
+
612
+ for (const peerId of peerSet) {
613
+ const peerData = this.peerData.get(peerId);
614
+
615
+ // Skip hubs, only send regular peers
616
+ if (peerData?.isHub) {
617
+ continue;
618
+ }
619
+
620
+ // Skip if not connected or not announced
621
+ const connection = this.connections.get(peerId);
622
+ if (!connection || connection.readyState !== WebSocket.OPEN || !peerData?.announced) {
623
+ continue;
624
+ }
625
+
626
+ // Send peer-discovered message to the hub
627
+ const peerAnnouncement = {
628
+ type: 'peer-discovered',
629
+ data: {
630
+ peerId,
631
+ isHub: false,
632
+ ...peerData.data
633
+ },
634
+ networkName: networkName,
635
+ fromPeerId: 'system',
636
+ targetPeerId: hubPeerId,
637
+ timestamp: Date.now()
638
+ };
639
+
640
+ try {
641
+ this.sendToConnection(hubConnection, peerAnnouncement);
642
+ totalSent++;
643
+ } catch (error) {
644
+ console.error(`โŒ Error sending peer ${peerId.substring(0, 8)}... to hub:`, error.message);
645
+ }
646
+ }
647
+ }
648
+
649
+ if (totalSent > 0) {
650
+ console.log(`๐Ÿ“ก Sent ${totalSent} local peer(s) to hub ${hubPeerId.substring(0, 8)}...`);
651
+ }
652
+ }
653
+
654
+ /**
655
+ * Handle messages from bootstrap hubs
656
+ */
657
+ handleBootstrapMessage(uri, message) {
658
+ const { type, data, fromPeerId, targetPeerId, networkName } = message;
659
+
660
+ switch (type) {
661
+ case 'connected':
662
+ console.log(`โœ… Bootstrap hub acknowledged connection: ${uri}`);
663
+ break;
664
+
665
+ case 'peer-discovered':
666
+ if (data?.isHub) {
667
+ console.log(`๐Ÿข Discovered hub via bootstrap: ${data.peerId?.substring(0, 8)}...`);
668
+ this.emit('hubDiscovered', { peerId: data.peerId, via: uri, data });
669
+ } else if (data?.peerId) {
670
+ // Regular peer discovered on another hub - notify our local peers in same network
671
+ const discoveredPeerId = data.peerId;
672
+ const discoveredNetwork = networkName || 'global';
673
+
674
+ console.log(`๐Ÿ“ฅ Peer ${discoveredPeerId.substring(0, 8)}... discovered on another hub (network: ${discoveredNetwork})`);
675
+
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
+ });
689
+ }
690
+ });
691
+ }
692
+ break;
693
+
694
+ case 'peer-disconnected':
695
+ if (data?.isHub) {
696
+ console.log(`๐Ÿข Hub disconnected: ${data.peerId?.substring(0, 8)}...`);
697
+ }
698
+ break;
699
+
700
+ case 'offer':
701
+ case 'answer':
702
+ case 'ice-candidate':
703
+ // Check if target peer is on this hub
704
+ if (targetPeerId) {
705
+ const targetConnection = this.connections.get(targetPeerId);
706
+ if (targetConnection && targetConnection.readyState === WebSocket.OPEN) {
707
+ // Forward to local peer
708
+ console.log(`๐Ÿ“ฅ Received ${type} from ${fromPeerId?.substring(0, 8)}... for local peer ${targetPeerId.substring(0, 8)}...`);
709
+ this.sendToConnection(targetConnection, message);
710
+ } else {
711
+ // Not our peer, relay to other bootstrap hubs
712
+ console.log(`๐Ÿ”„ Relaying ${type} from ${fromPeerId?.substring(0, 8)}... for ${targetPeerId.substring(0, 8)}... (not local)`);
713
+ for (const [otherUri, connInfo] of this.bootstrapConnections) {
714
+ if (otherUri !== uri && connInfo.connected && connInfo.ws.readyState === WebSocket.OPEN) {
715
+ connInfo.ws.send(JSON.stringify(message));
716
+ }
717
+ }
718
+ }
719
+ } else {
720
+ console.log(`โš ๏ธ Received ${type} without targetPeerId via ${uri}`);
721
+ }
722
+ this.emit('bootstrapSignaling', { type, data, fromPeerId, targetPeerId, uri });
723
+ break;
724
+
725
+ case 'pong':
726
+ // Heartbeat response
727
+ break;
728
+
729
+ default:
730
+ console.log(`๐Ÿ“จ Received ${type} from bootstrap hub ${uri}`);
731
+ }
732
+ }
733
+
734
+ /**
735
+ * Disconnect from all bootstrap hubs
736
+ */
737
+ disconnectFromBootstrapHubs() {
738
+ console.log(`๐Ÿ”Œ Disconnecting from ${this.bootstrapConnections.size} bootstrap hub(s)...`);
739
+
740
+ for (const [uri, info] of this.bootstrapConnections) {
741
+ if (info.reconnectTimer) {
742
+ clearTimeout(info.reconnectTimer);
743
+ }
744
+
745
+ if (info.ws && info.ws.readyState === WebSocket.OPEN) {
746
+ info.ws.close(1000, 'Hub shutting down');
747
+ }
748
+ }
749
+
750
+ this.bootstrapConnections.clear();
751
+ }
752
+
166
753
  /**
167
754
  * Setup WebSocket connection handlers
168
755
  */
@@ -172,12 +759,26 @@ export class PeerPigeonServer extends EventEmitter {
172
759
  const peerId = url.searchParams.get('peerId');
173
760
 
174
761
  // Validate peer ID
175
- if (!peerId || !/^[a-fA-F0-9]{40}$/.test(peerId)) {
762
+ if (!peerId || !this.validatePeerId(peerId)) {
176
763
  console.log('โŒ Invalid peer ID, closing connection');
177
764
  ws.close(1008, 'Invalid peerId format');
178
765
  return;
179
766
  }
180
767
 
768
+ // Check if peerId is already connected
769
+ if (this.connections.has(peerId)) {
770
+ const existingConnection = this.connections.get(peerId);
771
+ if (existingConnection.readyState === existingConnection.OPEN) {
772
+ console.log(`โš ๏ธ Peer ${peerId.substring(0, 8)}... already connected, closing duplicate`);
773
+ ws.close(1008, 'Peer already connected');
774
+ return;
775
+ } else {
776
+ // Clean up stale connection
777
+ console.log(`๐Ÿ”„ Replacing stale connection for ${peerId.substring(0, 8)}...`);
778
+ this.cleanupPeer(peerId);
779
+ }
780
+ }
781
+
181
782
  // Check connection limit
182
783
  if (this.connections.size >= this.maxConnections) {
183
784
  console.log('โŒ Maximum connections reached, closing connection');
@@ -191,9 +792,13 @@ export class PeerPigeonServer extends EventEmitter {
191
792
  peerId,
192
793
  connectedAt: Date.now(),
193
794
  lastActivity: Date.now(),
194
- remoteAddress: req.socket.remoteAddress
795
+ remoteAddress: req.socket.remoteAddress,
796
+ connected: true
195
797
  });
196
798
 
799
+ // Set up connection metadata
800
+ ws.connectedAt = Date.now();
801
+
197
802
  console.log(`โœ… Peer connected: ${peerId.substring(0, 8)}... (${this.connections.size} total)`);
198
803
  this.emit('peerConnected', { peerId, totalConnections: this.connections.size });
199
804
 
@@ -250,20 +855,37 @@ export class PeerPigeonServer extends EventEmitter {
250
855
  return;
251
856
  }
252
857
 
858
+ const { type, data: messageData, targetPeerId, networkName, fromPeerId: originalFromPeerId } = message;
859
+
253
860
  // Log message type
254
- console.log(`๐Ÿ“จ Message from ${peerId.substring(0, 8)}...: ${message.type}`);
861
+ console.log(`๐Ÿ“จ Received ${type} from ${peerId.substring(0, 8)}... in network: ${networkName || 'global'}`);
862
+
863
+ // Preserve the original fromPeerId if it exists (for relayed messages from other hubs)
864
+ // Otherwise use the peerId of the connection
865
+ const responseMessage = {
866
+ type,
867
+ data: messageData,
868
+ fromPeerId: originalFromPeerId || peerId,
869
+ targetPeerId,
870
+ networkName: networkName || 'global',
871
+ timestamp: Date.now()
872
+ };
255
873
 
256
- switch (message.type) {
874
+ switch (type) {
257
875
  case 'announce':
258
- this.handleAnnounce(peerId, message);
876
+ this.handleAnnounce(peerId, message, responseMessage);
259
877
  break;
260
878
  case 'goodbye':
261
- this.handleGoodbye(peerId, message);
879
+ this.handleGoodbye(peerId, message, responseMessage);
262
880
  break;
263
881
  case 'offer':
264
882
  case 'answer':
265
883
  case 'ice-candidate':
266
- this.handleSignaling(peerId, message);
884
+ this.handleSignaling(peerId, message, responseMessage);
885
+ break;
886
+ case 'peer-discovered':
887
+ // Handle peer discovery from other hubs
888
+ this.handlePeerDiscovered(peerId, message);
267
889
  break;
268
890
  case 'ping':
269
891
  this.handlePing(peerId, message);
@@ -272,85 +894,255 @@ export class PeerPigeonServer extends EventEmitter {
272
894
  this.handleCleanup(peerId, message);
273
895
  break;
274
896
  default:
275
- console.log(`โ“ Unknown message type from ${peerId.substring(0, 8)}...: ${message.type}`);
897
+ console.log(`โš ๏ธ Ignoring non-signaling message type '${type}' - peers should route their own messages`);
898
+ const connection = this.connections.get(peerId);
899
+ if (connection && connection.readyState === WebSocket.OPEN) {
900
+ this.sendToConnection(connection, {
901
+ type: 'error',
902
+ error: `Signaling server does not route '${type}' messages. Use WebRTC data channels for peer-to-peer communication.`,
903
+ timestamp: Date.now()
904
+ });
905
+ }
906
+ break;
276
907
  }
277
908
  }
278
909
 
279
910
  /**
280
911
  * Handle peer announcement
281
912
  */
282
- handleAnnounce(peerId, message) {
283
- console.log(`๐Ÿ“ข Peer announced: ${peerId.substring(0, 8)}...`);
913
+ handleAnnounce(peerId, message, responseMessage) {
914
+ // Extract network name from the message
915
+ const peerNetworkName = message.networkName || 'global';
916
+
917
+ // Detect if this peer is a hub
918
+ const isHub = message.data?.isHub === true || peerNetworkName === this.hubMeshNamespace;
919
+
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}`);
924
+ }
284
925
 
285
- // Update peer data
926
+ // Update peer data with network information
286
927
  const peerInfo = this.peerData.get(peerId);
287
928
  if (peerInfo) {
288
929
  peerInfo.announced = true;
289
930
  peerInfo.announcedAt = Date.now();
931
+ peerInfo.networkName = peerNetworkName;
932
+ peerInfo.data = message.data;
933
+ peerInfo.isHub = isHub;
290
934
  }
291
935
 
292
- // Notify other peers about this peer
293
- this.broadcastToOthers(peerId, {
294
- type: 'peer-discovered',
295
- data: {
296
- peerId,
297
- timestamp: Date.now(),
298
- ...message.data
299
- },
300
- fromPeerId: 'system',
301
- timestamp: Date.now()
936
+ // Register as hub if applicable
937
+ if (isHub) {
938
+ this.registerHub(peerId, {
939
+ networkName: peerNetworkName,
940
+ data: message.data,
941
+ connectedAt: peerInfo?.connectedAt || Date.now()
942
+ });
943
+
944
+ // When a new hub announces itself, send it all our local peers
945
+ if (this.isHub) {
946
+ console.log(`๐Ÿ“ก New hub connected, sending our local peers to ${peerId.substring(0, 8)}...`);
947
+ this.sendLocalPeersToHub(peerId);
948
+ }
949
+ }
950
+
951
+ // Add peer to network tracking
952
+ if (!this.networkPeers.has(peerNetworkName)) {
953
+ this.networkPeers.set(peerNetworkName, new Set());
954
+ }
955
+ this.networkPeers.get(peerNetworkName).add(peerId);
956
+
957
+ // If this is a hub, broadcast this peer to ALL other connected hubs (both bootstrap and incoming)
958
+ if (this.isHub && !isHub) {
959
+ const connectedHubs = [];
960
+
961
+ // 1. Add outgoing bootstrap connections
962
+ for (const [uri, connInfo] of this.bootstrapConnections) {
963
+ if (connInfo.connected && connInfo.ws.readyState === WebSocket.OPEN) {
964
+ connectedHubs.push({ type: 'bootstrap', ws: connInfo.ws, id: uri });
965
+ }
966
+ }
967
+
968
+ // 2. Add incoming hub connections (hubs that connected to us)
969
+ for (const [hubPeerId, hubInfo] of this.hubs) {
970
+ // Skip self and the announcing hub
971
+ if (hubPeerId === this.hubPeerId || hubPeerId === peerId) {
972
+ continue;
973
+ }
974
+ const hubConnection = this.connections.get(hubPeerId);
975
+ if (hubConnection && hubConnection.readyState === WebSocket.OPEN) {
976
+ connectedHubs.push({ type: 'incoming', ws: hubConnection, id: hubPeerId });
977
+ }
978
+ }
979
+
980
+ if (connectedHubs.length > 0) {
981
+ console.log(`๐Ÿ“ก Broadcasting peer ${peerId.substring(0, 8)}... to ${connectedHubs.length} connected hub(s)`);
982
+ const peerAnnouncement = {
983
+ type: 'peer-discovered',
984
+ data: {
985
+ peerId,
986
+ isHub: false,
987
+ ...message.data
988
+ },
989
+ networkName: peerNetworkName,
990
+ fromPeerId: 'system',
991
+ timestamp: Date.now()
992
+ };
993
+
994
+ for (const hub of connectedHubs) {
995
+ try {
996
+ if (hub.type === 'bootstrap') {
997
+ hub.ws.send(JSON.stringify(peerAnnouncement));
998
+ } else {
999
+ this.sendToConnection(hub.ws, peerAnnouncement);
1000
+ }
1001
+ } catch (error) {
1002
+ console.error(`โŒ Error broadcasting to hub ${hub.id}:`, error.message);
1003
+ }
1004
+ }
1005
+ }
1006
+ }
1007
+
1008
+ // Get active peers in the same network
1009
+ const activePeers = this.getActivePeers(peerId, peerNetworkName);
1010
+
1011
+ // Validate peers
1012
+ const validatedPeers = [];
1013
+ for (const otherPeerId of activePeers) {
1014
+ const connection = this.connections.get(otherPeerId);
1015
+ if (connection && connection.readyState === connection.OPEN) {
1016
+ validatedPeers.push(otherPeerId);
1017
+ } else {
1018
+ console.log(`๐Ÿงน Found dead connection during announce: ${otherPeerId.substring(0, 8)}...`);
1019
+ this.cleanupPeer(otherPeerId);
1020
+ }
1021
+ }
1022
+
1023
+ const hubType = isHub ? 'hub' : 'peer';
1024
+ console.log(`๐Ÿ“ข Announcing ${hubType} ${peerId.substring(0, 8)}... to ${validatedPeers.length} validated peers in network: ${peerNetworkName}`);
1025
+
1026
+ // Send peer-discovered messages to validated peers only
1027
+ validatedPeers.forEach(otherPeerId => {
1028
+ const otherPeerData = this.peerData.get(otherPeerId);
1029
+ this.sendToConnection(this.connections.get(otherPeerId), {
1030
+ type: 'peer-discovered',
1031
+ data: {
1032
+ peerId,
1033
+ isHub,
1034
+ ...message.data
1035
+ },
1036
+ networkName: peerNetworkName,
1037
+ fromPeerId: 'system',
1038
+ targetPeerId: otherPeerId,
1039
+ timestamp: Date.now()
1040
+ });
302
1041
  });
303
1042
 
304
- this.emit('peerAnnounced', { peerId });
1043
+ // Send existing validated peers to the new peer (include their hub status)
1044
+ const newPeerConnection = this.connections.get(peerId);
1045
+ validatedPeers.forEach(existingPeerId => {
1046
+ const existingPeerData = this.peerData.get(existingPeerId);
1047
+ this.sendToConnection(newPeerConnection, {
1048
+ type: 'peer-discovered',
1049
+ data: {
1050
+ peerId: existingPeerId,
1051
+ isHub: existingPeerData?.isHub || false,
1052
+ ...existingPeerData?.data
1053
+ },
1054
+ networkName: peerNetworkName,
1055
+ fromPeerId: 'system',
1056
+ targetPeerId: peerId,
1057
+ timestamp: Date.now()
1058
+ });
1059
+ });
1060
+
1061
+ this.emit('peerAnnounced', { peerId, networkName: peerNetworkName, isHub });
305
1062
  }
306
1063
 
307
1064
  /**
308
1065
  * Handle peer goodbye
309
1066
  */
310
- handleGoodbye(peerId, message) {
1067
+ handleGoodbye(peerId, message, responseMessage) {
311
1068
  console.log(`๐Ÿ‘‹ Peer goodbye: ${peerId.substring(0, 8)}...`);
312
1069
 
313
- // Notify other peers about disconnection
314
- this.broadcastToOthers(peerId, {
315
- type: 'peer-disconnected',
316
- data: {
317
- peerId,
318
- reason: message.data?.reason || 'goodbye',
319
- timestamp: Date.now()
320
- },
321
- fromPeerId: 'system',
322
- timestamp: Date.now()
323
- });
324
-
1070
+ // Broadcast to closest peers before removing peer data
1071
+ this.broadcastToClosestPeers(peerId, responseMessage);
1072
+
325
1073
  // Remove peer
326
- this.removePeer(peerId);
1074
+ this.cleanupPeer(peerId);
327
1075
  this.emit('peerGoodbye', { peerId });
328
1076
  }
329
1077
 
330
1078
  /**
331
1079
  * Handle WebRTC signaling messages
332
1080
  */
333
- handleSignaling(peerId, message) {
1081
+ handleSignaling(peerId, message, responseMessage) {
334
1082
  const targetPeerId = message.targetPeerId;
1083
+ const networkName = message.networkName || 'global';
1084
+
1085
+ console.log(`๐Ÿ” SIGNALING DEBUG: Received ${message.type} from ${peerId.substring(0, 8)}... to ${targetPeerId?.substring(0, 8)}... in network '${networkName}'`);
1086
+
335
1087
  if (!targetPeerId) {
336
1088
  console.log(`โŒ No target peer ID in signaling message from ${peerId.substring(0, 8)}...`);
337
1089
  return;
338
1090
  }
339
1091
 
340
1092
  const targetConnection = this.connections.get(targetPeerId);
341
- if (!targetConnection) {
342
- console.log(`โŒ Target peer ${targetPeerId.substring(0, 8)}... not found for signaling`);
343
- return;
1093
+
1094
+ // Only validate network if target peer is local (we have their data)
1095
+ if (targetConnection) {
1096
+ const targetPeerData = this.peerData.get(targetPeerId);
1097
+ const targetNetwork = targetPeerData?.networkName || 'global';
1098
+
1099
+ 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`);
1101
+ return;
1102
+ }
1103
+
1104
+ // Target is local - forward directly
1105
+ console.log(`โœ… Forwarding ${message.type} to LOCAL peer ${targetPeerId.substring(0, 8)}...`);
1106
+ this.sendToConnection(targetConnection, responseMessage);
1107
+ } else {
1108
+ // Target peer not on this hub - relay to other hubs
1109
+ console.log(`๐Ÿ”„ Target peer ${targetPeerId.substring(0, 8)}... NOT LOCAL, relaying to other hubs (network: ${networkName})`);
1110
+
1111
+ let relayed = false;
1112
+
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)`);
1116
+
1117
+ for (const [uri, connInfo] of this.bootstrapConnections) {
1118
+ if (connInfo.connected && connInfo.ws.readyState === WebSocket.OPEN) {
1119
+ connInfo.ws.send(JSON.stringify(responseMessage));
1120
+ console.log(`โœ… Relayed ${message.type} to bootstrap hub ${uri}`);
1121
+ relayed = true;
1122
+ }
1123
+ }
1124
+ }
1125
+
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)`);
1129
+
1130
+ for (const [hubPeerId, hubInfo] of this.hubs) {
1131
+ const hubConnection = this.connections.get(hubPeerId);
1132
+ if (hubConnection && hubConnection.readyState === WebSocket.OPEN) {
1133
+ hubConnection.send(JSON.stringify(responseMessage));
1134
+ console.log(`โœ… Forwarded ${message.type} to hub ${hubPeerId.substring(0, 8)}...`);
1135
+ relayed = true;
1136
+ }
1137
+ }
1138
+ }
1139
+
1140
+ if (!relayed) {
1141
+ console.log(`โŒ FAILED TO RELAY: No hubs available for ${targetPeerId.substring(0, 8)}... (network: ${networkName})`);
1142
+ console.log(` - Bootstrap connections: ${this.bootstrapConnections.size}`);
1143
+ console.log(` - Connected hubs: ${this.hubs.size}`);
1144
+ }
344
1145
  }
345
-
346
- // Forward signaling message to target peer
347
- this.sendToConnection(targetConnection, {
348
- ...message,
349
- fromPeerId: peerId,
350
- timestamp: Date.now()
351
- });
352
-
353
- console.log(`๐Ÿ”„ Forwarded ${message.type} from ${peerId.substring(0, 8)}... to ${targetPeerId.substring(0, 8)}...`);
354
1146
  }
355
1147
 
356
1148
  /**
@@ -378,6 +1170,59 @@ export class PeerPigeonServer extends EventEmitter {
378
1170
  // This is just for logging purposes
379
1171
  }
380
1172
 
1173
+ /**
1174
+ * Handle peer discovery messages from other hubs
1175
+ */
1176
+ handlePeerDiscovered(fromHubPeerId, message) {
1177
+ const { data: messageData, networkName } = message;
1178
+ const discoveredPeerId = messageData?.peerId;
1179
+
1180
+ if (!discoveredPeerId || !networkName) {
1181
+ console.log(`โš ๏ธ Invalid peer-discovered message from ${fromHubPeerId.substring(0, 8)}...`);
1182
+ return;
1183
+ }
1184
+
1185
+ // Check if sender is a hub
1186
+ const senderPeerData = this.peerData.get(fromHubPeerId);
1187
+ const isFromHub = senderPeerData?.isHub || senderPeerData?.networkName === this.hubMeshNamespace;
1188
+
1189
+ if (!isFromHub) {
1190
+ console.log(`โš ๏ธ Received peer-discovered from non-hub peer ${fromHubPeerId.substring(0, 8)}... - ignoring`);
1191
+ return;
1192
+ }
1193
+
1194
+ console.log(`๐Ÿ” Received peer discovery from hub ${fromHubPeerId.substring(0, 8)}... - Peer ${discoveredPeerId.substring(0, 8)}... in network '${networkName}'`);
1195
+
1196
+ // Forward to all local CLIENT peers in the same network (exclude hubs)
1197
+ const localPeers = this.networkPeers.get(networkName);
1198
+ if (localPeers && localPeers.size > 0) {
1199
+ let forwardedCount = 0;
1200
+ for (const localPeerId of localPeers) {
1201
+ // Skip hubs - only forward to client peers
1202
+ const localPeerData = this.peerData.get(localPeerId);
1203
+ if (localPeerData?.isHub) {
1204
+ continue;
1205
+ }
1206
+
1207
+ const ws = this.connections.get(localPeerId);
1208
+ if (ws && ws.readyState === ws.OPEN) {
1209
+ ws.send(JSON.stringify({
1210
+ type: 'peer-discovered',
1211
+ data: messageData,
1212
+ networkName,
1213
+ fromPeerId: 'system',
1214
+ targetPeerId: localPeerId,
1215
+ timestamp: Date.now()
1216
+ }));
1217
+ forwardedCount++;
1218
+ }
1219
+ }
1220
+ console.log(`โœ… Forwarded peer-discovered to ${forwardedCount} local peer(s) in network '${networkName}'`);
1221
+ } else {
1222
+ console.log(`โ„น๏ธ No local peers in network '${networkName}' to forward to`);
1223
+ }
1224
+ }
1225
+
381
1226
  /**
382
1227
  * Handle peer disconnection
383
1228
  */
@@ -397,17 +1242,67 @@ export class PeerPigeonServer extends EventEmitter {
397
1242
  });
398
1243
 
399
1244
  // Remove peer
400
- this.removePeer(peerId);
1245
+ this.cleanupPeer(peerId);
401
1246
  this.emit('peerDisconnected', { peerId, code, reason, totalConnections: this.connections.size });
402
1247
  }
403
1248
 
404
1249
  /**
405
- * Remove peer from server
1250
+ * Remove peer from server with network cleanup
406
1251
  */
407
- removePeer(peerId) {
1252
+ cleanupPeer(peerId) {
1253
+ const wasConnected = this.connections.has(peerId);
1254
+ const peerInfo = this.peerData.get(peerId);
1255
+ const isHub = peerInfo?.isHub || false;
1256
+
408
1257
  this.connections.delete(peerId);
409
1258
  this.peerData.delete(peerId);
410
- console.log(`๐Ÿ—‘๏ธ Removed peer: ${peerId.substring(0, 8)}... (${this.connections.size} remaining)`);
1259
+
1260
+ // Unregister hub if applicable
1261
+ if (isHub) {
1262
+ this.unregisterHub(peerId);
1263
+ }
1264
+
1265
+ // Remove from network tracking
1266
+ if (peerInfo && peerInfo.networkName) {
1267
+ const networkPeerSet = this.networkPeers.get(peerInfo.networkName);
1268
+ if (networkPeerSet) {
1269
+ networkPeerSet.delete(peerId);
1270
+ // Clean up empty network sets
1271
+ if (networkPeerSet.size === 0) {
1272
+ this.networkPeers.delete(peerInfo.networkName);
1273
+ }
1274
+ }
1275
+ }
1276
+
1277
+ if (wasConnected) {
1278
+ const peerType = isHub ? 'hub' : 'peer';
1279
+ console.log(`๐Ÿงน Cleaned up ${peerType}: ${peerId.substring(0, 8)}... from network: ${peerInfo?.networkName || 'unknown'}`);
1280
+
1281
+ // Notify other peers in the same network about disconnection
1282
+ if (peerInfo && peerInfo.networkName) {
1283
+ const activePeers = this.getActivePeers(null, peerInfo.networkName);
1284
+ activePeers.forEach(otherPeerId => {
1285
+ this.sendToConnection(this.connections.get(otherPeerId), {
1286
+ type: 'peer-disconnected',
1287
+ data: {
1288
+ peerId,
1289
+ isHub
1290
+ },
1291
+ networkName: peerInfo.networkName,
1292
+ fromPeerId: 'system',
1293
+ targetPeerId: otherPeerId,
1294
+ timestamp: Date.now()
1295
+ });
1296
+ });
1297
+ }
1298
+ }
1299
+ }
1300
+
1301
+ /**
1302
+ * Remove peer from server (backwards compatibility)
1303
+ */
1304
+ removePeer(peerId) {
1305
+ this.cleanupPeer(peerId);
411
1306
  }
412
1307
 
413
1308
  /**
@@ -445,6 +1340,22 @@ export class PeerPigeonServer extends EventEmitter {
445
1340
  return sentCount;
446
1341
  }
447
1342
 
1343
+ /**
1344
+ * Broadcast message to closest peers in same network
1345
+ */
1346
+ broadcastToClosestPeers(fromPeerId, message, maxPeers = 5) {
1347
+ const peerInfo = this.peerData.get(fromPeerId);
1348
+ const networkName = peerInfo?.networkName || 'global';
1349
+ const activePeers = this.getActivePeers(fromPeerId, networkName);
1350
+ const closestPeers = this.findClosestPeers(fromPeerId, activePeers, maxPeers);
1351
+
1352
+ console.log(`Broadcasting from ${fromPeerId.substring(0, 8)}... to ${closestPeers.length} closest peers in network: ${networkName}`);
1353
+
1354
+ closestPeers.forEach(peerId => {
1355
+ this.sendToConnection(this.connections.get(peerId), message);
1356
+ });
1357
+ }
1358
+
448
1359
  /**
449
1360
  * Start cleanup timer
450
1361
  */
@@ -458,33 +1369,17 @@ export class PeerPigeonServer extends EventEmitter {
458
1369
  * Perform cleanup of inactive connections
459
1370
  */
460
1371
  performCleanup() {
461
- const now = Date.now();
462
- const disconnectedPeers = [];
463
-
464
- for (const [peerId, peerInfo] of this.peerData) {
465
- if (now - peerInfo.lastActivity > this.peerTimeout) {
466
- console.log(`๐Ÿงน Cleaning up inactive peer: ${peerId.substring(0, 8)}...`);
467
-
468
- const connection = this.connections.get(peerId);
469
- if (connection) {
470
- try {
471
- connection.close(1000, 'Inactive timeout');
472
- } catch (error) {
473
- console.error(`Error closing inactive connection for ${peerId}:`, error);
474
- }
475
- }
476
-
477
- disconnectedPeers.push(peerId);
478
- }
1372
+ const totalConnections = this.connections.size;
1373
+
1374
+ // Clean up all networks
1375
+ for (const [networkName] of this.networkPeers) {
1376
+ this.getActivePeers(null, networkName); // This will clean up stale connections
479
1377
  }
1378
+
1379
+ const cleanedUp = totalConnections - this.connections.size;
480
1380
 
481
- // Remove disconnected peers
482
- disconnectedPeers.forEach(peerId => {
483
- this.removePeer(peerId);
484
- });
485
-
486
- if (disconnectedPeers.length > 0) {
487
- console.log(`๐Ÿงน Cleaned up ${disconnectedPeers.length} inactive peers`);
1381
+ if (cleanedUp > 0) {
1382
+ console.log(`๐Ÿงน Periodic cleanup: removed ${cleanedUp} stale connections, ${this.connections.size} active across ${this.networkPeers.size} networks`);
488
1383
  }
489
1384
  }
490
1385
 
@@ -492,23 +1387,88 @@ export class PeerPigeonServer extends EventEmitter {
492
1387
  * Get server statistics
493
1388
  */
494
1389
  getStats() {
1390
+ const bootstrapStats = {
1391
+ total: this.bootstrapConnections.size,
1392
+ connected: 0
1393
+ };
1394
+
1395
+ for (const [, info] of this.bootstrapConnections) {
1396
+ if (info.connected) {
1397
+ bootstrapStats.connected++;
1398
+ }
1399
+ }
1400
+
495
1401
  return {
496
1402
  isRunning: this.isRunning,
1403
+ isHub: this.isHub,
1404
+ hubPeerId: this.hubPeerId,
1405
+ hubMeshNamespace: this.hubMeshNamespace,
497
1406
  connections: this.connections.size,
498
1407
  peers: this.peerData.size,
1408
+ hubs: this.hubs.size,
1409
+ networks: this.networkPeers.size,
1410
+ bootstrapHubs: bootstrapStats,
499
1411
  maxConnections: this.maxConnections,
500
- uptime: this.isRunning ? Date.now() - this.startTime : 0,
1412
+ uptime: this.isRunning && this.startTime ? Date.now() - this.startTime : 0,
501
1413
  host: this.host,
502
1414
  port: this.port
503
1415
  };
504
1416
  }
505
1417
 
1418
+ /**
1419
+ * Get hub statistics
1420
+ */
1421
+ getHubStats() {
1422
+ const connectedHubs = this.getConnectedHubs();
1423
+ const bootstrapHubsInfo = [];
1424
+
1425
+ for (const [uri, info] of this.bootstrapConnections) {
1426
+ bootstrapHubsInfo.push({
1427
+ uri,
1428
+ connected: info.connected,
1429
+ lastAttempt: info.lastAttempt,
1430
+ attemptNumber: info.attemptNumber
1431
+ });
1432
+ }
1433
+
1434
+ return {
1435
+ totalHubs: this.hubs.size,
1436
+ connectedHubs: connectedHubs.length,
1437
+ hubs: connectedHubs,
1438
+ bootstrapHubs: bootstrapHubsInfo
1439
+ };
1440
+ }
1441
+
506
1442
  /**
507
1443
  * Get list of connected peers
508
1444
  */
509
1445
  getPeers() {
510
1446
  return Array.from(this.peerData.values());
511
1447
  }
1448
+
1449
+ /**
1450
+ * Get the current hub mesh namespace
1451
+ */
1452
+ getHubMeshNamespace() {
1453
+ return this.hubMeshNamespace;
1454
+ }
1455
+
1456
+ /**
1457
+ * Set the hub mesh namespace (only when server is not running)
1458
+ */
1459
+ setHubMeshNamespace(namespace) {
1460
+ if (this.isRunning) {
1461
+ throw new Error('Cannot change hub mesh namespace while server is running. Stop the server first.');
1462
+ }
1463
+
1464
+ if (typeof namespace !== 'string' || namespace.trim().length === 0) {
1465
+ throw new Error('Hub mesh namespace must be a non-empty string');
1466
+ }
1467
+
1468
+ this.hubMeshNamespace = namespace.trim();
1469
+ console.log(`๐ŸŒ Hub mesh namespace set to: ${this.hubMeshNamespace}`);
1470
+ return this.hubMeshNamespace;
1471
+ }
512
1472
  }
513
1473
 
514
1474
  // For backwards compatibility and standalone usage