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.
- package/README.md +144 -4
- package/examples/browser/app.js +40 -39
- package/examples/browser/crypto-test.html +427 -0
- package/examples/browser/index.html +161 -0
- package/examples/browser/styles.css +216 -0
- package/examples/browser/ui-old.js +1926 -0
- package/examples/browser/ui.js +2226 -1692
- package/examples/node/test-crypto-media.js +137 -0
- package/examples/node/test-crypto.js +146 -0
- package/examples/node/test-node.js +114 -115
- package/package.json +51 -8
- package/src/CleanupManager.js +154 -154
- package/src/ConnectionManager.js +772 -749
- package/src/CryptoManager.js +612 -0
- package/src/EnvironmentDetector.js +381 -381
- package/src/EventEmitter.js +19 -19
- package/src/EvictionManager.js +211 -211
- package/src/GossipManager.js +447 -366
- package/src/MediaManager.js +218 -195
- package/src/MeshOptimizer.js +165 -166
- package/src/PeerConnection.js +850 -758
- package/src/PeerDiscovery.js +255 -259
- package/src/PeerPigeonMesh.js +1082 -723
- package/src/SignalingClient.js +517 -518
- package/src/SignalingHandler.js +295 -291
- package/src/StorageManager.js +105 -105
- package/src/TimerUtils.js +29 -29
- package/src/WebDHT.js +951 -951
- package/websocket-server/server.js +371 -332
|
@@ -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();
|
|
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
|
-
|
|
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
|
-
|
|
30
|
-
|
|
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
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
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
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
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
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
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
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
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
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
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
|
-
|
|
96
|
+
}
|
|
97
|
+
return false;
|
|
102
98
|
}
|
|
103
99
|
|
|
104
100
|
function sendToConnection(peerId, data) {
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
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
|
-
|
|
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
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
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
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
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
|
-
|
|
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(
|
|
162
|
+
console.log('๐ Starting PeerPigeon WebSocket server...');
|
|
167
163
|
|
|
168
164
|
// Periodic cleanup of stale connections
|
|
169
165
|
setInterval(() => {
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
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)
|
|
176
|
+
// Use DHT logic to select a SINGLE peer to do the pinging instead of server pinging all
|
|
180
177
|
setInterval(() => {
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
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
|
-
|
|
191
|
-
|
|
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
|
-
}
|
|
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
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
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
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
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
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
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
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
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
|
-
|
|
358
|
-
|
|
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
|
-
|
|
361
|
-
|
|
362
|
-
|
|
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
|
-
|
|
368
|
-
|
|
369
|
-
|
|
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
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
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
|
-
|
|
392
|
-
|
|
393
|
-
|
|
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
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
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
|
-
|
|
415
|
-
|
|
453
|
+
console.error('โ Uncaught Exception:', error);
|
|
454
|
+
process.exit(1);
|
|
416
455
|
});
|
|
417
456
|
|
|
418
457
|
process.on('unhandledRejection', (reason, promise) => {
|
|
419
|
-
|
|
420
|
-
|
|
458
|
+
console.error('โ Unhandled Rejection at:', promise, 'reason:', reason);
|
|
459
|
+
process.exit(1);
|
|
421
460
|
});
|
|
422
461
|
|
|
423
462
|
// Export for programmatic use
|