peerpigeon 0.0.2 → 0.0.4

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 (36) hide show
  1. package/README.md +4 -4
  2. package/examples/node/test-node.js +153 -0
  3. package/index.js +12 -0
  4. package/package.json +3 -3
  5. package/src/ConnectionManager.js +11 -4
  6. package/src/EnvironmentDetector.js +441 -0
  7. package/src/GossipManager.js +11 -3
  8. package/src/MediaManager.js +14 -0
  9. package/src/PeerConnection.js +30 -13
  10. package/src/PeerDiscovery.js +10 -3
  11. package/src/PeerPigeonMesh.js +187 -2
  12. package/src/SignalingClient.js +65 -12
  13. package/src/StorageManager.js +48 -6
  14. package/src/TimerUtils.js +36 -8
  15. package/websocket-server/server.js +148 -22
  16. package/websocket-server/node_modules/.package-lock.json +0 -29
  17. package/websocket-server/node_modules/ws/LICENSE +0 -20
  18. package/websocket-server/node_modules/ws/README.md +0 -548
  19. package/websocket-server/node_modules/ws/browser.js +0 -8
  20. package/websocket-server/node_modules/ws/index.js +0 -13
  21. package/websocket-server/node_modules/ws/lib/buffer-util.js +0 -131
  22. package/websocket-server/node_modules/ws/lib/constants.js +0 -18
  23. package/websocket-server/node_modules/ws/lib/event-target.js +0 -292
  24. package/websocket-server/node_modules/ws/lib/extension.js +0 -203
  25. package/websocket-server/node_modules/ws/lib/limiter.js +0 -55
  26. package/websocket-server/node_modules/ws/lib/permessage-deflate.js +0 -528
  27. package/websocket-server/node_modules/ws/lib/receiver.js +0 -706
  28. package/websocket-server/node_modules/ws/lib/sender.js +0 -602
  29. package/websocket-server/node_modules/ws/lib/stream.js +0 -161
  30. package/websocket-server/node_modules/ws/lib/subprotocol.js +0 -62
  31. package/websocket-server/node_modules/ws/lib/validation.js +0 -152
  32. package/websocket-server/node_modules/ws/lib/websocket-server.js +0 -550
  33. package/websocket-server/node_modules/ws/lib/websocket.js +0 -1388
  34. package/websocket-server/node_modules/ws/package.json +0 -69
  35. package/websocket-server/node_modules/ws/wrapper.mjs +0 -8
  36. package/websocket-server/package-lock.json +0 -39
package/src/TimerUtils.js CHANGED
@@ -3,11 +3,23 @@
3
3
  * by debugging tools, preventing "Illegal invocation" errors.
4
4
  */
5
5
 
6
+ import { environmentDetector } from './EnvironmentDetector.js';
7
+
6
8
  // Store original timer functions to avoid issues with wrapped functions
7
- const originalSetInterval = window.setInterval;
8
- const originalSetTimeout = window.setTimeout;
9
- const originalClearInterval = window.clearInterval;
10
- const originalClearTimeout = window.clearTimeout;
9
+ let originalSetInterval, originalSetTimeout, originalClearInterval, originalClearTimeout;
10
+
11
+ if (environmentDetector.isBrowser) {
12
+ originalSetInterval = window.setInterval;
13
+ originalSetTimeout = window.setTimeout;
14
+ originalClearInterval = window.clearInterval;
15
+ originalClearTimeout = window.clearTimeout;
16
+ } else {
17
+ // In Node.js or other environments, use global functions
18
+ originalSetInterval = setInterval;
19
+ originalSetTimeout = setTimeout;
20
+ originalClearInterval = clearInterval;
21
+ originalClearTimeout = clearTimeout;
22
+ }
11
23
 
12
24
  /**
13
25
  * Safe setInterval that uses the original function to avoid context issues
@@ -16,7 +28,11 @@ const originalClearTimeout = window.clearTimeout;
16
28
  * @returns {number} - Interval ID
17
29
  */
18
30
  export function safeSetInterval(callback, delay) {
19
- return originalSetInterval.call(window, callback, delay);
31
+ if (environmentDetector.isBrowser) {
32
+ return originalSetInterval.call(window, callback, delay);
33
+ } else {
34
+ return originalSetInterval(callback, delay);
35
+ }
20
36
  }
21
37
 
22
38
  /**
@@ -26,7 +42,11 @@ export function safeSetInterval(callback, delay) {
26
42
  * @returns {number} - Timeout ID
27
43
  */
28
44
  export function safeSetTimeout(callback, delay) {
29
- return originalSetTimeout.call(window, callback, delay);
45
+ if (environmentDetector.isBrowser) {
46
+ return originalSetTimeout.call(window, callback, delay);
47
+ } else {
48
+ return originalSetTimeout(callback, delay);
49
+ }
30
50
  }
31
51
 
32
52
  /**
@@ -34,7 +54,11 @@ export function safeSetTimeout(callback, delay) {
34
54
  * @param {number} id - Interval ID to clear
35
55
  */
36
56
  export function safeClearInterval(id) {
37
- return originalClearInterval.call(window, id);
57
+ if (environmentDetector.isBrowser) {
58
+ return originalClearInterval.call(window, id);
59
+ } else {
60
+ return originalClearInterval(id);
61
+ }
38
62
  }
39
63
 
40
64
  /**
@@ -42,5 +66,9 @@ export function safeClearInterval(id) {
42
66
  * @param {number} id - Timeout ID to clear
43
67
  */
44
68
  export function safeClearTimeout(id) {
45
- return originalClearTimeout.call(window, id);
69
+ if (environmentDetector.isBrowser) {
70
+ return originalClearTimeout.call(window, id);
71
+ } else {
72
+ return originalClearTimeout(id);
73
+ }
46
74
  }
@@ -1,4 +1,4 @@
1
- import { WebSocketServer } from 'ws';
1
+ import { WebSocketServer, WebSocket } from 'ws';
2
2
  import { createServer } from 'http';
3
3
  import { URL } from 'url';
4
4
 
@@ -50,14 +50,57 @@ function findClosestPeers(targetPeerId, allPeerIds, maxPeers = 3) {
50
50
 
51
51
  function getActivePeers(excludePeerId = null) {
52
52
  const peers = [];
53
+ const stalePeers = [];
54
+
53
55
  for (const [peerId, connection] of connections) {
54
- if (peerId !== excludePeerId && connection.readyState === WebSocket.OPEN) {
55
- peers.push(peerId);
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
+ }
56
63
  }
57
64
  }
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
+
58
73
  return peers;
59
74
  }
60
75
 
76
+ 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;
88
+ }
89
+
90
+ 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
+ }
100
+ }
101
+ return false;
102
+ }
103
+
61
104
  function sendToConnection(peerId, data) {
62
105
  const connection = connections.get(peerId);
63
106
  if (connection && connection.readyState === WebSocket.OPEN) {
@@ -66,12 +109,39 @@ function sendToConnection(peerId, data) {
66
109
  return true;
67
110
  } catch (error) {
68
111
  console.error(`Error sending to ${peerId}:`, error);
112
+ // Clean up failed connection
113
+ cleanupPeer(peerId);
69
114
  return false;
70
115
  }
116
+ } else if (connection && (connection.readyState === WebSocket.CLOSED || connection.readyState === WebSocket.CLOSING)) {
117
+ // Clean up closed connection
118
+ cleanupPeer(peerId);
71
119
  }
72
120
  return false;
73
121
  }
74
122
 
123
+ 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
+ }
143
+ }
144
+
75
145
  function broadcastToClosestPeers(fromPeerId, message, maxPeers = 5) {
76
146
  const activePeers = getActivePeers(fromPeerId);
77
147
  const closestPeers = findClosestPeers(fromPeerId, activePeers, maxPeers);
@@ -95,6 +165,33 @@ const wss = new WebSocketServer({ server });
95
165
 
96
166
  console.log(`🚀 Starting PeerPigeon WebSocket server...`);
97
167
 
168
+ // Periodic cleanup of stale connections
169
+ 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
+ }
177
+ }, 30000); // Clean up every 30 seconds
178
+
179
+ // Heartbeat ping every 30 seconds
180
+ 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
+ }
188
+ }
189
+
190
+ if (stalePeers.length > 0) {
191
+ console.log(`🧹 Heartbeat cleanup: removed ${stalePeers.length} unresponsive connections`);
192
+ }
193
+ }, 30000); // Ping every 30 seconds
194
+
98
195
  wss.on('connection', (ws, req) => {
99
196
  let peerId = null;
100
197
 
@@ -110,6 +207,20 @@ wss.on('connection', (ws, req) => {
110
207
 
111
208
  peerId = queryPeerId;
112
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
+ }
222
+ }
223
+
113
224
  // Store connection
114
225
  connections.set(peerId, ws);
115
226
  peerData.set(peerId, {
@@ -118,6 +229,15 @@ wss.on('connection', (ws, req) => {
118
229
  connected: true
119
230
  });
120
231
 
232
+ // Set up connection metadata
233
+ ws.connectedAt = Date.now();
234
+ ws.lastPong = Date.now();
235
+
236
+ // Set up pong handler for heartbeat
237
+ ws.on('pong', () => {
238
+ ws.lastPong = Date.now();
239
+ });
240
+
121
241
  console.log(`✅ Peer ${peerId.substring(0, 8)}... connected (${connections.size} total)`);
122
242
 
123
243
  // Send connection confirmation
@@ -163,11 +283,25 @@ wss.on('connection', (ws, req) => {
163
283
  connected: true
164
284
  });
165
285
 
286
+ // Get active peers with immediate validation
166
287
  const activePeers = getActivePeers(peerId);
167
- console.log(`📢 Announcing ${peerId.substring(0, 8)}... to ${activePeers.length} peers`);
168
288
 
169
- // Send peer-discovered messages to other peers
170
- activePeers.forEach(otherPeerId => {
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 => {
171
305
  sendToConnection(otherPeerId, {
172
306
  type: 'peer-discovered',
173
307
  data: { peerId, ...messageData },
@@ -177,8 +311,8 @@ wss.on('connection', (ws, req) => {
177
311
  });
178
312
  });
179
313
 
180
- // Send existing peers to the new peer
181
- activePeers.forEach(existingPeerId => {
314
+ // Send existing validated peers to the new peer
315
+ validatedPeers.forEach(existingPeerId => {
182
316
  const existingPeerData = peerData.get(existingPeerId);
183
317
  ws.send(JSON.stringify({
184
318
  type: 'peer-discovered',
@@ -235,20 +369,7 @@ wss.on('connection', (ws, req) => {
235
369
  console.log(`🔌 Peer ${peerId?.substring(0, 8)}... disconnected (${code}: ${reason})`);
236
370
 
237
371
  if (peerId) {
238
- connections.delete(peerId);
239
- peerData.delete(peerId);
240
-
241
- // Notify other peers
242
- const activePeers = getActivePeers();
243
- activePeers.forEach(otherPeerId => {
244
- sendToConnection(otherPeerId, {
245
- type: 'peer-disconnected',
246
- data: { peerId },
247
- fromPeerId: 'system',
248
- targetPeerId: otherPeerId,
249
- timestamp: Date.now()
250
- });
251
- });
372
+ cleanupPeer(peerId);
252
373
  }
253
374
 
254
375
  console.log(`📊 Active connections: ${connections.size}`);
@@ -257,6 +378,11 @@ wss.on('connection', (ws, req) => {
257
378
  // Handle connection errors
258
379
  ws.on('error', (error) => {
259
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);
385
+ }
260
386
  });
261
387
  });
262
388
 
@@ -1,29 +0,0 @@
1
- {
2
- "name": "local-websocket-server",
3
- "version": "1.0.0",
4
- "lockfileVersion": 3,
5
- "requires": true,
6
- "packages": {
7
- "node_modules/ws": {
8
- "version": "8.18.3",
9
- "resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz",
10
- "integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==",
11
- "license": "MIT",
12
- "engines": {
13
- "node": ">=10.0.0"
14
- },
15
- "peerDependencies": {
16
- "bufferutil": "^4.0.1",
17
- "utf-8-validate": ">=5.0.2"
18
- },
19
- "peerDependenciesMeta": {
20
- "bufferutil": {
21
- "optional": true
22
- },
23
- "utf-8-validate": {
24
- "optional": true
25
- }
26
- }
27
- }
28
- }
29
- }
@@ -1,20 +0,0 @@
1
- Copyright (c) 2011 Einar Otto Stangvik <einaros@gmail.com>
2
- Copyright (c) 2013 Arnout Kazemier and contributors
3
- Copyright (c) 2016 Luigi Pinca and contributors
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy of
6
- this software and associated documentation files (the "Software"), to deal in
7
- the Software without restriction, including without limitation the rights to
8
- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
- the Software, and to permit persons to whom the Software is furnished to do so,
10
- subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17
- FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18
- COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19
- IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
- CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.