peerpigeon 0.0.4 โ†’ 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 60 seconds
87
- return timeSinceLastPong < 60000;
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,261 +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
- // Heartbeat ping every 30 seconds
175
+ // DHT-based heartbeat ping every 9 minutes (540 seconds)
176
+ // Use DHT logic to select a SINGLE peer to do the pinging instead of server pinging all
180
177
  setInterval(() => {
181
- console.log(`๐Ÿ“ Pinging ${connections.size} connections...`);
182
- const stalePeers = [];
183
-
184
- for (const [peerId, connection] of connections) {
185
- if (!pingConnection(peerId, connection)) {
186
- stalePeers.push(peerId);
187
- }
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`);
188
196
  }
189
-
190
- if (stalePeers.length > 0) {
191
- console.log(`๐Ÿงน Heartbeat cleanup: removed ${stalePeers.length} unresponsive connections`);
197
+ }
198
+ }, 540000); // Ping every 9 minutes (540 seconds)
199
+
200
+ // DHT-based peer selection for ping duty
201
+ function selectPeerForPing(target, peerIds) {
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;
192
213
  }
193
- }, 30000); // Ping every 30 seconds
214
+ }
215
+
216
+ return closestPeer;
217
+ }
218
+
219
+ // XOR distance calculation for DHT peer selection
220
+ function calculateXORDistance(id1, id2) {
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;
230
+ }
194
231
 
195
232
  wss.on('connection', (ws, req) => {
196
- let peerId = null;
197
-
198
- // Extract peerId from query parameters
199
- const url = new URL(req.url, `http://${req.headers.host}`);
200
- const queryPeerId = url.searchParams.get('peerId');
201
-
202
- if (!queryPeerId || !validatePeerId(queryPeerId)) {
203
- console.log(`โŒ Invalid peerId: ${queryPeerId}`);
204
- ws.close(1008, 'Invalid peerId');
205
- return;
206
- }
207
-
208
- peerId = queryPeerId;
209
-
210
- // Check if peerId is already connected
211
- if (connections.has(peerId)) {
212
- const existingConnection = connections.get(peerId);
213
- if (existingConnection.readyState === WebSocket.OPEN) {
214
- console.log(`โš ๏ธ Peer ${peerId.substring(0, 8)}... already connected, closing duplicate`);
215
- ws.close(1008, 'Peer already connected');
216
- return;
217
- } else {
218
- // Clean up stale connection
219
- console.log(`๐Ÿ”„ Replacing stale connection for ${peerId.substring(0, 8)}...`);
220
- cleanupPeer(peerId);
221
- }
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);
222
258
  }
223
-
224
- // Store connection
225
- connections.set(peerId, ws);
226
- peerData.set(peerId, {
227
- peerId,
228
- timestamp: Date.now(),
229
- connected: true
230
- });
231
-
232
- // Set up connection metadata
233
- 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', () => {
234
275
  ws.lastPong = Date.now();
235
-
236
- // Set up pong handler for heartbeat
237
- ws.on('pong', () => {
238
- ws.lastPong = Date.now();
239
- });
240
-
241
- console.log(`โœ… Peer ${peerId.substring(0, 8)}... connected (${connections.size} total)`);
242
-
243
- // Send connection confirmation
244
- ws.send(JSON.stringify({
245
- type: 'connected',
246
- 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,
247
300
  timestamp: Date.now()
248
- }));
249
-
250
- // Handle incoming messages
251
- ws.on('message', (data) => {
252
- try {
253
- const message = JSON.parse(data);
254
- const { type, data: messageData, targetPeerId, maxPeers } = message;
255
-
256
- console.log(`๐Ÿ“จ Received ${type} from ${peerId.substring(0, 8)}...`);
257
-
258
- const responseMessage = {
259
- type,
260
- data: messageData,
261
- fromPeerId: peerId,
262
- targetPeerId,
263
- timestamp: Date.now()
264
- };
265
-
266
- // Handle different message types
267
- switch (type) {
268
- case 'ping':
269
- // Respond with pong
270
- ws.send(JSON.stringify({
271
- type: 'pong',
272
- timestamp: Date.now(),
273
- originalTimestamp: messageData?.timestamp
274
- }));
275
- break;
276
-
277
- case 'announce':
278
- // Handle peer announcement
279
- peerData.set(peerId, {
280
- peerId,
281
- timestamp: Date.now(),
282
- data: messageData,
283
- connected: true
284
- });
285
-
286
- // Get active peers with immediate validation
287
- const activePeers = getActivePeers(peerId);
288
-
289
- // Double-check each active peer with a quick ping test
290
- const validatedPeers = [];
291
- for (const otherPeerId of activePeers) {
292
- const connection = connections.get(otherPeerId);
293
- if (connection && isConnectionAlive(connection)) {
294
- validatedPeers.push(otherPeerId);
295
- } else {
296
- console.log(`๏ฟฝ Found dead connection during announce: ${otherPeerId.substring(0, 8)}...`);
297
- cleanupPeer(otherPeerId);
298
- }
299
- }
300
-
301
- console.log(`๏ฟฝ๐Ÿ“ข Announcing ${peerId.substring(0, 8)}... to ${validatedPeers.length} validated peers`);
302
-
303
- // Send peer-discovered messages to validated peers only
304
- validatedPeers.forEach(otherPeerId => {
305
- sendToConnection(otherPeerId, {
306
- type: 'peer-discovered',
307
- data: { peerId, ...messageData },
308
- fromPeerId: 'system',
309
- targetPeerId: otherPeerId,
310
- timestamp: Date.now()
311
- });
312
- });
313
-
314
- // Send existing validated peers to the new peer
315
- validatedPeers.forEach(existingPeerId => {
316
- const existingPeerData = peerData.get(existingPeerId);
317
- ws.send(JSON.stringify({
318
- type: 'peer-discovered',
319
- data: { peerId: existingPeerId, ...existingPeerData?.data },
320
- fromPeerId: 'system',
321
- targetPeerId: peerId,
322
- timestamp: Date.now()
323
- }));
324
- });
325
- break;
326
-
327
- case 'goodbye':
328
- // Handle peer disconnect
329
- peerData.delete(peerId);
330
- broadcastToClosestPeers(peerId, responseMessage);
331
- break;
332
-
333
- case 'offer':
334
- case 'answer':
335
- case 'ice-candidate':
336
- // Handle WebRTC signaling
337
- if (targetPeerId) {
338
- const success = sendToSpecificPeer(targetPeerId, responseMessage);
339
- if (!success) {
340
- console.log(`โš ๏ธ Failed to send ${type} to ${targetPeerId.substring(0, 8)}... (peer not found)`);
341
- }
342
- } else {
343
- console.log(`โš ๏ธ ${type} message missing targetPeerId`);
344
- }
345
- break;
346
-
347
- default:
348
- // Handle generic messages
349
- if (targetPeerId) {
350
- sendToSpecificPeer(targetPeerId, responseMessage);
351
- } else {
352
- broadcastToClosestPeers(peerId, responseMessage, maxPeers || 10);
353
- }
354
- 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);
355
335
  }
356
-
357
- } catch (error) {
358
- 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);
359
354
  ws.send(JSON.stringify({
360
- type: 'error',
361
- error: 'Invalid message format',
362
- timestamp: Date.now()
355
+ type: 'peer-discovered',
356
+ data: { peerId: existingPeerId, ...existingPeerData?.data },
357
+ fromPeerId: 'system',
358
+ targetPeerId: peerId,
359
+ timestamp: Date.now()
363
360
  }));
361
+ });
362
+ break;
364
363
  }
365
- });
366
-
367
- // Handle connection close
368
- ws.on('close', (code, reason) => {
369
- console.log(`๐Ÿ”Œ Peer ${peerId?.substring(0, 8)}... disconnected (${code}: ${reason})`);
370
-
371
- if (peerId) {
372
- cleanupPeer(peerId);
364
+
365
+ case 'goodbye': {
366
+ // Handle peer disconnect
367
+ peerData.delete(peerId);
368
+ broadcastToClosestPeers(peerId, responseMessage);
369
+ break;
373
370
  }
374
-
375
- console.log(`๐Ÿ“Š Active connections: ${connections.size}`);
376
- });
377
-
378
- // Handle connection errors
379
- ws.on('error', (error) => {
380
- console.error(`โŒ WebSocket error for ${peerId?.substring(0, 8)}...:`, error);
381
-
382
- // Clean up errored connection
383
- if (peerId && (ws.readyState === WebSocket.CLOSED || ws.readyState === WebSocket.CLOSING)) {
384
- 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;
385
385
  }
386
- });
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
+ });
387
426
  });
388
427
 
389
428
  // Start server
390
429
  server.listen(PORT, HOST, () => {
391
- console.log(`๐ŸŒ PeerPigeon WebSocket server running on ws://${HOST}:${PORT}`);
392
- console.log(`๐Ÿ“ Usage: Connect with ?peerId=<40-char-hex-id>`);
393
- 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...');
394
433
  });
395
434
 
396
435
  // Handle graceful shutdown
397
436
  process.on('SIGINT', () => {
398
- console.log('\n๐Ÿ›‘ Shutting down WebSocket server...');
399
-
400
- // Close all connections
401
- for (const [peerId, connection] of connections) {
402
- connection.close(1001, 'Server shutting down');
403
- }
404
-
405
- // Close server
406
- server.close(() => {
407
- console.log('โœ… WebSocket server closed');
408
- process.exit(0);
409
- });
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
+ });
410
449
  });
411
450
 
412
451
  // Error handling
413
452
  process.on('uncaughtException', (error) => {
414
- console.error('โŒ Uncaught Exception:', error);
415
- process.exit(1);
453
+ console.error('โŒ Uncaught Exception:', error);
454
+ process.exit(1);
416
455
  });
417
456
 
418
457
  process.on('unhandledRejection', (reason, promise) => {
419
- console.error('โŒ Unhandled Rejection at:', promise, 'reason:', reason);
420
- process.exit(1);
458
+ console.error('โŒ Unhandled Rejection at:', promise, 'reason:', reason);
459
+ process.exit(1);
421
460
  });
422
461
 
423
462
  // Export for programmatic use