peerpigeon 0.0.5 โ†’ 0.0.6

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.
@@ -4,7 +4,7 @@ import { URL } from 'url';
4
4
 
5
5
  /**
6
6
  * Local WebSocket Server for PeerPigeon Development
7
- *
7
+ *
8
8
  * This server provides WebSocket signaling functionality
9
9
  * for local development and testing of the PeerPigeon mesh network.
10
10
  */
@@ -14,147 +14,143 @@ const HOST = process.env.HOST || 'localhost';
14
14
 
15
15
  // In-memory storage for connections and peer data
16
16
  const connections = new Map(); // peerId -> WebSocket connection
17
- const peerData = new Map(); // peerId -> { peerId, timestamp, data }
17
+ const peerData = new Map(); // peerId -> { peerId, timestamp, data }
18
18
 
19
19
  // Utility functions
20
- function generateId() {
21
- return Date.now().toString(36) + Math.random().toString(36).substr(2);
22
- }
23
-
24
20
  function validatePeerId(peerId) {
25
- return typeof peerId === 'string' && /^[a-fA-F0-9]{40}$/.test(peerId);
21
+ return typeof peerId === 'string' && /^[a-fA-F0-9]{40}$/.test(peerId);
26
22
  }
27
23
 
28
24
  function findClosestPeers(targetPeerId, allPeerIds, maxPeers = 3) {
29
- if (!targetPeerId || !allPeerIds || allPeerIds.length === 0) {
30
- return [];
25
+ if (!targetPeerId || !allPeerIds || allPeerIds.length === 0) {
26
+ return [];
27
+ }
28
+
29
+ // XOR distance calculation (simplified)
30
+ const distances = allPeerIds.map(peerId => {
31
+ let distance = 0;
32
+ const minLength = Math.min(targetPeerId.length, peerId.length);
33
+
34
+ for (let i = 0; i < minLength; i++) {
35
+ const xor = parseInt(targetPeerId[i], 16) ^ parseInt(peerId[i], 16);
36
+ distance += xor;
31
37
  }
32
-
33
- // XOR distance calculation (simplified)
34
- const distances = allPeerIds.map(peerId => {
35
- let distance = 0;
36
- const minLength = Math.min(targetPeerId.length, peerId.length);
37
-
38
- for (let i = 0; i < minLength; i++) {
39
- const xor = parseInt(targetPeerId[i], 16) ^ parseInt(peerId[i], 16);
40
- distance += xor;
41
- }
42
-
43
- return { peerId, distance };
44
- });
45
-
46
- // Sort by distance and return closest peers
47
- distances.sort((a, b) => a.distance - b.distance);
48
- return distances.slice(0, maxPeers).map(item => item.peerId);
38
+
39
+ return { peerId, distance };
40
+ });
41
+
42
+ // Sort by distance and return closest peers
43
+ distances.sort((a, b) => a.distance - b.distance);
44
+ return distances.slice(0, maxPeers).map(item => item.peerId);
49
45
  }
50
46
 
51
47
  function getActivePeers(excludePeerId = null) {
52
- const peers = [];
53
- const stalePeers = [];
54
-
55
- for (const [peerId, connection] of connections) {
56
- if (peerId !== excludePeerId) {
57
- if (connection.readyState === WebSocket.OPEN && isConnectionAlive(connection)) {
58
- peers.push(peerId);
59
- } else {
60
- // Mark stale connections for cleanup
61
- stalePeers.push(peerId);
62
- }
63
- }
48
+ const peers = [];
49
+ const stalePeers = [];
50
+
51
+ for (const [peerId, connection] of connections) {
52
+ if (peerId !== excludePeerId) {
53
+ if (connection.readyState === WebSocket.OPEN && isConnectionAlive(connection)) {
54
+ peers.push(peerId);
55
+ } else {
56
+ // Mark stale connections for cleanup
57
+ stalePeers.push(peerId);
58
+ }
64
59
  }
65
-
66
- // Clean up stale connections
67
- stalePeers.forEach(peerId => {
68
- console.log(`๐Ÿงน Cleaning up stale connection: ${peerId.substring(0, 8)}...`);
69
- connections.delete(peerId);
70
- peerData.delete(peerId);
71
- });
72
-
73
- return peers;
60
+ }
61
+
62
+ // Clean up stale connections
63
+ stalePeers.forEach(peerId => {
64
+ console.log(`๐Ÿงน Cleaning up stale connection: ${peerId.substring(0, 8)}...`);
65
+ connections.delete(peerId);
66
+ peerData.delete(peerId);
67
+ });
68
+
69
+ return peers;
74
70
  }
75
71
 
76
72
  function isConnectionAlive(connection) {
77
- if (!connection || connection.readyState !== WebSocket.OPEN) {
78
- return false;
79
- }
80
-
81
- // Check if we've received a recent pong or if this is a fresh connection
82
- const now = Date.now();
83
- const lastPong = connection.lastPong || connection.connectedAt || now;
84
- const timeSinceLastPong = now - lastPong;
85
-
86
- // Consider connection dead if no pong for more than 12 minutes (since we ping every 9 minutes)
87
- return timeSinceLastPong < 720000; // 12 minutes
73
+ if (!connection || connection.readyState !== WebSocket.OPEN) {
74
+ return false;
75
+ }
76
+
77
+ // Check if we've received a recent pong or if this is a fresh connection
78
+ const now = Date.now();
79
+ const lastPong = connection.lastPong || connection.connectedAt || now;
80
+ const timeSinceLastPong = now - lastPong;
81
+
82
+ // Consider connection dead if no pong for more than 12 minutes (since we ping every 9 minutes)
83
+ return timeSinceLastPong < 720000; // 12 minutes
88
84
  }
89
85
 
90
86
  function pingConnection(peerId, connection) {
91
- if (connection.readyState === WebSocket.OPEN) {
92
- try {
93
- connection.ping();
94
- return true;
95
- } catch (error) {
96
- console.log(`๐Ÿ“ Failed to ping ${peerId.substring(0, 8)}...:`, error.message);
97
- cleanupPeer(peerId);
98
- return false;
99
- }
87
+ if (connection.readyState === WebSocket.OPEN) {
88
+ try {
89
+ connection.ping();
90
+ return true;
91
+ } catch (error) {
92
+ console.log(`๐Ÿ“ Failed to ping ${peerId.substring(0, 8)}...:`, error.message);
93
+ cleanupPeer(peerId);
94
+ return false;
100
95
  }
101
- return false;
96
+ }
97
+ return false;
102
98
  }
103
99
 
104
100
  function sendToConnection(peerId, data) {
105
- const connection = connections.get(peerId);
106
- if (connection && connection.readyState === WebSocket.OPEN) {
107
- try {
108
- connection.send(JSON.stringify(data));
109
- return true;
110
- } catch (error) {
111
- console.error(`Error sending to ${peerId}:`, error);
112
- // Clean up failed connection
113
- cleanupPeer(peerId);
114
- return false;
115
- }
116
- } else if (connection && (connection.readyState === WebSocket.CLOSED || connection.readyState === WebSocket.CLOSING)) {
117
- // Clean up closed connection
118
- cleanupPeer(peerId);
101
+ const connection = connections.get(peerId);
102
+ if (connection && connection.readyState === WebSocket.OPEN) {
103
+ try {
104
+ connection.send(JSON.stringify(data));
105
+ return true;
106
+ } catch (error) {
107
+ console.error(`Error sending to ${peerId}:`, error);
108
+ // Clean up failed connection
109
+ cleanupPeer(peerId);
110
+ return false;
119
111
  }
120
- return false;
112
+ } else if (connection && (connection.readyState === WebSocket.CLOSED || connection.readyState === WebSocket.CLOSING)) {
113
+ // Clean up closed connection
114
+ cleanupPeer(peerId);
115
+ }
116
+ return false;
121
117
  }
122
118
 
123
119
  function cleanupPeer(peerId) {
124
- const wasConnected = connections.has(peerId);
125
- connections.delete(peerId);
126
- peerData.delete(peerId);
127
-
128
- if (wasConnected) {
129
- console.log(`๐Ÿงน Cleaned up peer: ${peerId.substring(0, 8)}...`);
130
-
131
- // Notify other peers about disconnection
132
- const activePeers = getActivePeers();
133
- activePeers.forEach(otherPeerId => {
134
- sendToConnection(otherPeerId, {
135
- type: 'peer-disconnected',
136
- data: { peerId },
137
- fromPeerId: 'system',
138
- targetPeerId: otherPeerId,
139
- timestamp: Date.now()
140
- });
141
- });
142
- }
120
+ const wasConnected = connections.has(peerId);
121
+ connections.delete(peerId);
122
+ peerData.delete(peerId);
123
+
124
+ if (wasConnected) {
125
+ console.log(`๐Ÿงน Cleaned up peer: ${peerId.substring(0, 8)}...`);
126
+
127
+ // Notify other peers about disconnection
128
+ const activePeers = getActivePeers();
129
+ activePeers.forEach(otherPeerId => {
130
+ sendToConnection(otherPeerId, {
131
+ type: 'peer-disconnected',
132
+ data: { peerId },
133
+ fromPeerId: 'system',
134
+ targetPeerId: otherPeerId,
135
+ timestamp: Date.now()
136
+ });
137
+ });
138
+ }
143
139
  }
144
140
 
145
141
  function broadcastToClosestPeers(fromPeerId, message, maxPeers = 5) {
146
- const activePeers = getActivePeers(fromPeerId);
147
- const closestPeers = findClosestPeers(fromPeerId, activePeers, maxPeers);
148
-
149
- console.log(`Broadcasting from ${fromPeerId} to ${closestPeers.length} closest peers`);
150
-
151
- closestPeers.forEach(peerId => {
152
- sendToConnection(peerId, message);
153
- });
142
+ const activePeers = getActivePeers(fromPeerId);
143
+ const closestPeers = findClosestPeers(fromPeerId, activePeers, maxPeers);
144
+
145
+ console.log(`Broadcasting from ${fromPeerId} to ${closestPeers.length} closest peers`);
146
+
147
+ closestPeers.forEach(peerId => {
148
+ sendToConnection(peerId, message);
149
+ });
154
150
  }
155
151
 
156
152
  function sendToSpecificPeer(targetPeerId, message) {
157
- return sendToConnection(targetPeerId, message);
153
+ return sendToConnection(targetPeerId, message);
158
154
  }
159
155
 
160
156
  // Create HTTP server
@@ -163,302 +159,304 @@ const server = createServer();
163
159
  // Create WebSocket server
164
160
  const wss = new WebSocketServer({ server });
165
161
 
166
- console.log(`๐Ÿš€ Starting PeerPigeon WebSocket server...`);
162
+ console.log('๐Ÿš€ Starting PeerPigeon WebSocket server...');
167
163
 
168
164
  // Periodic cleanup of stale connections
169
165
  setInterval(() => {
170
- const totalConnections = connections.size;
171
- const activePeers = getActivePeers(); // This will clean up stale connections
172
- const cleanedUp = totalConnections - connections.size;
173
-
174
- if (cleanedUp > 0) {
175
- console.log(`๐Ÿงน Periodic cleanup: removed ${cleanedUp} stale connections, ${connections.size} active`);
176
- }
166
+ const totalConnections = connections.size;
167
+ getActivePeers(); // This will clean up stale connections
168
+ const cleanedUp = totalConnections - connections.size;
169
+
170
+ if (cleanedUp > 0) {
171
+ console.log(`๐Ÿงน Periodic cleanup: removed ${cleanedUp} stale connections, ${connections.size} active`);
172
+ }
177
173
  }, 30000); // Clean up every 30 seconds
178
174
 
179
175
  // DHT-based heartbeat ping every 9 minutes (540 seconds)
180
176
  // Use DHT logic to select a SINGLE peer to do the pinging instead of server pinging all
181
177
  setInterval(() => {
182
- const activePeers = Array.from(connections.keys());
183
-
184
- if (activePeers.length === 0) {
185
- console.log(`๐Ÿ“ No peers to ping`);
186
- return;
187
- }
188
-
189
- // Use XOR distance to select the peer closest to a deterministic target
190
- // This ensures the same peer is consistently selected across intervals
191
- const pingTarget = '0000000000000000000000000000000000000000'; // Deterministic target for ping selection
192
- const selectedPeer = selectPeerForPing(pingTarget, activePeers);
193
-
194
- if (selectedPeer) {
195
- const connection = connections.get(selectedPeer);
196
- console.log(`๐Ÿ“ DHT-selected peer ${selectedPeer.substring(0, 8)}... for heartbeat ping (${activePeers.length} total peers)`);
197
-
198
- if (!pingConnection(selectedPeer, connection)) {
199
- console.log(`๐Ÿงน DHT-selected peer ${selectedPeer.substring(0, 8)}... failed ping, cleaned up`);
200
- }
178
+ const activePeers = Array.from(connections.keys());
179
+
180
+ if (activePeers.length === 0) {
181
+ console.log('๐Ÿ“ No peers to ping');
182
+ return;
183
+ }
184
+
185
+ // Use XOR distance to select the peer closest to a deterministic target
186
+ // This ensures the same peer is consistently selected across intervals
187
+ const pingTarget = '0000000000000000000000000000000000000000'; // Deterministic target for ping selection
188
+ const selectedPeer = selectPeerForPing(pingTarget, activePeers);
189
+
190
+ if (selectedPeer) {
191
+ const connection = connections.get(selectedPeer);
192
+ console.log(`๐Ÿ“ DHT-selected peer ${selectedPeer.substring(0, 8)}... for heartbeat ping (${activePeers.length} total peers)`);
193
+
194
+ if (!pingConnection(selectedPeer, connection)) {
195
+ console.log(`๐Ÿงน DHT-selected peer ${selectedPeer.substring(0, 8)}... failed ping, cleaned up`);
201
196
  }
197
+ }
202
198
  }, 540000); // Ping every 9 minutes (540 seconds)
203
199
 
204
200
  // DHT-based peer selection for ping duty
205
201
  function selectPeerForPing(target, peerIds) {
206
- if (!peerIds || peerIds.length === 0) return null;
207
-
208
- // Use XOR distance to find the peer closest to the target
209
- let closestPeer = null;
210
- let closestDistance = Infinity;
211
-
212
- for (const peerId of peerIds) {
213
- const distance = calculateXORDistance(target, peerId);
214
- if (distance < closestDistance) {
215
- closestDistance = distance;
216
- closestPeer = peerId;
217
- }
202
+ if (!peerIds || peerIds.length === 0) return null;
203
+
204
+ // Use XOR distance to find the peer closest to the target
205
+ let closestPeer = null;
206
+ let closestDistance = Infinity;
207
+
208
+ for (const peerId of peerIds) {
209
+ const distance = calculateXORDistance(target, peerId);
210
+ if (distance < closestDistance) {
211
+ closestDistance = distance;
212
+ closestPeer = peerId;
218
213
  }
219
-
220
- return closestPeer;
214
+ }
215
+
216
+ return closestPeer;
221
217
  }
222
218
 
223
219
  // XOR distance calculation for DHT peer selection
224
220
  function calculateXORDistance(id1, id2) {
225
- let distance = 0;
226
- const minLength = Math.min(id1.length, id2.length);
227
-
228
- for (let i = 0; i < minLength; i++) {
229
- const xor = parseInt(id1[i], 16) ^ parseInt(id2[i], 16);
230
- distance += xor;
231
- }
232
-
233
- return distance;
221
+ let distance = 0;
222
+ const minLength = Math.min(id1.length, id2.length);
223
+
224
+ for (let i = 0; i < minLength; i++) {
225
+ const xor = parseInt(id1[i], 16) ^ parseInt(id2[i], 16);
226
+ distance += xor;
227
+ }
228
+
229
+ return distance;
234
230
  }
235
231
 
236
232
  wss.on('connection', (ws, req) => {
237
- let peerId = null;
238
-
239
- // Extract peerId from query parameters
240
- const url = new URL(req.url, `http://${req.headers.host}`);
241
- const queryPeerId = url.searchParams.get('peerId');
242
-
243
- if (!queryPeerId || !validatePeerId(queryPeerId)) {
244
- console.log(`โŒ Invalid peerId: ${queryPeerId}`);
245
- ws.close(1008, 'Invalid peerId');
246
- return;
247
- }
248
-
249
- peerId = queryPeerId;
250
-
251
- // Check if peerId is already connected
252
- if (connections.has(peerId)) {
253
- const existingConnection = connections.get(peerId);
254
- if (existingConnection.readyState === WebSocket.OPEN) {
255
- console.log(`โš ๏ธ Peer ${peerId.substring(0, 8)}... already connected, closing duplicate`);
256
- ws.close(1008, 'Peer already connected');
257
- return;
258
- } else {
259
- // Clean up stale connection
260
- console.log(`๐Ÿ”„ Replacing stale connection for ${peerId.substring(0, 8)}...`);
261
- cleanupPeer(peerId);
262
- }
233
+ let peerId = null;
234
+
235
+ // Extract peerId from query parameters
236
+ const url = new URL(req.url, `http://${req.headers.host}`);
237
+ const queryPeerId = url.searchParams.get('peerId');
238
+
239
+ if (!queryPeerId || !validatePeerId(queryPeerId)) {
240
+ console.log(`โŒ Invalid peerId: ${queryPeerId}`);
241
+ ws.close(1008, 'Invalid peerId');
242
+ return;
243
+ }
244
+
245
+ peerId = queryPeerId;
246
+
247
+ // Check if peerId is already connected
248
+ if (connections.has(peerId)) {
249
+ const existingConnection = connections.get(peerId);
250
+ if (existingConnection.readyState === WebSocket.OPEN) {
251
+ console.log(`โš ๏ธ Peer ${peerId.substring(0, 8)}... already connected, closing duplicate`);
252
+ ws.close(1008, 'Peer already connected');
253
+ return;
254
+ } else {
255
+ // Clean up stale connection
256
+ console.log(`๐Ÿ”„ Replacing stale connection for ${peerId.substring(0, 8)}...`);
257
+ cleanupPeer(peerId);
263
258
  }
264
-
265
- // Store connection
266
- connections.set(peerId, ws);
267
- peerData.set(peerId, {
268
- peerId,
269
- timestamp: Date.now(),
270
- connected: true
271
- });
272
-
273
- // Set up connection metadata
274
- ws.connectedAt = Date.now();
259
+ }
260
+
261
+ // Store connection
262
+ connections.set(peerId, ws);
263
+ peerData.set(peerId, {
264
+ peerId,
265
+ timestamp: Date.now(),
266
+ connected: true
267
+ });
268
+
269
+ // Set up connection metadata
270
+ ws.connectedAt = Date.now();
271
+ ws.lastPong = Date.now();
272
+
273
+ // Set up pong handler for heartbeat
274
+ ws.on('pong', () => {
275
275
  ws.lastPong = Date.now();
276
-
277
- // Set up pong handler for heartbeat
278
- ws.on('pong', () => {
279
- ws.lastPong = Date.now();
280
- });
281
-
282
- console.log(`โœ… Peer ${peerId.substring(0, 8)}... connected (${connections.size} total)`);
283
-
284
- // Send connection confirmation
285
- ws.send(JSON.stringify({
286
- type: 'connected',
287
- peerId: peerId,
276
+ });
277
+
278
+ console.log(`โœ… Peer ${peerId.substring(0, 8)}... connected (${connections.size} total)`);
279
+
280
+ // Send connection confirmation
281
+ ws.send(JSON.stringify({
282
+ type: 'connected',
283
+ peerId,
284
+ timestamp: Date.now()
285
+ }));
286
+
287
+ // Handle incoming messages
288
+ ws.on('message', (data) => {
289
+ try {
290
+ const message = JSON.parse(data);
291
+ const { type, data: messageData, targetPeerId, maxPeers } = message;
292
+
293
+ console.log(`๐Ÿ“จ Received ${type} from ${peerId.substring(0, 8)}...`);
294
+
295
+ const responseMessage = {
296
+ type,
297
+ data: messageData,
298
+ fromPeerId: peerId,
299
+ targetPeerId,
288
300
  timestamp: Date.now()
289
- }));
290
-
291
- // Handle incoming messages
292
- ws.on('message', (data) => {
293
- try {
294
- const message = JSON.parse(data);
295
- const { type, data: messageData, targetPeerId, maxPeers } = message;
296
-
297
- console.log(`๐Ÿ“จ Received ${type} from ${peerId.substring(0, 8)}...`);
298
-
299
- const responseMessage = {
300
- type,
301
- data: messageData,
302
- fromPeerId: peerId,
303
- targetPeerId,
304
- timestamp: Date.now()
305
- };
306
-
307
- // Handle different message types
308
- switch (type) {
309
- case 'ping':
310
- // Respond with pong
311
- ws.send(JSON.stringify({
312
- type: 'pong',
313
- timestamp: Date.now(),
314
- originalTimestamp: messageData?.timestamp
315
- }));
316
- break;
317
-
318
- case 'announce':
319
- // Handle peer announcement
320
- peerData.set(peerId, {
321
- peerId,
322
- timestamp: Date.now(),
323
- data: messageData,
324
- connected: true
325
- });
326
-
327
- // Get active peers with immediate validation
328
- const activePeers = getActivePeers(peerId);
329
-
330
- // Double-check each active peer with a quick ping test
331
- const validatedPeers = [];
332
- for (const otherPeerId of activePeers) {
333
- const connection = connections.get(otherPeerId);
334
- if (connection && isConnectionAlive(connection)) {
335
- validatedPeers.push(otherPeerId);
336
- } else {
337
- console.log(`๏ฟฝ Found dead connection during announce: ${otherPeerId.substring(0, 8)}...`);
338
- cleanupPeer(otherPeerId);
339
- }
340
- }
341
-
342
- console.log(`๏ฟฝ๐Ÿ“ข Announcing ${peerId.substring(0, 8)}... to ${validatedPeers.length} validated peers`);
343
-
344
- // Send peer-discovered messages to validated peers only
345
- validatedPeers.forEach(otherPeerId => {
346
- sendToConnection(otherPeerId, {
347
- type: 'peer-discovered',
348
- data: { peerId, ...messageData },
349
- fromPeerId: 'system',
350
- targetPeerId: otherPeerId,
351
- timestamp: Date.now()
352
- });
353
- });
354
-
355
- // Send existing validated peers to the new peer
356
- validatedPeers.forEach(existingPeerId => {
357
- const existingPeerData = peerData.get(existingPeerId);
358
- ws.send(JSON.stringify({
359
- type: 'peer-discovered',
360
- data: { peerId: existingPeerId, ...existingPeerData?.data },
361
- fromPeerId: 'system',
362
- targetPeerId: peerId,
363
- timestamp: Date.now()
364
- }));
365
- });
366
- break;
367
-
368
- case 'goodbye':
369
- // Handle peer disconnect
370
- peerData.delete(peerId);
371
- broadcastToClosestPeers(peerId, responseMessage);
372
- break;
373
-
374
- case 'offer':
375
- case 'answer':
376
- case 'ice-candidate':
377
- // Handle WebRTC signaling
378
- if (targetPeerId) {
379
- const success = sendToSpecificPeer(targetPeerId, responseMessage);
380
- if (!success) {
381
- console.log(`โš ๏ธ Failed to send ${type} to ${targetPeerId.substring(0, 8)}... (peer not found)`);
382
- }
383
- } else {
384
- console.log(`โš ๏ธ ${type} message missing targetPeerId`);
385
- }
386
- break;
387
-
388
- default:
389
- // Handle generic messages
390
- if (targetPeerId) {
391
- sendToSpecificPeer(targetPeerId, responseMessage);
392
- } else {
393
- broadcastToClosestPeers(peerId, responseMessage, maxPeers || 10);
394
- }
395
- break;
301
+ };
302
+
303
+ // Handle different message types
304
+ switch (type) {
305
+ case 'ping':
306
+ // Respond with pong
307
+ ws.send(JSON.stringify({
308
+ type: 'pong',
309
+ timestamp: Date.now(),
310
+ originalTimestamp: messageData?.timestamp
311
+ }));
312
+ break;
313
+
314
+ case 'announce': {
315
+ // Handle peer announcement
316
+ peerData.set(peerId, {
317
+ peerId,
318
+ timestamp: Date.now(),
319
+ data: messageData,
320
+ connected: true
321
+ });
322
+
323
+ // Get active peers with immediate validation
324
+ const activePeers = getActivePeers(peerId);
325
+
326
+ // Double-check each active peer with a quick ping test
327
+ const validatedPeers = [];
328
+ for (const otherPeerId of activePeers) {
329
+ const connection = connections.get(otherPeerId);
330
+ if (connection && isConnectionAlive(connection)) {
331
+ validatedPeers.push(otherPeerId);
332
+ } else {
333
+ console.log(`๏ฟฝ Found dead connection during announce: ${otherPeerId.substring(0, 8)}...`);
334
+ cleanupPeer(otherPeerId);
396
335
  }
397
-
398
- } catch (error) {
399
- console.error(`โŒ Error handling message from ${peerId?.substring(0, 8)}...:`, error);
336
+ }
337
+
338
+ console.log(`๏ฟฝ๐Ÿ“ข Announcing ${peerId.substring(0, 8)}... to ${validatedPeers.length} validated peers`);
339
+
340
+ // Send peer-discovered messages to validated peers only
341
+ validatedPeers.forEach(otherPeerId => {
342
+ sendToConnection(otherPeerId, {
343
+ type: 'peer-discovered',
344
+ data: { peerId, ...messageData },
345
+ fromPeerId: 'system',
346
+ targetPeerId: otherPeerId,
347
+ timestamp: Date.now()
348
+ });
349
+ });
350
+
351
+ // Send existing validated peers to the new peer
352
+ validatedPeers.forEach(existingPeerId => {
353
+ const existingPeerData = peerData.get(existingPeerId);
400
354
  ws.send(JSON.stringify({
401
- type: 'error',
402
- error: 'Invalid message format',
403
- timestamp: Date.now()
355
+ type: 'peer-discovered',
356
+ data: { peerId: existingPeerId, ...existingPeerData?.data },
357
+ fromPeerId: 'system',
358
+ targetPeerId: peerId,
359
+ timestamp: Date.now()
404
360
  }));
361
+ });
362
+ break;
405
363
  }
406
- });
407
-
408
- // Handle connection close
409
- ws.on('close', (code, reason) => {
410
- console.log(`๐Ÿ”Œ Peer ${peerId?.substring(0, 8)}... disconnected (${code}: ${reason})`);
411
-
412
- if (peerId) {
413
- cleanupPeer(peerId);
364
+
365
+ case 'goodbye': {
366
+ // Handle peer disconnect
367
+ peerData.delete(peerId);
368
+ broadcastToClosestPeers(peerId, responseMessage);
369
+ break;
414
370
  }
415
-
416
- console.log(`๐Ÿ“Š Active connections: ${connections.size}`);
417
- });
418
-
419
- // Handle connection errors
420
- ws.on('error', (error) => {
421
- console.error(`โŒ WebSocket error for ${peerId?.substring(0, 8)}...:`, error);
422
-
423
- // Clean up errored connection
424
- if (peerId && (ws.readyState === WebSocket.CLOSED || ws.readyState === WebSocket.CLOSING)) {
425
- cleanupPeer(peerId);
371
+
372
+ case 'offer':
373
+ case 'answer':
374
+ case 'ice-candidate': {
375
+ // Handle WebRTC signaling
376
+ if (targetPeerId) {
377
+ const success = sendToSpecificPeer(targetPeerId, responseMessage);
378
+ if (!success) {
379
+ console.log(`โš ๏ธ Failed to send ${type} to ${targetPeerId.substring(0, 8)}... (peer not found)`);
380
+ }
381
+ } else {
382
+ console.log(`โš ๏ธ ${type} message missing targetPeerId`);
383
+ }
384
+ break;
426
385
  }
427
- });
386
+
387
+ default:
388
+ // Handle generic messages
389
+ if (targetPeerId) {
390
+ sendToSpecificPeer(targetPeerId, responseMessage);
391
+ } else {
392
+ broadcastToClosestPeers(peerId, responseMessage, maxPeers || 10);
393
+ }
394
+ break;
395
+ }
396
+ } catch (error) {
397
+ console.error(`โŒ Error handling message from ${peerId?.substring(0, 8)}...:`, error);
398
+ ws.send(JSON.stringify({
399
+ type: 'error',
400
+ error: 'Invalid message format',
401
+ timestamp: Date.now()
402
+ }));
403
+ }
404
+ });
405
+
406
+ // Handle connection close
407
+ ws.on('close', (code, reason) => {
408
+ console.log(`๐Ÿ”Œ Peer ${peerId?.substring(0, 8)}... disconnected (${code}: ${reason})`);
409
+
410
+ if (peerId) {
411
+ cleanupPeer(peerId);
412
+ }
413
+
414
+ console.log(`๐Ÿ“Š Active connections: ${connections.size}`);
415
+ });
416
+
417
+ // Handle connection errors
418
+ ws.on('error', (error) => {
419
+ console.error(`โŒ WebSocket error for ${peerId?.substring(0, 8)}...:`, error);
420
+
421
+ // Clean up errored connection
422
+ if (peerId && (ws.readyState === WebSocket.CLOSED || ws.readyState === WebSocket.CLOSING)) {
423
+ cleanupPeer(peerId);
424
+ }
425
+ });
428
426
  });
429
427
 
430
428
  // Start server
431
429
  server.listen(PORT, HOST, () => {
432
- console.log(`๐ŸŒ PeerPigeon WebSocket server running on ws://${HOST}:${PORT}`);
433
- console.log(`๐Ÿ“ Usage: Connect with ?peerId=<40-char-hex-id>`);
434
- console.log(`๐Ÿ“Š Ready to handle peer connections...`);
430
+ console.log(`๐ŸŒ PeerPigeon WebSocket server running on ws://${HOST}:${PORT}`);
431
+ console.log('๐Ÿ“ Usage: Connect with ?peerId=<40-char-hex-id>');
432
+ console.log('๐Ÿ“Š Ready to handle peer connections...');
435
433
  });
436
434
 
437
435
  // Handle graceful shutdown
438
436
  process.on('SIGINT', () => {
439
- console.log('\n๐Ÿ›‘ Shutting down WebSocket server...');
440
-
441
- // Close all connections
442
- for (const [peerId, connection] of connections) {
443
- connection.close(1001, 'Server shutting down');
444
- }
445
-
446
- // Close server
447
- server.close(() => {
448
- console.log('โœ… WebSocket server closed');
449
- process.exit(0);
450
- });
437
+ console.log('\n๐Ÿ›‘ Shutting down WebSocket server...');
438
+
439
+ // Close all connections
440
+ for (const [, connection] of connections) {
441
+ connection.close(1001, 'Server shutting down');
442
+ }
443
+
444
+ // Close server
445
+ server.close(() => {
446
+ console.log('โœ… WebSocket server closed');
447
+ process.exit(0);
448
+ });
451
449
  });
452
450
 
453
451
  // Error handling
454
452
  process.on('uncaughtException', (error) => {
455
- console.error('โŒ Uncaught Exception:', error);
456
- process.exit(1);
453
+ console.error('โŒ Uncaught Exception:', error);
454
+ process.exit(1);
457
455
  });
458
456
 
459
457
  process.on('unhandledRejection', (reason, promise) => {
460
- console.error('โŒ Unhandled Rejection at:', promise, 'reason:', reason);
461
- process.exit(1);
458
+ console.error('โŒ Unhandled Rejection at:', promise, 'reason:', reason);
459
+ process.exit(1);
462
460
  });
463
461
 
464
462
  // Export for programmatic use